xlog.c 270.3 KB
Newer Older
1
/*-------------------------------------------------------------------------
2 3
 *
 * xlog.c
4
 *		PostgreSQL transaction log manager
5 6
 *
 *
7
 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
8
 * Portions Copyright (c) 1994, Regents of the University of California
9
 *
10
 * $PostgreSQL: pgsql/src/backend/access/transam/xlog.c,v 1.387 2010/04/02 13:10:56 sriggs Exp $
11 12 13
 *
 *-------------------------------------------------------------------------
 */
14

15 16
#include "postgres.h"

17
#include <ctype.h>
T
Tom Lane 已提交
18
#include <signal.h>
19
#include <time.h>
20
#include <fcntl.h>
21
#include <sys/stat.h>
22
#include <sys/time.h>
23 24
#include <sys/wait.h>
#include <unistd.h>
25

26
#include "access/clog.h"
27
#include "access/multixact.h"
28
#include "access/subtrans.h"
29
#include "access/transam.h"
30
#include "access/tuptoaster.h"
31
#include "access/twophase.h"
32
#include "access/xact.h"
33
#include "access/xlog_internal.h"
34
#include "access/xlogutils.h"
35
#include "catalog/catversion.h"
T
Tom Lane 已提交
36
#include "catalog/pg_control.h"
37
#include "catalog/pg_database.h"
38 39
#include "catalog/pg_type.h"
#include "funcapi.h"
40
#include "libpq/pqsignal.h"
41
#include "miscadmin.h"
42
#include "pgstat.h"
43
#include "postmaster/bgwriter.h"
44 45
#include "replication/walreceiver.h"
#include "replication/walsender.h"
46
#include "storage/bufmgr.h"
47
#include "storage/fd.h"
48
#include "storage/ipc.h"
49
#include "storage/pmsignal.h"
50
#include "storage/procarray.h"
51
#include "storage/smgr.h"
52
#include "storage/spin.h"
53
#include "utils/builtins.h"
54
#include "utils/guc.h"
55
#include "utils/ps_status.h"
56
#include "utils/relmapper.h"
57
#include "pg_trace.h"
58

59

60 61
/* File path names (all relative to $PGDATA) */
#define BACKUP_LABEL_FILE		"backup_label"
62
#define BACKUP_LABEL_OLD		"backup_label.old"
63 64 65 66
#define RECOVERY_COMMAND_FILE	"recovery.conf"
#define RECOVERY_COMMAND_DONE	"recovery.done"


T
Tom Lane 已提交
67 68
/* User-settable parameters */
int			CheckPointSegments = 3;
V
Vadim B. Mikheev 已提交
69
int			XLOGbuffers = 8;
70
int			XLogArchiveTimeout = 0;
71
bool		XLogArchiveMode = false;
72
char	   *XLogArchiveCommand = NULL;
B
Bruce Momjian 已提交
73
bool		XLogRequestRecoveryConnections = true;
74
int			MaxStandbyDelay = 30;
75
bool		fullPageWrites = true;
76
bool		log_checkpoints = false;
77
int			sync_method = DEFAULT_SYNC_METHOD;
T
Tom Lane 已提交
78

79 80 81 82
#ifdef WAL_DEBUG
bool		XLOG_DEBUG = false;
#endif

83
/*
84 85 86 87 88
 * XLOGfileslop is the maximum number of preallocated future XLOG segments.
 * When we are done with an old XLOG segment file, we will recycle it as a
 * future XLOG segment as long as there aren't already XLOGfileslop future
 * segments; else we'll delete it.  This could be made a separate GUC
 * variable, but at present I think it's sufficient to hardwire it as
B
Bruce Momjian 已提交
89
 * 2*CheckPointSegments+1.	Under normal conditions, a checkpoint will free
90 91 92
 * no more than 2*CheckPointSegments log segments, and we want to recycle all
 * of them; the +1 allows boundary cases to happen without wasting a
 * delete/create-segment cycle.
93 94 95
 */
#define XLOGfileslop	(2*CheckPointSegments + 1)

96 97 98 99
/*
 * GUC support
 */
const struct config_enum_entry sync_method_options[] = {
100
	{"fsync", SYNC_METHOD_FSYNC, false},
101
#ifdef HAVE_FSYNC_WRITETHROUGH
102
	{"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
103 104
#endif
#ifdef HAVE_FDATASYNC
105
	{"fdatasync", SYNC_METHOD_FDATASYNC, false},
106 107
#endif
#ifdef OPEN_SYNC_FLAG
108
	{"open_sync", SYNC_METHOD_OPEN, false},
109 110
#endif
#ifdef OPEN_DATASYNC_FLAG
111
	{"open_datasync", SYNC_METHOD_OPEN_DSYNC, false},
112
#endif
113
	{NULL, 0, false}
114
};
T
Tom Lane 已提交
115

116 117 118 119 120 121 122
/*
 * Statistics for current checkpoint are collected in this global struct.
 * Because only the background writer or a stand-alone backend can perform
 * checkpoints, this will be unused in normal backends.
 */
CheckpointStatsData CheckpointStats;

T
Tom Lane 已提交
123
/*
124 125
 * ThisTimeLineID will be same in all backends --- it identifies current
 * WAL timeline for the database system.
T
Tom Lane 已提交
126
 */
127
TimeLineID	ThisTimeLineID = 0;
V
WAL  
Vadim B. Mikheev 已提交
128

129
/*
130
 * Are we doing recovery from XLOG?
131
 *
132 133 134 135 136
 * This is only ever true in the startup process; it should be read as meaning
 * "this process is replaying WAL records", rather than "the system is in
 * recovery mode".  It should be examined primarily by functions that need
 * to act differently when called from a WAL redo function (e.g., to skip WAL
 * logging).  To check whether the system is in recovery regardless of which
137 138
 * process you're running in, use RecoveryInProgress() but only after shared
 * memory startup and lock initialization.
139
 */
T
Tom Lane 已提交
140
bool		InRecovery = false;
B
Bruce Momjian 已提交
141

142
/* Are we in Hot Standby mode? Only valid in startup process, see xlog.h */
B
Bruce Momjian 已提交
143
HotStandbyState standbyState = STANDBY_DISABLED;
144

B
Bruce Momjian 已提交
145
static XLogRecPtr LastRec;
146

147 148
/*
 * Local copy of SharedRecoveryInProgress variable. True actually means "not
149
 * known, need to check the shared state".
150 151 152
 */
static bool LocalRecoveryInProgress = true;

153 154 155 156 157 158
/*
 * Local state for XLogInsertAllowed():
 *		1: unconditionally allowed to insert XLOG
 *		0: unconditionally not allowed to insert XLOG
 *		-1: must check RecoveryInProgress(); disallow until it is false
 * Most processes start with -1 and transition to 1 after seeing that recovery
B
Bruce Momjian 已提交
159
 * is not in progress.	But we can also force the value for special cases.
160 161 162 163 164 165 166 167
 * The coding in XLogInsertAllowed() depends on the first two of these states
 * being numerically the same as bool true and false.
 */
static int	LocalXLogInsertAllowed = -1;

/* Are we recovering using offline XLOG archives? */
static bool InArchiveRecovery = false;

168
/* Was the last xlog file restored from archive, or local? */
B
Bruce Momjian 已提交
169
static bool restoredFromArchive = false;
170

171
/* options taken from recovery.conf for archive recovery */
172
static char *recoveryRestoreCommand = NULL;
173
static char *recoveryEndCommand = NULL;
174
static char *restartPointCommand = NULL;
175
static RecoveryTargetType recoveryTarget = RECOVERY_TARGET_UNSET;
176
static bool recoveryTargetInclusive = true;
B
Bruce Momjian 已提交
177
static TransactionId recoveryTargetXid;
178
static TimestampTz recoveryTargetTime;
179
static TimestampTz recoveryLastXTime = 0;
180

181 182 183
/* options taken from recovery.conf for XLOG streaming */
static bool StandbyMode = false;
static char *PrimaryConnInfo = NULL;
B
Bruce Momjian 已提交
184
char	   *TriggerFile = NULL;
185

186
/* if recoveryStopsHere returns true, it saves actual stop xid/time here */
B
Bruce Momjian 已提交
187
static TransactionId recoveryStopXid;
188
static TimestampTz recoveryStopTime;
B
Bruce Momjian 已提交
189
static bool recoveryStopAfter;
190 191 192 193 194 195 196 197 198 199 200 201 202

/*
 * During normal operation, the only timeline we care about is ThisTimeLineID.
 * During recovery, however, things are more complicated.  To simplify life
 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
 * scan through the WAL history (that is, it is the line that was active when
 * the currently-scanned WAL record was generated).  We also need these
 * timeline values:
 *
 * recoveryTargetTLI: the desired timeline that we want to end in.
 *
 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
 * its known parents, newest first (so recoveryTargetTLI is always the
B
Bruce Momjian 已提交
203
 * first list member).	Only these TLIs are expected to be seen in the WAL
204 205 206 207 208 209 210 211 212
 * segments we read, and indeed only these TLIs will be considered as
 * candidate WAL files to open at all.
 *
 * curFileTLI: the TLI appearing in the name of the current input WAL file.
 * (This is not necessarily the same as ThisTimeLineID, because we could
 * be scanning data that was copied from an ancestor timeline when the current
 * file was created.)  During a sequential scan we do not allow this value
 * to decrease.
 */
B
Bruce Momjian 已提交
213 214 215
static TimeLineID recoveryTargetTLI;
static List *expectedTLIs;
static TimeLineID curFileTLI;
216

T
Tom Lane 已提交
217 218
/*
 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
219 220 221 222
 * current backend.  It is updated for all inserts.  XactLastRecEnd points to
 * end+1 of the last record, and is reset when we end a top-level transaction,
 * or start a new one; so it can be used to tell if the current transaction has
 * created any XLOG records.
T
Tom Lane 已提交
223 224
 */
static XLogRecPtr ProcLastRecPtr = {0, 0};
225

226
XLogRecPtr	XactLastRecEnd = {0, 0};
227

T
Tom Lane 已提交
228 229 230
/*
 * RedoRecPtr is this backend's local copy of the REDO record pointer
 * (which is almost but not quite the same as a pointer to the most recent
B
Bruce Momjian 已提交
231
 * CHECKPOINT record).	We update this from the shared-memory copy,
T
Tom Lane 已提交
232
 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
B
Bruce Momjian 已提交
233
 * hold the Insert lock).  See XLogInsert for details.	We are also allowed
234
 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
235 236
 * see GetRedoRecPtr.  A freshly spawned backend obtains the value during
 * InitXLOGAccess.
T
Tom Lane 已提交
237
 */
238
static XLogRecPtr RedoRecPtr;
239

240 241 242 243 244 245 246 247 248 249 250 251
/*
 * RedoStartLSN points to the checkpoint's REDO location which is specified
 * in a backup label file, backup history file or control file. In standby
 * mode, XLOG streaming usually starts from the position where an invalid
 * record was found. But if we fail to read even the initial checkpoint
 * record, we use the REDO location instead of the checkpoint location as
 * the start position of XLOG streaming. Otherwise we would have to jump
 * backwards to the REDO location after reading the checkpoint record,
 * because the REDO record can precede the checkpoint record.
 */
static XLogRecPtr RedoStartLSN = {0, 0};

T
Tom Lane 已提交
252 253 254 255 256 257 258 259 260
/*----------
 * Shared-memory data structures for XLOG control
 *
 * LogwrtRqst indicates a byte position that we need to write and/or fsync
 * the log up to (all records before that point must be written or fsynced).
 * LogwrtResult indicates the byte positions we have already written/fsynced.
 * These structs are identical but are declared separately to indicate their
 * slightly different functions.
 *
261
 * We do a lot of pushups to minimize the amount of access to lockable
T
Tom Lane 已提交
262 263 264
 * shared memory values.  There are actually three shared-memory copies of
 * LogwrtResult, plus one unshared copy in each backend.  Here's how it works:
 *		XLogCtl->LogwrtResult is protected by info_lck
265 266 267 268
 *		XLogCtl->Write.LogwrtResult is protected by WALWriteLock
 *		XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
 * One must hold the associated lock to read or write any of these, but
 * of course no lock is needed to read/write the unshared LogwrtResult.
T
Tom Lane 已提交
269 270 271
 *
 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
 * right", since both are updated by a write or flush operation before
272 273
 * it releases WALWriteLock.  The point of keeping XLogCtl->Write.LogwrtResult
 * is that it can be examined/modified by code that already holds WALWriteLock
T
Tom Lane 已提交
274 275 276
 * without needing to grab info_lck as well.
 *
 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
B
Bruce Momjian 已提交
277
 * but is updated when convenient.	Again, it exists for the convenience of
278
 * code that is already holding WALInsertLock but not the other locks.
T
Tom Lane 已提交
279 280 281 282 283 284 285 286 287 288
 *
 * The unshared LogwrtResult may lag behind any or all of these, and again
 * is updated when convenient.
 *
 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
 * (protected by info_lck), but we don't need to cache any copies of it.
 *
 * Note that this all works because the request and result positions can only
 * advance forward, never back up, and so we can easily determine which of two
 * values is "more up to date".
289 290 291 292 293 294 295 296 297 298 299 300 301
 *
 * info_lck is only held long enough to read/update the protected variables,
 * so it's a plain spinlock.  The other locks are held longer (potentially
 * over I/O operations), so we use LWLocks for them.  These locks are:
 *
 * WALInsertLock: must be held to insert a record into the WAL buffers.
 *
 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
 * XLogFlush).
 *
 * ControlFileLock: must be held to read/update control file or create
 * new log file.
 *
302
 * CheckpointLock: must be held to do a checkpoint or restartpoint (ensures
303 304
 * only one checkpointer at a time; currently, with all checkpoints done by
 * the bgwriter, this is just pro forma).
305
 *
T
Tom Lane 已提交
306 307
 *----------
 */
308

T
Tom Lane 已提交
309
typedef struct XLogwrtRqst
310
{
T
Tom Lane 已提交
311 312
	XLogRecPtr	Write;			/* last byte + 1 to write out */
	XLogRecPtr	Flush;			/* last byte + 1 to flush */
313
} XLogwrtRqst;
314

315 316 317 318 319 320
typedef struct XLogwrtResult
{
	XLogRecPtr	Write;			/* last byte + 1 written out */
	XLogRecPtr	Flush;			/* last byte + 1 flushed */
} XLogwrtResult;

T
Tom Lane 已提交
321 322 323
/*
 * Shared state data for XLogInsert.
 */
324 325
typedef struct XLogCtlInsert
{
B
Bruce Momjian 已提交
326 327
	XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
	XLogRecPtr	PrevRecord;		/* start of previously-inserted record */
328
	int			curridx;		/* current block index in cache */
B
Bruce Momjian 已提交
329 330 331
	XLogPageHeader currpage;	/* points to header of block in cache */
	char	   *currpos;		/* current insertion point in cache */
	XLogRecPtr	RedoRecPtr;		/* current redo point for insertions */
332
	bool		forcePageWrites;	/* forcing full-page writes for PITR? */
333 334
} XLogCtlInsert;

T
Tom Lane 已提交
335 336 337
/*
 * Shared state data for XLogWrite/XLogFlush.
 */
338 339
typedef struct XLogCtlWrite
{
B
Bruce Momjian 已提交
340 341
	XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
	int			curridx;		/* cache index of next block to write */
342
	pg_time_t	lastSegSwitchTime;		/* time of last xlog segment switch */
343 344
} XLogCtlWrite;

T
Tom Lane 已提交
345 346 347
/*
 * Total shared-memory state for XLOG.
 */
348 349
typedef struct XLogCtlData
{
350
	/* Protected by WALInsertLock: */
B
Bruce Momjian 已提交
351
	XLogCtlInsert Insert;
352

T
Tom Lane 已提交
353
	/* Protected by info_lck: */
B
Bruce Momjian 已提交
354 355
	XLogwrtRqst LogwrtRqst;
	XLogwrtResult LogwrtResult;
356 357
	uint32		ckptXidEpoch;	/* nextXID & epoch of latest checkpoint */
	TransactionId ckptXid;
B
Bruce Momjian 已提交
358
	XLogRecPtr	asyncCommitLSN; /* LSN of newest async commit */
359

360
	/* Protected by WALWriteLock: */
B
Bruce Momjian 已提交
361 362
	XLogCtlWrite Write;

T
Tom Lane 已提交
363
	/*
B
Bruce Momjian 已提交
364 365 366
	 * These values do not change after startup, although the pointed-to pages
	 * and xlblocks values certainly do.  Permission to read/write the pages
	 * and xlblocks values depends on WALInsertLock and WALWriteLock.
T
Tom Lane 已提交
367
	 */
B
Bruce Momjian 已提交
368
	char	   *pages;			/* buffers for unwritten XLOG pages */
369
	XLogRecPtr *xlblocks;		/* 1st byte ptr-s + XLOG_BLCKSZ */
370
	int			XLogCacheBlck;	/* highest allocated xlog buffer index */
371
	TimeLineID	ThisTimeLineID;
372
	TimeLineID	RecoveryTargetTLI;
373 374 375 376 377
	/*
	 * restartPointCommand is read from recovery.conf but needs to be in
	 * shared memory so that the bgwriter process can access it.
	 */
	char		restartPointCommand[MAXPGPATH];
T
Tom Lane 已提交
378

379 380
	/*
	 * SharedRecoveryInProgress indicates if we're still in crash or archive
381
	 * recovery.  Protected by info_lck.
382 383 384 385
	 */
	bool		SharedRecoveryInProgress;

	/*
386 387
	 * During recovery, we keep a copy of the latest checkpoint record here.
	 * Used by the background writer when it wants to create a restartpoint.
388 389 390 391 392 393 394 395
	 *
	 * Protected by info_lck.
	 */
	XLogRecPtr	lastCheckPointRecPtr;
	CheckPoint	lastCheckPoint;

	/* end+1 of the last record replayed (or being replayed) */
	XLogRecPtr	replayEndRecPtr;
396
	/* timestamp of last record replayed (or being replayed) */
B
Bruce Momjian 已提交
397
	TimestampTz recoveryLastXTime;
398 399
	/* end+1 of the last record replayed */
	XLogRecPtr	recoveryLastRecPtr;
400

401
	slock_t		info_lck;		/* locks shared variables shown above */
402 403
} XLogCtlData;

404
static XLogCtlData *XLogCtl = NULL;
405

406
/*
T
Tom Lane 已提交
407
 * We maintain an image of pg_control in shared memory.
408
 */
409
static ControlFileData *ControlFile = NULL;
410

T
Tom Lane 已提交
411 412 413 414 415
/*
 * Macros for managing XLogInsert state.  In most cases, the calling routine
 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
 * so these are passed as parameters instead of being fetched via XLogCtl.
 */
416

T
Tom Lane 已提交
417 418
/* Free space remaining in the current xlog page buffer */
#define INSERT_FREESPACE(Insert)  \
419
	(XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
T
Tom Lane 已提交
420 421 422 423 424 425

/* Construct XLogRecPtr value for current insertion point */
#define INSERT_RECPTR(recptr,Insert,curridx)  \
	( \
	  (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
	  (recptr).xrecoff = \
B
Bruce Momjian 已提交
426
		XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
T
Tom Lane 已提交
427 428 429 430 431 432 433
	)

#define PrevBufIdx(idx)		\
		(((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))

#define NextBufIdx(idx)		\
		(((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
434

T
Tom Lane 已提交
435 436 437 438
/*
 * Private, possibly out-of-date copy of shared LogwrtResult.
 * See discussion above.
 */
439
static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
440

T
Tom Lane 已提交
441 442 443 444 445 446 447 448 449 450
/*
 * openLogFile is -1 or a kernel FD for an open log file segment.
 * When it's open, openLogOff is the current seek offset in the file.
 * openLogId/openLogSeg identify the segment.  These variables are only
 * used to write the XLOG, and so will normally refer to the active segment.
 */
static int	openLogFile = -1;
static uint32 openLogId = 0;
static uint32 openLogSeg = 0;
static uint32 openLogOff = 0;
451

452 453 454 455 456 457 458 459
/*
 * Codes indicating where we got a WAL file from during recovery, or where
 * to attempt to get one.
 */
#define XLOG_FROM_ARCHIVE		(1<<0)	/* Restored using restore_command */
#define XLOG_FROM_PG_XLOG		(1<<1)	/* Existing file in pg_xlog */
#define XLOG_FROM_STREAM		(1<<2)	/* Streamed from master */

T
Tom Lane 已提交
460 461 462 463
/*
 * These variables are used similarly to the ones above, but for reading
 * the XLOG.  Note, however, that readOff generally represents the offset
 * of the page just read, not the seek position of the FD itself, which
464
 * will be just past that page. readLen indicates how much of the current
465 466
 * page has been read into readBuf, and readSource indicates where we got
 * the currently open file from.
T
Tom Lane 已提交
467
 */
468 469 470 471
static int	readFile = -1;
static uint32 readId = 0;
static uint32 readSeg = 0;
static uint32 readOff = 0;
472
static uint32 readLen = 0;
473
static int readSource = 0;		/* XLOG_FROM_* code */
B
Bruce Momjian 已提交
474

475 476 477 478 479
/*
 * Keeps track of which sources we've tried to read the current WAL
 * record from and failed.
 */
static int failedSources = 0;
B
Bruce Momjian 已提交
480

481
/* Buffer for currently read page (XLOG_BLCKSZ bytes) */
T
Tom Lane 已提交
482
static char *readBuf = NULL;
B
Bruce Momjian 已提交
483

484 485 486 487
/* Buffer for current ReadRecord result (expandable) */
static char *readRecordBuf = NULL;
static uint32 readRecordBufSize = 0;

T
Tom Lane 已提交
488
/* State information for XLOG reading */
B
Bruce Momjian 已提交
489 490
static XLogRecPtr ReadRecPtr;	/* start of last record read */
static XLogRecPtr EndRecPtr;	/* end+1 of last record read */
491
static TimeLineID lastPageTLI = 0;
492

493 494 495
static XLogRecPtr minRecoveryPoint;		/* local copy of
										 * ControlFile->minRecoveryPoint */
static bool updateMinRecoveryPoint = true;
496

V
WAL  
Vadim B. Mikheev 已提交
497 498
static bool InRedo = false;

499
/*
500
 * Flags set by interrupt handlers for later service in the redo loop.
501
 */
502
static volatile sig_atomic_t got_SIGHUP = false;
503
static volatile sig_atomic_t shutdown_requested = false;
504

505 506
/*
 * Flag set when executing a restore command, to tell SIGTERM signal handler
507
 * that it's safe to just proc_exit.
508 509 510
 */
static volatile sig_atomic_t in_restore_command = false;

511

512 513
static void XLogArchiveNotify(const char *xlog);
static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
514 515
static bool XLogArchiveCheckDone(const char *xlog);
static bool XLogArchiveIsBusy(const char *xlog);
516 517
static void XLogArchiveCleanup(const char *xlog);
static void readRecoveryCommandFile(void);
518
static void exitArchiveRecovery(TimeLineID endTLI,
B
Bruce Momjian 已提交
519
					uint32 endLogId, uint32 endLogSeg);
520
static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
521
static void CheckRequiredParameterValues(CheckPoint checkPoint);
522
static void LocalSetXLogInsertAllowed(void);
523
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
T
Tom Lane 已提交
524

525
static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
B
Bruce Momjian 已提交
526
				XLogRecPtr *lsn, BkpBlock *bkpb);
527 528
static bool AdvanceXLInsertBuffer(bool new_segment);
static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
529 530
static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
531
					   bool use_lock);
B
Bruce Momjian 已提交
532
static int XLogFileRead(uint32 log, uint32 seg, int emode, TimeLineID tli,
533
			 int source, bool notexistOk);
B
Bruce Momjian 已提交
534
static int XLogFileReadAnyTLI(uint32 log, uint32 seg, int emode,
535
				   int sources);
536 537
static bool XLogPageRead(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt,
			 bool randAccess);
538
static int emode_for_corrupt_record(int emode);
B
Bruce Momjian 已提交
539
static void XLogFileClose(void);
540
static bool RestoreArchivedFile(char *path, const char *xlogfname,
B
Bruce Momjian 已提交
541
					const char *recovername, off_t expectedSize);
542 543
static void ExecuteRecoveryCommand(char *command, char *commandName,
					   bool failOnerror);
544 545
static void PreallocXlogFiles(XLogRecPtr endptr);
static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
546
static void ValidateXLOGDirectoryStructure(void);
547
static void CleanupBackupHistory(void);
548
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
549
static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt);
550
static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
551
static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
552 553 554 555
static List *readTimeLineHistory(TimeLineID targetTLI);
static bool existsTimeLineHistory(TimeLineID probeTLI);
static TimeLineID findNewestTimeLine(TimeLineID startTLI);
static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
B
Bruce Momjian 已提交
556 557
					 TimeLineID endTLI,
					 uint32 endLogId, uint32 endLogSeg);
T
Tom Lane 已提交
558 559
static void WriteControlFile(void);
static void ReadControlFile(void);
560
static char *str_time(pg_time_t tnow);
561
static bool CheckForStandbyTrigger(void);
562

563
#ifdef WAL_DEBUG
564
static void xlog_outrec(StringInfo buf, XLogRecord *record);
565
#endif
566
static void pg_start_backup_callback(int code, Datum arg);
567
static bool read_backup_label(XLogRecPtr *checkPointLoc);
568
static void rm_redo_error_callback(void *arg);
569
static int	get_sync_bit(int method);
T
Tom Lane 已提交
570 571 572 573 574


/*
 * Insert an XLOG record having the specified RMID and info bytes,
 * with the body of the record being the data chunk(s) described by
575
 * the rdata chain (see xlog.h for notes about rdata).
T
Tom Lane 已提交
576 577 578 579 580 581 582 583 584 585 586
 *
 * Returns XLOG pointer to end of record (beginning of next record).
 * This can be used as LSN for data pages affected by the logged action.
 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
 * before the data page can be written out.  This implements the basic
 * WAL rule "write the log before the data".)
 *
 * NB: this routine feels free to scribble on the XLogRecData structs,
 * though not on the data they reference.  This is OK since the XLogRecData
 * structs are always just temporaries in the calling code.
 */
587
XLogRecPtr
588
XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
589
{
B
Bruce Momjian 已提交
590 591
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecord *record;
T
Tom Lane 已提交
592
	XLogContRecord *contrecord;
B
Bruce Momjian 已提交
593 594 595
	XLogRecPtr	RecPtr;
	XLogRecPtr	WriteRqst;
	uint32		freespace;
596
	int			curridx;
B
Bruce Momjian 已提交
597 598 599 600 601
	XLogRecData *rdt;
	Buffer		dtbuf[XLR_MAX_BKP_BLOCKS];
	bool		dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
	BkpBlock	dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
	XLogRecPtr	dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
602 603 604 605
	XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
	XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
	XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
	pg_crc32	rdata_crc;
B
Bruce Momjian 已提交
606 607 608 609
	uint32		len,
				write_len;
	unsigned	i;
	bool		updrqst;
610
	bool		doPageWrites;
611
	bool		isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
V
Vadim B. Mikheev 已提交
612

613
	/* cross-check on whether we should be here or not */
614 615
	if (!XLogInsertAllowed())
		elog(ERROR, "cannot make new WAL entries during recovery");
616

617
	/* info's high bits are reserved for use by me */
V
Vadim B. Mikheev 已提交
618
	if (info & XLR_INFO_MASK)
619
		elog(PANIC, "invalid xlog info mask %02X", info);
V
Vadim B. Mikheev 已提交
620

621 622
	TRACE_POSTGRESQL_XLOG_INSERT(rmid, info);

T
Tom Lane 已提交
623
	/*
B
Bruce Momjian 已提交
624 625
	 * In bootstrap mode, we don't actually log anything but XLOG resources;
	 * return a phony record pointer.
T
Tom Lane 已提交
626
	 */
V
Vadim B. Mikheev 已提交
627
	if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
V
WAL  
Vadim B. Mikheev 已提交
628 629
	{
		RecPtr.xlogid = 0;
B
Bruce Momjian 已提交
630
		RecPtr.xrecoff = SizeOfXLogLongPHD;		/* start of 1st chkpt record */
631
		return RecPtr;
V
WAL  
Vadim B. Mikheev 已提交
632 633
	}

T
Tom Lane 已提交
634
	/*
635
	 * Here we scan the rdata chain, determine which buffers must be backed
T
Tom Lane 已提交
636
	 * up, and compute the CRC values for the data.  Note that the record
B
Bruce Momjian 已提交
637 638 639 640
	 * header isn't added into the CRC initially since we don't know the final
	 * length or info bits quite yet.  Thus, the CRC will represent the CRC of
	 * the whole record in the order "rdata, then backup blocks, then record
	 * header".
T
Tom Lane 已提交
641
	 *
642 643 644 645 646
	 * We may have to loop back to here if a race condition is detected below.
	 * We could prevent the race by doing all this work while holding the
	 * insert lock, but it seems better to avoid doing CRC calculations while
	 * holding the lock.  This means we have to be careful about modifying the
	 * rdata chain until we know we aren't going to loop back again.  The only
B
Bruce Momjian 已提交
647 648 649 650 651
	 * change we allow ourselves to make earlier is to set rdt->data = NULL in
	 * chain items we have decided we will have to back up the whole buffer
	 * for.  This is OK because we will certainly decide the same thing again
	 * for those items if we do it over; doing it here saves an extra pass
	 * over the chain later.
T
Tom Lane 已提交
652
	 */
653
begin:;
T
Tom Lane 已提交
654 655 656 657 658 659
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
	{
		dtbuf[i] = InvalidBuffer;
		dtbuf_bkp[i] = false;
	}

660 661 662 663 664 665 666 667
	/*
	 * Decide if we need to do full-page writes in this XLOG record: true if
	 * full_page_writes is on or we have a PITR request for it.  Since we
	 * don't yet have the insert lock, forcePageWrites could change under us,
	 * but we'll recheck it once we have the lock.
	 */
	doPageWrites = fullPageWrites || Insert->forcePageWrites;

668
	INIT_CRC32(rdata_crc);
T
Tom Lane 已提交
669
	len = 0;
B
Bruce Momjian 已提交
670
	for (rdt = rdata;;)
671 672 673
	{
		if (rdt->buffer == InvalidBuffer)
		{
T
Tom Lane 已提交
674
			/* Simple data, just include it */
675
			len += rdt->len;
676
			COMP_CRC32(rdata_crc, rdt->data, rdt->len);
677
		}
T
Tom Lane 已提交
678
		else
679
		{
T
Tom Lane 已提交
680 681
			/* Find info for buffer */
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
682
			{
T
Tom Lane 已提交
683
				if (rdt->buffer == dtbuf[i])
684
				{
685
					/* Buffer already referenced by earlier chain item */
T
Tom Lane 已提交
686 687 688 689 690
					if (dtbuf_bkp[i])
						rdt->data = NULL;
					else if (rdt->data)
					{
						len += rdt->len;
691
						COMP_CRC32(rdata_crc, rdt->data, rdt->len);
T
Tom Lane 已提交
692 693
					}
					break;
694
				}
T
Tom Lane 已提交
695
				if (dtbuf[i] == InvalidBuffer)
696
				{
T
Tom Lane 已提交
697 698
					/* OK, put it in this slot */
					dtbuf[i] = rdt->buffer;
699 700
					if (XLogCheckBuffer(rdt, doPageWrites,
										&(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
T
Tom Lane 已提交
701 702 703 704 705 706 707
					{
						dtbuf_bkp[i] = true;
						rdt->data = NULL;
					}
					else if (rdt->data)
					{
						len += rdt->len;
708
						COMP_CRC32(rdata_crc, rdt->data, rdt->len);
T
Tom Lane 已提交
709 710
					}
					break;
711 712
				}
			}
T
Tom Lane 已提交
713
			if (i >= XLR_MAX_BKP_BLOCKS)
714
				elog(PANIC, "can backup at most %d blocks per xlog record",
T
Tom Lane 已提交
715
					 XLR_MAX_BKP_BLOCKS);
716
		}
717
		/* Break out of loop when rdt points to last chain item */
718 719 720 721 722
		if (rdt->next == NULL)
			break;
		rdt = rdt->next;
	}

723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
	/*
	 * Now add the backup block headers and data into the CRC
	 */
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
	{
		if (dtbuf_bkp[i])
		{
			BkpBlock   *bkpb = &(dtbuf_xlg[i]);
			char	   *page;

			COMP_CRC32(rdata_crc,
					   (char *) bkpb,
					   sizeof(BkpBlock));
			page = (char *) BufferGetBlock(dtbuf[i]);
			if (bkpb->hole_length == 0)
			{
				COMP_CRC32(rdata_crc,
						   page,
						   BLCKSZ);
			}
			else
			{
				/* must skip the hole */
				COMP_CRC32(rdata_crc,
						   page,
						   bkpb->hole_offset);
				COMP_CRC32(rdata_crc,
						   page + (bkpb->hole_offset + bkpb->hole_length),
						   BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
			}
		}
	}

T
Tom Lane 已提交
756
	/*
757 758
	 * NOTE: We disallow len == 0 because it provides a useful bit of extra
	 * error checking in ReadRecord.  This means that all callers of
B
Bruce Momjian 已提交
759 760 761
	 * XLogInsert must supply at least some not-in-a-buffer data.  However, we
	 * make an exception for XLOG SWITCH records because we don't want them to
	 * ever cross a segment boundary.
T
Tom Lane 已提交
762
	 */
763
	if (len == 0 && !isLogSwitch)
764
		elog(PANIC, "invalid xlog record length %u", len);
765

766
	START_CRIT_SECTION();
767

768 769 770
	/* Now wait to get insert lock */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);

T
Tom Lane 已提交
771
	/*
B
Bruce Momjian 已提交
772 773 774
	 * Check to see if my RedoRecPtr is out of date.  If so, may have to go
	 * back and recompute everything.  This can only happen just after a
	 * checkpoint, so it's better to be slow in this case and fast otherwise.
775 776
	 *
	 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
B
Bruce Momjian 已提交
777 778
	 * affect the contents of the XLOG record, so we'll update our local copy
	 * but not force a recomputation.
T
Tom Lane 已提交
779 780
	 */
	if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
781
	{
T
Tom Lane 已提交
782 783 784
		Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
		RedoRecPtr = Insert->RedoRecPtr;

785
		if (doPageWrites)
786
		{
787
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
T
Tom Lane 已提交
788
			{
789 790 791 792 793 794 795 796 797 798 799 800 801
				if (dtbuf[i] == InvalidBuffer)
					continue;
				if (dtbuf_bkp[i] == false &&
					XLByteLE(dtbuf_lsn[i], RedoRecPtr))
				{
					/*
					 * Oops, this buffer now needs to be backed up, but we
					 * didn't think so above.  Start over.
					 */
					LWLockRelease(WALInsertLock);
					END_CRIT_SECTION();
					goto begin;
				}
T
Tom Lane 已提交
802
			}
803 804 805
		}
	}

806
	/*
B
Bruce Momjian 已提交
807 808 809 810
	 * Also check to see if forcePageWrites was just turned on; if we weren't
	 * already doing full-page writes then go back and recompute. (If it was
	 * just turned off, we could recompute the record without full pages, but
	 * we choose not to bother.)
811 812 813 814 815 816 817 818 819
	 */
	if (Insert->forcePageWrites && !doPageWrites)
	{
		/* Oops, must redo it with full-page data */
		LWLockRelease(WALInsertLock);
		END_CRIT_SECTION();
		goto begin;
	}

T
Tom Lane 已提交
820
	/*
B
Bruce Momjian 已提交
821 822 823 824
	 * Make additional rdata chain entries for the backup blocks, so that we
	 * don't need to special-case them in the write loop.  Note that we have
	 * now irrevocably changed the input rdata chain.  At the exit of this
	 * loop, write_len includes the backup block data.
T
Tom Lane 已提交
825
	 *
826 827 828
	 * Also set the appropriate info bits to show which buffers were backed
	 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
	 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
T
Tom Lane 已提交
829 830 831
	 */
	write_len = len;
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
832
	{
833 834 835
		BkpBlock   *bkpb;
		char	   *page;

836
		if (!dtbuf_bkp[i])
837 838
			continue;

T
Tom Lane 已提交
839
		info |= XLR_SET_BKP_BLOCK(i);
840

841 842 843 844 845
		bkpb = &(dtbuf_xlg[i]);
		page = (char *) BufferGetBlock(dtbuf[i]);

		rdt->next = &(dtbuf_rdt1[i]);
		rdt = rdt->next;
846

847 848
		rdt->data = (char *) bkpb;
		rdt->len = sizeof(BkpBlock);
T
Tom Lane 已提交
849
		write_len += sizeof(BkpBlock);
850

851 852
		rdt->next = &(dtbuf_rdt2[i]);
		rdt = rdt->next;
853

854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
		if (bkpb->hole_length == 0)
		{
			rdt->data = page;
			rdt->len = BLCKSZ;
			write_len += BLCKSZ;
			rdt->next = NULL;
		}
		else
		{
			/* must skip the hole */
			rdt->data = page;
			rdt->len = bkpb->hole_offset;
			write_len += bkpb->hole_offset;

			rdt->next = &(dtbuf_rdt3[i]);
			rdt = rdt->next;

			rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
			rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
			write_len += rdt->len;
			rdt->next = NULL;
		}
876 877
	}

878 879 880 881 882 883 884
	/*
	 * If we backed up any full blocks and online backup is not in progress,
	 * mark the backup blocks as removable.  This allows the WAL archiver to
	 * know whether it is safe to compress archived WAL data by transforming
	 * full-block records into the non-full-block format.
	 *
	 * Note: we could just set the flag whenever !forcePageWrites, but
B
Bruce Momjian 已提交
885 886
	 * defining it like this leaves the info bit free for some potential other
	 * use in records without any backup blocks.
887 888 889 890
	 */
	if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
		info |= XLR_BKP_REMOVABLE;

891
	/*
892
	 * If there isn't enough space on the current XLOG page for a record
B
Bruce Momjian 已提交
893
	 * header, advance to the next page (leaving the unused space as zeroes).
894
	 */
T
Tom Lane 已提交
895 896
	updrqst = false;
	freespace = INSERT_FREESPACE(Insert);
897 898
	if (freespace < SizeOfXLogRecord)
	{
899
		updrqst = AdvanceXLInsertBuffer(false);
900 901 902
		freespace = INSERT_FREESPACE(Insert);
	}

903
	/* Compute record's XLOG location */
T
Tom Lane 已提交
904
	curridx = Insert->curridx;
905 906 907
	INSERT_RECPTR(RecPtr, Insert, curridx);

	/*
B
Bruce Momjian 已提交
908 909 910 911 912
	 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
	 * segment, we need not insert it (and don't want to because we'd like
	 * consecutive switch requests to be no-ops).  Instead, make sure
	 * everything is written and flushed through the end of the prior segment,
	 * and return the prior segment's end address.
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
	 */
	if (isLogSwitch &&
		(RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
	{
		/* We can release insert lock immediately */
		LWLockRelease(WALInsertLock);

		RecPtr.xrecoff -= SizeOfXLogLongPHD;
		if (RecPtr.xrecoff == 0)
		{
			/* crossing a logid boundary */
			RecPtr.xlogid -= 1;
			RecPtr.xrecoff = XLogFileSize;
		}

		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
		LogwrtResult = XLogCtl->Write.LogwrtResult;
		if (!XLByteLE(RecPtr, LogwrtResult.Flush))
		{
			XLogwrtRqst FlushRqst;

			FlushRqst.Write = RecPtr;
			FlushRqst.Flush = RecPtr;
			XLogWrite(FlushRqst, false, false);
		}
		LWLockRelease(WALWriteLock);

		END_CRIT_SECTION();

		return RecPtr;
	}
T
Tom Lane 已提交
944

945 946
	/* Insert record header */

947
	record = (XLogRecord *) Insert->currpos;
948
	record->xl_prev = Insert->PrevRecord;
949
	record->xl_xid = GetCurrentTransactionIdIfAny();
950
	record->xl_tot_len = SizeOfXLogRecord + write_len;
T
Tom Lane 已提交
951
	record->xl_len = len;		/* doesn't include backup blocks */
952
	record->xl_info = info;
953
	record->xl_rmid = rmid;
954

955 956 957 958
	/* Now we can finish computing the record's CRC */
	COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
			   SizeOfXLogRecord - sizeof(pg_crc32));
	FIN_CRC32(rdata_crc);
959 960
	record->xl_crc = rdata_crc;

961
#ifdef WAL_DEBUG
V
WAL  
Vadim B. Mikheev 已提交
962 963
	if (XLOG_DEBUG)
	{
B
Bruce Momjian 已提交
964
		StringInfoData buf;
V
WAL  
Vadim B. Mikheev 已提交
965

966
		initStringInfo(&buf);
967 968
		appendStringInfo(&buf, "INSERT @ %X/%X: ",
						 RecPtr.xlogid, RecPtr.xrecoff);
969
		xlog_outrec(&buf, record);
970
		if (rdata->data != NULL)
V
WAL  
Vadim B. Mikheev 已提交
971
		{
972 973
			appendStringInfo(&buf, " - ");
			RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
V
WAL  
Vadim B. Mikheev 已提交
974
		}
975 976
		elog(LOG, "%s", buf.data);
		pfree(buf.data);
V
WAL  
Vadim B. Mikheev 已提交
977
	}
978
#endif
V
WAL  
Vadim B. Mikheev 已提交
979

T
Tom Lane 已提交
980 981 982 983
	/* Record begin of record in appropriate places */
	ProcLastRecPtr = RecPtr;
	Insert->PrevRecord = RecPtr;

984
	Insert->currpos += SizeOfXLogRecord;
T
Tom Lane 已提交
985
	freespace -= SizeOfXLogRecord;
986

T
Tom Lane 已提交
987 988 989 990
	/*
	 * Append the data, including backup blocks if any
	 */
	while (write_len)
991
	{
992 993 994 995
		while (rdata->data == NULL)
			rdata = rdata->next;

		if (freespace > 0)
996
		{
997 998 999 1000 1001
			if (rdata->len > freespace)
			{
				memcpy(Insert->currpos, rdata->data, freespace);
				rdata->data += freespace;
				rdata->len -= freespace;
T
Tom Lane 已提交
1002
				write_len -= freespace;
1003 1004 1005 1006 1007
			}
			else
			{
				memcpy(Insert->currpos, rdata->data, rdata->len);
				freespace -= rdata->len;
T
Tom Lane 已提交
1008
				write_len -= rdata->len;
1009 1010 1011 1012
				Insert->currpos += rdata->len;
				rdata = rdata->next;
				continue;
			}
1013 1014
		}

1015
		/* Use next buffer */
1016
		updrqst = AdvanceXLInsertBuffer(false);
T
Tom Lane 已提交
1017 1018 1019 1020 1021 1022
		curridx = Insert->curridx;
		/* Insert cont-record header */
		Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
		contrecord = (XLogContRecord *) Insert->currpos;
		contrecord->xl_rem_len = write_len;
		Insert->currpos += SizeOfXLogContRecord;
1023
		freespace = INSERT_FREESPACE(Insert);
1024
	}
1025

T
Tom Lane 已提交
1026 1027
	/* Ensure next record will be properly aligned */
	Insert->currpos = (char *) Insert->currpage +
B
Bruce Momjian 已提交
1028
		MAXALIGN(Insert->currpos - (char *) Insert->currpage);
T
Tom Lane 已提交
1029
	freespace = INSERT_FREESPACE(Insert);
1030

V
Vadim B. Mikheev 已提交
1031
	/*
B
Bruce Momjian 已提交
1032 1033
	 * The recptr I return is the beginning of the *next* record. This will be
	 * stored as LSN for changed data pages...
V
Vadim B. Mikheev 已提交
1034
	 */
T
Tom Lane 已提交
1035
	INSERT_RECPTR(RecPtr, Insert, curridx);
V
Vadim B. Mikheev 已提交
1036

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
	/*
	 * If the record is an XLOG_SWITCH, we must now write and flush all the
	 * existing data, and then forcibly advance to the start of the next
	 * segment.  It's not good to do this I/O while holding the insert lock,
	 * but there seems too much risk of confusion if we try to release the
	 * lock sooner.  Fortunately xlog switch needn't be a high-performance
	 * operation anyway...
	 */
	if (isLogSwitch)
	{
		XLogCtlWrite *Write = &XLogCtl->Write;
		XLogwrtRqst FlushRqst;
		XLogRecPtr	OldSegEnd;

1051 1052
		TRACE_POSTGRESQL_XLOG_SWITCH();

1053 1054 1055
		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);

		/*
B
Bruce Momjian 已提交
1056 1057
		 * Flush through the end of the page containing XLOG_SWITCH, and
		 * perform end-of-segment actions (eg, notifying archiver).
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
		 */
		WriteRqst = XLogCtl->xlblocks[curridx];
		FlushRqst.Write = WriteRqst;
		FlushRqst.Flush = WriteRqst;
		XLogWrite(FlushRqst, false, true);

		/* Set up the next buffer as first page of next segment */
		/* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
		(void) AdvanceXLInsertBuffer(true);

		/* There should be no unwritten data */
		curridx = Insert->curridx;
		Assert(curridx == Write->curridx);

		/* Compute end address of old segment */
		OldSegEnd = XLogCtl->xlblocks[curridx];
		OldSegEnd.xrecoff -= XLOG_BLCKSZ;
		if (OldSegEnd.xrecoff == 0)
		{
			/* crossing a logid boundary */
			OldSegEnd.xlogid -= 1;
			OldSegEnd.xrecoff = XLogFileSize;
		}

		/* Make it look like we've written and synced all of old segment */
		LogwrtResult.Write = OldSegEnd;
		LogwrtResult.Flush = OldSegEnd;

		/*
		 * Update shared-memory status --- this code should match XLogWrite
		 */
		{
			/* use volatile pointer to prevent code rearrangement */
			volatile XLogCtlData *xlogctl = XLogCtl;

			SpinLockAcquire(&xlogctl->info_lck);
			xlogctl->LogwrtResult = LogwrtResult;
			if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
				xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
			if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
				xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
			SpinLockRelease(&xlogctl->info_lck);
		}

		Write->LogwrtResult = LogwrtResult;

		LWLockRelease(WALWriteLock);

		updrqst = false;		/* done already */
	}
1108
	else
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
	{
		/* normal case, ie not xlog switch */

		/* Need to update shared LogwrtRqst if some block was filled up */
		if (freespace < SizeOfXLogRecord)
		{
			/* curridx is filled and available for writing out */
			updrqst = true;
		}
		else
		{
			/* if updrqst already set, write through end of previous buf */
			curridx = PrevBufIdx(curridx);
		}
		WriteRqst = XLogCtl->xlblocks[curridx];
	}
1125

1126
	LWLockRelease(WALInsertLock);
1127 1128 1129

	if (updrqst)
	{
1130 1131 1132
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

1133
		SpinLockAcquire(&xlogctl->info_lck);
T
Tom Lane 已提交
1134
		/* advance global request to include new block(s) */
1135 1136
		if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
			xlogctl->LogwrtRqst.Write = WriteRqst;
T
Tom Lane 已提交
1137
		/* update local result copy while I have the chance */
1138
		LogwrtResult = xlogctl->LogwrtResult;
1139
		SpinLockRelease(&xlogctl->info_lck);
1140 1141
	}

1142
	XactLastRecEnd = RecPtr;
1143

1144
	END_CRIT_SECTION();
1145

1146
	return RecPtr;
1147
}
1148

1149
/*
1150 1151 1152
 * Determine whether the buffer referenced by an XLogRecData item has to
 * be backed up, and if so fill a BkpBlock struct for it.  In any case
 * save the buffer's LSN at *lsn.
1153
 */
1154
static bool
1155
XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1156
				XLogRecPtr *lsn, BkpBlock *bkpb)
1157
{
1158
	Page		page;
1159

1160
	page = BufferGetPage(rdata->buffer);
1161 1162

	/*
B
Bruce Momjian 已提交
1163 1164 1165
	 * XXX We assume page LSN is first data on *every* page that can be passed
	 * to XLogInsert, whether it otherwise has the standard page layout or
	 * not.
1166
	 */
1167
	*lsn = PageGetLSN(page);
1168

1169
	if (doPageWrites &&
1170
		XLByteLE(PageGetLSN(page), RedoRecPtr))
1171
	{
1172 1173 1174
		/*
		 * The page needs to be backed up, so set up *bkpb
		 */
1175
		BufferGetTag(rdata->buffer, &bkpb->node, &bkpb->fork, &bkpb->block);
1176

1177 1178 1179
		if (rdata->buffer_std)
		{
			/* Assume we can omit data between pd_lower and pd_upper */
1180 1181
			uint16		lower = ((PageHeader) page)->pd_lower;
			uint16		upper = ((PageHeader) page)->pd_upper;
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

			if (lower >= SizeOfPageHeaderData &&
				upper > lower &&
				upper <= BLCKSZ)
			{
				bkpb->hole_offset = lower;
				bkpb->hole_length = upper - lower;
			}
			else
			{
				/* No "hole" to compress out */
				bkpb->hole_offset = 0;
				bkpb->hole_length = 0;
			}
		}
		else
		{
			/* Not a standard page header, don't try to eliminate "hole" */
			bkpb->hole_offset = 0;
			bkpb->hole_length = 0;
		}
1203

1204
		return true;			/* buffer requires backup */
1205
	}
1206 1207

	return false;				/* buffer does not need to be backed up */
1208 1209
}

1210 1211 1212 1213 1214 1215
/*
 * XLogArchiveNotify
 *
 * Create an archive notification file
 *
 * The name of the notification file is the message that will be picked up
1216
 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1217
 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1218
 * then when complete, rename it to 0000000100000001000000C6.done
1219 1220 1221 1222 1223
 */
static void
XLogArchiveNotify(const char *xlog)
{
	char		archiveStatusPath[MAXPGPATH];
B
Bruce Momjian 已提交
1224
	FILE	   *fd;
1225 1226 1227 1228

	/* insert an otherwise empty file called <XLOG>.ready */
	StatusFilePath(archiveStatusPath, xlog, ".ready");
	fd = AllocateFile(archiveStatusPath, "w");
B
Bruce Momjian 已提交
1229 1230
	if (fd == NULL)
	{
1231 1232 1233 1234 1235 1236
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not create archive status file \"%s\": %m",
						archiveStatusPath)));
		return;
	}
B
Bruce Momjian 已提交
1237 1238
	if (FreeFile(fd))
	{
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not write archive status file \"%s\": %m",
						archiveStatusPath)));
		return;
	}

	/* Notify archiver that it's got something to do */
	if (IsUnderPostmaster)
		SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
}

/*
 * Convenience routine to notify using log/seg representation of filename
 */
static void
XLogArchiveNotifySeg(uint32 log, uint32 seg)
{
	char		xlog[MAXFNAMELEN];

1259
	XLogFileName(xlog, ThisTimeLineID, log, seg);
1260 1261 1262 1263
	XLogArchiveNotify(xlog);
}

/*
1264
 * XLogArchiveCheckDone
1265
 *
1266 1267 1268 1269
 * This is called when we are ready to delete or recycle an old XLOG segment
 * file or backup history file.  If it is okay to delete it then return true.
 * If it is not time to delete it, make sure a .ready file exists, and return
 * false.
1270 1271
 *
 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1272 1273 1274 1275
 * then return false; else create <XLOG>.ready and return false.
 *
 * The reason we do things this way is so that if the original attempt to
 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1276 1277
 */
static bool
1278
XLogArchiveCheckDone(const char *xlog)
1279 1280 1281 1282
{
	char		archiveStatusPath[MAXPGPATH];
	struct stat stat_buf;

1283 1284 1285 1286 1287
	/* Always deletable if archiving is off */
	if (!XLogArchivingActive())
		return true;

	/* First check for .done --- this means archiver is done with it */
1288 1289 1290 1291 1292 1293 1294
	StatusFilePath(archiveStatusPath, xlog, ".done");
	if (stat(archiveStatusPath, &stat_buf) == 0)
		return true;

	/* check for .ready --- this means archiver is still busy with it */
	StatusFilePath(archiveStatusPath, xlog, ".ready");
	if (stat(archiveStatusPath, &stat_buf) == 0)
B
Bruce Momjian 已提交
1295
		return false;
1296 1297 1298 1299 1300 1301 1302

	/* Race condition --- maybe archiver just finished, so recheck */
	StatusFilePath(archiveStatusPath, xlog, ".done");
	if (stat(archiveStatusPath, &stat_buf) == 0)
		return true;

	/* Retry creation of the .ready file */
1303
	XLogArchiveNotify(xlog);
1304 1305 1306
	return false;
}

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
/*
 * XLogArchiveIsBusy
 *
 * Check to see if an XLOG segment file is still unarchived.
 * This is almost but not quite the inverse of XLogArchiveCheckDone: in
 * the first place we aren't chartered to recreate the .ready file, and
 * in the second place we should consider that if the file is already gone
 * then it's not busy.  (This check is needed to handle the race condition
 * that a checkpoint already deleted the no-longer-needed file.)
 */
static bool
XLogArchiveIsBusy(const char *xlog)
{
	char		archiveStatusPath[MAXPGPATH];
	struct stat stat_buf;

	/* First check for .done --- this means archiver is done with it */
	StatusFilePath(archiveStatusPath, xlog, ".done");
	if (stat(archiveStatusPath, &stat_buf) == 0)
		return false;

	/* check for .ready --- this means archiver is still busy with it */
	StatusFilePath(archiveStatusPath, xlog, ".ready");
	if (stat(archiveStatusPath, &stat_buf) == 0)
		return true;

	/* Race condition --- maybe archiver just finished, so recheck */
	StatusFilePath(archiveStatusPath, xlog, ".done");
	if (stat(archiveStatusPath, &stat_buf) == 0)
		return false;

	/*
1339 1340 1341
	 * Check to see if the WAL file has been removed by checkpoint, which
	 * implies it has already been archived, and explains why we can't see a
	 * status file for it.
1342 1343 1344 1345 1346 1347 1348 1349 1350
	 */
	snprintf(archiveStatusPath, MAXPGPATH, XLOGDIR "/%s", xlog);
	if (stat(archiveStatusPath, &stat_buf) != 0 &&
		errno == ENOENT)
		return false;

	return true;
}

1351 1352 1353
/*
 * XLogArchiveCleanup
 *
1354
 * Cleanup archive notification file(s) for a particular xlog segment
1355 1356 1357 1358
 */
static void
XLogArchiveCleanup(const char *xlog)
{
B
Bruce Momjian 已提交
1359
	char		archiveStatusPath[MAXPGPATH];
1360

1361
	/* Remove the .done file */
1362 1363 1364
	StatusFilePath(archiveStatusPath, xlog, ".done");
	unlink(archiveStatusPath);
	/* should we complain about failure? */
1365 1366 1367 1368 1369

	/* Remove the .ready file if present --- normally it shouldn't be */
	StatusFilePath(archiveStatusPath, xlog, ".ready");
	unlink(archiveStatusPath);
	/* should we complain about failure? */
1370 1371
}

T
Tom Lane 已提交
1372 1373 1374 1375
/*
 * Advance the Insert state to the next buffer page, writing out the next
 * buffer if it still contains unwritten data.
 *
1376 1377 1378 1379
 * If new_segment is TRUE then we set up the next buffer page as the first
 * page of the next xlog segment file, possibly but not usually the next
 * consecutive file page.
 *
T
Tom Lane 已提交
1380
 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1381
 * just-filled page.  If we can do this for free (without an extra lock),
T
Tom Lane 已提交
1382 1383 1384
 * we do so here.  Otherwise the caller must do it.  We return TRUE if the
 * request update still needs to be done, FALSE if we did it internally.
 *
1385
 * Must be called with WALInsertLock held.
T
Tom Lane 已提交
1386 1387
 */
static bool
1388
AdvanceXLInsertBuffer(bool new_segment)
1389
{
T
Tom Lane 已提交
1390 1391
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogCtlWrite *Write = &XLogCtl->Write;
1392
	int			nextidx = NextBufIdx(Insert->curridx);
T
Tom Lane 已提交
1393 1394 1395
	bool		update_needed = true;
	XLogRecPtr	OldPageRqstPtr;
	XLogwrtRqst WriteRqst;
1396 1397
	XLogRecPtr	NewPageEndPtr;
	XLogPageHeader NewPage;
1398

T
Tom Lane 已提交
1399 1400 1401
	/* Use Insert->LogwrtResult copy if it's more fresh */
	if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
		LogwrtResult = Insert->LogwrtResult;
V
WAL  
Vadim B. Mikheev 已提交
1402

T
Tom Lane 已提交
1403
	/*
B
Bruce Momjian 已提交
1404 1405 1406
	 * Get ending-offset of the buffer page we need to replace (this may be
	 * zero if the buffer hasn't been used yet).  Fall through if it's already
	 * written out.
T
Tom Lane 已提交
1407 1408 1409 1410 1411 1412
	 */
	OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
	if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
	{
		/* nope, got work to do... */
		XLogRecPtr	FinishedPageRqstPtr;
1413

T
Tom Lane 已提交
1414
		FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1415

1416
		/* Before waiting, get info_lck and update LogwrtResult */
1417 1418 1419 1420
		{
			/* use volatile pointer to prevent code rearrangement */
			volatile XLogCtlData *xlogctl = XLogCtl;

1421
			SpinLockAcquire(&xlogctl->info_lck);
1422 1423 1424
			if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
				xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
			LogwrtResult = xlogctl->LogwrtResult;
1425
			SpinLockRelease(&xlogctl->info_lck);
1426
		}
1427 1428 1429 1430 1431 1432 1433 1434 1435

		update_needed = false;	/* Did the shared-request update */

		if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
		{
			/* OK, someone wrote it already */
			Insert->LogwrtResult = LogwrtResult;
		}
		else
1436
		{
1437 1438 1439 1440
			/* Must acquire write lock */
			LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
			LogwrtResult = Write->LogwrtResult;
			if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1441
			{
1442 1443 1444
				/* OK, someone wrote it already */
				LWLockRelease(WALWriteLock);
				Insert->LogwrtResult = LogwrtResult;
T
Tom Lane 已提交
1445
			}
1446
			else
T
Tom Lane 已提交
1447 1448
			{
				/*
B
Bruce Momjian 已提交
1449 1450
				 * Have to write buffers while holding insert lock. This is
				 * not good, so only write as much as we absolutely must.
T
Tom Lane 已提交
1451
				 */
1452
				TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
T
Tom Lane 已提交
1453 1454 1455
				WriteRqst.Write = OldPageRqstPtr;
				WriteRqst.Flush.xlogid = 0;
				WriteRqst.Flush.xrecoff = 0;
1456
				XLogWrite(WriteRqst, false, false);
1457
				LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
1458
				Insert->LogwrtResult = LogwrtResult;
1459
				TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
1460 1461 1462 1463
			}
		}
	}

T
Tom Lane 已提交
1464
	/*
B
Bruce Momjian 已提交
1465 1466
	 * Now the next buffer slot is free and we can set it up to be the next
	 * output page.
T
Tom Lane 已提交
1467
	 */
1468
	NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1469 1470 1471 1472 1473 1474 1475 1476

	if (new_segment)
	{
		/* force it to a segment start point */
		NewPageEndPtr.xrecoff += XLogSegSize - 1;
		NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
	}

1477
	if (NewPageEndPtr.xrecoff >= XLogFileSize)
1478
	{
T
Tom Lane 已提交
1479
		/* crossing a logid boundary */
1480
		NewPageEndPtr.xlogid += 1;
1481
		NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1482
	}
T
Tom Lane 已提交
1483
	else
1484
		NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1485
	XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1486
	NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
B
Bruce Momjian 已提交
1487

T
Tom Lane 已提交
1488
	Insert->curridx = nextidx;
1489
	Insert->currpage = NewPage;
B
Bruce Momjian 已提交
1490 1491

	Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
B
Bruce Momjian 已提交
1492

T
Tom Lane 已提交
1493
	/*
B
Bruce Momjian 已提交
1494 1495
	 * Be sure to re-zero the buffer so that bytes beyond what we've written
	 * will look like zeroes and not valid XLOG records...
T
Tom Lane 已提交
1496
	 */
1497
	MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1498

1499 1500 1501
	/*
	 * Fill the new page's header
	 */
B
Bruce Momjian 已提交
1502 1503
	NewPage   ->xlp_magic = XLOG_PAGE_MAGIC;

1504
	/* NewPage->xlp_info = 0; */	/* done by memset */
B
Bruce Momjian 已提交
1505 1506
	NewPage   ->xlp_tli = ThisTimeLineID;
	NewPage   ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1507
	NewPage   ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
T
Tom Lane 已提交
1508

1509
	/*
1510
	 * If first page of an XLOG segment file, make it a long header.
1511 1512 1513
	 */
	if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
	{
1514
		XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1515

1516 1517
		NewLongPage->xlp_sysid = ControlFile->system_identifier;
		NewLongPage->xlp_seg_size = XLogSegSize;
1518
		NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
B
Bruce Momjian 已提交
1519 1520 1521
		NewPage   ->xlp_info |= XLP_LONG_HEADER;

		Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1522 1523
	}

T
Tom Lane 已提交
1524
	return update_needed;
1525 1526
}

1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
/*
 * Check whether we've consumed enough xlog space that a checkpoint is needed.
 *
 * Caller must have just finished filling the open log file (so that
 * openLogId/openLogSeg are valid).  We measure the distance from RedoRecPtr
 * to the open log file and see if that exceeds CheckPointSegments.
 *
 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
 */
static bool
XLogCheckpointNeeded(void)
{
	/*
1540 1541
	 * A straight computation of segment number could overflow 32 bits. Rather
	 * than assuming we have working 64-bit arithmetic, we compare the
B
Bruce Momjian 已提交
1542 1543
	 * highest-order bits separately, and force a checkpoint immediately when
	 * they change.
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
	 */
	uint32		old_segno,
				new_segno;
	uint32		old_highbits,
				new_highbits;

	old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
		(RedoRecPtr.xrecoff / XLogSegSize);
	old_highbits = RedoRecPtr.xlogid / XLogSegSize;
	new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile + openLogSeg;
	new_highbits = openLogId / XLogSegSize;
	if (new_highbits != old_highbits ||
B
Bruce Momjian 已提交
1556
		new_segno >= old_segno + (uint32) (CheckPointSegments - 1))
1557 1558 1559 1560
		return true;
	return false;
}

T
Tom Lane 已提交
1561 1562 1563
/*
 * Write and/or fsync the log at least as far as WriteRqst indicates.
 *
1564 1565 1566 1567 1568
 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
 * may stop at any convenient boundary (such as a cache or logfile boundary).
 * This option allows us to avoid uselessly issuing multiple writes when a
 * single one would do.
 *
1569 1570 1571 1572 1573 1574
 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
 * perform end-of-segment actions after writing the last page, even if
 * it's not physically the end of its segment.  (NB: this will work properly
 * only if caller specifies WriteRqst == page-end and flexible == false,
 * and there is some data to write.)
 *
1575
 * Must be called with WALWriteLock held.
T
Tom Lane 已提交
1576
 */
1577
static void
1578
XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1579
{
1580
	XLogCtlWrite *Write = &XLogCtl->Write;
T
Tom Lane 已提交
1581
	bool		ispartialpage;
1582
	bool		last_iteration;
1583
	bool		finishing_seg;
1584
	bool		use_existent;
1585 1586 1587 1588
	int			curridx;
	int			npages;
	int			startidx;
	uint32		startoffset;
1589

1590 1591 1592
	/* We should always be inside a critical section here */
	Assert(CritSectionCount > 0);

B
Bruce Momjian 已提交
1593
	/*
B
Bruce Momjian 已提交
1594
	 * Update local LogwrtResult (caller probably did this already, but...)
B
Bruce Momjian 已提交
1595
	 */
T
Tom Lane 已提交
1596 1597
	LogwrtResult = Write->LogwrtResult;

1598 1599 1600
	/*
	 * Since successive pages in the xlog cache are consecutively allocated,
	 * we can usually gather multiple pages together and issue just one
B
Bruce Momjian 已提交
1601 1602 1603 1604 1605
	 * write() call.  npages is the number of pages we have determined can be
	 * written together; startidx is the cache block index of the first one,
	 * and startoffset is the file offset at which it should go. The latter
	 * two variables are only valid when npages > 0, but we must initialize
	 * all of them to keep the compiler quiet.
1606 1607 1608 1609 1610 1611 1612 1613 1614
	 */
	npages = 0;
	startidx = 0;
	startoffset = 0;

	/*
	 * Within the loop, curridx is the cache block index of the page to
	 * consider writing.  We advance Write->curridx only after successfully
	 * writing pages.  (Right now, this refinement is useless since we are
B
Bruce Momjian 已提交
1615 1616
	 * going to PANIC if any error occurs anyway; but someday it may come in
	 * useful.)
1617 1618
	 */
	curridx = Write->curridx;
B
 
Bruce Momjian 已提交
1619

T
Tom Lane 已提交
1620
	while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1621
	{
1622
		/*
B
Bruce Momjian 已提交
1623 1624 1625
		 * Make sure we're not ahead of the insert process.  This could happen
		 * if we're passed a bogus WriteRqst.Write that is past the end of the
		 * last page that's been initialized by AdvanceXLInsertBuffer.
1626
		 */
1627
		if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1628
			elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1629
				 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1630 1631
				 XLogCtl->xlblocks[curridx].xlogid,
				 XLogCtl->xlblocks[curridx].xrecoff);
1632

T
Tom Lane 已提交
1633
		/* Advance LogwrtResult.Write to end of current buffer page */
1634
		LogwrtResult.Write = XLogCtl->xlblocks[curridx];
T
Tom Lane 已提交
1635 1636 1637
		ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);

		if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1638
		{
T
Tom Lane 已提交
1639
			/*
1640 1641
			 * Switch to new logfile segment.  We cannot have any pending
			 * pages here (since we dump what we have at segment end).
T
Tom Lane 已提交
1642
			 */
1643
			Assert(npages == 0);
T
Tom Lane 已提交
1644
			if (openLogFile >= 0)
1645
				XLogFileClose();
T
Tom Lane 已提交
1646 1647
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);

1648 1649 1650 1651
			/* create/use new log file */
			use_existent = true;
			openLogFile = XLogFileInit(openLogId, openLogSeg,
									   &use_existent, true);
T
Tom Lane 已提交
1652
			openLogOff = 0;
1653 1654
		}

1655
		/* Make sure we have the current logfile open */
T
Tom Lane 已提交
1656
		if (openLogFile < 0)
1657
		{
T
Tom Lane 已提交
1658
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1659
			openLogFile = XLogFileOpen(openLogId, openLogSeg);
T
Tom Lane 已提交
1660
			openLogOff = 0;
1661 1662
		}

1663 1664 1665 1666 1667
		/* Add current page to the set of pending pages-to-dump */
		if (npages == 0)
		{
			/* first of group */
			startidx = curridx;
1668
			startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1669 1670
		}
		npages++;
1671

T
Tom Lane 已提交
1672
		/*
B
Bruce Momjian 已提交
1673 1674 1675 1676
		 * Dump the set if this will be the last loop iteration, or if we are
		 * at the last page of the cache area (since the next page won't be
		 * contiguous in memory), or if we are at the end of the logfile
		 * segment.
T
Tom Lane 已提交
1677
		 */
1678 1679
		last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);

1680
		finishing_seg = !ispartialpage &&
1681
			(startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1682

1683
		if (last_iteration ||
1684 1685
			curridx == XLogCtl->XLogCacheBlck ||
			finishing_seg)
T
Tom Lane 已提交
1686
		{
1687 1688
			char	   *from;
			Size		nbytes;
1689

1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
			/* Need to seek in the file? */
			if (openLogOff != startoffset)
			{
				if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
					ereport(PANIC,
							(errcode_for_file_access(),
							 errmsg("could not seek in log file %u, "
									"segment %u to offset %u: %m",
									openLogId, openLogSeg, startoffset)));
				openLogOff = startoffset;
			}

			/* OK to write the page(s) */
1703 1704
			from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
			nbytes = npages * (Size) XLOG_BLCKSZ;
1705 1706 1707 1708 1709 1710 1711 1712 1713
			errno = 0;
			if (write(openLogFile, from, nbytes) != nbytes)
			{
				/* if write didn't set errno, assume no disk space */
				if (errno == 0)
					errno = ENOSPC;
				ereport(PANIC,
						(errcode_for_file_access(),
						 errmsg("could not write to log file %u, segment %u "
P
Peter Eisentraut 已提交
1714
								"at offset %u, length %lu: %m",
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
								openLogId, openLogSeg,
								openLogOff, (unsigned long) nbytes)));
			}

			/* Update state for write */
			openLogOff += nbytes;
			Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
			npages = 0;

			/*
			 * If we just wrote the whole last page of a logfile segment,
			 * fsync the segment immediately.  This avoids having to go back
			 * and re-open prior segments when an fsync request comes along
			 * later. Doing it here ensures that one and only one backend will
			 * perform this fsync.
			 *
1731 1732 1733
			 * We also do this if this is the last page written for an xlog
			 * switch.
			 *
1734
			 * This is also the right place to notify the Archiver that the
B
Bruce Momjian 已提交
1735
			 * segment is ready to copy to archival storage, and to update the
1736 1737 1738
			 * timer for archive_timeout, and to signal for a checkpoint if
			 * too many logfile segments have been used since the last
			 * checkpoint.
1739
			 */
1740
			if (finishing_seg || (xlog_switch && last_iteration))
1741
			{
1742
				issue_xlog_fsync(openLogFile, openLogId, openLogSeg);
B
Bruce Momjian 已提交
1743
				LogwrtResult.Flush = LogwrtResult.Write;		/* end of page */
1744 1745 1746

				if (XLogArchivingActive())
					XLogArchiveNotifySeg(openLogId, openLogSeg);
1747

1748
				Write->lastSegSwitchTime = (pg_time_t) time(NULL);
1749 1750

				/*
1751
				 * Signal bgwriter to start a checkpoint if we've consumed too
1752
				 * much xlog since the last one.  For speed, we first check
B
Bruce Momjian 已提交
1753 1754 1755
				 * using the local copy of RedoRecPtr, which might be out of
				 * date; if it looks like a checkpoint is needed, forcibly
				 * update RedoRecPtr and recheck.
1756
				 */
1757 1758
				if (IsUnderPostmaster &&
					XLogCheckpointNeeded())
1759
				{
1760 1761
					(void) GetRedoRecPtr();
					if (XLogCheckpointNeeded())
1762
						RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1763
				}
1764
			}
T
Tom Lane 已提交
1765
		}
1766

T
Tom Lane 已提交
1767 1768 1769 1770 1771 1772
		if (ispartialpage)
		{
			/* Only asked to write a partial page */
			LogwrtResult.Write = WriteRqst.Write;
			break;
		}
1773 1774 1775 1776 1777
		curridx = NextBufIdx(curridx);

		/* If flexible, break out of loop as soon as we wrote something */
		if (flexible && npages == 0)
			break;
1778
	}
1779 1780 1781

	Assert(npages == 0);
	Assert(curridx == Write->curridx);
1782

T
Tom Lane 已提交
1783 1784 1785 1786 1787
	/*
	 * If asked to flush, do so
	 */
	if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
		XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1788
	{
T
Tom Lane 已提交
1789
		/*
B
Bruce Momjian 已提交
1790 1791 1792
		 * Could get here without iterating above loop, in which case we might
		 * have no open file or the wrong one.	However, we do not need to
		 * fsync more than one file.
T
Tom Lane 已提交
1793
		 */
1794 1795
		if (sync_method != SYNC_METHOD_OPEN &&
			sync_method != SYNC_METHOD_OPEN_DSYNC)
T
Tom Lane 已提交
1796
		{
1797
			if (openLogFile >= 0 &&
B
Bruce Momjian 已提交
1798
				!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1799
				XLogFileClose();
1800 1801 1802
			if (openLogFile < 0)
			{
				XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1803
				openLogFile = XLogFileOpen(openLogId, openLogSeg);
1804 1805
				openLogOff = 0;
			}
1806
			issue_xlog_fsync(openLogFile, openLogId, openLogSeg);
T
Tom Lane 已提交
1807 1808
		}
		LogwrtResult.Flush = LogwrtResult.Write;
1809 1810
	}

T
Tom Lane 已提交
1811 1812 1813
	/*
	 * Update shared-memory status
	 *
B
Bruce Momjian 已提交
1814
	 * We make sure that the shared 'request' values do not fall behind the
B
Bruce Momjian 已提交
1815 1816
	 * 'result' values.  This is not absolutely essential, but it saves some
	 * code in a couple of places.
T
Tom Lane 已提交
1817
	 */
1818 1819 1820 1821
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

1822
		SpinLockAcquire(&xlogctl->info_lck);
1823 1824 1825 1826 1827
		xlogctl->LogwrtResult = LogwrtResult;
		if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
			xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
		if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
			xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1828
		SpinLockRelease(&xlogctl->info_lck);
1829
	}
1830

T
Tom Lane 已提交
1831 1832 1833
	Write->LogwrtResult = LogwrtResult;
}

1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
/*
 * Record the LSN for an asynchronous transaction commit.
 * (This should not be called for aborts, nor for synchronous commits.)
 */
void
XLogSetAsyncCommitLSN(XLogRecPtr asyncCommitLSN)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

	SpinLockAcquire(&xlogctl->info_lck);
	if (XLByteLT(xlogctl->asyncCommitLSN, asyncCommitLSN))
		xlogctl->asyncCommitLSN = asyncCommitLSN;
	SpinLockRelease(&xlogctl->info_lck);
}

1850 1851 1852 1853
/*
 * Advance minRecoveryPoint in control file.
 *
 * If we crash during recovery, we must reach this point again before the
1854 1855
 * database is consistent.
 *
1856
 * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
1857
 * is only updated if it's not already greater than or equal to 'lsn'.
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
 */
static void
UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
{
	/* Quick check using our local copy of the variable */
	if (!updateMinRecoveryPoint || (!force && XLByteLE(lsn, minRecoveryPoint)))
		return;

	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);

	/* update local copy */
	minRecoveryPoint = ControlFile->minRecoveryPoint;

	/*
	 * An invalid minRecoveryPoint means that we need to recover all the WAL,
1873 1874
	 * i.e., we're doing crash recovery.  We never modify the control file's
	 * value in that case, so we can short-circuit future checks here too.
1875 1876 1877 1878 1879 1880 1881
	 */
	if (minRecoveryPoint.xlogid == 0 && minRecoveryPoint.xrecoff == 0)
		updateMinRecoveryPoint = false;
	else if (force || XLByteLT(minRecoveryPoint, lsn))
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;
1882
		XLogRecPtr	newMinRecoveryPoint;
1883 1884 1885 1886

		/*
		 * To avoid having to update the control file too often, we update it
		 * all the way to the last record being replayed, even though 'lsn'
1887 1888 1889 1890
		 * would suffice for correctness.  This also allows the 'force' case
		 * to not need a valid 'lsn' value.
		 *
		 * Another important reason for doing it this way is that the passed
B
Bruce Momjian 已提交
1891 1892 1893 1894
		 * 'lsn' value could be bogus, i.e., past the end of available WAL, if
		 * the caller got it from a corrupted heap page.  Accepting such a
		 * value as the min recovery point would prevent us from coming up at
		 * all.  Instead, we just log a warning and continue with recovery.
1895
		 * (See also the comments about corrupt LSNs in XLogFlush.)
1896 1897 1898 1899 1900
		 */
		SpinLockAcquire(&xlogctl->info_lck);
		newMinRecoveryPoint = xlogctl->replayEndRecPtr;
		SpinLockRelease(&xlogctl->info_lck);

1901 1902
		if (!force && XLByteLT(newMinRecoveryPoint, lsn))
			elog(WARNING,
B
Bruce Momjian 已提交
1903
			   "xlog min recovery request %X/%X is past current point %X/%X",
1904 1905 1906
				 lsn.xlogid, lsn.xrecoff,
				 newMinRecoveryPoint.xlogid, newMinRecoveryPoint.xrecoff);

1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
		/* update control file */
		if (XLByteLT(ControlFile->minRecoveryPoint, newMinRecoveryPoint))
		{
			ControlFile->minRecoveryPoint = newMinRecoveryPoint;
			UpdateControlFile();
			minRecoveryPoint = newMinRecoveryPoint;

			ereport(DEBUG2,
					(errmsg("updated min recovery point to %X/%X",
						minRecoveryPoint.xlogid, minRecoveryPoint.xrecoff)));
		}
	}
	LWLockRelease(ControlFileLock);
}

T
Tom Lane 已提交
1922 1923 1924
/*
 * Ensure that all XLOG data through the given position is flushed to disk.
 *
1925
 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
T
Tom Lane 已提交
1926 1927 1928 1929 1930 1931 1932 1933
 * already held, and we try to avoid acquiring it if possible.
 */
void
XLogFlush(XLogRecPtr record)
{
	XLogRecPtr	WriteRqstPtr;
	XLogwrtRqst WriteRqst;

1934
	/*
1935
	 * During REDO, we are reading not writing WAL.  Therefore, instead of
B
Bruce Momjian 已提交
1936 1937 1938 1939
	 * trying to flush the WAL, we should update minRecoveryPoint instead. We
	 * test XLogInsertAllowed(), not InRecovery, because we need the bgwriter
	 * to act this way too, and because when the bgwriter tries to write the
	 * end-of-recovery checkpoint, it should indeed flush.
1940
	 */
1941
	if (!XLogInsertAllowed())
1942 1943
	{
		UpdateMinRecoveryPoint(record, false);
T
Tom Lane 已提交
1944
		return;
1945
	}
T
Tom Lane 已提交
1946 1947 1948 1949 1950

	/* Quick exit if already known flushed */
	if (XLByteLE(record, LogwrtResult.Flush))
		return;

1951
#ifdef WAL_DEBUG
1952
	if (XLOG_DEBUG)
1953
		elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1954 1955 1956
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1957
#endif
1958

T
Tom Lane 已提交
1959 1960 1961 1962
	START_CRIT_SECTION();

	/*
	 * Since fsync is usually a horribly expensive operation, we try to
B
Bruce Momjian 已提交
1963 1964 1965 1966
	 * piggyback as much data as we can on each fsync: if we see any more data
	 * entered into the xlog buffer, we'll write and fsync that too, so that
	 * the final value of LogwrtResult.Flush is as large as possible. This
	 * gives us some chance of avoiding another fsync immediately after.
T
Tom Lane 已提交
1967 1968 1969 1970 1971
	 */

	/* initialize to given target; may increase below */
	WriteRqstPtr = record;

1972
	/* read LogwrtResult and update local state */
1973 1974 1975 1976
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

1977
		SpinLockAcquire(&xlogctl->info_lck);
1978 1979 1980
		if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
			WriteRqstPtr = xlogctl->LogwrtRqst.Write;
		LogwrtResult = xlogctl->LogwrtResult;
1981
		SpinLockRelease(&xlogctl->info_lck);
1982
	}
1983 1984 1985

	/* done already? */
	if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
1986
	{
1987 1988 1989 1990
		/* now wait for the write lock */
		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
		LogwrtResult = XLogCtl->Write.LogwrtResult;
		if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
1991
		{
1992 1993 1994 1995 1996 1997
			/* try to write/flush later additions to XLOG as well */
			if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
			{
				XLogCtlInsert *Insert = &XLogCtl->Insert;
				uint32		freespace = INSERT_FREESPACE(Insert);

B
Bruce Momjian 已提交
1998
				if (freespace < SizeOfXLogRecord)		/* buffer is full */
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
					WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
				else
				{
					WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
					WriteRqstPtr.xrecoff -= freespace;
				}
				LWLockRelease(WALInsertLock);
				WriteRqst.Write = WriteRqstPtr;
				WriteRqst.Flush = WriteRqstPtr;
			}
			else
			{
				WriteRqst.Write = WriteRqstPtr;
				WriteRqst.Flush = record;
			}
2014
			XLogWrite(WriteRqst, false, false);
T
Tom Lane 已提交
2015
		}
2016
		LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
2017 2018 2019
	}

	END_CRIT_SECTION();
2020 2021 2022

	/*
	 * If we still haven't flushed to the request point then we have a
B
Bruce Momjian 已提交
2023 2024
	 * problem; most likely, the requested flush point is past end of XLOG.
	 * This has been seen to occur when a disk page has a corrupted LSN.
2025
	 *
2026 2027 2028 2029
	 * Formerly we treated this as a PANIC condition, but that hurts the
	 * system's robustness rather than helping it: we do not want to take down
	 * the whole system due to corruption on one data page.  In particular, if
	 * the bad page is encountered again during recovery then we would be
2030
	 * unable to restart the database at all!  (This scenario actually
B
Bruce Momjian 已提交
2031 2032 2033 2034 2035
	 * happened in the field several times with 7.1 releases.)	As of 8.4, bad
	 * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
	 * the only time we can reach here during recovery is while flushing the
	 * end-of-recovery checkpoint record, and we don't expect that to have a
	 * bad LSN.
2036
	 *
B
Bruce Momjian 已提交
2037 2038 2039 2040
	 * Note that for calls from xact.c, the ERROR will be promoted to PANIC
	 * since xact.c calls this routine inside a critical section.  However,
	 * calls from bufmgr.c are not within critical sections and so we will not
	 * force a restart for a bad LSN on a data page.
2041 2042
	 */
	if (XLByteLT(LogwrtResult.Flush, record))
2043
		elog(ERROR,
B
Bruce Momjian 已提交
2044
		"xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
2045 2046
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
2047 2048
}

2049 2050 2051 2052 2053 2054
/*
 * Flush xlog, but without specifying exactly where to flush to.
 *
 * We normally flush only completed blocks; but if there is nothing to do on
 * that basis, we check for unflushed async commits in the current incomplete
 * block, and flush through the latest one of those.  Thus, if async commits
B
Bruce Momjian 已提交
2055
 * are not being used, we will flush complete blocks only.	We can guarantee
2056
 * that async commits reach disk after at most three cycles; normally only
B
Bruce Momjian 已提交
2057
 * one or two.	(We allow XLogWrite to write "flexibly", meaning it can stop
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
 * at the end of the buffer ring; this makes a difference only with very high
 * load or long wal_writer_delay, but imposes one extra cycle for the worst
 * case for async commits.)
 *
 * This routine is invoked periodically by the background walwriter process.
 */
void
XLogBackgroundFlush(void)
{
	XLogRecPtr	WriteRqstPtr;
	bool		flexible = true;

2070 2071 2072 2073
	/* XLOG doesn't need flushing during recovery */
	if (RecoveryInProgress())
		return;

2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
	/* read LogwrtResult and update local state */
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		SpinLockAcquire(&xlogctl->info_lck);
		LogwrtResult = xlogctl->LogwrtResult;
		WriteRqstPtr = xlogctl->LogwrtRqst.Write;
		SpinLockRelease(&xlogctl->info_lck);
	}

	/* back off to last completed page boundary */
	WriteRqstPtr.xrecoff -= WriteRqstPtr.xrecoff % XLOG_BLCKSZ;

	/* if we have already flushed that far, consider async commit records */
	if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

2094
		SpinLockAcquire(&xlogctl->info_lck);
2095
		WriteRqstPtr = xlogctl->asyncCommitLSN;
2096
		SpinLockRelease(&xlogctl->info_lck);
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
		flexible = false;		/* ensure it all gets written */
	}

	/* Done if already known flushed */
	if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
		return;

#ifdef WAL_DEBUG
	if (XLOG_DEBUG)
		elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
			 WriteRqstPtr.xlogid, WriteRqstPtr.xrecoff,
			 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
#endif

	START_CRIT_SECTION();

	/* now wait for the write lock */
	LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
	LogwrtResult = XLogCtl->Write.LogwrtResult;
	if (!XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
	{
		XLogwrtRqst WriteRqst;

		WriteRqst.Write = WriteRqstPtr;
		WriteRqst.Flush = WriteRqstPtr;
		XLogWrite(WriteRqst, flexible, false);
	}
	LWLockRelease(WALWriteLock);

	END_CRIT_SECTION();
}

2130 2131 2132 2133 2134 2135 2136 2137 2138
/*
 * Test whether XLOG data has been flushed up to (at least) the given position.
 *
 * Returns true if a flush is still needed.  (It may be that someone else
 * is already in process of flushing that far, however.)
 */
bool
XLogNeedsFlush(XLogRecPtr record)
{
2139 2140 2141 2142 2143
	/*
	 * During recovery, we don't flush WAL but update minRecoveryPoint
	 * instead. So "needs flush" is taken to mean whether minRecoveryPoint
	 * would need to be updated.
	 */
2144
	if (RecoveryInProgress())
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
	{
		/* Quick exit if already known updated */
		if (XLByteLE(record, minRecoveryPoint) || !updateMinRecoveryPoint)
			return false;

		/*
		 * Update local copy of minRecoveryPoint. But if the lock is busy,
		 * just return a conservative guess.
		 */
		if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
			return true;
		minRecoveryPoint = ControlFile->minRecoveryPoint;
		LWLockRelease(ControlFileLock);

		/*
B
Bruce Momjian 已提交
2160 2161 2162 2163
		 * An invalid minRecoveryPoint means that we need to recover all the
		 * WAL, i.e., we're doing crash recovery.  We never modify the control
		 * file's value in that case, so we can short-circuit future checks
		 * here too.
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
		 */
		if (minRecoveryPoint.xlogid == 0 && minRecoveryPoint.xrecoff == 0)
			updateMinRecoveryPoint = false;

		/* check again */
		if (XLByteLE(record, minRecoveryPoint) || !updateMinRecoveryPoint)
			return false;
		else
			return true;
	}
2174

2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
	/* Quick exit if already known flushed */
	if (XLByteLE(record, LogwrtResult.Flush))
		return false;

	/* read LogwrtResult and update local state */
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		SpinLockAcquire(&xlogctl->info_lck);
		LogwrtResult = xlogctl->LogwrtResult;
		SpinLockRelease(&xlogctl->info_lck);
	}

	/* check again */
	if (XLByteLE(record, LogwrtResult.Flush))
		return false;

	return true;
}

T
Tom Lane 已提交
2196 2197 2198
/*
 * Create a new XLOG file segment, or open a pre-existing one.
 *
2199 2200 2201
 * log, seg: identify segment to be created/opened.
 *
 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
B
Bruce Momjian 已提交
2202
 * pre-existing file will be deleted).	On return, TRUE if a pre-existing
2203 2204
 * file was used.
 *
2205
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2206
 * place.  This should be TRUE except during bootstrap log creation.  The
2207
 * caller must *not* hold the lock at call.
2208
 *
T
Tom Lane 已提交
2209
 * Returns FD of opened file.
2210 2211 2212 2213 2214
 *
 * Note: errors here are ERROR not PANIC because we might or might not be
 * inside a critical section (eg, during checkpoint there is no reason to
 * take down the system on failure).  They will promote to PANIC if we are
 * in a critical section.
T
Tom Lane 已提交
2215
 */
2216
int
2217 2218
XLogFileInit(uint32 log, uint32 seg,
			 bool *use_existent, bool use_lock)
2219
{
2220
	char		path[MAXPGPATH];
2221
	char		tmppath[MAXPGPATH];
2222
	char	   *zbuffer;
2223 2224 2225
	uint32		installed_log;
	uint32		installed_seg;
	int			max_advance;
2226
	int			fd;
2227
	int			nbytes;
2228

2229
	XLogFilePath(path, ThisTimeLineID, log, seg);
V
Vadim B. Mikheev 已提交
2230 2231

	/*
B
Bruce Momjian 已提交
2232
	 * Try to use existent file (checkpoint maker may have created it already)
V
Vadim B. Mikheev 已提交
2233
	 */
2234
	if (*use_existent)
V
Vadim B. Mikheev 已提交
2235
	{
2236
		fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2237
						   S_IRUSR | S_IWUSR);
V
Vadim B. Mikheev 已提交
2238 2239 2240
		if (fd < 0)
		{
			if (errno != ENOENT)
2241
				ereport(ERROR,
2242
						(errcode_for_file_access(),
2243
						 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2244
								path, log, seg)));
V
Vadim B. Mikheev 已提交
2245 2246
		}
		else
2247
			return fd;
V
Vadim B. Mikheev 已提交
2248 2249
	}

2250
	/*
B
Bruce Momjian 已提交
2251 2252 2253 2254
	 * Initialize an empty (all zeroes) segment.  NOTE: it is possible that
	 * another process is doing the same thing.  If so, we will end up
	 * pre-creating an extra log segment.  That seems OK, and better than
	 * holding the lock throughout this lengthy process.
2255
	 */
2256 2257
	elog(DEBUG2, "creating and filling new WAL file");

2258
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2259 2260

	unlink(tmppath);
2261

2262
	/* do not use get_sync_bit() here --- want to fsync only at end of fill */
2263
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
T
Tom Lane 已提交
2264
					   S_IRUSR | S_IWUSR);
2265
	if (fd < 0)
2266
		ereport(ERROR,
2267
				(errcode_for_file_access(),
2268
				 errmsg("could not create file \"%s\": %m", tmppath)));
2269

2270
	/*
B
Bruce Momjian 已提交
2271 2272 2273 2274 2275 2276 2277
	 * Zero-fill the file.	We have to do this the hard way to ensure that all
	 * the file space has really been allocated --- on platforms that allow
	 * "holes" in files, just seeking to the end doesn't allocate intermediate
	 * space.  This way, we know that we have all the space and (after the
	 * fsync below) that all the indirect blocks are down on disk.	Therefore,
	 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
	 * log file.
2278 2279 2280 2281
	 *
	 * Note: palloc zbuffer, instead of just using a local char array, to
	 * ensure it is reasonably well-aligned; this may save a few cycles
	 * transferring data to the kernel.
2282
	 */
2283 2284
	zbuffer = (char *) palloc0(XLOG_BLCKSZ);
	for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
2285
	{
2286
		errno = 0;
2287
		if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
T
Tom Lane 已提交
2288
		{
B
Bruce Momjian 已提交
2289
			int			save_errno = errno;
T
Tom Lane 已提交
2290

B
Bruce Momjian 已提交
2291
			/*
B
Bruce Momjian 已提交
2292
			 * If we fail to make the file, delete it to release disk space
B
Bruce Momjian 已提交
2293
			 */
2294
			unlink(tmppath);
2295 2296
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;
T
Tom Lane 已提交
2297

2298
			ereport(ERROR,
2299
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2300
					 errmsg("could not write to file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2301
		}
2302
	}
2303
	pfree(zbuffer);
2304

2305
	if (pg_fsync(fd) != 0)
2306
		ereport(ERROR,
2307
				(errcode_for_file_access(),
2308
				 errmsg("could not fsync file \"%s\": %m", tmppath)));
2309

2310
	if (close(fd))
2311
		ereport(ERROR,
2312 2313
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2314

2315
	/*
2316 2317
	 * Now move the segment into place with its final name.
	 *
2318
	 * If caller didn't want to use a pre-existing file, get rid of any
B
Bruce Momjian 已提交
2319 2320 2321
	 * pre-existing file.  Otherwise, cope with possibility that someone else
	 * has created the file while we were filling ours: if so, use ours to
	 * pre-create a future log segment.
2322
	 */
2323 2324 2325 2326 2327
	installed_log = log;
	installed_seg = seg;
	max_advance = XLOGfileslop;
	if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
								*use_existent, &max_advance,
2328 2329
								use_lock))
	{
2330 2331 2332 2333 2334
		/*
		 * No need for any more future segments, or InstallXLogFileSegment()
		 * failed to rename the file into place. If the rename failed, opening
		 * the file below will fail.
		 */
2335 2336 2337 2338 2339 2340 2341
		unlink(tmppath);
	}

	/* Set flag to tell caller there was no existent file */
	*use_existent = false;

	/* Now open original target segment (might not be file I just made) */
2342
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2343 2344
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
2345
		ereport(ERROR,
2346
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2347 2348
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2349

2350 2351
	elog(DEBUG2, "done creating and filling new WAL file");

2352
	return fd;
2353 2354
}

2355 2356 2357 2358 2359 2360 2361 2362 2363
/*
 * Create a new XLOG file segment by copying a pre-existing one.
 *
 * log, seg: identify segment to be created.
 *
 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
 *		a different timeline)
 *
 * Currently this is only used during recovery, and so there are no locking
B
Bruce Momjian 已提交
2364
 * considerations.	But we should be just as tense as XLogFileInit to avoid
2365 2366 2367 2368 2369 2370 2371 2372
 * emplacing a bogus file.
 */
static void
XLogFileCopy(uint32 log, uint32 seg,
			 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
{
	char		path[MAXPGPATH];
	char		tmppath[MAXPGPATH];
2373
	char		buffer[XLOG_BLCKSZ];
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
	int			srcfd;
	int			fd;
	int			nbytes;

	/*
	 * Open the source file
	 */
	XLogFilePath(path, srcTLI, srclog, srcseg);
	srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
	if (srcfd < 0)
2384
		ereport(ERROR,
2385 2386 2387 2388 2389 2390
				(errcode_for_file_access(),
				 errmsg("could not open file \"%s\": %m", path)));

	/*
	 * Copy into a temp file name.
	 */
2391
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2392 2393 2394

	unlink(tmppath);

2395
	/* do not use get_sync_bit() here --- want to fsync only at end of fill */
2396 2397 2398
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
2399
		ereport(ERROR,
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m", tmppath)));

	/*
	 * Do the data copying.
	 */
	for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
	{
		errno = 0;
		if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
		{
			if (errno != 0)
2412
				ereport(ERROR,
2413 2414 2415
						(errcode_for_file_access(),
						 errmsg("could not read file \"%s\": %m", path)));
			else
2416
				ereport(ERROR,
B
Bruce Momjian 已提交
2417
						(errmsg("not enough data in file \"%s\"", path)));
2418 2419 2420 2421 2422 2423 2424
		}
		errno = 0;
		if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
		{
			int			save_errno = errno;

			/*
B
Bruce Momjian 已提交
2425
			 * If we fail to make the file, delete it to release disk space
2426 2427 2428 2429 2430
			 */
			unlink(tmppath);
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;

2431
			ereport(ERROR,
2432
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2433
					 errmsg("could not write to file \"%s\": %m", tmppath)));
2434 2435 2436 2437
		}
	}

	if (pg_fsync(fd) != 0)
2438
		ereport(ERROR,
2439 2440 2441 2442
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
2443
		ereport(ERROR,
2444 2445 2446 2447 2448 2449 2450 2451
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));

	close(srcfd);

	/*
	 * Now move the segment into place with its final name.
	 */
2452
	if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2453
		elog(ERROR, "InstallXLogFileSegment should not have failed");
2454 2455
}

2456 2457 2458 2459 2460 2461
/*
 * Install a new XLOG segment file as a current or future log segment.
 *
 * This is used both to install a newly-created segment (which has a temp
 * filename while it's being created) and to recycle an old segment.
 *
2462 2463 2464
 * *log, *seg: identify segment to install as (or first possible target).
 * When find_free is TRUE, these are modified on return to indicate the
 * actual installation location or last segment searched.
2465 2466 2467 2468 2469 2470 2471
 *
 * tmppath: initial name of file to install.  It will be renamed into place.
 *
 * find_free: if TRUE, install the new segment at the first empty log/seg
 * number at or after the passed numbers.  If FALSE, install the new segment
 * exactly where specified, deleting any existing segment file there.
 *
2472 2473 2474 2475
 * *max_advance: maximum number of log/seg slots to advance past the starting
 * point.  Fail if no free slot is found in this range.  On return, reduced
 * by the number of slots skipped over.  (Irrelevant, and may be NULL,
 * when find_free is FALSE.)
2476
 *
2477
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2478
 * place.  This should be TRUE except during bootstrap log creation.  The
2479
 * caller must *not* hold the lock at call.
2480
 *
2481 2482 2483
 * Returns TRUE if the file was installed successfully.  FALSE indicates that
 * max_advance limit was exceeded, or an error occurred while renaming the
 * file into place.
2484 2485
 */
static bool
2486 2487
InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
2488 2489 2490
					   bool use_lock)
{
	char		path[MAXPGPATH];
2491
	struct stat stat_buf;
2492

2493
	XLogFilePath(path, ThisTimeLineID, *log, *seg);
2494 2495 2496 2497 2498

	/*
	 * We want to be sure that only one process does this at a time.
	 */
	if (use_lock)
2499
		LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2500

2501 2502 2503 2504 2505
	if (!find_free)
	{
		/* Force installation: get rid of any pre-existing segment file */
		unlink(path);
	}
2506 2507
	else
	{
2508
		/* Find a free slot to put it in */
2509
		while (stat(path, &stat_buf) == 0)
2510
		{
2511
			if (*max_advance <= 0)
2512 2513 2514
			{
				/* Failed to find a free slot within specified range */
				if (use_lock)
2515
					LWLockRelease(ControlFileLock);
2516 2517
				return false;
			}
2518 2519 2520
			NextLogSeg(*log, *seg);
			(*max_advance)--;
			XLogFilePath(path, ThisTimeLineID, *log, *seg);
2521 2522 2523 2524 2525 2526 2527
		}
	}

	/*
	 * Prefer link() to rename() here just to be really sure that we don't
	 * overwrite an existing logfile.  However, there shouldn't be one, so
	 * rename() is an acceptable substitute except for the truly paranoid.
2528
	 */
2529
#if HAVE_WORKING_LINK
2530
	if (link(tmppath, path) < 0)
2531 2532 2533 2534
	{
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
2535
				(errcode_for_file_access(),
2536
				 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2537
						tmppath, path, *log, *seg)));
2538 2539
		return false;
	}
2540
	unlink(tmppath);
2541
#else
2542
	if (rename(tmppath, path) < 0)
2543
	{
2544 2545 2546
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
2547
				(errcode_for_file_access(),
2548
				 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2549
						tmppath, path, *log, *seg)));
2550
		return false;
2551
	}
2552
#endif
V
Vadim B. Mikheev 已提交
2553

2554
	if (use_lock)
2555
		LWLockRelease(ControlFileLock);
2556

2557
	return true;
2558 2559
}

T
Tom Lane 已提交
2560
/*
2561
 * Open a pre-existing logfile segment for writing.
T
Tom Lane 已提交
2562
 */
2563
int
2564
XLogFileOpen(uint32 log, uint32 seg)
2565
{
2566 2567
	char		path[MAXPGPATH];
	int			fd;
2568

2569
	XLogFilePath(path, ThisTimeLineID, log, seg);
2570

2571
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2572
					   S_IRUSR | S_IWUSR);
2573
	if (fd < 0)
2574 2575
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2576 2577
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2578 2579 2580 2581 2582 2583

	return fd;
}

/*
 * Open a logfile segment for reading (during recovery).
2584 2585 2586
 *
 * If fromArchive is true, the segment is retrieved from archive, otherwise
 * it's read from pg_xlog.
2587 2588
 */
static int
2589
XLogFileRead(uint32 log, uint32 seg, int emode, TimeLineID tli,
2590
			 int source, bool notfoundOk)
2591 2592
{
	char		xlogfname[MAXFNAMELEN];
2593
	char		activitymsg[MAXFNAMELEN + 16];
2594
	char		path[MAXPGPATH];
2595
	int			fd;
2596

B
Bruce Momjian 已提交
2597
	XLogFileName(xlogfname, tli, log, seg);
2598

2599
	switch (source)
B
Bruce Momjian 已提交
2600
	{
2601 2602 2603 2604 2605
		case XLOG_FROM_ARCHIVE:
			/* Report recovery progress in PS display */
			snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
					 xlogfname);
			set_ps_display(activitymsg, false);
2606

2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
			restoredFromArchive = RestoreArchivedFile(path, xlogfname,
													  "RECOVERYXLOG",
													  XLogSegSize);
			if (!restoredFromArchive)
				return -1;
			break;

		case XLOG_FROM_PG_XLOG:
			XLogFilePath(path, tli, log, seg);
			restoredFromArchive = false;
			break;

		default:
			elog(ERROR, "invalid XLogFileRead source %d", source);
B
Bruce Momjian 已提交
2621
	}
2622

B
Bruce Momjian 已提交
2623 2624 2625 2626 2627
	fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
	if (fd >= 0)
	{
		/* Success! */
		curFileTLI = tli;
2628

B
Bruce Momjian 已提交
2629 2630 2631 2632 2633
		/* Report recovery progress in PS display */
		snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
				 xlogfname);
		set_ps_display(activitymsg, false);

2634
		readSource = source;
B
Bruce Momjian 已提交
2635 2636 2637 2638 2639 2640 2641 2642
		return fd;
	}
	if (errno != ENOENT || !notfoundOk) /* unexpected failure? */
		ereport(PANIC,
				(errcode_for_file_access(),
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
	return -1;
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
}

/*
 * Open a logfile segment for reading (during recovery).
 *
 * This version searches for the segment with any TLI listed in expectedTLIs.
 * If not in StandbyMode and fromArchive is true, the segment is also
 * searched in pg_xlog if not found in archive.
 */
static int
2653
XLogFileReadAnyTLI(uint32 log, uint32 seg, int emode, int sources)
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
{
	char		path[MAXPGPATH];
	ListCell   *cell;
	int			fd;

	/*
	 * Loop looking for a suitable timeline ID: we might need to read any of
	 * the timelines listed in expectedTLIs.
	 *
	 * We expect curFileTLI on entry to be the TLI of the preceding file in
	 * sequence, or 0 if there was no predecessor.	We do not allow curFileTLI
	 * to go backwards; this prevents us from picking up the wrong file when a
	 * parent timeline extends to higher segment numbers than the child we
	 * want to read.
	 */
	foreach(cell, expectedTLIs)
	{
		TimeLineID	tli = (TimeLineID) lfirst_int(cell);

		if (tli < curFileTLI)
			break;				/* don't bother looking at too-old TLIs */

2676 2677 2678 2679 2680 2681 2682 2683 2684
		if (sources & XLOG_FROM_ARCHIVE)
		{
			fd = XLogFileRead(log, seg, emode, tli, XLOG_FROM_ARCHIVE, true);
			if (fd != -1)
			{
				elog(DEBUG1, "got WAL segment from archive");
				return fd;
			}
		}
2685

2686
		if (sources & XLOG_FROM_PG_XLOG)
2687
		{
2688
			fd = XLogFileRead(log, seg, emode, tli, XLOG_FROM_PG_XLOG, true);
2689 2690 2691
			if (fd != -1)
				return fd;
		}
2692 2693 2694 2695 2696 2697 2698
	}

	/* Couldn't find it.  For simplicity, complain about front timeline */
	XLogFilePath(path, recoveryTargetTLI, log, seg);
	errno = ENOENT;
	ereport(emode,
			(errcode_for_file_access(),
B
Bruce Momjian 已提交
2699 2700
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2701
	return -1;
2702 2703
}

2704 2705 2706 2707 2708 2709 2710 2711 2712
/*
 * Close the current logfile segment for writing.
 */
static void
XLogFileClose(void)
{
	Assert(openLogFile >= 0);

	/*
2713
	 * WAL segment files will not be re-read in normal operation, so we advise
2714
	 * the OS to release any cached pages.	But do not do so if WAL archiving
B
Bruce Momjian 已提交
2715 2716
	 * or streaming is active, because archiver and walsender process could
	 * use the cache to read the WAL segment.
2717
	 */
2718
#if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2719
	if (!XLogIsNeeded())
2720
		(void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2721
#endif
2722

2723 2724
	if (close(openLogFile))
		ereport(PANIC,
B
Bruce Momjian 已提交
2725 2726 2727
				(errcode_for_file_access(),
				 errmsg("could not close log file %u, segment %u: %m",
						openLogId, openLogSeg)));
2728 2729 2730
	openLogFile = -1;
}

2731
/*
2732
 * Attempt to retrieve the specified file from off-line archival storage.
2733
 * If successful, fill "path" with its complete path (note that this will be
2734 2735
 * a temp file name that doesn't follow the normal naming convention), and
 * return TRUE.
2736
 *
2737 2738 2739
 * If not successful, fill "path" with the name of the normal on-line file
 * (which may or may not actually exist, but we'll try to use it), and return
 * FALSE.
2740 2741 2742 2743
 *
 * For fixed-size files, the caller may pass the expected size as an
 * additional crosscheck on successful recovery.  If the file size is not
 * known, set expectedSize = 0.
2744
 */
2745 2746
static bool
RestoreArchivedFile(char *path, const char *xlogfname,
2747
					const char *recovername, off_t expectedSize)
2748
{
B
Bruce Momjian 已提交
2749 2750
	char		xlogpath[MAXPGPATH];
	char		xlogRestoreCmd[MAXPGPATH];
2751
	char		lastRestartPointFname[MAXPGPATH];
B
Bruce Momjian 已提交
2752 2753
	char	   *dp;
	char	   *endp;
2754
	const char *sp;
B
Bruce Momjian 已提交
2755
	int			rc;
2756
	bool		signaled;
2757
	struct stat stat_buf;
B
Bruce Momjian 已提交
2758 2759
	uint32		restartLog;
	uint32		restartSeg;
2760

2761
	/* In standby mode, restore_command might not be supplied */
2762
	if (recoveryRestoreCommand == NULL)
2763 2764
		goto not_available;

2765
	/*
B
Bruce Momjian 已提交
2766 2767 2768 2769
	 * When doing archive recovery, we always prefer an archived log file even
	 * if a file of the same name exists in XLOGDIR.  The reason is that the
	 * file in XLOGDIR could be an old, un-filled or partly-filled version
	 * that was copied and restored as part of backing up $PGDATA.
2770
	 *
B
Bruce Momjian 已提交
2771
	 * We could try to optimize this slightly by checking the local copy
B
Bruce Momjian 已提交
2772 2773 2774 2775
	 * lastchange timestamp against the archived copy, but we have no API to
	 * do this, nor can we guarantee that the lastchange timestamp was
	 * preserved correctly when we copied to archive. Our aim is robustness,
	 * so we elect not to do this.
2776
	 *
2777 2778 2779
	 * If we cannot obtain the log file from the archive, however, we will try
	 * to use the XLOGDIR file if it exists.  This is so that we can make use
	 * of log segments that weren't yet transferred to the archive.
2780
	 *
2781 2782 2783 2784
	 * Notice that we don't actually overwrite any files when we copy back
	 * from archive because the recoveryRestoreCommand may inadvertently
	 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
	 * fallback to the segments remaining in current XLOGDIR later. The
B
Bruce Momjian 已提交
2785 2786
	 * copy-from-archive filename is always the same, ensuring that we don't
	 * run out of disk space on long recoveries.
2787
	 */
2788
	snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2789 2790

	/*
2791
	 * Make sure there is no existing file named recovername.
2792 2793 2794 2795 2796 2797
	 */
	if (stat(xlogpath, &stat_buf) != 0)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
2798
					 errmsg("could not stat file \"%s\": %m",
2799 2800 2801 2802 2803 2804 2805
							xlogpath)));
	}
	else
	{
		if (unlink(xlogpath) != 0)
			ereport(FATAL,
					(errcode_for_file_access(),
2806
					 errmsg("could not remove file \"%s\": %m",
2807 2808 2809
							xlogpath)));
	}

2810 2811
	/*
	 * Calculate the archive file cutoff point for use during log shipping
2812 2813
	 * replication. All files earlier than this point can be deleted from the
	 * archive, though there is no requirement to do so.
2814 2815
	 *
	 * We initialise this with the filename of an InvalidXLogRecPtr, which
2816 2817
	 * will prevent the deletion of any WAL files from the archive because of
	 * the alphabetic sorting property of WAL filenames.
2818 2819 2820
	 *
	 * Once we have successfully located the redo pointer of the checkpoint
	 * from which we start recovery we never request a file prior to the redo
2821 2822 2823 2824
	 * pointer of the last restartpoint. When redo begins we know that we have
	 * successfully located it, so there is no need for additional status
	 * flags to signify the point when we can begin deleting WAL files from
	 * the archive.
2825 2826 2827 2828 2829 2830 2831 2832 2833
	 */
	if (InRedo)
	{
		XLByteToSeg(ControlFile->checkPointCopy.redo,
					restartLog, restartSeg);
		XLogFileName(lastRestartPointFname,
					 ControlFile->checkPointCopy.ThisTimeLineID,
					 restartLog, restartSeg);
		/* we shouldn't need anything earlier than last restart point */
2834
		Assert(strcmp(lastRestartPointFname, xlogfname) <= 0);
2835 2836 2837 2838
	}
	else
		XLogFileName(lastRestartPointFname, 0, 0, 0);

2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
	/*
	 * construct the command to be executed
	 */
	dp = xlogRestoreCmd;
	endp = xlogRestoreCmd + MAXPGPATH - 1;
	*endp = '\0';

	for (sp = recoveryRestoreCommand; *sp; sp++)
	{
		if (*sp == '%')
		{
			switch (sp[1])
			{
				case 'p':
2853
					/* %p: relative path of target file */
2854
					sp++;
B
Bruce Momjian 已提交
2855
					StrNCpy(dp, xlogpath, endp - dp);
2856
					make_native_path(dp);
2857 2858 2859 2860 2861
					dp += strlen(dp);
					break;
				case 'f':
					/* %f: filename of desired file */
					sp++;
B
Bruce Momjian 已提交
2862
					StrNCpy(dp, xlogfname, endp - dp);
2863 2864
					dp += strlen(dp);
					break;
2865 2866 2867 2868 2869 2870
				case 'r':
					/* %r: filename of last restartpoint */
					sp++;
					StrNCpy(dp, lastRestartPointFname, endp - dp);
					dp += strlen(dp);
					break;
2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
				case '%':
					/* convert %% to a single % */
					sp++;
					if (dp < endp)
						*dp++ = *sp;
					break;
				default:
					/* otherwise treat the % as not special */
					if (dp < endp)
						*dp++ = *sp;
					break;
			}
		}
		else
		{
			if (dp < endp)
				*dp++ = *sp;
		}
	}
	*dp = '\0';

	ereport(DEBUG3,
B
Bruce Momjian 已提交
2893
			(errmsg_internal("executing restore command \"%s\"",
2894 2895
							 xlogRestoreCmd)));

2896 2897
	/*
	 * Set in_restore_command to tell the signal handler that we should exit
2898
	 * right away on SIGTERM. We know that we're at a safe point to do that.
2899 2900 2901 2902 2903
	 * Check if we had already received the signal, so that we don't miss a
	 * shutdown request received just before this.
	 */
	in_restore_command = true;
	if (shutdown_requested)
2904
		proc_exit(1);
2905

2906
	/*
2907
	 * Copy xlog from archival storage to XLOGDIR
2908 2909
	 */
	rc = system(xlogRestoreCmd);
2910 2911 2912

	in_restore_command = false;

2913 2914
	if (rc == 0)
	{
2915 2916 2917 2918 2919 2920 2921
		/*
		 * command apparently succeeded, but let's make sure the file is
		 * really there now and has the correct size.
		 */
		if (stat(xlogpath, &stat_buf) == 0)
		{
			if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2922
			{
B
Bruce Momjian 已提交
2923
				int			elevel;
2924 2925 2926 2927 2928 2929 2930

				/*
				 * If we find a partial file in standby mode, we assume it's
				 * because it's just being copied to the archive, and keep
				 * trying.
				 *
				 * Otherwise treat a wrong-sized file as FATAL to ensure the
B
Bruce Momjian 已提交
2931
				 * DBA would notice it, but is that too strong? We could try
2932 2933
				 * to plow ahead with a local copy of the file ... but the
				 * problem is that there probably isn't one, and we'd
B
Bruce Momjian 已提交
2934 2935
				 * incorrectly conclude we've reached the end of WAL and we're
				 * done recovering ...
2936 2937 2938 2939 2940 2941
				 */
				if (StandbyMode && stat_buf.st_size < expectedSize)
					elevel = DEBUG1;
				else
					elevel = FATAL;
				ereport(elevel,
2942 2943 2944 2945
						(errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
								xlogfname,
								(unsigned long) stat_buf.st_size,
								(unsigned long) expectedSize)));
2946 2947
				return false;
			}
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
			else
			{
				ereport(LOG,
						(errmsg("restored log file \"%s\" from archive",
								xlogfname)));
				strcpy(path, xlogpath);
				return true;
			}
		}
		else
		{
			/* stat failed */
			if (errno != ENOENT)
				ereport(FATAL,
						(errcode_for_file_access(),
P
Peter Eisentraut 已提交
2963
						 errmsg("could not stat file \"%s\": %m",
2964
								xlogpath)));
2965 2966 2967 2968
		}
	}

	/*
2969
	 * Remember, we rollforward UNTIL the restore fails so failure here is
B
Bruce Momjian 已提交
2970
	 * just part of the process... that makes it difficult to determine
B
Bruce Momjian 已提交
2971 2972 2973
	 * whether the restore failed because there isn't an archive to restore,
	 * or because the administrator has specified the restore program
	 * incorrectly.  We have to assume the former.
2974 2975
	 *
	 * However, if the failure was due to any sort of signal, it's best to
B
Bruce Momjian 已提交
2976 2977 2978
	 * punt and abort recovery.  (If we "return false" here, upper levels will
	 * assume that recovery is complete and start up the database!) It's
	 * essential to abort on child SIGINT and SIGQUIT, because per spec
2979
	 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2980 2981 2982 2983 2984
	 * those it's a good bet we should have gotten it too.
	 *
	 * On SIGTERM, assume we have received a fast shutdown request, and exit
	 * cleanly. It's pure chance whether we receive the SIGTERM first, or the
	 * child process. If we receive it first, the signal handler will call
2985 2986 2987
	 * proc_exit, otherwise we do it here. If we or the child process received
	 * SIGTERM for any other reason than a fast shutdown request, postmaster
	 * will perform an immediate shutdown when it sees us exiting
2988
	 * unexpectedly.
2989
	 *
B
Bruce Momjian 已提交
2990 2991 2992 2993
	 * Per the Single Unix Spec, shells report exit status > 128 when a called
	 * command died on a signal.  Also, 126 and 127 are used to report
	 * problems such as an unfindable command; treat those as fatal errors
	 * too.
2994
	 */
2995
	if (WIFSIGNALED(rc) && WTERMSIG(rc) == SIGTERM)
2996
		proc_exit(1);
2997

2998 2999 3000
	signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;

	ereport(signaled ? FATAL : DEBUG2,
B
Bruce Momjian 已提交
3001 3002
		(errmsg("could not restore file \"%s\" from archive: return code %d",
				xlogfname, rc)));
3003

3004
not_available:
B
Bruce Momjian 已提交
3005

3006
	/*
B
Bruce Momjian 已提交
3007 3008
	 * if an archived file is not available, there might still be a version of
	 * this file in XLOGDIR, so return that as the filename to open.
3009
	 *
B
Bruce Momjian 已提交
3010 3011
	 * In many recovery scenarios we expect this to fail also, but if so that
	 * just means we've reached the end of WAL.
3012
	 */
3013
	snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
3014
	return false;
3015 3016
}

3017
/*
3018 3019 3020 3021 3022 3023 3024 3025
 * Attempt to execute an external shell command during recovery.
 *
 * 'command' is the shell command to be executed, 'commandName' is a
 * human-readable name describing the command emitted in the logs. If
 * 'failonSignal' is true and the command is killed by a signal, a FATAL
 * error is thrown. Otherwise a WARNING is emitted.
 *
 * This is currently used for restore_end_command and restartpoint_command.
3026 3027
 */
static void
3028
ExecuteRecoveryCommand(char *command, char *commandName, bool failOnSignal)
3029
{
3030
	char		xlogRecoveryCmd[MAXPGPATH];
3031 3032 3033 3034 3035 3036 3037 3038 3039
	char		lastRestartPointFname[MAXPGPATH];
	char	   *dp;
	char	   *endp;
	const char *sp;
	int			rc;
	bool		signaled;
	uint32		restartLog;
	uint32		restartSeg;

3040
	Assert(command && commandName);
3041 3042 3043

	/*
	 * Calculate the archive file cutoff point for use during log shipping
3044 3045
	 * replication. All files earlier than this point can be deleted from the
	 * archive, though there is no requirement to do so.
3046
	 */
3047 3048 3049 3050 3051 3052 3053
	LWLockAcquire(ControlFileLock, LW_SHARED);
	XLByteToSeg(ControlFile->checkPointCopy.redo,
				restartLog, restartSeg);
	XLogFileName(lastRestartPointFname,
				 ControlFile->checkPointCopy.ThisTimeLineID,
				 restartLog, restartSeg);
	LWLockRelease(ControlFileLock);
3054 3055 3056 3057

	/*
	 * construct the command to be executed
	 */
3058 3059
	dp = xlogRecoveryCmd;
	endp = xlogRecoveryCmd + MAXPGPATH - 1;
3060 3061
	*endp = '\0';

3062
	for (sp = command; *sp; sp++)
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
	{
		if (*sp == '%')
		{
			switch (sp[1])
			{
				case 'r':
					/* %r: filename of last restartpoint */
					sp++;
					StrNCpy(dp, lastRestartPointFname, endp - dp);
					dp += strlen(dp);
					break;
				case '%':
					/* convert %% to a single % */
					sp++;
					if (dp < endp)
						*dp++ = *sp;
					break;
				default:
					/* otherwise treat the % as not special */
					if (dp < endp)
						*dp++ = *sp;
					break;
			}
		}
		else
		{
			if (dp < endp)
				*dp++ = *sp;
		}
	}
	*dp = '\0';

	ereport(DEBUG3,
3096
			(errmsg_internal("executing %s \"%s\"", commandName, command)));
3097 3098

	/*
T
Tom Lane 已提交
3099
	 * execute the constructed command
3100
	 */
3101
	rc = system(xlogRecoveryCmd);
3102 3103 3104 3105
	if (rc != 0)
	{
		/*
		 * If the failure was due to any sort of signal, it's best to punt and
3106
		 * abort recovery. See also detailed comments on signals in
3107 3108 3109 3110
		 * RestoreArchivedFile().
		 */
		signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;

3111 3112 3113 3114 3115 3116 3117
		/*
		 * translator: First %s represents a recovery.conf parameter name like
		 * "recovery_end_command", and the 2nd is the value of that parameter.
		 */
		ereport((signaled && failOnSignal) ? FATAL : WARNING,
				(errmsg("%s \"%s\": return code %d", commandName,
						command, rc)));
3118 3119 3120
	}
}

V
Vadim B. Mikheev 已提交
3121
/*
3122 3123 3124 3125 3126 3127 3128 3129
 * Preallocate log files beyond the specified log endpoint.
 *
 * XXX this is currently extremely conservative, since it forces only one
 * future log segment to exist, and even that only if we are 75% done with
 * the current one.  This is only appropriate for very low-WAL-volume systems.
 * High-volume systems will be OK once they've built up a sufficient set of
 * recycled log segments, but the startup transient is likely to include
 * a lot of segment creations by foreground processes, which is not so good.
T
Tom Lane 已提交
3130
 */
3131
static void
T
Tom Lane 已提交
3132 3133 3134 3135 3136
PreallocXlogFiles(XLogRecPtr endptr)
{
	uint32		_logId;
	uint32		_logSeg;
	int			lf;
3137
	bool		use_existent;
T
Tom Lane 已提交
3138 3139

	XLByteToPrevSeg(endptr, _logId, _logSeg);
B
Bruce Momjian 已提交
3140
	if ((endptr.xrecoff - 1) % XLogSegSize >=
B
Bruce Momjian 已提交
3141
		(uint32) (0.75 * XLogSegSize))
T
Tom Lane 已提交
3142 3143
	{
		NextLogSeg(_logId, _logSeg);
3144 3145
		use_existent = true;
		lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
T
Tom Lane 已提交
3146
		close(lf);
3147
		if (!use_existent)
3148
			CheckpointStats.ckpt_segs_added++;
T
Tom Lane 已提交
3149 3150 3151 3152
	}
}

/*
3153
 * Recycle or remove all log files older or equal to passed log/seg#
3154 3155 3156
 *
 * endptr is current (or recent) end of xlog; this is used to determine
 * whether we want to recycle rather than delete no-longer-wanted log files.
V
Vadim B. Mikheev 已提交
3157 3158
 */
static void
3159
RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
V
Vadim B. Mikheev 已提交
3160
{
3161 3162
	uint32		endlogId;
	uint32		endlogSeg;
3163
	int			max_advance;
B
Bruce Momjian 已提交
3164 3165
	DIR		   *xldir;
	struct dirent *xlde;
3166
	char		lastoff[MAXFNAMELEN];
B
Bruce Momjian 已提交
3167
	char		path[MAXPGPATH];
B
Bruce Momjian 已提交
3168

3169 3170 3171
#ifdef WIN32
	char		newpath[MAXPGPATH];
#endif
3172
	struct stat statbuf;
V
Vadim B. Mikheev 已提交
3173

3174 3175 3176 3177
	/*
	 * Initialize info about where to try to recycle to.  We allow recycling
	 * segments up to XLOGfileslop segments beyond the current XLOG location.
	 */
3178
	XLByteToPrevSeg(endptr, endlogId, endlogSeg);
3179
	max_advance = XLOGfileslop;
V
Vadim B. Mikheev 已提交
3180

3181
	xldir = AllocateDir(XLOGDIR);
V
Vadim B. Mikheev 已提交
3182
	if (xldir == NULL)
3183
		ereport(ERROR,
3184
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
3185 3186
				 errmsg("could not open transaction log directory \"%s\": %m",
						XLOGDIR)));
V
Vadim B. Mikheev 已提交
3187

3188
	XLogFileName(lastoff, ThisTimeLineID, log, seg);
V
Vadim B. Mikheev 已提交
3189

3190
	while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
V
Vadim B. Mikheev 已提交
3191
	{
3192
		/*
3193
		 * We ignore the timeline part of the XLOG segment identifiers in
B
Bruce Momjian 已提交
3194 3195 3196 3197 3198
		 * deciding whether a segment is still needed.	This ensures that we
		 * won't prematurely remove a segment from a parent timeline. We could
		 * probably be a little more proactive about removing segments of
		 * non-parent timelines, but that would be a whole lot more
		 * complicated.
3199
		 *
B
Bruce Momjian 已提交
3200 3201
		 * We use the alphanumeric sorting property of the filenames to decide
		 * which ones are earlier than the lastoff segment.
3202
		 */
3203 3204 3205
		if (strlen(xlde->d_name) == 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
V
Vadim B. Mikheev 已提交
3206
		{
3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217
			/*
			 * Normally we don't delete old XLOG files during recovery to
			 * avoid accidentally deleting a file that looks stale due to a
			 * bug or hardware issue, but in fact contains important data.
			 * During streaming recovery, however, we will eventually fill the
			 * disk if we never clean up, so we have to. That's not an issue
			 * with file-based archive recovery because in that case we
			 * restore one XLOG file at a time, on-demand, and with a
			 * different filename that can't be confused with regular XLOG
			 * files.
			 */
3218
			if (WalRcvInProgress() || XLogArchiveCheckDone(xlde->d_name))
3219
			{
3220
				snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3221

3222
				/*
B
Bruce Momjian 已提交
3223
				 * Before deleting the file, see if it can be recycled as a
3224 3225 3226
				 * future log segment. Only recycle normal files, pg_standby
				 * for example can create symbolic links pointing to a
				 * separate archive directory.
3227
				 */
3228 3229 3230
				if (lstat(path, &statbuf) == 0 && S_ISREG(statbuf.st_mode) &&
					InstallXLogFileSegment(&endlogId, &endlogSeg, path,
										   true, &max_advance, true))
3231
				{
3232
					ereport(DEBUG2,
B
Bruce Momjian 已提交
3233 3234
							(errmsg("recycled transaction log file \"%s\"",
									xlde->d_name)));
3235
					CheckpointStats.ckpt_segs_recycled++;
3236 3237 3238 3239 3240 3241
					/* Needn't recheck that slot on future iterations */
					if (max_advance > 0)
					{
						NextLogSeg(endlogId, endlogSeg);
						max_advance--;
					}
3242 3243 3244 3245
				}
				else
				{
					/* No need for any more future segments... */
B
Bruce Momjian 已提交
3246
					int			rc;
3247

3248
					ereport(DEBUG2,
B
Bruce Momjian 已提交
3249 3250
							(errmsg("removing transaction log file \"%s\"",
									xlde->d_name)));
3251 3252

#ifdef WIN32
B
Bruce Momjian 已提交
3253

3254 3255 3256 3257
					/*
					 * On Windows, if another process (e.g another backend)
					 * holds the file open in FILE_SHARE_DELETE mode, unlink
					 * will succeed, but the file will still show up in
B
Bruce Momjian 已提交
3258 3259 3260 3261
					 * directory listing until the last handle is closed. To
					 * avoid confusing the lingering deleted file for a live
					 * WAL file that needs to be archived, rename it before
					 * deleting it.
3262 3263 3264 3265 3266 3267 3268
					 *
					 * If another process holds the file open without
					 * FILE_SHARE_DELETE flag, rename will fail. We'll try
					 * again at the next checkpoint.
					 */
					snprintf(newpath, MAXPGPATH, "%s.deleted", path);
					if (rename(path, newpath) != 0)
3269 3270
					{
						ereport(LOG,
3271
								(errcode_for_file_access(),
3272
								 errmsg("could not rename old transaction log file \"%s\": %m",
3273
										path)));
3274 3275
						continue;
					}
3276 3277 3278 3279 3280
					rc = unlink(newpath);
#else
					rc = unlink(path);
#endif
					if (rc != 0)
3281 3282
					{
						ereport(LOG,
3283 3284 3285
								(errcode_for_file_access(),
								 errmsg("could not remove old transaction log file \"%s\": %m",
										path)));
3286 3287
						continue;
					}
3288
					CheckpointStats.ckpt_segs_removed++;
3289
				}
3290 3291

				XLogArchiveCleanup(xlde->d_name);
3292
			}
V
Vadim B. Mikheev 已提交
3293 3294
		}
	}
B
Bruce Momjian 已提交
3295

3296
	FreeDir(xldir);
V
Vadim B. Mikheev 已提交
3297 3298
}

3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
/*
 * Verify whether pg_xlog and pg_xlog/archive_status exist.
 * If the latter does not exist, recreate it.
 *
 * It is not the goal of this function to verify the contents of these
 * directories, but to help in cases where someone has performed a cluster
 * copy for PITR purposes but omitted pg_xlog from the copy.
 *
 * We could also recreate pg_xlog if it doesn't exist, but a deliberate
 * policy decision was made not to.  It is fairly common for pg_xlog to be
 * a symlink, and if that was the DBA's intent then automatically making a
 * plain directory would result in degraded performance with no notice.
 */
static void
ValidateXLOGDirectoryStructure(void)
{
	char		path[MAXPGPATH];
3316
	struct stat stat_buf;
3317 3318 3319 3320

	/* Check for pg_xlog; if it doesn't exist, error out */
	if (stat(XLOGDIR, &stat_buf) != 0 ||
		!S_ISDIR(stat_buf.st_mode))
3321
		ereport(FATAL,
3322 3323 3324 3325 3326 3327 3328 3329 3330
				(errmsg("required WAL directory \"%s\" does not exist",
						XLOGDIR)));

	/* Check for archive_status */
	snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
	if (stat(path, &stat_buf) == 0)
	{
		/* Check for weird cases where it exists but isn't a directory */
		if (!S_ISDIR(stat_buf.st_mode))
3331
			ereport(FATAL,
3332 3333 3334 3335 3336 3337 3338 3339
					(errmsg("required WAL directory \"%s\" does not exist",
							path)));
	}
	else
	{
		ereport(LOG,
				(errmsg("creating missing WAL directory \"%s\"", path)));
		if (mkdir(path, 0700) < 0)
3340
			ereport(FATAL,
3341 3342 3343 3344 3345
					(errmsg("could not create missing directory \"%s\": %m",
							path)));
	}
}

3346
/*
3347 3348 3349
 * Remove previous backup history files.  This also retries creation of
 * .ready files for any backup history files for which XLogArchiveNotify
 * failed earlier.
3350 3351
 */
static void
3352
CleanupBackupHistory(void)
3353 3354 3355 3356 3357
{
	DIR		   *xldir;
	struct dirent *xlde;
	char		path[MAXPGPATH];

3358
	xldir = AllocateDir(XLOGDIR);
3359 3360 3361
	if (xldir == NULL)
		ereport(ERROR,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
3362 3363
				 errmsg("could not open transaction log directory \"%s\": %m",
						XLOGDIR)));
3364

3365
	while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3366 3367 3368 3369 3370 3371
	{
		if (strlen(xlde->d_name) > 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
				   ".backup") == 0)
		{
3372
			if (XLogArchiveCheckDone(xlde->d_name))
3373 3374
			{
				ereport(DEBUG2,
B
Bruce Momjian 已提交
3375 3376
				(errmsg("removing transaction log backup history file \"%s\"",
						xlde->d_name)));
3377
				snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3378 3379 3380 3381 3382 3383 3384 3385 3386
				unlink(path);
				XLogArchiveCleanup(xlde->d_name);
			}
		}
	}

	FreeDir(xldir);
}

T
Tom Lane 已提交
3387 3388 3389 3390
/*
 * Restore the backup blocks present in an XLOG record, if any.
 *
 * We assume all of the record has been read into memory at *record.
3391 3392 3393 3394 3395 3396 3397 3398 3399
 *
 * Note: when a backup block is available in XLOG, we restore it
 * unconditionally, even if the page in the database appears newer.
 * This is to protect ourselves against database pages that were partially
 * or incorrectly written during a crash.  We assume that the XLOG data
 * must be good because it has passed a CRC check, while the database
 * page might not be.  This will force us to replay all subsequent
 * modifications of the page that appear in XLOG, rather than possibly
 * ignoring them as already applied, but that's not a huge drawback.
3400 3401
 *
 * If 'cleanup' is true, a cleanup lock is used when restoring blocks.
3402 3403 3404 3405 3406
 * Otherwise, a normal exclusive lock is used.	During crash recovery, that's
 * just pro forma because there can't be any regular backends in the system,
 * but in hot standby mode the distinction is important. The 'cleanup'
 * argument applies to all backup blocks in the WAL record, that suffices for
 * now.
T
Tom Lane 已提交
3407
 */
3408 3409
void
RestoreBkpBlocks(XLogRecPtr lsn, XLogRecord *record, bool cleanup)
3410 3411 3412 3413 3414 3415 3416
{
	Buffer		buffer;
	Page		page;
	BkpBlock	bkpb;
	char	   *blk;
	int			i;

3417 3418 3419
	if (!(record->xl_info & XLR_BKP_BLOCK_MASK))
		return;

B
Bruce Momjian 已提交
3420
	blk = (char *) XLogRecGetData(record) + record->xl_len;
T
Tom Lane 已提交
3421
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3422
	{
T
Tom Lane 已提交
3423
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3424 3425
			continue;

3426
		memcpy(&bkpb, blk, sizeof(BkpBlock));
3427 3428
		blk += sizeof(BkpBlock);

3429 3430
		buffer = XLogReadBufferExtended(bkpb.node, bkpb.fork, bkpb.block,
										RBM_ZERO);
3431
		Assert(BufferIsValid(buffer));
3432 3433 3434 3435 3436
		if (cleanup)
			LockBufferForCleanup(buffer);
		else
			LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);

3437
		page = (Page) BufferGetPage(buffer);
3438

3439
		if (bkpb.hole_length == 0)
3440
		{
3441 3442 3443 3444 3445 3446 3447 3448 3449 3450
			memcpy((char *) page, blk, BLCKSZ);
		}
		else
		{
			/* must zero-fill the hole */
			MemSet((char *) page, 0, BLCKSZ);
			memcpy((char *) page, blk, bkpb.hole_offset);
			memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
				   blk + bkpb.hole_offset,
				   BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
3451 3452
		}

3453 3454
		PageSetLSN(page, lsn);
		PageSetTLI(page, ThisTimeLineID);
3455 3456
		MarkBufferDirty(buffer);
		UnlockReleaseBuffer(buffer);
3457

3458
		blk += BLCKSZ - bkpb.hole_length;
3459 3460 3461
	}
}

T
Tom Lane 已提交
3462 3463 3464 3465 3466 3467 3468
/*
 * CRC-check an XLOG record.  We do not believe the contents of an XLOG
 * record (other than to the minimal extent of computing the amount of
 * data to read in) until we've checked the CRCs.
 *
 * We assume all of the record has been read into memory at *record.
 */
3469 3470 3471
static bool
RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
{
3472
	pg_crc32	crc;
3473 3474
	int			i;
	uint32		len = record->xl_len;
3475
	BkpBlock	bkpb;
3476 3477
	char	   *blk;

3478 3479 3480
	/* First the rmgr data */
	INIT_CRC32(crc);
	COMP_CRC32(crc, XLogRecGetData(record), len);
3481

3482
	/* Add in the backup blocks, if any */
B
Bruce Momjian 已提交
3483
	blk = (char *) XLogRecGetData(record) + len;
T
Tom Lane 已提交
3484
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3485
	{
B
Bruce Momjian 已提交
3486
		uint32		blen;
3487

T
Tom Lane 已提交
3488
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3489 3490
			continue;

3491 3492
		memcpy(&bkpb, blk, sizeof(BkpBlock));
		if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
3493
		{
3494
			ereport(emode,
3495 3496 3497
					(errmsg("incorrect hole size in record at %X/%X",
							recptr.xlogid, recptr.xrecoff)));
			return false;
3498
		}
3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520
		blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
		COMP_CRC32(crc, blk, blen);
		blk += blen;
	}

	/* Check that xl_tot_len agrees with our calculation */
	if (blk != (char *) record + record->xl_tot_len)
	{
		ereport(emode,
				(errmsg("incorrect total length in record at %X/%X",
						recptr.xlogid, recptr.xrecoff)));
		return false;
	}

	/* Finally include the record header */
	COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
			   SizeOfXLogRecord - sizeof(pg_crc32));
	FIN_CRC32(crc);

	if (!EQ_CRC32(record->xl_crc, crc))
	{
		ereport(emode,
B
Bruce Momjian 已提交
3521 3522
		(errmsg("incorrect resource manager data checksum in record at %X/%X",
				recptr.xlogid, recptr.xrecoff)));
3523
		return false;
3524 3525
	}

3526
	return true;
3527 3528
}

T
Tom Lane 已提交
3529 3530 3531 3532 3533 3534
/*
 * Attempt to read an XLOG record.
 *
 * If RecPtr is not NULL, try to read a record at that position.  Otherwise
 * try to read a record just after the last one previously read.
 *
3535
 * If no valid record is available, returns NULL, or fails if emode is PANIC.
3536
 * (emode must be either PANIC, LOG)
T
Tom Lane 已提交
3537
 *
3538 3539
 * The record is copied into readRecordBuf, so that on successful return,
 * the returned record pointer always points there.
T
Tom Lane 已提交
3540
 */
3541
static XLogRecord *
3542
ReadRecord(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt)
3543
{
3544
	XLogRecord *record;
3545
	char	   *buffer;
3546
	XLogRecPtr	tmpRecPtr = EndRecPtr;
3547
	bool		randAccess = false;
T
Tom Lane 已提交
3548 3549
	uint32		len,
				total_len;
3550 3551
	uint32		targetRecOff;
	uint32		pageHeaderSize;
T
Tom Lane 已提交
3552 3553 3554 3555

	if (readBuf == NULL)
	{
		/*
B
Bruce Momjian 已提交
3556 3557 3558 3559 3560
		 * First time through, permanently allocate readBuf.  We do it this
		 * way, rather than just making a static array, for two reasons: (1)
		 * no need to waste the storage in most instantiations of the backend;
		 * (2) a static char array isn't guaranteed to have any particular
		 * alignment, whereas malloc() will provide MAXALIGN'd storage.
T
Tom Lane 已提交
3561
		 */
3562
		readBuf = (char *) malloc(XLOG_BLCKSZ);
T
Tom Lane 已提交
3563 3564
		Assert(readBuf != NULL);
	}
3565

T
Tom Lane 已提交
3566
	if (RecPtr == NULL)
3567
	{
3568
		RecPtr = &tmpRecPtr;
3569 3570

		/*
B
Bruce Momjian 已提交
3571 3572
		 * Align recptr to next page if no more records can fit on the current
		 * page.
3573
		 */
3574 3575
		if (XLOG_BLCKSZ - (RecPtr->xrecoff % XLOG_BLCKSZ) < SizeOfXLogRecord)
		{
3576
			NextLogPage(tmpRecPtr);
3577 3578
			/* We will account for page header size below */
		}
3579 3580 3581 3582 3583 3584

		if (tmpRecPtr.xrecoff >= XLogFileSize)
		{
			(tmpRecPtr.xlogid)++;
			tmpRecPtr.xrecoff = 0;
		}
3585 3586 3587 3588 3589 3590 3591
	}
	else
	{
		if (!XRecOffIsValid(RecPtr->xrecoff))
			ereport(PANIC,
					(errmsg("invalid record offset at %X/%X",
							RecPtr->xlogid, RecPtr->xrecoff)));
B
Bruce Momjian 已提交
3592

3593
		/*
B
Bruce Momjian 已提交
3594 3595 3596 3597 3598
		 * Since we are going to a random position in WAL, forget any prior
		 * state about what timeline we were in, and allow it to be any
		 * timeline in expectedTLIs.  We also set a flag to allow curFileTLI
		 * to go backwards (but we can't reset that variable right here, since
		 * we might not change files at all).
3599 3600 3601
		 */
		lastPageTLI = 0;		/* see comment in ValidXLOGHeader */
		randAccess = true;		/* allow curFileTLI to go backwards too */
3602 3603
	}

3604 3605 3606
	/* This is the first try to read this page. */
	failedSources = 0;
retry:
3607 3608 3609
	/* Read the page containing the record */
	if (!XLogPageRead(RecPtr, emode, fetching_ckpt, randAccess))
		return NULL;
3610

3611
	pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3612
	targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
3613 3614 3615
	if (targetRecOff == 0)
	{
		/*
B
Bruce Momjian 已提交
3616 3617 3618
		 * Can only get here in the continuing-from-prev-page case, because
		 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
		 * to skip over the new page's header.
3619 3620 3621 3622 3623 3624
		 */
		tmpRecPtr.xrecoff += pageHeaderSize;
		targetRecOff = pageHeaderSize;
	}
	else if (targetRecOff < pageHeaderSize)
	{
3625
		ereport(emode_for_corrupt_record(emode),
3626 3627 3628 3629
				(errmsg("invalid record offset at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
		goto next_record_is_invalid;
	}
T
Tom Lane 已提交
3630
	if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3631
		targetRecOff == pageHeaderSize)
3632
	{
3633
		ereport(emode_for_corrupt_record(emode),
3634 3635
				(errmsg("contrecord is requested by %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
3636 3637
		goto next_record_is_invalid;
	}
3638
	record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3639

T
Tom Lane 已提交
3640
	/*
B
Bruce Momjian 已提交
3641 3642
	 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
	 * required.
T
Tom Lane 已提交
3643
	 */
3644 3645 3646 3647
	if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
	{
		if (record->xl_len != 0)
		{
3648
			ereport(emode_for_corrupt_record(emode),
3649 3650 3651 3652 3653 3654
					(errmsg("invalid xlog switch record at %X/%X",
							RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
	}
	else if (record->xl_len == 0)
3655
	{
3656
		ereport(emode_for_corrupt_record(emode),
3657 3658
				(errmsg("record with zero length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
3659 3660
		goto next_record_is_invalid;
	}
3661 3662 3663 3664
	if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
		record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
		XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
	{
3665
		ereport(emode_for_corrupt_record(emode),
3666 3667 3668 3669
				(errmsg("invalid record length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
		goto next_record_is_invalid;
	}
3670 3671
	if (record->xl_rmid > RM_MAX_ID)
	{
3672
		ereport(emode_for_corrupt_record(emode),
3673
				(errmsg("invalid resource manager ID %u at %X/%X",
B
Bruce Momjian 已提交
3674
						record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3675 3676
		goto next_record_is_invalid;
	}
3677 3678 3679
	if (randAccess)
	{
		/*
B
Bruce Momjian 已提交
3680 3681
		 * We can't exactly verify the prev-link, but surely it should be less
		 * than the record's own address.
3682 3683 3684
		 */
		if (!XLByteLT(record->xl_prev, *RecPtr))
		{
3685
			ereport(emode_for_corrupt_record(emode),
3686 3687 3688 3689 3690 3691 3692 3693 3694
					(errmsg("record with incorrect prev-link %X/%X at %X/%X",
							record->xl_prev.xlogid, record->xl_prev.xrecoff,
							RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
	}
	else
	{
		/*
B
Bruce Momjian 已提交
3695 3696 3697
		 * Record's prev-link should exactly match our previous location. This
		 * check guards against torn WAL pages where a stale but valid-looking
		 * WAL record starts on a sector boundary.
3698 3699 3700
		 */
		if (!XLByteEQ(record->xl_prev, ReadRecPtr))
		{
3701
			ereport(emode_for_corrupt_record(emode),
3702 3703 3704 3705 3706 3707
					(errmsg("record with incorrect prev-link %X/%X at %X/%X",
							record->xl_prev.xlogid, record->xl_prev.xrecoff,
							RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
	}
B
Bruce Momjian 已提交
3708

T
Tom Lane 已提交
3709
	/*
B
Bruce Momjian 已提交
3710
	 * Allocate or enlarge readRecordBuf as needed.  To avoid useless small
3711 3712 3713 3714
	 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
	 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with.  (That is
	 * enough for all "normal" records, but very large commit or abort records
	 * might need more space.)
T
Tom Lane 已提交
3715
	 */
3716
	total_len = record->xl_tot_len;
3717
	if (total_len > readRecordBufSize)
3718
	{
3719 3720
		uint32		newSize = total_len;

3721 3722
		newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
		newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3723 3724 3725 3726 3727 3728 3729
		if (readRecordBuf)
			free(readRecordBuf);
		readRecordBuf = (char *) malloc(newSize);
		if (!readRecordBuf)
		{
			readRecordBufSize = 0;
			/* We treat this as a "bogus data" condition */
3730
			ereport(emode_for_corrupt_record(emode),
3731 3732 3733 3734 3735
					(errmsg("record length %u at %X/%X too long",
							total_len, RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
		readRecordBufSize = newSize;
3736
	}
3737 3738

	buffer = readRecordBuf;
3739
	len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
T
Tom Lane 已提交
3740
	if (total_len > len)
3741
	{
T
Tom Lane 已提交
3742 3743
		/* Need to reassemble record */
		XLogContRecord *contrecord;
3744
		XLogRecPtr	pagelsn;
B
Bruce Momjian 已提交
3745
		uint32		gotlen = len;
3746

3747 3748 3749 3750
		/* Initialize pagelsn to the beginning of the page this record is on */
		pagelsn = *RecPtr;
		pagelsn.xrecoff = (pagelsn.xrecoff / XLOG_BLCKSZ) * XLOG_BLCKSZ;

T
Tom Lane 已提交
3751
		memcpy(buffer, record, len);
3752
		record = (XLogRecord *) buffer;
T
Tom Lane 已提交
3753
		buffer += len;
3754
		for (;;)
3755
		{
3756 3757 3758
			/* Calculate pointer to beginning of next page */
			pagelsn.xrecoff += XLOG_BLCKSZ;
			if (pagelsn.xrecoff >= XLogFileSize)
3759
			{
3760 3761
				(pagelsn.xlogid)++;
				pagelsn.xrecoff = 0;
3762
			}
3763 3764 3765
			/* Wait for the next page to become available */
			if (!XLogPageRead(&pagelsn, emode, false, false))
				return NULL;
3766

3767
			/* Check that the continuation record looks valid */
T
Tom Lane 已提交
3768
			if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3769
			{
3770
				ereport(emode_for_corrupt_record(emode),
3771 3772
						(errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
								readId, readSeg, readOff)));
3773 3774
				goto next_record_is_invalid;
			}
3775 3776
			pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
			contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
B
Bruce Momjian 已提交
3777
			if (contrecord->xl_rem_len == 0 ||
T
Tom Lane 已提交
3778
				total_len != (contrecord->xl_rem_len + gotlen))
3779
			{
3780
				ereport(emode_for_corrupt_record(emode),
3781 3782 3783
						(errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
								contrecord->xl_rem_len,
								readId, readSeg, readOff)));
3784 3785
				goto next_record_is_invalid;
			}
3786
			len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
T
Tom Lane 已提交
3787
			if (contrecord->xl_rem_len > len)
3788
			{
B
Bruce Momjian 已提交
3789
				memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
T
Tom Lane 已提交
3790 3791 3792 3793 3794 3795 3796 3797
				gotlen += len;
				buffer += len;
				continue;
			}
			memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
				   contrecord->xl_rem_len);
			break;
		}
3798
		if (!RecordIsValid(record, *RecPtr, emode_for_corrupt_record(emode)))
T
Tom Lane 已提交
3799
			goto next_record_is_invalid;
3800
		pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
T
Tom Lane 已提交
3801 3802
		EndRecPtr.xlogid = readId;
		EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3803 3804
			pageHeaderSize +
			MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3805

T
Tom Lane 已提交
3806
		ReadRecPtr = *RecPtr;
3807
		/* needn't worry about XLOG SWITCH, it can't cross page boundaries */
T
Tom Lane 已提交
3808
		return record;
3809 3810
	}

T
Tom Lane 已提交
3811
	/* Record does not cross a page boundary */
3812
	if (!RecordIsValid(record, *RecPtr, emode_for_corrupt_record(emode)))
T
Tom Lane 已提交
3813 3814 3815
		goto next_record_is_invalid;
	EndRecPtr.xlogid = RecPtr->xlogid;
	EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3816

T
Tom Lane 已提交
3817 3818
	ReadRecPtr = *RecPtr;
	memcpy(buffer, record, total_len);
B
Bruce Momjian 已提交
3819

3820 3821 3822 3823 3824 3825 3826 3827
	/*
	 * Special processing if it's an XLOG SWITCH record
	 */
	if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
	{
		/* Pretend it extends to end of segment */
		EndRecPtr.xrecoff += XLogSegSize - 1;
		EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
B
Bruce Momjian 已提交
3828

3829
		/*
B
Bruce Momjian 已提交
3830 3831 3832
		 * Pretend that readBuf contains the last page of the segment. This is
		 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
		 * segment.
3833 3834 3835
		 */
		readOff = XLogSegSize - XLOG_BLCKSZ;
	}
T
Tom Lane 已提交
3836
	return (XLogRecord *) buffer;
3837

3838 3839 3840
next_record_is_invalid:
	failedSources |= readSource;

3841 3842 3843 3844 3845
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
3846 3847 3848 3849 3850 3851

	/* In standby-mode, keep trying */
	if (StandbyMode)
		goto retry;
	else
		return NULL;
3852 3853
}

3854 3855 3856 3857
/*
 * Check whether the xlog header of a page just read in looks valid.
 *
 * This is just a convenience subroutine to avoid duplicated code in
B
Bruce Momjian 已提交
3858
 * ReadRecord.	It's not intended for use from anywhere else.
3859 3860
 */
static bool
3861
ValidXLOGHeader(XLogPageHeader hdr, int emode)
3862
{
3863 3864
	XLogRecPtr	recaddr;

3865 3866
	if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
	{
3867 3868 3869
		ereport(emode,
				(errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
						hdr->xlp_magic, readId, readSeg, readOff)));
3870 3871 3872 3873
		return false;
	}
	if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
	{
3874 3875 3876
		ereport(emode,
				(errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
						hdr->xlp_info, readId, readSeg, readOff)));
3877 3878
		return false;
	}
3879
	if (hdr->xlp_info & XLP_LONG_HEADER)
3880
	{
3881
		XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
B
Bruce Momjian 已提交
3882

3883
		if (longhdr->xlp_sysid != ControlFile->system_identifier)
3884
		{
3885 3886
			char		fhdrident_str[32];
			char		sysident_str[32];
3887

3888
			/*
B
Bruce Momjian 已提交
3889 3890
			 * Format sysids separately to keep platform-dependent format code
			 * out of the translatable message string.
3891 3892 3893 3894 3895 3896
			 */
			snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
					 longhdr->xlp_sysid);
			snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
					 ControlFile->system_identifier);
			ereport(emode,
P
Peter Eisentraut 已提交
3897 3898
					(errmsg("WAL file is from different database system"),
					 errdetail("WAL file database system identifier is %s, pg_control database system identifier is %s.",
B
Bruce Momjian 已提交
3899
							   fhdrident_str, sysident_str)));
3900 3901 3902 3903 3904
			return false;
		}
		if (longhdr->xlp_seg_size != XLogSegSize)
		{
			ereport(emode,
P
Peter Eisentraut 已提交
3905
					(errmsg("WAL file is from different database system"),
B
Bruce Momjian 已提交
3906
					 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3907 3908
			return false;
		}
3909 3910 3911
		if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
		{
			ereport(emode,
P
Peter Eisentraut 已提交
3912
					(errmsg("WAL file is from different database system"),
3913 3914 3915
					 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
			return false;
		}
3916
	}
3917 3918 3919 3920 3921 3922 3923 3924 3925
	else if (readOff == 0)
	{
		/* hmm, first page of file doesn't have a long header? */
		ereport(emode,
				(errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
						hdr->xlp_info, readId, readSeg, readOff)));
		return false;
	}

3926 3927 3928 3929 3930 3931
	recaddr.xlogid = readId;
	recaddr.xrecoff = readSeg * XLogSegSize + readOff;
	if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
	{
		ereport(emode,
				(errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
B
Bruce Momjian 已提交
3932
						hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953
						readId, readSeg, readOff)));
		return false;
	}

	/*
	 * Check page TLI is one of the expected values.
	 */
	if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
	{
		ereport(emode,
				(errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
						hdr->xlp_tli,
						readId, readSeg, readOff)));
		return false;
	}

	/*
	 * Since child timelines are always assigned a TLI greater than their
	 * immediate parent's TLI, we should never see TLI go backwards across
	 * successive pages of a consistent WAL sequence.
	 *
B
Bruce Momjian 已提交
3954 3955 3956
	 * Of course this check should only be applied when advancing sequentially
	 * across pages; therefore ReadRecord resets lastPageTLI to zero when
	 * going to a random page.
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973
	 */
	if (hdr->xlp_tli < lastPageTLI)
	{
		ereport(emode,
				(errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
						hdr->xlp_tli, lastPageTLI,
						readId, readSeg, readOff)));
		return false;
	}
	lastPageTLI = hdr->xlp_tli;
	return true;
}

/*
 * Try to read a timeline's history file.
 *
 * If successful, return the list of component TLIs (the given TLI followed by
B
Bruce Momjian 已提交
3974
 * its ancestor TLIs).	If we can't find the history file, assume that the
3975 3976 3977 3978 3979 3980 3981 3982 3983 3984
 * timeline has no parents, and return a list of just the specified timeline
 * ID.
 */
static List *
readTimeLineHistory(TimeLineID targetTLI)
{
	List	   *result;
	char		path[MAXPGPATH];
	char		histfname[MAXFNAMELEN];
	char		fline[MAXPGPATH];
B
Bruce Momjian 已提交
3985
	FILE	   *fd;
3986

3987 3988 3989 3990
	/* Timeline 1 does not have a history file, so no need to check */
	if (targetTLI == 1)
		return list_make1_int((int) targetTLI);

3991 3992 3993
	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, targetTLI);
3994
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3995 3996 3997 3998
	}
	else
		TLHistoryFilePath(path, targetTLI);

B
Bruce Momjian 已提交
3999
	fd = AllocateFile(path, "r");
4000 4001 4002 4003 4004
	if (fd == NULL)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
4005
					 errmsg("could not open file \"%s\": %m", path)));
4006 4007 4008 4009 4010 4011
		/* Not there, so assume no parents */
		return list_make1_int((int) targetTLI);
	}

	result = NIL;

B
Bruce Momjian 已提交
4012 4013 4014
	/*
	 * Parse the file...
	 */
4015
	while (fgets(fline, sizeof(fline), fd) != NULL)
4016 4017
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
4018 4019 4020
		char	   *ptr;
		char	   *endptr;
		TimeLineID	tli;
4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040

		for (ptr = fline; *ptr; ptr++)
		{
			if (!isspace((unsigned char) *ptr))
				break;
		}
		if (*ptr == '\0' || *ptr == '#')
			continue;

		/* expect a numeric timeline ID as first field of line */
		tli = (TimeLineID) strtoul(ptr, &endptr, 0);
		if (endptr == ptr)
			ereport(FATAL,
					(errmsg("syntax error in history file: %s", fline),
					 errhint("Expected a numeric timeline ID.")));

		if (result &&
			tli <= (TimeLineID) linitial_int(result))
			ereport(FATAL,
					(errmsg("invalid data in history file: %s", fline),
B
Bruce Momjian 已提交
4041
				   errhint("Timeline IDs must be in increasing sequence.")));
4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054

		/* Build list with newest item first */
		result = lcons_int((int) tli, result);

		/* we ignore the remainder of each line */
	}

	FreeFile(fd);

	if (result &&
		targetTLI <= (TimeLineID) linitial_int(result))
		ereport(FATAL,
				(errmsg("invalid data in history file \"%s\"", path),
B
Bruce Momjian 已提交
4055
			errhint("Timeline IDs must be less than child timeline's ID.")));
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073

	result = lcons_int((int) targetTLI, result);

	ereport(DEBUG3,
			(errmsg_internal("history of timeline %u is %s",
							 targetTLI, nodeToString(result))));

	return result;
}

/*
 * Probe whether a timeline history file exists for the given timeline ID
 */
static bool
existsTimeLineHistory(TimeLineID probeTLI)
{
	char		path[MAXPGPATH];
	char		histfname[MAXFNAMELEN];
B
Bruce Momjian 已提交
4074
	FILE	   *fd;
4075

4076 4077 4078 4079
	/* Timeline 1 does not have a history file, so no need to check */
	if (probeTLI == 1)
		return false;

4080 4081 4082
	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, probeTLI);
4083
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098
	}
	else
		TLHistoryFilePath(path, probeTLI);

	fd = AllocateFile(path, "r");
	if (fd != NULL)
	{
		FreeFile(fd);
		return true;
	}
	else
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
4099
					 errmsg("could not open file \"%s\": %m", path)));
4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117
		return false;
	}
}

/*
 * Find the newest existing timeline, assuming that startTLI exists.
 *
 * Note: while this is somewhat heuristic, it does positively guarantee
 * that (result + 1) is not a known timeline, and therefore it should
 * be safe to assign that ID to a new timeline.
 */
static TimeLineID
findNewestTimeLine(TimeLineID startTLI)
{
	TimeLineID	newestTLI;
	TimeLineID	probeTLI;

	/*
B
Bruce Momjian 已提交
4118 4119
	 * The algorithm is just to probe for the existence of timeline history
	 * files.  XXX is it useful to allow gaps in the sequence?
4120 4121 4122
	 */
	newestTLI = startTLI;

B
Bruce Momjian 已提交
4123
	for (probeTLI = startTLI + 1;; probeTLI++)
4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146
	{
		if (existsTimeLineHistory(probeTLI))
		{
			newestTLI = probeTLI;		/* probeTLI exists */
		}
		else
		{
			/* doesn't exist, assume we're done */
			break;
		}
	}

	return newestTLI;
}

/*
 * Create a new timeline history file.
 *
 *	newTLI: ID of the new timeline
 *	parentTLI: ID of its immediate parent
 *	endTLI et al: ID of the last used WAL file, for annotation purposes
 *
 * Currently this is only used during recovery, and so there are no locking
B
Bruce Momjian 已提交
4147
 * considerations.	But we should be just as tense as XLogFileInit to avoid
4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162
 * emplacing a bogus file.
 */
static void
writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
					 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
{
	char		path[MAXPGPATH];
	char		tmppath[MAXPGPATH];
	char		histfname[MAXFNAMELEN];
	char		xlogfname[MAXFNAMELEN];
	char		buffer[BLCKSZ];
	int			srcfd;
	int			fd;
	int			nbytes;

B
Bruce Momjian 已提交
4163
	Assert(newTLI > parentTLI); /* else bad selection of newTLI */
4164 4165 4166 4167

	/*
	 * Write into a temp file name.
	 */
4168
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
4169 4170 4171

	unlink(tmppath);

4172
	/* do not use get_sync_bit() here --- want to fsync only at end of fill */
4173 4174 4175
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
4176
		ereport(ERROR,
4177 4178 4179 4180 4181 4182 4183 4184 4185
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m", tmppath)));

	/*
	 * If a history file exists for the parent, copy it verbatim
	 */
	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, parentTLI);
4186
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
4187 4188 4189 4190 4191 4192 4193 4194
	}
	else
		TLHistoryFilePath(path, parentTLI);

	srcfd = BasicOpenFile(path, O_RDONLY, 0);
	if (srcfd < 0)
	{
		if (errno != ENOENT)
4195
			ereport(ERROR,
4196
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
4197
					 errmsg("could not open file \"%s\": %m", path)));
4198 4199 4200 4201 4202 4203 4204 4205 4206
		/* Not there, so assume parent has no parents */
	}
	else
	{
		for (;;)
		{
			errno = 0;
			nbytes = (int) read(srcfd, buffer, sizeof(buffer));
			if (nbytes < 0 || errno != 0)
4207
				ereport(ERROR,
4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221
						(errcode_for_file_access(),
						 errmsg("could not read file \"%s\": %m", path)));
			if (nbytes == 0)
				break;
			errno = 0;
			if ((int) write(fd, buffer, nbytes) != nbytes)
			{
				int			save_errno = errno;

				/*
				 * If we fail to make the file, delete it to release disk
				 * space
				 */
				unlink(tmppath);
B
Bruce Momjian 已提交
4222 4223

				/*
B
Bruce Momjian 已提交
4224
				 * if write didn't set errno, assume problem is no disk space
B
Bruce Momjian 已提交
4225
				 */
4226 4227
				errno = save_errno ? save_errno : ENOSPC;

4228
				ereport(ERROR,
4229
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
4230
					 errmsg("could not write to file \"%s\": %m", tmppath)));
4231 4232 4233 4234 4235 4236 4237 4238
			}
		}
		close(srcfd);
	}

	/*
	 * Append one line with the details of this timeline split.
	 *
B
Bruce Momjian 已提交
4239 4240
	 * If we did have a parent file, insert an extra newline just in case the
	 * parent file failed to end with one.
4241 4242 4243
	 */
	XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);

4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269
	/*
	 * Write comment to history file to explain why and where timeline changed.
	 * Comment varies according to the recovery target used.
	 */
	if (recoveryTarget == RECOVERY_TARGET_XID)
		snprintf(buffer, sizeof(buffer),
				 "%s%u\t%s\t%s transaction %u\n",
				 (srcfd < 0) ? "" : "\n",
				 parentTLI,
				 xlogfname,
				 recoveryStopAfter ? "after" : "before",
				 recoveryStopXid);
	if (recoveryTarget == RECOVERY_TARGET_TIME)
		snprintf(buffer, sizeof(buffer),
				 "%s%u\t%s\t%s %s\n",
				 (srcfd < 0) ? "" : "\n",
				 parentTLI,
				 xlogfname,
				 recoveryStopAfter ? "after" : "before",
				 timestamptz_to_str(recoveryStopTime));
	else
		snprintf(buffer, sizeof(buffer),
				 "%s%u\t%s\tno recovery target specified\n",
				 (srcfd < 0) ? "" : "\n",
				 parentTLI,
				 xlogfname);
4270 4271 4272 4273 4274 4275 4276 4277

	nbytes = strlen(buffer);
	errno = 0;
	if ((int) write(fd, buffer, nbytes) != nbytes)
	{
		int			save_errno = errno;

		/*
B
Bruce Momjian 已提交
4278
		 * If we fail to make the file, delete it to release disk space
4279 4280 4281 4282 4283
		 */
		unlink(tmppath);
		/* if write didn't set errno, assume problem is no disk space */
		errno = save_errno ? save_errno : ENOSPC;

4284
		ereport(ERROR,
4285 4286 4287 4288 4289
				(errcode_for_file_access(),
				 errmsg("could not write to file \"%s\": %m", tmppath)));
	}

	if (pg_fsync(fd) != 0)
4290
		ereport(ERROR,
4291 4292 4293 4294
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
4295
		ereport(ERROR,
4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));


	/*
	 * Now move the completed history file into place with its final name.
	 */
	TLHistoryFilePath(path, newTLI);

	/*
	 * Prefer link() to rename() here just to be really sure that we don't
	 * overwrite an existing logfile.  However, there shouldn't be one, so
	 * rename() is an acceptable substitute except for the truly paranoid.
	 */
#if HAVE_WORKING_LINK
	if (link(tmppath, path) < 0)
4312
		ereport(ERROR,
4313 4314 4315 4316 4317 4318
				(errcode_for_file_access(),
				 errmsg("could not link file \"%s\" to \"%s\": %m",
						tmppath, path)));
	unlink(tmppath);
#else
	if (rename(tmppath, path) < 0)
4319
		ereport(ERROR,
4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331
				(errcode_for_file_access(),
				 errmsg("could not rename file \"%s\" to \"%s\": %m",
						tmppath, path)));
#endif

	/* The history file can be archived immediately. */
	TLHistoryFileName(histfname, newTLI);
	XLogArchiveNotify(histfname);
}

/*
 * I/O routines for pg_control
4332 4333
 *
 * *ControlFile is a buffer in shared memory that holds an image of the
B
Bruce Momjian 已提交
4334
 * contents of pg_control.	WriteControlFile() initializes pg_control
4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347
 * given a preloaded buffer, ReadControlFile() loads the buffer from
 * the pg_control file (during postmaster or standalone-backend startup),
 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
 *
 * For simplicity, WriteControlFile() initializes the fields of pg_control
 * that are related to checking backend/database compatibility, and
 * ReadControlFile() verifies they are correct.  We could split out the
 * I/O and compatibility-check functions, but there seems no need currently.
 */
static void
WriteControlFile(void)
{
	int			fd;
B
Bruce Momjian 已提交
4348
	char		buffer[PG_CONTROL_SIZE];		/* need not be aligned */
4349 4350

	/*
T
Tom Lane 已提交
4351
	 * Initialize version and compatibility-check fields
4352
	 */
T
Tom Lane 已提交
4353 4354
	ControlFile->pg_control_version = PG_CONTROL_VERSION;
	ControlFile->catalog_version_no = CATALOG_VERSION_NO;
4355 4356 4357 4358

	ControlFile->maxAlign = MAXIMUM_ALIGNOF;
	ControlFile->floatFormat = FLOATFORMAT_VALUE;

4359 4360
	ControlFile->blcksz = BLCKSZ;
	ControlFile->relseg_size = RELSEG_SIZE;
4361
	ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4362
	ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
4363 4364

	ControlFile->nameDataLen = NAMEDATALEN;
4365
	ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
4366

4367 4368
	ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;

4369
#ifdef HAVE_INT64_TIMESTAMP
4370
	ControlFile->enableIntTimes = true;
4371
#else
4372
	ControlFile->enableIntTimes = false;
4373
#endif
4374 4375
	ControlFile->float4ByVal = FLOAT4PASSBYVAL;
	ControlFile->float8ByVal = FLOAT8PASSBYVAL;
4376

T
Tom Lane 已提交
4377
	/* Contents are protected with a CRC */
4378 4379 4380 4381 4382
	INIT_CRC32(ControlFile->crc);
	COMP_CRC32(ControlFile->crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(ControlFile->crc);
T
Tom Lane 已提交
4383

4384
	/*
4385 4386 4387 4388 4389
	 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
	 * excess over sizeof(ControlFileData).  This reduces the odds of
	 * premature-EOF errors when reading pg_control.  We'll still fail when we
	 * check the contents of the file, but hopefully with a more specific
	 * error than "couldn't read pg_control".
4390
	 */
4391 4392
	if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
		elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
4393

4394
	memset(buffer, 0, PG_CONTROL_SIZE);
4395 4396
	memcpy(buffer, ControlFile, sizeof(ControlFileData));

4397 4398
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
4399
					   S_IRUSR | S_IWUSR);
4400
	if (fd < 0)
4401 4402 4403
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not create control file \"%s\": %m",
4404
						XLOG_CONTROL_FILE)));
4405

4406
	errno = 0;
4407
	if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
4408 4409 4410 4411
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
4412 4413
		ereport(PANIC,
				(errcode_for_file_access(),
4414
				 errmsg("could not write to control file: %m")));
4415
	}
4416

4417
	if (pg_fsync(fd) != 0)
4418 4419
		ereport(PANIC,
				(errcode_for_file_access(),
4420
				 errmsg("could not fsync control file: %m")));
4421

4422 4423 4424 4425
	if (close(fd))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close control file: %m")));
4426 4427 4428 4429 4430
}

static void
ReadControlFile(void)
{
4431
	pg_crc32	crc;
4432 4433 4434 4435 4436
	int			fd;

	/*
	 * Read data...
	 */
4437 4438 4439
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
4440
	if (fd < 0)
4441 4442 4443
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
4444
						XLOG_CONTROL_FILE)));
4445 4446

	if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4447 4448
		ereport(PANIC,
				(errcode_for_file_access(),
4449
				 errmsg("could not read from control file: %m")));
4450 4451 4452

	close(fd);

T
Tom Lane 已提交
4453
	/*
B
Bruce Momjian 已提交
4454 4455 4456 4457
	 * Check for expected pg_control format version.  If this is wrong, the
	 * CRC check will likely fail because we'll be checking the wrong number
	 * of bytes.  Complaining about wrong version will probably be more
	 * enlightening than complaining about wrong CRC.
T
Tom Lane 已提交
4458
	 */
4459 4460 4461 4462 4463

	if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4464 4465
		 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
			ControlFile->pg_control_version, ControlFile->pg_control_version,
4466 4467 4468
						   PG_CONTROL_VERSION, PG_CONTROL_VERSION),
				 errhint("This could be a problem of mismatched byte ordering.  It looks like you need to initdb.")));

T
Tom Lane 已提交
4469
	if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
4470 4471 4472
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
B
Bruce Momjian 已提交
4473 4474
				  " but the server was compiled with PG_CONTROL_VERSION %d.",
						ControlFile->pg_control_version, PG_CONTROL_VERSION),
4475
				 errhint("It looks like you need to initdb.")));
4476

T
Tom Lane 已提交
4477
	/* Now check the CRC. */
4478 4479 4480 4481 4482
	INIT_CRC32(crc);
	COMP_CRC32(crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(crc);
4483

4484
	if (!EQ_CRC32(crc, ControlFile->crc))
4485
		ereport(FATAL,
4486
				(errmsg("incorrect checksum in control file")));
4487

4488
	/*
4489
	 * Do compatibility checking immediately.  If the database isn't
4490 4491
	 * compatible with the backend executable, we want to abort before we can
	 * possibly do any damage.
4492
	 */
T
Tom Lane 已提交
4493
	if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
4494 4495 4496
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
B
Bruce Momjian 已提交
4497 4498
				  " but the server was compiled with CATALOG_VERSION_NO %d.",
						ControlFile->catalog_version_no, CATALOG_VERSION_NO),
4499
				 errhint("It looks like you need to initdb.")));
4500 4501 4502
	if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
4503 4504 4505 4506
		   errdetail("The database cluster was initialized with MAXALIGN %d,"
					 " but the server was compiled with MAXALIGN %d.",
					 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
				 errhint("It looks like you need to initdb.")));
4507 4508 4509
	if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
P
Peter Eisentraut 已提交
4510
				 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4511
				 errhint("It looks like you need to initdb.")));
4512
	if (ControlFile->blcksz != BLCKSZ)
4513 4514
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
4515 4516 4517 4518
			 errdetail("The database cluster was initialized with BLCKSZ %d,"
					   " but the server was compiled with BLCKSZ %d.",
					   ControlFile->blcksz, BLCKSZ),
				 errhint("It looks like you need to recompile or initdb.")));
4519
	if (ControlFile->relseg_size != RELSEG_SIZE)
4520 4521
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
4522 4523 4524 4525
		errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
				  " but the server was compiled with RELSEG_SIZE %d.",
				  ControlFile->relseg_size, RELSEG_SIZE),
				 errhint("It looks like you need to recompile or initdb.")));
4526 4527 4528
	if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
4529 4530 4531
		errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
				  " but the server was compiled with XLOG_BLCKSZ %d.",
				  ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4532
				 errhint("It looks like you need to recompile or initdb.")));
4533 4534 4535 4536
	if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
B
Bruce Momjian 已提交
4537
					   " but the server was compiled with XLOG_SEG_SIZE %d.",
4538
						   ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
B
Bruce Momjian 已提交
4539
				 errhint("It looks like you need to recompile or initdb.")));
4540
	if (ControlFile->nameDataLen != NAMEDATALEN)
4541 4542
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
4543 4544 4545 4546
		errdetail("The database cluster was initialized with NAMEDATALEN %d,"
				  " but the server was compiled with NAMEDATALEN %d.",
				  ControlFile->nameDataLen, NAMEDATALEN),
				 errhint("It looks like you need to recompile or initdb.")));
4547
	if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4548 4549
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
4550
				 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
B
Bruce Momjian 已提交
4551
					  " but the server was compiled with INDEX_MAX_KEYS %d.",
4552
						   ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
B
Bruce Momjian 已提交
4553
				 errhint("It looks like you need to recompile or initdb.")));
4554 4555 4556 4557
	if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
B
Bruce Momjian 已提交
4558 4559
				" but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
			  ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4560
				 errhint("It looks like you need to recompile or initdb.")));
4561 4562

#ifdef HAVE_INT64_TIMESTAMP
4563
	if (ControlFile->enableIntTimes != true)
4564 4565 4566
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
4567 4568
				  " but the server was compiled with HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
4569
#else
4570
	if (ControlFile->enableIntTimes != false)
4571 4572 4573
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
4574 4575
			   " but the server was compiled without HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
4576 4577
#endif

4578 4579 4580 4581 4582
#ifdef USE_FLOAT4_BYVAL
	if (ControlFile->float4ByVal != true)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without USE_FLOAT4_BYVAL"
4583
					  " but the server was compiled with USE_FLOAT4_BYVAL."),
4584 4585 4586 4587 4588
				 errhint("It looks like you need to recompile or initdb.")));
#else
	if (ControlFile->float4ByVal != false)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
4589 4590
		errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
				  " but the server was compiled without USE_FLOAT4_BYVAL."),
4591 4592 4593 4594 4595 4596 4597 4598
				 errhint("It looks like you need to recompile or initdb.")));
#endif

#ifdef USE_FLOAT8_BYVAL
	if (ControlFile->float8ByVal != true)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4599
					  " but the server was compiled with USE_FLOAT8_BYVAL."),
4600 4601 4602 4603 4604
				 errhint("It looks like you need to recompile or initdb.")));
#else
	if (ControlFile->float8ByVal != false)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
4605 4606
		errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
				  " but the server was compiled without USE_FLOAT8_BYVAL."),
4607 4608
				 errhint("It looks like you need to recompile or initdb.")));
#endif
4609 4610
}

4611
void
4612
UpdateControlFile(void)
4613
{
4614
	int			fd;
4615

4616 4617 4618 4619 4620
	INIT_CRC32(ControlFile->crc);
	COMP_CRC32(ControlFile->crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(ControlFile->crc);
4621

4622 4623 4624
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
4625
	if (fd < 0)
4626 4627 4628
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
4629
						XLOG_CONTROL_FILE)));
4630

4631
	errno = 0;
4632
	if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4633 4634 4635 4636
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
4637 4638
		ereport(PANIC,
				(errcode_for_file_access(),
4639
				 errmsg("could not write to control file: %m")));
4640
	}
4641

4642
	if (pg_fsync(fd) != 0)
4643 4644
		ereport(PANIC,
				(errcode_for_file_access(),
4645
				 errmsg("could not fsync control file: %m")));
4646

4647 4648 4649 4650
	if (close(fd))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close control file: %m")));
4651 4652
}

4653 4654 4655 4656 4657 4658 4659 4660 4661 4662
/*
 * Returns the unique system identifier from control file.
 */
uint64
GetSystemIdentifier(void)
{
	Assert(ControlFile != NULL);
	return ControlFile->system_identifier;
}

4663
/*
T
Tom Lane 已提交
4664
 * Initialization of shared memory for XLOG
4665
 */
4666
Size
4667
XLOGShmemSize(void)
4668
{
4669
	Size		size;
4670

4671 4672 4673 4674 4675 4676 4677
	/* XLogCtl */
	size = sizeof(XLogCtlData);
	/* xlblocks array */
	size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
	/* extra alignment padding for XLOG I/O buffers */
	size = add_size(size, ALIGNOF_XLOG_BUFFER);
	/* and the buffers themselves */
4678
	size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4679 4680

	/*
B
Bruce Momjian 已提交
4681 4682 4683
	 * Note: we don't count ControlFileData, it comes out of the "slop factor"
	 * added by CreateSharedMemoryAndSemaphores.  This lets us use this
	 * routine again below to compute the actual allocation size.
4684 4685 4686
	 */

	return size;
4687 4688 4689 4690 4691
}

void
XLOGShmemInit(void)
{
4692 4693
	bool		foundCFile,
				foundXLog;
4694
	char	   *allocptr;
4695

4696
	ControlFile = (ControlFileData *)
4697
		ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4698 4699
	XLogCtl = (XLogCtlData *)
		ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4700

4701
	if (foundCFile || foundXLog)
4702 4703
	{
		/* both should be present or neither */
4704
		Assert(foundCFile && foundXLog);
4705 4706
		return;
	}
4707

T
Tom Lane 已提交
4708
	memset(XLogCtl, 0, sizeof(XLogCtlData));
B
Bruce Momjian 已提交
4709

T
Tom Lane 已提交
4710
	/*
B
Bruce Momjian 已提交
4711 4712 4713
	 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
	 * multiple of the alignment for same, so no extra alignment padding is
	 * needed here.
T
Tom Lane 已提交
4714
	 */
4715 4716
	allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
	XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
T
Tom Lane 已提交
4717
	memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4718
	allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
B
Bruce Momjian 已提交
4719

T
Tom Lane 已提交
4720
	/*
4721
	 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
T
Tom Lane 已提交
4722
	 */
4723 4724
	allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
	XLogCtl->pages = allocptr;
4725
	memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
T
Tom Lane 已提交
4726 4727

	/*
B
Bruce Momjian 已提交
4728 4729
	 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
	 * in additional info.)
T
Tom Lane 已提交
4730 4731
	 */
	XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4732
	XLogCtl->SharedRecoveryInProgress = true;
T
Tom Lane 已提交
4733
	XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4734
	SpinLockInit(&XLogCtl->info_lck);
T
Tom Lane 已提交
4735

4736
	/*
B
Bruce Momjian 已提交
4737 4738 4739
	 * If we are not in bootstrap mode, pg_control should already exist. Read
	 * and validate it immediately (see comments in ReadControlFile() for the
	 * reasons why).
4740 4741 4742
	 */
	if (!IsBootstrapProcessingMode())
		ReadControlFile();
4743 4744 4745
}

/*
T
Tom Lane 已提交
4746 4747
 * This func must be called ONCE on system install.  It creates pg_control
 * and the initial XLOG segment.
4748 4749
 */
void
T
Tom Lane 已提交
4750
BootStrapXLOG(void)
4751
{
4752
	CheckPoint	checkPoint;
T
Tom Lane 已提交
4753 4754
	char	   *buffer;
	XLogPageHeader page;
4755
	XLogLongPageHeader longpage;
4756
	XLogRecord *record;
B
Bruce Momjian 已提交
4757
	bool		use_existent;
4758 4759
	uint64		sysidentifier;
	struct timeval tv;
4760
	pg_crc32	crc;
4761

4762
	/*
B
Bruce Momjian 已提交
4763 4764 4765 4766 4767 4768 4769 4770 4771 4772
	 * Select a hopefully-unique system identifier code for this installation.
	 * We use the result of gettimeofday(), including the fractional seconds
	 * field, as being about as unique as we can easily get.  (Think not to
	 * use random(), since it hasn't been seeded and there's no portable way
	 * to seed it other than the system clock value...)  The upper half of the
	 * uint64 value is just the tv_sec part, while the lower half is the XOR
	 * of tv_sec and tv_usec.  This is to ensure that we don't lose uniqueness
	 * unnecessarily if "uint64" is really only 32 bits wide.  A person
	 * knowing this encoding can determine the initialization time of the
	 * installation, which could perhaps be useful sometimes.
4773 4774 4775 4776 4777
	 */
	gettimeofday(&tv, NULL);
	sysidentifier = ((uint64) tv.tv_sec) << 32;
	sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);

4778 4779 4780
	/* First timeline ID is always 1 */
	ThisTimeLineID = 1;

4781
	/* page buffer must be aligned suitably for O_DIRECT */
4782
	buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4783
	page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4784
	memset(page, 0, XLOG_BLCKSZ);
T
Tom Lane 已提交
4785

4786
	/* Set up information for the initial checkpoint record */
4787
	checkPoint.redo.xlogid = 0;
4788 4789
	checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
	checkPoint.ThisTimeLineID = ThisTimeLineID;
4790
	checkPoint.nextXidEpoch = 0;
4791
	checkPoint.nextXid = FirstNormalTransactionId;
4792
	checkPoint.nextOid = FirstBootstrapObjectId;
4793
	checkPoint.nextMulti = FirstMultiXactId;
4794
	checkPoint.nextMultiOffset = 0;
4795 4796
	checkPoint.oldestXid = FirstNormalTransactionId;
	checkPoint.oldestXidDB = TemplateDbOid;
4797
	checkPoint.time = (pg_time_t) time(NULL);
4798
	checkPoint.oldestActiveXid = InvalidTransactionId;
4799

4800 4801 4802
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
	ShmemVariableCache->oidCount = 0;
4803
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4804
	SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
4805

4806
	/* Set up the XLOG page header */
4807
	page->xlp_magic = XLOG_PAGE_MAGIC;
4808 4809
	page->xlp_info = XLP_LONG_HEADER;
	page->xlp_tli = ThisTimeLineID;
4810 4811
	page->xlp_pageaddr.xlogid = 0;
	page->xlp_pageaddr.xrecoff = 0;
4812 4813 4814
	longpage = (XLogLongPageHeader) page;
	longpage->xlp_sysid = sysidentifier;
	longpage->xlp_seg_size = XLogSegSize;
4815
	longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4816 4817

	/* Insert the initial checkpoint record */
4818
	record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4819
	record->xl_prev.xlogid = 0;
4820
	record->xl_prev.xrecoff = 0;
4821
	record->xl_xid = InvalidTransactionId;
4822
	record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4823
	record->xl_len = sizeof(checkPoint);
T
Tom Lane 已提交
4824
	record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4825
	record->xl_rmid = RM_XLOG_ID;
T
Tom Lane 已提交
4826
	memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4827

4828 4829 4830 4831 4832
	INIT_CRC32(crc);
	COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
	COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
			   SizeOfXLogRecord - sizeof(pg_crc32));
	FIN_CRC32(crc);
4833 4834
	record->xl_crc = crc;

4835
	/* Create first XLOG segment file */
4836 4837
	use_existent = false;
	openLogFile = XLogFileInit(0, 0, &use_existent, false);
4838

4839
	/* Write the first page with the initial record */
4840
	errno = 0;
4841
	if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4842 4843 4844 4845
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
4846 4847
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4848
			  errmsg("could not write bootstrap transaction log file: %m")));
4849
	}
4850

T
Tom Lane 已提交
4851
	if (pg_fsync(openLogFile) != 0)
4852 4853
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4854
			  errmsg("could not fsync bootstrap transaction log file: %m")));
4855

4856 4857 4858
	if (close(openLogFile))
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4859
			  errmsg("could not close bootstrap transaction log file: %m")));
4860

T
Tom Lane 已提交
4861
	openLogFile = -1;
4862

4863 4864
	/* Now create pg_control */

4865
	memset(ControlFile, 0, sizeof(ControlFileData));
T
Tom Lane 已提交
4866
	/* Initialize pg_control status fields */
4867
	ControlFile->system_identifier = sysidentifier;
T
Tom Lane 已提交
4868 4869
	ControlFile->state = DB_SHUTDOWNED;
	ControlFile->time = checkPoint.time;
4870
	ControlFile->checkPoint = checkPoint.redo;
T
Tom Lane 已提交
4871
	ControlFile->checkPointCopy = checkPoint;
4872
	/* some additional ControlFile fields are set in WriteControlFile() */
4873

4874
	WriteControlFile();
4875 4876 4877

	/* Bootstrap the commit log, too */
	BootStrapCLOG();
4878
	BootStrapSUBTRANS();
4879
	BootStrapMultiXact();
4880

4881
	pfree(buffer);
4882 4883
}

4884
static char *
4885
str_time(pg_time_t tnow)
4886
{
4887
	static char buf[128];
4888

4889 4890 4891
	pg_strftime(buf, sizeof(buf),
				"%Y-%m-%d %H:%M:%S %Z",
				pg_localtime(&tnow, log_timezone));
4892

4893
	return buf;
4894 4895
}

4896 4897
/*
 * See if there is a recovery command file (recovery.conf), and if so
4898
 * read in parameters for archive recovery and XLOG streaming.
4899 4900 4901 4902 4903 4904 4905 4906
 *
 * XXX longer term intention is to expand this to
 * cater for additional parameters and controls
 * possibly use a flex lexer similar to the GUC one
 */
static void
readRecoveryCommandFile(void)
{
B
Bruce Momjian 已提交
4907 4908 4909 4910 4911 4912
	FILE	   *fd;
	char		cmdline[MAXPGPATH];
	TimeLineID	rtli = 0;
	bool		rtliGiven = false;
	bool		syntaxError = false;

4913
	fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4914 4915 4916 4917 4918
	if (fd == NULL)
	{
		if (errno == ENOENT)
			return;				/* not there, so no archive recovery */
		ereport(FATAL,
B
Bruce Momjian 已提交
4919
				(errcode_for_file_access(),
4920
				 errmsg("could not open recovery command file \"%s\": %m",
4921
						RECOVERY_COMMAND_FILE)));
4922 4923
	}

B
Bruce Momjian 已提交
4924 4925 4926
	/*
	 * Parse the file...
	 */
4927
	while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4928 4929
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
4930 4931 4932
		char	   *ptr;
		char	   *tok1;
		char	   *tok2;
4933 4934 4935 4936 4937 4938 4939 4940 4941 4942

		for (ptr = cmdline; *ptr; ptr++)
		{
			if (!isspace((unsigned char) *ptr))
				break;
		}
		if (*ptr == '\0' || *ptr == '#')
			continue;

		/* identify the quoted parameter value */
B
Bruce Momjian 已提交
4943
		tok1 = strtok(ptr, "'");
4944 4945 4946 4947 4948
		if (!tok1)
		{
			syntaxError = true;
			break;
		}
B
Bruce Momjian 已提交
4949
		tok2 = strtok(NULL, "'");
4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962
		if (!tok2)
		{
			syntaxError = true;
			break;
		}
		/* reparse to get just the parameter name */
		tok1 = strtok(ptr, " \t=");
		if (!tok1)
		{
			syntaxError = true;
			break;
		}

B
Bruce Momjian 已提交
4963 4964
		if (strcmp(tok1, "restore_command") == 0)
		{
4965
			recoveryRestoreCommand = pstrdup(tok2);
4966
			ereport(DEBUG2,
4967
					(errmsg("restore_command = '%s'",
4968 4969
							recoveryRestoreCommand)));
		}
4970 4971 4972
		else if (strcmp(tok1, "recovery_end_command") == 0)
		{
			recoveryEndCommand = pstrdup(tok2);
4973
			ereport(DEBUG2,
4974 4975 4976
					(errmsg("recovery_end_command = '%s'",
							recoveryEndCommand)));
		}
4977 4978 4979 4980 4981 4982 4983
		else if (strcmp(tok1, "restartpoint_command") == 0)
		{
			restartPointCommand = pstrdup(tok2);
			ereport(DEBUG2,
					(errmsg("restartpoint_command = '%s'",
							restartPointCommand)));
		}
B
Bruce Momjian 已提交
4984 4985
		else if (strcmp(tok1, "recovery_target_timeline") == 0)
		{
4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998
			rtliGiven = true;
			if (strcmp(tok2, "latest") == 0)
				rtli = 0;
			else
			{
				errno = 0;
				rtli = (TimeLineID) strtoul(tok2, NULL, 0);
				if (errno == EINVAL || errno == ERANGE)
					ereport(FATAL,
							(errmsg("recovery_target_timeline is not a valid number: \"%s\"",
									tok2)));
			}
			if (rtli)
4999
				ereport(DEBUG2,
5000 5001
						(errmsg("recovery_target_timeline = %u", rtli)));
			else
5002
				ereport(DEBUG2,
5003 5004
						(errmsg("recovery_target_timeline = latest")));
		}
B
Bruce Momjian 已提交
5005 5006
		else if (strcmp(tok1, "recovery_target_xid") == 0)
		{
5007 5008 5009 5010
			errno = 0;
			recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
			if (errno == EINVAL || errno == ERANGE)
				ereport(FATAL,
B
Bruce Momjian 已提交
5011 5012
				 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
						 tok2)));
5013
			ereport(DEBUG2,
5014 5015
					(errmsg("recovery_target_xid = %u",
							recoveryTargetXid)));
5016
			recoveryTarget = RECOVERY_TARGET_XID;
5017
		}
B
Bruce Momjian 已提交
5018 5019
		else if (strcmp(tok1, "recovery_target_time") == 0)
		{
5020 5021 5022 5023
			/*
			 * if recovery_target_xid specified, then this overrides
			 * recovery_target_time
			 */
5024
			if (recoveryTarget == RECOVERY_TARGET_XID)
5025
				continue;
5026
			recoveryTarget = RECOVERY_TARGET_TIME;
B
Bruce Momjian 已提交
5027

5028
			/*
5029
			 * Convert the time string given by the user to TimestampTz form.
5030
			 */
5031 5032
			recoveryTargetTime =
				DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
B
Bruce Momjian 已提交
5033
														CStringGetDatum(tok2),
5034 5035
												ObjectIdGetDatum(InvalidOid),
														Int32GetDatum(-1)));
5036
			ereport(DEBUG2,
5037
					(errmsg("recovery_target_time = '%s'",
5038
							timestamptz_to_str(recoveryTargetTime))));
5039
		}
B
Bruce Momjian 已提交
5040 5041
		else if (strcmp(tok1, "recovery_target_inclusive") == 0)
		{
5042 5043 5044
			/*
			 * does nothing if a recovery_target is not also set
			 */
5045
			if (!parse_bool(tok2, &recoveryTargetInclusive))
5046 5047 5048
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("parameter \"recovery_target_inclusive\" requires a Boolean value")));
5049
			ereport(DEBUG2,
5050 5051
					(errmsg("recovery_target_inclusive = %s", tok2)));
		}
5052 5053 5054 5055 5056 5057
		else if (strcmp(tok1, "standby_mode") == 0)
		{
			if (!parse_bool(tok2, &StandbyMode))
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("parameter \"standby_mode\" requires a Boolean value")));
5058
			ereport(DEBUG2,
5059 5060 5061 5062 5063
					(errmsg("standby_mode = '%s'", tok2)));
		}
		else if (strcmp(tok1, "primary_conninfo") == 0)
		{
			PrimaryConnInfo = pstrdup(tok2);
5064
			ereport(DEBUG2,
5065 5066 5067 5068 5069 5070
					(errmsg("primary_conninfo = '%s'",
							PrimaryConnInfo)));
		}
		else if (strcmp(tok1, "trigger_file") == 0)
		{
			TriggerFile = pstrdup(tok2);
5071
			ereport(DEBUG2,
5072 5073 5074
					(errmsg("trigger_file = '%s'",
							TriggerFile)));
		}
5075 5076 5077 5078 5079 5080 5081 5082
		else
			ereport(FATAL,
					(errmsg("unrecognized recovery parameter \"%s\"",
							tok1)));
	}

	FreeFile(fd);

B
Bruce Momjian 已提交
5083 5084
	if (syntaxError)
		ereport(FATAL,
5085 5086
				(errmsg("syntax error in recovery command file: %s",
						cmdline),
B
Bruce Momjian 已提交
5087
			  errhint("Lines should have the format parameter = 'value'.")));
5088

5089 5090
	/* If not in standby mode, restore_command must be supplied */
	if (!StandbyMode && recoveryRestoreCommand == NULL)
5091
		ereport(FATAL,
5092
				(errmsg("recovery command file \"%s\" did not specify restore_command nor standby_mode",
5093
						RECOVERY_COMMAND_FILE)));
5094

5095 5096 5097
	/* Enable fetching from archive recovery area */
	InArchiveRecovery = true;

5098
	/*
B
Bruce Momjian 已提交
5099 5100 5101 5102
	 * If user specified recovery_target_timeline, validate it or compute the
	 * "latest" value.	We can't do this until after we've gotten the restore
	 * command and set InArchiveRecovery, because we need to fetch timeline
	 * history files from the archive.
5103
	 */
5104 5105 5106 5107 5108 5109 5110
	if (rtliGiven)
	{
		if (rtli)
		{
			/* Timeline 1 does not have a history file, all else should */
			if (rtli != 1 && !existsTimeLineHistory(rtli))
				ereport(FATAL,
5111
						(errmsg("recovery target timeline %u does not exist",
B
Bruce Momjian 已提交
5112
								rtli)));
5113 5114 5115 5116 5117 5118 5119 5120
			recoveryTargetTLI = rtli;
		}
		else
		{
			/* We start the "latest" search from pg_control's timeline */
			recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
		}
	}
5121 5122 5123 5124 5125 5126
}

/*
 * Exit archive-recovery state
 */
static void
5127
exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
5128
{
B
Bruce Momjian 已提交
5129 5130
	char		recoveryPath[MAXPGPATH];
	char		xlogpath[MAXPGPATH];
5131
	XLogRecPtr	InvalidXLogRecPtr = {0, 0};
5132 5133

	/*
5134
	 * We are no longer in archive recovery state.
5135 5136 5137
	 */
	InArchiveRecovery = false;

5138 5139 5140 5141 5142
	/*
	 * Update min recovery point one last time.
	 */
	UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);

5143
	/*
B
Bruce Momjian 已提交
5144 5145
	 * If the ending log segment is still open, close it (to avoid problems on
	 * Windows with trying to rename or delete an open file).
5146
	 */
5147 5148 5149 5150 5151
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
5152 5153

	/*
B
Bruce Momjian 已提交
5154 5155 5156 5157 5158 5159 5160
	 * If the segment was fetched from archival storage, we want to replace
	 * the existing xlog segment (if any) with the archival version.  This is
	 * because whatever is in XLOGDIR is very possibly older than what we have
	 * from the archives, since it could have come from restoring a PGDATA
	 * backup.	In any case, the archival version certainly is more
	 * descriptive of what our current database state is, because that is what
	 * we replayed from.
5161
	 *
5162 5163
	 * Note that if we are establishing a new timeline, ThisTimeLineID is
	 * already set to the new value, and so we will create a new file instead
5164 5165
	 * of overwriting any existing file.  (This is, in fact, always the case
	 * at present.)
5166
	 */
5167
	snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
5168
	XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
5169 5170 5171 5172 5173 5174 5175 5176 5177 5178

	if (restoredFromArchive)
	{
		ereport(DEBUG3,
				(errmsg_internal("moving last restored xlog to \"%s\"",
								 xlogpath)));
		unlink(xlogpath);		/* might or might not exist */
		if (rename(recoveryPath, xlogpath) != 0)
			ereport(FATAL,
					(errcode_for_file_access(),
5179
					 errmsg("could not rename file \"%s\" to \"%s\": %m",
5180 5181 5182 5183 5184 5185 5186 5187 5188 5189
							recoveryPath, xlogpath)));
		/* XXX might we need to fix permissions on the file? */
	}
	else
	{
		/*
		 * If the latest segment is not archival, but there's still a
		 * RECOVERYXLOG laying about, get rid of it.
		 */
		unlink(recoveryPath);	/* ignore any error */
B
Bruce Momjian 已提交
5190

5191
		/*
B
Bruce Momjian 已提交
5192 5193 5194
		 * If we are establishing a new timeline, we have to copy data from
		 * the last WAL segment of the old timeline to create a starting WAL
		 * segment for the new timeline.
5195 5196 5197 5198
		 *
		 * Notify the archiver that the last WAL segment of the old timeline
		 * is ready to copy to archival storage. Otherwise, it is not archived
		 * for a while.
5199 5200
		 */
		if (endTLI != ThisTimeLineID)
5201
		{
5202 5203
			XLogFileCopy(endLogId, endLogSeg,
						 endTLI, endLogId, endLogSeg);
5204 5205 5206 5207 5208 5209 5210

			if (XLogArchivingActive())
			{
				XLogFileName(xlogpath, endTLI, endLogId, endLogSeg);
				XLogArchiveNotify(xlogpath);
			}
		}
5211 5212 5213
	}

	/*
B
Bruce Momjian 已提交
5214 5215
	 * Let's just make real sure there are not .ready or .done flags posted
	 * for the new segment.
5216
	 */
5217 5218
	XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
	XLogArchiveCleanup(xlogpath);
5219

5220
	/* Get rid of any remaining recovered timeline-history file, too */
5221
	snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
B
Bruce Momjian 已提交
5222
	unlink(recoveryPath);		/* ignore any error */
5223 5224

	/*
B
Bruce Momjian 已提交
5225 5226
	 * Rename the config file out of the way, so that we don't accidentally
	 * re-enter archive recovery mode in a subsequent crash.
5227
	 */
5228 5229
	unlink(RECOVERY_COMMAND_DONE);
	if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
5230 5231
		ereport(FATAL,
				(errcode_for_file_access(),
5232
				 errmsg("could not rename file \"%s\" to \"%s\": %m",
5233
						RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244

	ereport(LOG,
			(errmsg("archive recovery complete")));
}

/*
 * For point-in-time recovery, this function decides whether we want to
 * stop applying the XLOG at or after the current record.
 *
 * Returns TRUE if we are stopping, FALSE otherwise.  On TRUE return,
 * *includeThis is set TRUE if we should apply this record before stopping.
5245 5246 5247
 *
 * We also track the timestamp of the latest applied COMMIT/ABORT record
 * in recoveryLastXTime, for logging purposes.
5248 5249
 * Also, some information is saved in recoveryStopXid et al for use in
 * annotating the new timeline's history file.
5250 5251 5252 5253 5254
 */
static bool
recoveryStopsHere(XLogRecord *record, bool *includeThis)
{
	bool		stopsHere;
B
Bruce Momjian 已提交
5255
	uint8		record_info;
B
Bruce Momjian 已提交
5256
	TimestampTz recordXtime;
5257 5258

	/* We only consider stopping at COMMIT or ABORT records */
5259
	if (record->xl_rmid == RM_XACT_ID)
5260
	{
5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271
		record_info = record->xl_info & ~XLR_INFO_MASK;
		if (record_info == XLOG_XACT_COMMIT)
		{
			xl_xact_commit *recordXactCommitData;

			recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
			recordXtime = recordXactCommitData->xact_time;
		}
		else if (record_info == XLOG_XACT_ABORT)
		{
			xl_xact_abort *recordXactAbortData;
5272

5273 5274 5275 5276 5277
			recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
			recordXtime = recordXactAbortData->xact_time;
		}
		else
			return false;
5278
	}
5279
	else if (record->xl_rmid == RM_XLOG_ID)
5280
	{
5281 5282 5283 5284 5285 5286 5287 5288 5289
		record_info = record->xl_info & ~XLR_INFO_MASK;
		if (record_info == XLOG_CHECKPOINT_SHUTDOWN ||
			record_info == XLOG_CHECKPOINT_ONLINE)
		{
			CheckPoint	checkPoint;

			memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
			recoveryLastXTime = checkPoint.time;
		}
5290

5291 5292 5293 5294 5295
		/*
		 * We don't want to stop recovery on a checkpoint record, but we do
		 * want to update recoveryLastXTime. So return is unconditional.
		 */
		return false;
5296 5297 5298 5299
	}
	else
		return false;

5300
	/* Do we have a PITR target at all? */
5301
	if (recoveryTarget == RECOVERY_TARGET_UNSET)
5302 5303
	{
		recoveryLastXTime = recordXtime;
5304
		return false;
5305
	}
5306

5307
	if (recoveryTarget == RECOVERY_TARGET_XID)
5308 5309
	{
		/*
B
Bruce Momjian 已提交
5310 5311
		 * there can be only one transaction end record with this exact
		 * transactionid
5312
		 *
B
Bruce Momjian 已提交
5313
		 * when testing for an xid, we MUST test for equality only, since
B
Bruce Momjian 已提交
5314 5315 5316
		 * transactions are numbered in the order they start, not the order
		 * they complete. A higher numbered xid will complete before you about
		 * 50% of the time...
5317 5318 5319 5320 5321 5322 5323 5324
		 */
		stopsHere = (record->xl_xid == recoveryTargetXid);
		if (stopsHere)
			*includeThis = recoveryTargetInclusive;
	}
	else
	{
		/*
B
Bruce Momjian 已提交
5325 5326 5327
		 * there can be many transactions that share the same commit time, so
		 * we stop after the last one, if we are inclusive, or stop at the
		 * first one if we are exclusive
5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338
		 */
		if (recoveryTargetInclusive)
			stopsHere = (recordXtime > recoveryTargetTime);
		else
			stopsHere = (recordXtime >= recoveryTargetTime);
		if (stopsHere)
			*includeThis = false;
	}

	if (stopsHere)
	{
5339 5340 5341 5342
		recoveryStopXid = record->xl_xid;
		recoveryStopTime = recordXtime;
		recoveryStopAfter = *includeThis;

5343 5344
		if (record_info == XLOG_XACT_COMMIT)
		{
5345
			if (recoveryStopAfter)
5346 5347
				ereport(LOG,
						(errmsg("recovery stopping after commit of transaction %u, time %s",
5348 5349
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
5350 5351 5352
			else
				ereport(LOG,
						(errmsg("recovery stopping before commit of transaction %u, time %s",
5353 5354
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
5355 5356 5357
		}
		else
		{
5358
			if (recoveryStopAfter)
5359 5360
				ereport(LOG,
						(errmsg("recovery stopping after abort of transaction %u, time %s",
5361 5362
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
5363 5364 5365
			else
				ereport(LOG,
						(errmsg("recovery stopping before abort of transaction %u, time %s",
5366 5367
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
5368
		}
5369 5370 5371

		if (recoveryStopAfter)
			recoveryLastXTime = recordXtime;
5372
	}
5373 5374
	else
		recoveryLastXTime = recordXtime;
5375 5376 5377 5378

	return stopsHere;
}

5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426
/*
 * Returns bool with current recovery mode, a global state.
 */
Datum
pg_is_in_recovery(PG_FUNCTION_ARGS)
{
	PG_RETURN_BOOL(RecoveryInProgress());
}

/*
 * Returns timestamp of last recovered commit/abort record.
 */
TimestampTz
GetLatestXLogTime(void)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

	SpinLockAcquire(&xlogctl->info_lck);
	recoveryLastXTime = xlogctl->recoveryLastXTime;
	SpinLockRelease(&xlogctl->info_lck);

	return recoveryLastXTime;
}

/*
 * Note that text field supplied is a parameter name and does not require translation
 */
#define RecoveryRequiresIntParameter(param_name, currValue, checkpointValue) \
{ \
	if (currValue < checkpointValue) \
		ereport(ERROR, \
			(errmsg("recovery connections cannot continue because " \
					"%s = %u is a lower setting than on WAL source server (value was %u)", \
					param_name, \
					currValue, \
					checkpointValue))); \
}

/*
 * Check to see if required parameters are set high enough on this server
 * for various aspects of recovery operation.
 */
static void
CheckRequiredParameterValues(CheckPoint checkPoint)
{
	/* We ignore autovacuum_max_workers when we make this test. */
	RecoveryRequiresIntParameter("max_connections",
B
Bruce Momjian 已提交
5427
								 MaxConnections, checkPoint.MaxConnections);
5428 5429

	RecoveryRequiresIntParameter("max_prepared_xacts",
B
Bruce Momjian 已提交
5430
						  max_prepared_xacts, checkPoint.max_prepared_xacts);
5431
	RecoveryRequiresIntParameter("max_locks_per_xact",
B
Bruce Momjian 已提交
5432
						  max_locks_per_xact, checkPoint.max_locks_per_xact);
5433 5434 5435

	if (!checkPoint.XLogStandbyInfoMode)
		ereport(ERROR,
B
Bruce Momjian 已提交
5436 5437
				(errmsg("recovery connections cannot start because the recovery_connections "
						"parameter is disabled on the WAL source server")));
5438 5439
}

5440
/*
T
Tom Lane 已提交
5441
 * This must be called ONCE during postmaster or standalone-backend startup
5442 5443
 */
void
T
Tom Lane 已提交
5444
StartupXLOG(void)
5445
{
5446 5447
	XLogCtlInsert *Insert;
	CheckPoint	checkPoint;
T
Tom Lane 已提交
5448
	bool		wasShutdown;
5449
	bool		reachedStopPoint = false;
5450
	bool		haveBackupLabel = false;
5451
	XLogRecPtr	RecPtr,
T
Tom Lane 已提交
5452 5453
				checkPointLoc,
				EndOfLog;
5454 5455
	uint32		endLogId;
	uint32		endLogSeg;
5456
	XLogRecord *record;
5457
	uint32		freespace;
5458
	TransactionId oldestActiveXID;
5459
	bool		bgwriterLaunched = false;
5460
	bool		backendsAllowed = false;
5461

5462
	/*
5463 5464
	 * Read control file and check XLOG status looks valid.
	 *
5465 5466
	 * Note: in most control paths, *ControlFile is already valid and we need
	 * not do ReadControlFile() here, but might as well do it to be sure.
5467
	 */
5468
	ReadControlFile();
5469

5470
	if (ControlFile->state < DB_SHUTDOWNED ||
5471
		ControlFile->state > DB_IN_PRODUCTION ||
5472
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
5473 5474
		ereport(FATAL,
				(errmsg("control file contains invalid data")));
5475 5476

	if (ControlFile->state == DB_SHUTDOWNED)
5477 5478 5479
		ereport(LOG,
				(errmsg("database system was shut down at %s",
						str_time(ControlFile->time))));
5480
	else if (ControlFile->state == DB_SHUTDOWNING)
5481
		ereport(LOG,
5482
				(errmsg("database system shutdown was interrupted; last known up at %s",
5483
						str_time(ControlFile->time))));
5484
	else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
5485
		ereport(LOG,
B
Bruce Momjian 已提交
5486 5487 5488 5489
		   (errmsg("database system was interrupted while in recovery at %s",
				   str_time(ControlFile->time)),
			errhint("This probably means that some data is corrupted and"
					" you will have to use the last backup for recovery.")));
5490 5491
	else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
		ereport(LOG,
B
Bruce Momjian 已提交
5492 5493
				(errmsg("database system was interrupted while in recovery at log time %s",
						str_time(ControlFile->checkPointCopy.time)),
5494
				 errhint("If this has occurred more than once some data might be corrupted"
B
Bruce Momjian 已提交
5495
			  " and you might need to choose an earlier recovery target.")));
5496
	else if (ControlFile->state == DB_IN_PRODUCTION)
5497
		ereport(LOG,
B
Bruce Momjian 已提交
5498 5499
			  (errmsg("database system was interrupted; last known up at %s",
					  str_time(ControlFile->time))));
5500

5501 5502
	/* This is just to allow attaching to startup process with a debugger */
#ifdef XLOG_REPLAY_DELAY
5503
	if (ControlFile->state != DB_SHUTDOWNED)
5504
		pg_usleep(60000000L);
5505 5506
#endif

5507 5508
	/*
	 * Verify that pg_xlog and pg_xlog/archive_status exist.  In cases where
5509 5510
	 * someone has performed a copy for PITR, these directories may have been
	 * excluded and need to be re-created.
5511 5512 5513
	 */
	ValidateXLOGDirectoryStructure();

5514
	/*
B
Bruce Momjian 已提交
5515 5516 5517 5518 5519 5520
	 * Clear out any old relcache cache files.	This is *necessary* if we do
	 * any WAL replay, since that would probably result in the cache files
	 * being out of sync with database reality.  In theory we could leave them
	 * in place if the database had been cleanly shut down, but it seems
	 * safest to just remove them always and let them be rebuilt during the
	 * first backend startup.
5521 5522 5523
	 */
	RelationCacheInitFileRemove();

5524
	/*
B
Bruce Momjian 已提交
5525 5526
	 * Initialize on the assumption we want to recover to the same timeline
	 * that's active according to pg_control.
5527 5528 5529
	 */
	recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;

5530
	/*
B
Bruce Momjian 已提交
5531 5532
	 * Check for recovery control file, and if so set up state for offline
	 * recovery
5533 5534 5535
	 */
	readRecoveryCommandFile();

5536 5537 5538
	/* Now we can determine the list of expected TLIs */
	expectedTLIs = readTimeLineHistory(recoveryTargetTLI);

5539 5540 5541 5542 5543 5544
	/*
	 * If pg_control's timeline is not in expectedTLIs, then we cannot
	 * proceed: the backup is not part of the history of the requested
	 * timeline.
	 */
	if (!list_member_int(expectedTLIs,
B
Bruce Momjian 已提交
5545
						 (int) ControlFile->checkPointCopy.ThisTimeLineID))
5546 5547 5548 5549 5550
		ereport(FATAL,
				(errmsg("requested timeline %u is not a child of database system timeline %u",
						recoveryTargetTLI,
						ControlFile->checkPointCopy.ThisTimeLineID)));

5551 5552 5553 5554
	/*
	 * Save the selected recovery target timeline ID and restartpoint_command
	 * in shared memory so that other processes can see them
	 */
5555
	XLogCtl->RecoveryTargetTLI = recoveryTargetTLI;
5556 5557 5558
	strncpy(XLogCtl->restartPointCommand,
			restartPointCommand ? restartPointCommand : "",
			sizeof(XLogCtl->restartPointCommand));
5559

5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577
	if (InArchiveRecovery)
	{
		if (StandbyMode)
			ereport(LOG,
					(errmsg("entering standby mode")));
		else if (recoveryTarget == RECOVERY_TARGET_XID)
			ereport(LOG,
					 (errmsg("starting point-in-time recovery to XID %u",
						 recoveryTargetXid)));
		else if (recoveryTarget == RECOVERY_TARGET_TIME)
			ereport(LOG,
					(errmsg("starting point-in-time recovery to %s",
							timestamptz_to_str(recoveryTargetTime))));
		else
			ereport(LOG,
					(errmsg("starting archive recovery")));
	}

5578
	if (read_backup_label(&checkPointLoc))
T
Tom Lane 已提交
5579
	{
5580
		/*
B
Bruce Momjian 已提交
5581 5582
		 * When a backup_label file is present, we want to roll forward from
		 * the checkpoint it identifies, rather than using pg_control.
5583
		 */
5584
		record = ReadCheckpointRecord(checkPointLoc, 0);
5585 5586
		if (record != NULL)
		{
5587
			ereport(DEBUG1,
5588
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
5589
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
5590 5591 5592 5593 5594
			InRecovery = true;	/* force recovery even if SHUTDOWNED */
		}
		else
		{
			ereport(PANIC,
B
Bruce Momjian 已提交
5595 5596
					(errmsg("could not locate required checkpoint record"),
					 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
5597
		}
5598 5599
		/* set flag to delete it later */
		haveBackupLabel = true;
T
Tom Lane 已提交
5600 5601 5602
	}
	else
	{
5603
		/*
B
Bruce Momjian 已提交
5604 5605
		 * Get the last valid checkpoint record.  If the latest one according
		 * to pg_control is broken, try the next-to-last one.
5606 5607
		 */
		checkPointLoc = ControlFile->checkPoint;
5608
		RedoStartLSN = ControlFile->checkPointCopy.redo;
5609
		record = ReadCheckpointRecord(checkPointLoc, 1);
T
Tom Lane 已提交
5610 5611
		if (record != NULL)
		{
5612
			ereport(DEBUG1,
5613
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
5614
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
T
Tom Lane 已提交
5615
		}
5616
		else if (StandbyMode)
5617 5618 5619 5620 5621 5622 5623 5624
		{
			/*
			 * The last valid checkpoint record required for a streaming
			 * recovery exists in neither standby nor the primary.
			 */
			ereport(PANIC,
					(errmsg("could not locate a valid checkpoint record")));
		}
T
Tom Lane 已提交
5625
		else
5626 5627
		{
			checkPointLoc = ControlFile->prevCheckPoint;
5628
			record = ReadCheckpointRecord(checkPointLoc, 2);
5629 5630 5631
			if (record != NULL)
			{
				ereport(LOG,
B
Bruce Momjian 已提交
5632 5633 5634
						(errmsg("using previous checkpoint record at %X/%X",
							  checkPointLoc.xlogid, checkPointLoc.xrecoff)));
				InRecovery = true;		/* force recovery even if SHUTDOWNED */
5635 5636 5637
			}
			else
				ereport(PANIC,
B
Bruce Momjian 已提交
5638
					 (errmsg("could not locate a valid checkpoint record")));
5639
		}
T
Tom Lane 已提交
5640
	}
5641

T
Tom Lane 已提交
5642 5643 5644
	LastRec = RecPtr = checkPointLoc;
	memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
	wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
5645

5646
	ereport(DEBUG1,
B
Bruce Momjian 已提交
5647 5648 5649
			(errmsg("redo record is at %X/%X; shutdown %s",
					checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
					wasShutdown ? "TRUE" : "FALSE")));
5650
	ereport(DEBUG1,
5651 5652 5653
			(errmsg("next transaction ID: %u/%u; next OID: %u",
					checkPoint.nextXidEpoch, checkPoint.nextXid,
					checkPoint.nextOid)));
5654
	ereport(DEBUG1,
5655 5656
			(errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
					checkPoint.nextMulti, checkPoint.nextMultiOffset)));
5657 5658 5659
	ereport(DEBUG1,
			(errmsg("oldest unfrozen transaction ID: %u, in database %u",
					checkPoint.oldestXid, checkPoint.oldestXidDB)));
5660
	if (!TransactionIdIsNormal(checkPoint.nextXid))
5661
		ereport(PANIC,
5662
				(errmsg("invalid next transaction ID")));
5663 5664 5665

	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
5666
	ShmemVariableCache->oidCount = 0;
5667
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5668
	SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5669

5670
	/*
B
Bruce Momjian 已提交
5671 5672 5673
	 * We must replay WAL entries using the same TimeLineID they were created
	 * under, so temporarily adopt the TLI indicated by the checkpoint (see
	 * also xlog_redo()).
5674
	 */
5675
	ThisTimeLineID = checkPoint.ThisTimeLineID;
5676

5677
	RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
V
WAL  
Vadim B. Mikheev 已提交
5678

5679
	if (XLByteLT(RecPtr, checkPoint.redo))
5680 5681
		ereport(PANIC,
				(errmsg("invalid redo in checkpoint record")));
5682

5683
	/*
B
Bruce Momjian 已提交
5684
	 * Check whether we need to force recovery from WAL.  If it appears to
B
Bruce Momjian 已提交
5685 5686
	 * have been a clean shutdown and we did not have a recovery.conf file,
	 * then assume no recovery needed.
5687
	 */
5688
	if (XLByteLT(checkPoint.redo, RecPtr))
5689
	{
T
Tom Lane 已提交
5690
		if (wasShutdown)
5691
			ereport(PANIC,
B
Bruce Momjian 已提交
5692
					(errmsg("invalid redo record in shutdown checkpoint")));
V
WAL  
Vadim B. Mikheev 已提交
5693
		InRecovery = true;
5694 5695
	}
	else if (ControlFile->state != DB_SHUTDOWNED)
V
WAL  
Vadim B. Mikheev 已提交
5696
		InRecovery = true;
5697 5698 5699 5700 5701
	else if (InArchiveRecovery)
	{
		/* force recovery due to presence of recovery.conf */
		InRecovery = true;
	}
5702

V
WAL  
Vadim B. Mikheev 已提交
5703
	/* REDO */
5704
	if (InRecovery)
5705
	{
B
Bruce Momjian 已提交
5706
		int			rmid;
5707

5708
		/*
B
Bruce Momjian 已提交
5709 5710 5711 5712
		 * Update pg_control to show that we are recovering and to show the
		 * selected checkpoint as the place we are starting from. We also mark
		 * pg_control with any minimum recovery stop point obtained from a
		 * backup history file.
5713
		 */
5714
		if (InArchiveRecovery)
5715
			ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
5716
		else
5717
		{
5718
			ereport(LOG,
5719 5720
					(errmsg("database system was not properly shut down; "
							"automatic recovery in progress")));
5721 5722 5723 5724 5725
			ControlFile->state = DB_IN_CRASH_RECOVERY;
		}
		ControlFile->prevCheckPoint = ControlFile->checkPoint;
		ControlFile->checkPoint = checkPointLoc;
		ControlFile->checkPointCopy = checkPoint;
5726 5727 5728 5729 5730 5731
		if (InArchiveRecovery)
		{
			/* initialize minRecoveryPoint if not set yet */
			if (XLByteLT(ControlFile->minRecoveryPoint, checkPoint.redo))
				ControlFile->minRecoveryPoint = checkPoint.redo;
		}
B
Bruce Momjian 已提交
5732

5733 5734 5735 5736 5737 5738
		/*
		 * set backupStartupPoint if we're starting archive recovery from a
		 * base backup
		 */
		if (haveBackupLabel)
			ControlFile->backupStartPoint = checkPoint.redo;
5739
		ControlFile->time = (pg_time_t) time(NULL);
5740
		/* No need to hold ControlFileLock yet, we aren't up far enough */
5741 5742
		UpdateControlFile();

5743
		/* initialize our local copy of minRecoveryPoint */
5744 5745 5746 5747 5748 5749 5750
		minRecoveryPoint = ControlFile->minRecoveryPoint;

		/*
		 * Reset pgstat data, because it may be invalid after recovery.
		 */
		pgstat_reset_all();

5751
		/*
B
Bruce Momjian 已提交
5752 5753 5754 5755 5756 5757
		 * If there was a backup label file, it's done its job and the info
		 * has now been propagated into pg_control.  We must get rid of the
		 * label file so that if we crash during recovery, we'll pick up at
		 * the latest recovery restartpoint instead of going all the way back
		 * to the backup start point.  It seems prudent though to just rename
		 * the file out of the way rather than delete it completely.
5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768
		 */
		if (haveBackupLabel)
		{
			unlink(BACKUP_LABEL_OLD);
			if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
				ereport(FATAL,
						(errcode_for_file_access(),
						 errmsg("could not rename file \"%s\" to \"%s\": %m",
								BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
		}

5769 5770
		/*
		 * Initialize recovery connections, if enabled. We won't let backends
B
Bruce Momjian 已提交
5771 5772
		 * in yet, not until we've reached the min recovery point specified in
		 * control file and we've established a recovery snapshot from a
5773 5774 5775 5776 5777
		 * running-xacts WAL record.
		 */
		if (InArchiveRecovery && XLogRequestRecoveryConnections)
		{
			TransactionId *xids;
B
Bruce Momjian 已提交
5778
			int			nxids;
5779 5780 5781

			CheckRequiredParameterValues(checkPoint);

5782 5783
			ereport(DEBUG1,
					(errmsg("initializing recovery connections")));
5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800

			InitRecoveryTransactionEnvironment();

			if (wasShutdown)
				oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
			else
				oldestActiveXID = checkPoint.oldestActiveXid;
			Assert(TransactionIdIsValid(oldestActiveXID));

			/* Startup commit log and related stuff */
			StartupCLOG();
			StartupSUBTRANS(oldestActiveXID);
			StartupMultiXact();

			ProcArrayInitRecoveryInfo(oldestActiveXID);
		}

5801
		/* Initialize resource managers */
5802 5803 5804 5805 5806 5807
		for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
		{
			if (RmgrTable[rmid].rm_startup != NULL)
				RmgrTable[rmid].rm_startup();
		}

5808
		/*
B
Bruce Momjian 已提交
5809 5810
		 * Find the first record that logically follows the checkpoint --- it
		 * might physically precede it, though.
5811
		 */
5812
		if (XLByteLT(checkPoint.redo, RecPtr))
5813 5814
		{
			/* back up to find the record */
5815
			record = ReadRecord(&(checkPoint.redo), PANIC, false);
5816
		}
B
Bruce Momjian 已提交
5817
		else
5818
		{
5819
			/* just have to read next record after CheckPoint */
5820
			record = ReadRecord(NULL, LOG, false);
5821
		}
5822

T
Tom Lane 已提交
5823
		if (record != NULL)
5824
		{
5825 5826
			bool		recoveryContinue = true;
			bool		recoveryApply = true;
5827
			bool		reachedMinRecoveryPoint = false;
B
Bruce Momjian 已提交
5828
			ErrorContextCallback errcontext;
5829

5830 5831 5832
			/* use volatile pointer to prevent code rearrangement */
			volatile XLogCtlData *xlogctl = XLogCtl;

5833
			/* initialize shared replayEndRecPtr and recoveryLastRecPtr */
5834 5835
			SpinLockAcquire(&xlogctl->info_lck);
			xlogctl->replayEndRecPtr = ReadRecPtr;
5836
			xlogctl->recoveryLastRecPtr = ReadRecPtr;
5837
			SpinLockRelease(&xlogctl->info_lck);
5838

V
WAL  
Vadim B. Mikheev 已提交
5839
			InRedo = true;
5840

5841 5842 5843
			ereport(LOG,
					(errmsg("redo starts at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5844 5845 5846 5847 5848 5849 5850 5851 5852 5853

			/*
			 * Let postmaster know we've started redo now, so that it can
			 * launch bgwriter to perform restartpoints.  We don't bother
			 * during crash recovery as restartpoints can only be performed
			 * during archive recovery.  And we'd like to keep crash recovery
			 * simple, to avoid introducing bugs that could you from
			 * recovering after crash.
			 *
			 * After this point, we can no longer assume that we're the only
5854 5855
			 * process in addition to postmaster!  Also, fsync requests are
			 * subsequently to be handled by the bgwriter, not locally.
5856 5857
			 */
			if (InArchiveRecovery && IsUnderPostmaster)
5858 5859
			{
				SetForwardFsyncRequests();
5860
				SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED);
5861 5862
				bgwriterLaunched = true;
			}
5863 5864 5865 5866

			/*
			 * main redo apply loop
			 */
5867 5868
			do
			{
5869
#ifdef WAL_DEBUG
5870
				if (XLOG_DEBUG ||
B
Bruce Momjian 已提交
5871
				 (rmid == RM_XACT_ID && trace_recovery_messages <= DEBUG2) ||
5872
					(rmid != RM_XACT_ID && trace_recovery_messages <= DEBUG3))
V
WAL  
Vadim B. Mikheev 已提交
5873
				{
B
Bruce Momjian 已提交
5874
					StringInfoData buf;
V
WAL  
Vadim B. Mikheev 已提交
5875

5876 5877
					initStringInfo(&buf);
					appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
B
Bruce Momjian 已提交
5878 5879
									 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
									 EndRecPtr.xlogid, EndRecPtr.xrecoff);
5880 5881 5882 5883
					xlog_outrec(&buf, record);
					appendStringInfo(&buf, " - ");
					RmgrTable[record->xl_rmid].rm_desc(&buf,
													   record->xl_info,
B
Bruce Momjian 已提交
5884
													 XLogRecGetData(record));
5885 5886
					elog(LOG, "%s", buf.data);
					pfree(buf.data);
V
WAL  
Vadim B. Mikheev 已提交
5887
				}
5888
#endif
V
WAL  
Vadim B. Mikheev 已提交
5889

5890 5891
				/* Handle interrupt signals of startup process */
				HandleStartupProcInterrupts();
5892

5893
				/*
5894
				 * Have we passed our safe starting point?
5895
				 */
5896
				if (!reachedMinRecoveryPoint &&
5897 5898
					XLByteLE(minRecoveryPoint, EndRecPtr) &&
					XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
5899 5900 5901
				{
					reachedMinRecoveryPoint = true;
					ereport(LOG,
B
Bruce Momjian 已提交
5902 5903
						(errmsg("consistent recovery state reached at %X/%X",
								EndRecPtr.xlogid, EndRecPtr.xrecoff)));
5904
				}
5905 5906

				/*
5907
				 * Have we got a valid starting snapshot that will allow
B
Bruce Momjian 已提交
5908 5909
				 * queries to be run? If so, we can tell postmaster that the
				 * database is consistent now, enabling connections.
5910
				 */
5911 5912 5913 5914
				if (standbyState == STANDBY_SNAPSHOT_READY &&
					!backendsAllowed &&
					reachedMinRecoveryPoint &&
					IsUnderPostmaster)
5915
				{
5916 5917
					backendsAllowed = true;
					SendPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT);
5918 5919
				}

5920 5921 5922 5923 5924
				/*
				 * Have we reached our recovery target?
				 */
				if (recoveryStopsHere(record, &recoveryApply))
				{
B
Bruce Momjian 已提交
5925
					reachedStopPoint = true;	/* see below */
5926 5927 5928 5929 5930
					recoveryContinue = false;
					if (!recoveryApply)
						break;
				}

5931 5932 5933 5934 5935 5936
				/* Setup error traceback support for ereport() */
				errcontext.callback = rm_redo_error_callback;
				errcontext.arg = (void *) record;
				errcontext.previous = error_context_stack;
				error_context_stack = &errcontext;

5937 5938
				/* nextXid must be beyond record's xid */
				if (TransactionIdFollowsOrEquals(record->xl_xid,
B
Bruce Momjian 已提交
5939
												 ShmemVariableCache->nextXid))
5940 5941 5942 5943 5944
				{
					ShmemVariableCache->nextXid = record->xl_xid;
					TransactionIdAdvance(ShmemVariableCache->nextXid);
				}

5945
				/*
5946 5947
				 * Update shared replayEndRecPtr before replaying this record,
				 * so that XLogFlush will update minRecoveryPoint correctly.
5948 5949 5950
				 */
				SpinLockAcquire(&xlogctl->info_lck);
				xlogctl->replayEndRecPtr = EndRecPtr;
5951
				xlogctl->recoveryLastXTime = recoveryLastXTime;
5952 5953
				SpinLockRelease(&xlogctl->info_lck);

5954 5955 5956 5957
				/* In Hot Standby mode, keep track of XIDs we've seen */
				if (InHotStandby && TransactionIdIsValid(record->xl_xid))
					RecordKnownAssignedTransactionIds(record->xl_xid);

5958
				RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
5959

5960 5961 5962
				/* Pop the error context stack */
				error_context_stack = errcontext.previous;

5963 5964 5965 5966 5967 5968 5969 5970
				/*
				 * Update shared recoveryLastRecPtr after this record has been
				 * replayed.
				 */
				SpinLockAcquire(&xlogctl->info_lck);
				xlogctl->recoveryLastRecPtr = EndRecPtr;
				SpinLockRelease(&xlogctl->info_lck);

5971 5972
				LastRec = ReadRecPtr;

5973
				record = ReadRecord(NULL, LOG, false);
5974
			} while (record != NULL && recoveryContinue);
B
Bruce Momjian 已提交
5975

5976 5977 5978 5979
			/*
			 * end of main redo apply loop
			 */

5980 5981 5982
			ereport(LOG,
					(errmsg("redo done at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5983 5984
			if (recoveryLastXTime)
				ereport(LOG,
B
Bruce Momjian 已提交
5985 5986
					 (errmsg("last completed transaction was at log time %s",
							 timestamptz_to_str(recoveryLastXTime))));
V
WAL  
Vadim B. Mikheev 已提交
5987
			InRedo = false;
5988 5989
		}
		else
5990 5991
		{
			/* there are no WAL records following the checkpoint */
5992 5993
			ereport(LOG,
					(errmsg("redo is not required")));
5994
		}
V
WAL  
Vadim B. Mikheev 已提交
5995 5996
	}

5997 5998 5999 6000 6001 6002 6003 6004 6005 6006
	/*
	 * If we launched a WAL receiver, it should be gone by now. It will trump
	 * over the startup checkpoint and subsequent records if it's still alive,
	 * so be extra sure that it's gone.
	 */
	if (WalRcvInProgress())
		elog(PANIC, "wal receiver still active");

	/*
	 * We are now done reading the xlog from stream. Turn off streaming
B
Bruce Momjian 已提交
6007 6008
	 * recovery to force fetching the files (which would be required at end of
	 * recovery, e.g., timeline history file) from archive or pg_xlog.
6009
	 */
6010
	StandbyMode = false;
6011

T
Tom Lane 已提交
6012
	/*
B
Bruce Momjian 已提交
6013 6014
	 * Re-fetch the last valid or last applied record, so we can identify the
	 * exact endpoint of what we consider the valid portion of WAL.
T
Tom Lane 已提交
6015
	 */
6016
	record = ReadRecord(&LastRec, PANIC, false);
T
Tom Lane 已提交
6017
	EndOfLog = EndRecPtr;
6018 6019
	XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);

6020 6021
	/*
	 * Complain if we did not roll forward far enough to render the backup
6022 6023 6024 6025
	 * dump consistent.  Note: it is indeed okay to look at the local variable
	 * minRecoveryPoint here, even though ControlFile->minRecoveryPoint might
	 * be further ahead --- ControlFile->minRecoveryPoint cannot have been
	 * advanced beyond the WAL we processed.
6026
	 */
6027 6028 6029
	if (InArchiveRecovery &&
		(XLByteLT(EndOfLog, minRecoveryPoint) ||
		 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint)))
6030
	{
6031
		if (reachedStopPoint)	/* stopped because of stop request */
6032
			ereport(FATAL,
6033
					(errmsg("requested recovery stop point is before consistent recovery point")));
B
Bruce Momjian 已提交
6034
		else	/* ran off end of WAL */
6035
			ereport(FATAL,
6036
					(errmsg("WAL ends before consistent recovery point")));
6037 6038
	}

6039 6040 6041
	/*
	 * Consider whether we need to assign a new timeline ID.
	 *
B
Bruce Momjian 已提交
6042 6043
	 * If we are doing an archive recovery, we always assign a new ID.	This
	 * handles a couple of issues.	If we stopped short of the end of WAL
6044 6045
	 * during recovery, then we are clearly generating a new timeline and must
	 * assign it a unique new ID.  Even if we ran to the end, modifying the
B
Bruce Momjian 已提交
6046 6047
	 * current last segment is problematic because it may result in trying to
	 * overwrite an already-archived copy of that segment, and we encourage
6048 6049 6050 6051
	 * DBAs to make their archive_commands reject that.  We can dodge the
	 * problem by making the new active segment have a new timeline ID.
	 *
	 * In a normal crash recovery, we can just extend the timeline we were in.
6052
	 */
6053
	if (InArchiveRecovery)
6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064
	{
		ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
		ereport(LOG,
				(errmsg("selected new timeline ID: %u", ThisTimeLineID)));
		writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
							 curFileTLI, endLogId, endLogSeg);
	}

	/* Save the selected TimeLineID in shared memory, too */
	XLogCtl->ThisTimeLineID = ThisTimeLineID;

6065
	/*
B
Bruce Momjian 已提交
6066 6067 6068 6069
	 * We are now done reading the old WAL.  Turn off archive fetching if it
	 * was active, and make a writable copy of the last WAL segment. (Note
	 * that we also have a copy of the last block of the old WAL in readBuf;
	 * we will use that below.)
6070 6071
	 */
	if (InArchiveRecovery)
6072
		exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
6073 6074 6075 6076 6077 6078 6079 6080

	/*
	 * Prepare to write WAL starting at EndOfLog position, and init xlog
	 * buffer cache using the block containing the last record from the
	 * previous incarnation.
	 */
	openLogId = endLogId;
	openLogSeg = endLogSeg;
6081
	openLogFile = XLogFileOpen(openLogId, openLogSeg);
T
Tom Lane 已提交
6082
	openLogOff = 0;
V
WAL  
Vadim B. Mikheev 已提交
6083
	Insert = &XLogCtl->Insert;
6084
	Insert->PrevRecord = LastRec;
6085 6086
	XLogCtl->xlblocks[0].xlogid = openLogId;
	XLogCtl->xlblocks[0].xrecoff =
6087
		((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
B
Bruce Momjian 已提交
6088 6089

	/*
B
Bruce Momjian 已提交
6090 6091 6092
	 * Tricky point here: readBuf contains the *last* block that the LastRec
	 * record spans, not the one it starts in.	The last block is indeed the
	 * one we want to use.
T
Tom Lane 已提交
6093
	 */
6094 6095
	Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
	memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
6096
	Insert->currpos = (char *) Insert->currpage +
6097
		(EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
V
WAL  
Vadim B. Mikheev 已提交
6098

T
Tom Lane 已提交
6099
	LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
V
WAL  
Vadim B. Mikheev 已提交
6100

T
Tom Lane 已提交
6101 6102 6103
	XLogCtl->Write.LogwrtResult = LogwrtResult;
	Insert->LogwrtResult = LogwrtResult;
	XLogCtl->LogwrtResult = LogwrtResult;
V
WAL  
Vadim B. Mikheev 已提交
6104

T
Tom Lane 已提交
6105 6106
	XLogCtl->LogwrtRqst.Write = EndOfLog;
	XLogCtl->LogwrtRqst.Flush = EndOfLog;
6107

6108 6109 6110 6111 6112 6113 6114 6115 6116 6117
	freespace = INSERT_FREESPACE(Insert);
	if (freespace > 0)
	{
		/* Make sure rest of page is zero */
		MemSet(Insert->currpos, 0, freespace);
		XLogCtl->Write.curridx = 0;
	}
	else
	{
		/*
B
Bruce Momjian 已提交
6118 6119
		 * Whenever Write.LogwrtResult points to exactly the end of a page,
		 * Write.curridx must point to the *next* page (see XLogWrite()).
6120
		 *
B
Bruce Momjian 已提交
6121
		 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
B
Bruce Momjian 已提交
6122
		 * this is sufficient.	The first actual attempt to insert a log
6123
		 * record will advance the insert state.
6124 6125 6126 6127
		 */
		XLogCtl->Write.curridx = NextBufIdx(0);
	}

6128
	/* Pre-scan prepared transactions to find out the range of XIDs present */
6129
	oldestActiveXID = PrescanPreparedTransactions(NULL, NULL);
6130

V
WAL  
Vadim B. Mikheev 已提交
6131
	if (InRecovery)
6132
	{
B
Bruce Momjian 已提交
6133
		int			rmid;
6134

6135 6136 6137 6138 6139 6140 6141
		/*
		 * Resource managers might need to write WAL records, eg, to record
		 * index cleanup actions.  So temporarily enable XLogInsertAllowed in
		 * this process only.
		 */
		LocalSetXLogInsertAllowed();

6142 6143 6144 6145 6146 6147 6148 6149 6150
		/*
		 * Allow resource managers to do any required cleanup.
		 */
		for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
		{
			if (RmgrTable[rmid].rm_cleanup != NULL)
				RmgrTable[rmid].rm_cleanup();
		}

6151 6152 6153
		/* Disallow XLogInsert again */
		LocalXLogInsertAllowed = -1;

6154 6155 6156 6157 6158 6159
		/*
		 * Check to see if the XLOG sequence contained any unresolved
		 * references to uninitialized pages.
		 */
		XLogCheckInvalidPages();

T
Tom Lane 已提交
6160
		/*
6161
		 * Perform a checkpoint to update all our recovery activity to disk.
6162
		 *
6163 6164 6165 6166 6167
		 * Note that we write a shutdown checkpoint rather than an on-line
		 * one. This is not particularly critical, but since we may be
		 * assigning a new TLI, using a shutdown checkpoint allows us to have
		 * the rule that TLI only changes in shutdown checkpoints, which
		 * allows some extra error checking in xlog_redo.
T
Tom Lane 已提交
6168
		 */
6169 6170 6171 6172 6173 6174
		if (bgwriterLaunched)
			RequestCheckpoint(CHECKPOINT_END_OF_RECOVERY |
							  CHECKPOINT_IMMEDIATE |
							  CHECKPOINT_WAIT);
		else
			CreateCheckPoint(CHECKPOINT_END_OF_RECOVERY | CHECKPOINT_IMMEDIATE);
6175

T
Tom Lane 已提交
6176 6177 6178
		/*
		 * And finally, execute the recovery_end_command, if any.
		 */
6179
		if (recoveryEndCommand)
6180 6181 6182
			ExecuteRecoveryCommand(recoveryEndCommand,
								   "recovery_end_command",
								   true);
6183
	}
6184

T
Tom Lane 已提交
6185 6186 6187
	/*
	 * Preallocate additional log files, if wanted.
	 */
6188
	PreallocXlogFiles(EndOfLog);
6189

6190 6191 6192
	/*
	 * Okay, we're officially UP.
	 */
V
WAL  
Vadim B. Mikheev 已提交
6193
	InRecovery = false;
6194

6195
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6196
	ControlFile->state = DB_IN_PRODUCTION;
6197
	ControlFile->time = (pg_time_t) time(NULL);
6198
	UpdateControlFile();
6199
	LWLockRelease(ControlFileLock);
6200

6201
	/* start the archive_timeout timer running */
6202
	XLogCtl->Write.lastSegSwitchTime = (pg_time_t) time(NULL);
6203

6204 6205 6206 6207
	/* initialize shared-memory copy of latest checkpoint XID/epoch */
	XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
	XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;

6208 6209 6210 6211
	/* also initialize latestCompletedXid, to nextXid - 1 */
	ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
	TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);

6212
	/*
B
Bruce Momjian 已提交
6213 6214
	 * Start up the commit log and related stuff, too. In hot standby mode we
	 * did this already before WAL replay.
6215 6216 6217 6218 6219 6220 6221
	 */
	if (standbyState == STANDBY_DISABLED)
	{
		StartupCLOG();
		StartupSUBTRANS(oldestActiveXID);
		StartupMultiXact();
	}
6222

6223 6224 6225
	/* Reload shared-memory state for prepared transactions */
	RecoverPreparedTransactions();

6226 6227 6228 6229 6230 6231 6232
	/*
	 * Shutdown the recovery environment. This must occur after
	 * RecoverPreparedTransactions(), see notes for lock_twophase_recover()
	 */
	if (standbyState != STANDBY_DISABLED)
		ShutdownRecoveryTransactionEnvironment();

T
Tom Lane 已提交
6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243
	/* Shut down readFile facility, free space */
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
	if (readBuf)
	{
		free(readBuf);
		readBuf = NULL;
	}
6244 6245 6246 6247 6248 6249
	if (readRecordBuf)
	{
		free(readRecordBuf);
		readRecordBuf = NULL;
		readRecordBufSize = 0;
	}
6250 6251

	/*
B
Bruce Momjian 已提交
6252
	 * All done.  Allow backends to write WAL.	(Although the bool flag is
6253 6254 6255
	 * probably atomic in itself, we use the info_lck here to ensure that
	 * there are no race conditions concerning visibility of other recent
	 * updates to shared memory.)
6256
	 */
6257 6258 6259 6260 6261 6262 6263 6264
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		SpinLockAcquire(&xlogctl->info_lck);
		xlogctl->SharedRecoveryInProgress = false;
		SpinLockRelease(&xlogctl->info_lck);
	}
6265 6266 6267 6268 6269
}

/*
 * Is the system still in recovery?
 *
6270 6271 6272
 * Unlike testing InRecovery, this works in any process that's connected to
 * shared memory.
 *
6273 6274 6275 6276 6277 6278 6279
 * As a side-effect, we initialize the local TimeLineID and RedoRecPtr
 * variables the first time we see that recovery is finished.
 */
bool
RecoveryInProgress(void)
{
	/*
B
Bruce Momjian 已提交
6280 6281 6282
	 * We check shared state each time only until we leave recovery mode. We
	 * can't re-enter recovery, so there's no need to keep checking after the
	 * shared variable has once been seen false.
6283 6284 6285 6286 6287 6288 6289 6290
	 */
	if (!LocalRecoveryInProgress)
		return false;
	else
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

6291 6292
		/* spinlock is essential on machines with weak memory ordering! */
		SpinLockAcquire(&xlogctl->info_lck);
6293
		LocalRecoveryInProgress = xlogctl->SharedRecoveryInProgress;
6294
		SpinLockRelease(&xlogctl->info_lck);
6295 6296

		/*
6297
		 * Initialize TimeLineID and RedoRecPtr when we discover that recovery
6298
		 * is finished. InitPostgres() relies upon this behaviour to ensure
B
Bruce Momjian 已提交
6299
		 * that InitXLOGAccess() is called at backend startup.	(If you change
6300
		 * this, see also LocalSetXLogInsertAllowed.)
6301 6302 6303 6304 6305 6306
		 */
		if (!LocalRecoveryInProgress)
			InitXLOGAccess();

		return LocalRecoveryInProgress;
	}
T
Tom Lane 已提交
6307 6308
}

6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319
/*
 * Is this process allowed to insert new WAL records?
 *
 * Ordinarily this is essentially equivalent to !RecoveryInProgress().
 * But we also have provisions for forcing the result "true" or "false"
 * within specific processes regardless of the global state.
 */
bool
XLogInsertAllowed(void)
{
	/*
B
Bruce Momjian 已提交
6320 6321 6322
	 * If value is "unconditionally true" or "unconditionally false", just
	 * return it.  This provides the normal fast path once recovery is known
	 * done.
6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333
	 */
	if (LocalXLogInsertAllowed >= 0)
		return (bool) LocalXLogInsertAllowed;

	/*
	 * Else, must check to see if we're still in recovery.
	 */
	if (RecoveryInProgress())
		return false;

	/*
B
Bruce Momjian 已提交
6334 6335
	 * On exit from recovery, reset to "unconditionally true", since there is
	 * no need to keep checking.
6336 6337 6338 6339 6340 6341 6342
	 */
	LocalXLogInsertAllowed = 1;
	return true;
}

/*
 * Make XLogInsertAllowed() return true in the current process only.
6343 6344 6345
 *
 * Note: it is allowed to switch LocalXLogInsertAllowed back to -1 later,
 * and even call LocalSetXLogInsertAllowed() again after that.
6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356
 */
static void
LocalSetXLogInsertAllowed(void)
{
	Assert(LocalXLogInsertAllowed == -1);
	LocalXLogInsertAllowed = 1;

	/* Initialize as RecoveryInProgress() would do when switching state */
	InitXLOGAccess();
}

6357 6358
/*
 * Subroutine to try to fetch and validate a prior checkpoint record.
6359 6360 6361
 *
 * whichChkpt identifies the checkpoint (merely for reporting purposes).
 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
6362
 */
T
Tom Lane 已提交
6363
static XLogRecord *
6364
ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
T
Tom Lane 已提交
6365 6366 6367 6368 6369
{
	XLogRecord *record;

	if (!XRecOffIsValid(RecPtr.xrecoff))
	{
6370 6371 6372 6373
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
6374
				(errmsg("invalid primary checkpoint link in control file")));
6375 6376 6377 6378 6379 6380 6381
				break;
			case 2:
				ereport(LOG,
						(errmsg("invalid secondary checkpoint link in control file")));
				break;
			default:
				ereport(LOG,
B
Bruce Momjian 已提交
6382
				   (errmsg("invalid checkpoint link in backup_label file")));
6383 6384
				break;
		}
T
Tom Lane 已提交
6385 6386 6387
		return NULL;
	}

6388
	record = ReadRecord(&RecPtr, LOG, true);
T
Tom Lane 已提交
6389 6390 6391

	if (record == NULL)
	{
6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
						(errmsg("invalid primary checkpoint record")));
				break;
			case 2:
				ereport(LOG,
						(errmsg("invalid secondary checkpoint record")));
				break;
			default:
				ereport(LOG,
						(errmsg("invalid checkpoint record")));
				break;
		}
T
Tom Lane 已提交
6407 6408 6409 6410
		return NULL;
	}
	if (record->xl_rmid != RM_XLOG_ID)
	{
6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
						(errmsg("invalid resource manager ID in primary checkpoint record")));
				break;
			case 2:
				ereport(LOG,
						(errmsg("invalid resource manager ID in secondary checkpoint record")));
				break;
			default:
				ereport(LOG,
B
Bruce Momjian 已提交
6423
				(errmsg("invalid resource manager ID in checkpoint record")));
6424 6425
				break;
		}
T
Tom Lane 已提交
6426 6427 6428 6429 6430
		return NULL;
	}
	if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
		record->xl_info != XLOG_CHECKPOINT_ONLINE)
	{
6431 6432 6433 6434
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
6435
				   (errmsg("invalid xl_info in primary checkpoint record")));
6436 6437 6438
				break;
			case 2:
				ereport(LOG,
B
Bruce Momjian 已提交
6439
				 (errmsg("invalid xl_info in secondary checkpoint record")));
6440 6441 6442 6443 6444 6445
				break;
			default:
				ereport(LOG,
						(errmsg("invalid xl_info in checkpoint record")));
				break;
		}
T
Tom Lane 已提交
6446 6447
		return NULL;
	}
6448 6449
	if (record->xl_len != sizeof(CheckPoint) ||
		record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
T
Tom Lane 已提交
6450
	{
6451 6452 6453 6454
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
6455
					(errmsg("invalid length of primary checkpoint record")));
6456 6457 6458
				break;
			case 2:
				ereport(LOG,
B
Bruce Momjian 已提交
6459
				  (errmsg("invalid length of secondary checkpoint record")));
6460 6461 6462 6463 6464 6465
				break;
			default:
				ereport(LOG,
						(errmsg("invalid length of checkpoint record")));
				break;
		}
T
Tom Lane 已提交
6466 6467 6468
		return NULL;
	}
	return record;
6469 6470
}

V
WAL  
Vadim B. Mikheev 已提交
6471
/*
6472 6473
 * This must be called during startup of a backend process, except that
 * it need not be called in a standalone backend (which does StartupXLOG
6474
 * instead).  We need to initialize the local copies of ThisTimeLineID and
6475 6476
 * RedoRecPtr.
 *
6477
 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
6478
 * process's copies of ThisTimeLineID and RedoRecPtr valid too.  This was
6479
 * unnecessary however, since the postmaster itself never touches XLOG anyway.
V
WAL  
Vadim B. Mikheev 已提交
6480 6481
 */
void
6482
InitXLOGAccess(void)
V
WAL  
Vadim B. Mikheev 已提交
6483
{
6484 6485
	/* ThisTimeLineID doesn't change so we need no lock to copy it */
	ThisTimeLineID = XLogCtl->ThisTimeLineID;
6486
	Assert(ThisTimeLineID != 0 || IsBootstrapProcessingMode());
6487

6488 6489
	/* Use GetRedoRecPtr to copy the RedoRecPtr safely */
	(void) GetRedoRecPtr();
6490 6491 6492 6493 6494 6495 6496 6497
}

/*
 * Once spawned, a backend may update its local RedoRecPtr from
 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
 * to do so.  This is done in XLogInsert() or GetRedoRecPtr().
 */
XLogRecPtr
6498 6499
GetRedoRecPtr(void)
{
6500 6501 6502
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

6503
	SpinLockAcquire(&xlogctl->info_lck);
6504 6505
	Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
	RedoRecPtr = xlogctl->Insert.RedoRecPtr;
6506
	SpinLockRelease(&xlogctl->info_lck);
6507 6508

	return RedoRecPtr;
V
WAL  
Vadim B. Mikheev 已提交
6509 6510
}

6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524
/*
 * GetInsertRecPtr -- Returns the current insert position.
 *
 * NOTE: The value *actually* returned is the position of the last full
 * xlog page. It lags behind the real insert position by at most 1 page.
 * For that, we don't need to acquire WALInsertLock which can be quite
 * heavily contended, and an approximation is enough for the current
 * usage of this function.
 */
XLogRecPtr
GetInsertRecPtr(void)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
B
Bruce Momjian 已提交
6525
	XLogRecPtr	recptr;
6526 6527 6528 6529 6530 6531 6532 6533

	SpinLockAcquire(&xlogctl->info_lck);
	recptr = xlogctl->LogwrtRqst.Write;
	SpinLockRelease(&xlogctl->info_lck);

	return recptr;
}

6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550
/*
 * GetWriteRecPtr -- Returns the current write position.
 */
XLogRecPtr
GetWriteRecPtr(void)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	XLogRecPtr	recptr;

	SpinLockAcquire(&xlogctl->info_lck);
	recptr = xlogctl->LogwrtResult.Write;
	SpinLockRelease(&xlogctl->info_lck);

	return recptr;
}

6551 6552 6553
/*
 * Get the time of the last xlog segment switch
 */
6554
pg_time_t
6555 6556
GetLastSegSwitchTime(void)
{
6557
	pg_time_t	result;
6558 6559 6560 6561 6562 6563 6564 6565 6566

	/* Need WALWriteLock, but shared lock is sufficient */
	LWLockAcquire(WALWriteLock, LW_SHARED);
	result = XLogCtl->Write.lastSegSwitchTime;
	LWLockRelease(WALWriteLock);

	return result;
}

6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577
/*
 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
 *
 * This is exported for use by code that would like to have 64-bit XIDs.
 * We don't really support such things, but all XIDs within the system
 * can be presumed "close to" the result, and thus the epoch associated
 * with them can be determined.
 */
void
GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
{
B
Bruce Momjian 已提交
6578 6579 6580
	uint32		ckptXidEpoch;
	TransactionId ckptXid;
	TransactionId nextXid;
6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606

	/* Must read checkpoint info first, else have race condition */
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		SpinLockAcquire(&xlogctl->info_lck);
		ckptXidEpoch = xlogctl->ckptXidEpoch;
		ckptXid = xlogctl->ckptXid;
		SpinLockRelease(&xlogctl->info_lck);
	}

	/* Now fetch current nextXid */
	nextXid = ReadNewTransactionId();

	/*
	 * nextXid is certainly logically later than ckptXid.  So if it's
	 * numerically less, it must have wrapped into the next epoch.
	 */
	if (nextXid < ckptXid)
		ckptXidEpoch++;

	*xid = nextXid;
	*epoch = ckptXidEpoch;
}

6607 6608 6609 6610 6611 6612 6613 6614 6615 6616
/*
 * GetRecoveryTargetTLI - get the recovery target timeline ID
 */
TimeLineID
GetRecoveryTargetTLI(void)
{
	/* RecoveryTargetTLI doesn't change so we need no lock to copy it */
	return XLogCtl->RecoveryTargetTLI;
}

6617
/*
T
Tom Lane 已提交
6618
 * This must be called ONCE during postmaster or standalone-backend shutdown
6619 6620
 */
void
6621
ShutdownXLOG(int code, Datum arg)
6622
{
6623 6624
	ereport(LOG,
			(errmsg("shutting down")));
6625

6626 6627 6628
	if (RecoveryInProgress())
		CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
	else
6629 6630 6631 6632 6633 6634 6635 6636 6637 6638
	{
		/*
		 * If archiving is enabled, rotate the last XLOG file so that all the
		 * remaining records are archived (postmaster wakes up the archiver
		 * process one more time at the end of shutdown). The checkpoint
		 * record will go to the next XLOG file and won't be archived (yet).
		 */
		if (XLogArchivingActive() && XLogArchiveCommandSet())
			RequestXLogSwitch();

6639
		CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
6640
	}
6641
	ShutdownCLOG();
6642
	ShutdownSUBTRANS();
6643
	ShutdownMultiXact();
6644

6645 6646
	ereport(LOG,
			(errmsg("database system is shut down")));
6647 6648
}

6649
/*
6650 6651 6652
 * Log start of a checkpoint.
 */
static void
6653
LogCheckpointStart(int flags, bool restartpoint)
6654
{
6655
	const char *msg;
6656 6657

	/*
6658 6659
	 * XXX: This is hopelessly untranslatable. We could call gettext_noop for
	 * the main message, but what about all the flags?
6660 6661
	 */
	if (restartpoint)
6662
		msg = "restartpoint starting:%s%s%s%s%s%s%s";
6663
	else
6664
		msg = "checkpoint starting:%s%s%s%s%s%s%s";
6665 6666

	elog(LOG, msg,
6667
		 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
6668
		 (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
6669 6670 6671 6672 6673 6674 6675
		 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
		 (flags & CHECKPOINT_FORCE) ? " force" : "",
		 (flags & CHECKPOINT_WAIT) ? " wait" : "",
		 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
		 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
}

6676
/*
6677 6678 6679
 * Log end of a checkpoint.
 */
static void
6680
LogCheckpointEnd(bool restartpoint)
6681
{
B
Bruce Momjian 已提交
6682 6683 6684 6685 6686 6687
	long		write_secs,
				sync_secs,
				total_secs;
	int			write_usecs,
				sync_usecs,
				total_usecs;
6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702

	CheckpointStats.ckpt_end_t = GetCurrentTimestamp();

	TimestampDifference(CheckpointStats.ckpt_start_t,
						CheckpointStats.ckpt_end_t,
						&total_secs, &total_usecs);

	TimestampDifference(CheckpointStats.ckpt_write_t,
						CheckpointStats.ckpt_sync_t,
						&write_secs, &write_usecs);

	TimestampDifference(CheckpointStats.ckpt_sync_t,
						CheckpointStats.ckpt_sync_end_t,
						&sync_secs, &sync_usecs);

6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722
	if (restartpoint)
		elog(LOG, "restartpoint complete: wrote %d buffers (%.1f%%); "
			 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
			 CheckpointStats.ckpt_bufs_written,
			 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
			 write_secs, write_usecs / 1000,
			 sync_secs, sync_usecs / 1000,
			 total_secs, total_usecs / 1000);
	else
		elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
			 "%d transaction log file(s) added, %d removed, %d recycled; "
			 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
			 CheckpointStats.ckpt_bufs_written,
			 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
			 CheckpointStats.ckpt_segs_added,
			 CheckpointStats.ckpt_segs_removed,
			 CheckpointStats.ckpt_segs_recycled,
			 write_secs, write_usecs / 1000,
			 sync_secs, sync_usecs / 1000,
			 total_secs, total_usecs / 1000);
6723 6724
}

T
Tom Lane 已提交
6725 6726
/*
 * Perform a checkpoint --- either during shutdown, or on-the-fly
6727
 *
6728 6729
 * flags is a bitwise OR of the following:
 *	CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
6730
 *	CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
6731
 *	CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
6732
 *		ignoring checkpoint_completion_target parameter.
6733
 *	CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
6734
 *		since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
6735
 *		CHECKPOINT_END_OF_RECOVERY).
6736
 *
6737
 * Note: flags contains other bits, of interest here only for logging purposes.
6738 6739
 * In particular note that this routine is synchronous and does not pay
 * attention to CHECKPOINT_WAIT.
T
Tom Lane 已提交
6740
 */
6741
void
6742
CreateCheckPoint(int flags)
6743
{
6744
	bool		shutdown;
6745 6746 6747
	CheckPoint	checkPoint;
	XLogRecPtr	recptr;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
B
Bruce Momjian 已提交
6748
	XLogRecData rdata;
6749
	uint32		freespace;
V
Vadim B. Mikheev 已提交
6750 6751
	uint32		_logId;
	uint32		_logSeg;
6752 6753
	TransactionId *inCommitXids;
	int			nInCommit;
V
Vadim B. Mikheev 已提交
6754

6755 6756 6757 6758
	/*
	 * An end-of-recovery checkpoint is really a shutdown checkpoint, just
	 * issued at a different time.
	 */
6759
	if (flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY))
6760 6761 6762
		shutdown = true;
	else
		shutdown = false;
6763

6764 6765 6766
	/* sanity check */
	if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
		elog(ERROR, "can't create a checkpoint during recovery");
6767

6768 6769 6770 6771 6772 6773 6774 6775
	/*
	 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
	 * (This is just pro forma, since in the present system structure there is
	 * only one process that is allowed to issue checkpoints at any given
	 * time.)
	 */
	LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);

6776 6777 6778 6779 6780 6781 6782 6783 6784 6785
	/*
	 * Prepare to accumulate statistics.
	 *
	 * Note: because it is possible for log_checkpoints to change while a
	 * checkpoint proceeds, we always accumulate stats, even if
	 * log_checkpoints is currently off.
	 */
	MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
	CheckpointStats.ckpt_start_t = GetCurrentTimestamp();

6786 6787 6788
	/*
	 * Use a critical section to force system panic if we have trouble.
	 */
6789 6790
	START_CRIT_SECTION();

6791 6792
	if (shutdown)
	{
6793
		LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6794
		ControlFile->state = DB_SHUTDOWNING;
6795
		ControlFile->time = (pg_time_t) time(NULL);
6796
		UpdateControlFile();
6797
		LWLockRelease(ControlFileLock);
6798
	}
T
Tom Lane 已提交
6799

6800
	/*
B
Bruce Momjian 已提交
6801 6802 6803
	 * Let smgr prepare for checkpoint; this has to happen before we determine
	 * the REDO pointer.  Note that smgr must not do anything that'd have to
	 * be undone if we decide no checkpoint is needed.
6804 6805 6806 6807
	 */
	smgrpreckpt();

	/* Begin filling in the checkpoint WAL record */
6808
	MemSet(&checkPoint, 0, sizeof(checkPoint));
6809
	checkPoint.time = (pg_time_t) time(NULL);
6810

6811 6812 6813 6814 6815 6816
	/* Set important parameter values for use when replaying WAL */
	checkPoint.MaxConnections = MaxConnections;
	checkPoint.max_prepared_xacts = max_prepared_xacts;
	checkPoint.max_locks_per_xact = max_locks_per_xact;
	checkPoint.XLogStandbyInfoMode = XLogStandbyInfoActive();

6817
	/*
6818 6819
	 * We must hold WALInsertLock while examining insert state to determine
	 * the checkpoint REDO pointer.
6820
	 */
6821
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
T
Tom Lane 已提交
6822 6823

	/*
B
Bruce Momjian 已提交
6824 6825 6826 6827 6828 6829 6830 6831
	 * If this isn't a shutdown or forced checkpoint, and we have not inserted
	 * any XLOG records since the start of the last checkpoint, skip the
	 * checkpoint.	The idea here is to avoid inserting duplicate checkpoints
	 * when the system is idle. That wastes log space, and more importantly it
	 * exposes us to possible loss of both current and previous checkpoint
	 * records if the machine crashes just as we're writing the update.
	 * (Perhaps it'd make even more sense to checkpoint only when the previous
	 * checkpoint record is in a different xlog page?)
T
Tom Lane 已提交
6832
	 *
6833 6834 6835 6836
	 * We have to make two tests to determine that nothing has happened since
	 * the start of the last checkpoint: current insertion point must match
	 * the end of the last checkpoint record, and its redo pointer must point
	 * to itself.
T
Tom Lane 已提交
6837
	 */
6838 6839
	if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
				  CHECKPOINT_FORCE)) == 0)
T
Tom Lane 已提交
6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851
	{
		XLogRecPtr	curInsert;

		INSERT_RECPTR(curInsert, Insert, Insert->curridx);
		if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
			curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
			MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
			ControlFile->checkPoint.xlogid ==
			ControlFile->checkPointCopy.redo.xlogid &&
			ControlFile->checkPoint.xrecoff ==
			ControlFile->checkPointCopy.redo.xrecoff)
		{
6852 6853
			LWLockRelease(WALInsertLock);
			LWLockRelease(CheckpointLock);
T
Tom Lane 已提交
6854 6855 6856 6857 6858
			END_CRIT_SECTION();
			return;
		}
	}

6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869
	/*
	 * An end-of-recovery checkpoint is created before anyone is allowed to
	 * write WAL. To allow us to write the checkpoint record, temporarily
	 * enable XLogInsertAllowed.  (This also ensures ThisTimeLineID is
	 * initialized, which we need here and in AdvanceXLInsertBuffer.)
	 */
	if (flags & CHECKPOINT_END_OF_RECOVERY)
		LocalSetXLogInsertAllowed();

	checkPoint.ThisTimeLineID = ThisTimeLineID;

T
Tom Lane 已提交
6870 6871 6872
	/*
	 * Compute new REDO record ptr = location of next XLOG record.
	 *
B
Bruce Momjian 已提交
6873 6874 6875 6876
	 * NB: this is NOT necessarily where the checkpoint record itself will be,
	 * since other backends may insert more XLOG records while we're off doing
	 * the buffer flush work.  Those XLOG records are logically after the
	 * checkpoint, even though physically before it.  Got that?
T
Tom Lane 已提交
6877 6878
	 */
	freespace = INSERT_FREESPACE(Insert);
6879 6880
	if (freespace < SizeOfXLogRecord)
	{
6881
		(void) AdvanceXLInsertBuffer(false);
T
Tom Lane 已提交
6882
		/* OK to ignore update return flag, since we will do flush anyway */
6883
		freespace = INSERT_FREESPACE(Insert);
6884
	}
T
Tom Lane 已提交
6885
	INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
B
Bruce Momjian 已提交
6886

T
Tom Lane 已提交
6887
	/*
B
Bruce Momjian 已提交
6888 6889
	 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
	 * must be done while holding the insert lock AND the info_lck.
6890
	 *
B
Bruce Momjian 已提交
6891
	 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
B
Bruce Momjian 已提交
6892 6893 6894 6895 6896
	 * pointing past where it really needs to point.  This is okay; the only
	 * consequence is that XLogInsert might back up whole buffers that it
	 * didn't really need to.  We can't postpone advancing RedoRecPtr because
	 * XLogInserts that happen while we are dumping buffers must assume that
	 * their buffer changes are not included in the checkpoint.
T
Tom Lane 已提交
6897
	 */
6898 6899 6900 6901
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

6902
		SpinLockAcquire(&xlogctl->info_lck);
6903
		RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
6904
		SpinLockRelease(&xlogctl->info_lck);
6905
	}
B
Bruce Momjian 已提交
6906

T
Tom Lane 已提交
6907
	/*
6908 6909
	 * Now we can release WAL insert lock, allowing other xacts to proceed
	 * while we are flushing disk buffers.
T
Tom Lane 已提交
6910
	 */
6911
	LWLockRelease(WALInsertLock);
6912

6913
	/*
B
Bruce Momjian 已提交
6914 6915
	 * If enabled, log checkpoint start.  We postpone this until now so as not
	 * to log anything if we decided to skip the checkpoint.
6916 6917
	 */
	if (log_checkpoints)
6918
		LogCheckpointStart(flags, false);
6919

6920 6921
	TRACE_POSTGRESQL_CHECKPOINT_START(flags);

6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936
	/*
	 * Before flushing data, we must wait for any transactions that are
	 * currently in their commit critical sections.  If an xact inserted its
	 * commit record into XLOG just before the REDO point, then a crash
	 * restart from the REDO point would not replay that record, which means
	 * that our flushing had better include the xact's update of pg_clog.  So
	 * we wait till he's out of his commit critical section before proceeding.
	 * See notes in RecordTransactionCommit().
	 *
	 * Because we've already released WALInsertLock, this test is a bit fuzzy:
	 * it is possible that we will wait for xacts we didn't really need to
	 * wait for.  But the delay should be short and it seems better to make
	 * checkpoint take a bit longer than to hold locks longer than necessary.
	 * (In fact, the whole reason we have this issue is that xact.c does
	 * commit record XLOG insertion and clog update as two separate steps
B
Bruce Momjian 已提交
6937 6938
	 * protected by different locks, but again that seems best on grounds of
	 * minimizing lock contention.)
6939
	 *
B
Bruce Momjian 已提交
6940 6941
	 * A transaction that has not yet set inCommit when we look cannot be at
	 * risk, since he's not inserted his commit record yet; and one that's
6942 6943 6944 6945 6946 6947 6948
	 * already cleared it is not at risk either, since he's done fixing clog
	 * and we will correctly flush the update below.  So we cannot miss any
	 * xacts we need to wait for.
	 */
	nInCommit = GetTransactionsInCommit(&inCommitXids);
	if (nInCommit > 0)
	{
B
Bruce Momjian 已提交
6949 6950 6951
		do
		{
			pg_usleep(10000L);	/* wait for 10 msec */
6952 6953 6954 6955
		} while (HaveTransactionsInCommit(inCommitXids, nInCommit));
	}
	pfree(inCommitXids);

6956 6957 6958
	/*
	 * Get the other info we need for the checkpoint record.
	 */
6959
	LWLockAcquire(XidGenLock, LW_SHARED);
6960
	checkPoint.nextXid = ShmemVariableCache->nextXid;
6961 6962
	checkPoint.oldestXid = ShmemVariableCache->oldestXid;
	checkPoint.oldestXidDB = ShmemVariableCache->oldestXidDB;
6963
	LWLockRelease(XidGenLock);
T
Tom Lane 已提交
6964

6965 6966 6967 6968 6969
	/* Increase XID epoch if we've wrapped around since last checkpoint */
	checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
	if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
		checkPoint.nextXidEpoch++;

6970
	LWLockAcquire(OidGenLock, LW_SHARED);
6971
	checkPoint.nextOid = ShmemVariableCache->nextOid;
6972 6973
	if (!shutdown)
		checkPoint.nextOid += ShmemVariableCache->oidCount;
6974
	LWLockRelease(OidGenLock);
6975

6976 6977 6978
	MultiXactGetCheckptMulti(shutdown,
							 &checkPoint.nextMulti,
							 &checkPoint.nextMultiOffset);
6979

T
Tom Lane 已提交
6980
	/*
B
Bruce Momjian 已提交
6981 6982
	 * Having constructed the checkpoint record, ensure all shmem disk buffers
	 * and commit-log buffers are flushed to disk.
6983
	 *
6984 6985
	 * This I/O could fail for various reasons.  If so, we will fail to
	 * complete the checkpoint, but there is no reason to force a system
6986
	 * panic. Accordingly, exit critical section while doing it.
T
Tom Lane 已提交
6987
	 */
6988 6989
	END_CRIT_SECTION();

6990
	CheckPointGuts(checkPoint.redo, flags);
6991

6992
	/*
B
Bruce Momjian 已提交
6993 6994 6995
	 * Take a snapshot of running transactions and write this to WAL. This
	 * allows us to reconstruct the state of running transactions during
	 * archive recovery, if required. Skip, if this info disabled.
6996 6997 6998 6999 7000 7001 7002
	 *
	 * If we are shutting down, or Startup process is completing crash
	 * recovery we don't need to write running xact data.
	 *
	 * Update checkPoint.nextXid since we have a later value
	 */
	if (!shutdown && XLogStandbyInfoActive())
B
Bruce Momjian 已提交
7003
		LogStandbySnapshot(&checkPoint.oldestActiveXid, &checkPoint.nextXid);
7004 7005 7006
	else
		checkPoint.oldestActiveXid = InvalidTransactionId;

7007 7008
	START_CRIT_SECTION();

T
Tom Lane 已提交
7009 7010 7011
	/*
	 * Now insert the checkpoint record into XLOG.
	 */
B
Bruce Momjian 已提交
7012
	rdata.data = (char *) (&checkPoint);
7013
	rdata.len = sizeof(checkPoint);
7014
	rdata.buffer = InvalidBuffer;
7015 7016
	rdata.next = NULL;

T
Tom Lane 已提交
7017 7018 7019 7020 7021 7022
	recptr = XLogInsert(RM_XLOG_ID,
						shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
						XLOG_CHECKPOINT_ONLINE,
						&rdata);

	XLogFlush(recptr);
7023

7024
	/*
B
Bruce Momjian 已提交
7025 7026 7027 7028
	 * We mustn't write any new WAL after a shutdown checkpoint, or it will be
	 * overwritten at next startup.  No-one should even try, this just allows
	 * sanity-checking.  In the case of an end-of-recovery checkpoint, we want
	 * to just temporarily disable writing until the system has exited
7029 7030 7031 7032 7033
	 * recovery.
	 */
	if (shutdown)
	{
		if (flags & CHECKPOINT_END_OF_RECOVERY)
B
Bruce Momjian 已提交
7034
			LocalXLogInsertAllowed = -1;		/* return to "check" state */
7035
		else
B
Bruce Momjian 已提交
7036
			LocalXLogInsertAllowed = 0; /* never again write WAL */
7037 7038
	}

T
Tom Lane 已提交
7039
	/*
B
Bruce Momjian 已提交
7040 7041
	 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
	 * = end of actual checkpoint record.
T
Tom Lane 已提交
7042 7043
	 */
	if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
7044 7045
		ereport(PANIC,
				(errmsg("concurrent transaction log activity while database system is shutting down")));
7046

T
Tom Lane 已提交
7047
	/*
7048 7049
	 * Select point at which we can truncate the log, which we base on the
	 * prior checkpoint's earliest info.
T
Tom Lane 已提交
7050
	 */
7051
	XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
7052

T
Tom Lane 已提交
7053 7054 7055
	/*
	 * Update the control file.
	 */
7056
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7057 7058
	if (shutdown)
		ControlFile->state = DB_SHUTDOWNED;
T
Tom Lane 已提交
7059 7060 7061
	ControlFile->prevCheckPoint = ControlFile->checkPoint;
	ControlFile->checkPoint = ProcLastRecPtr;
	ControlFile->checkPointCopy = checkPoint;
7062
	ControlFile->time = (pg_time_t) time(NULL);
7063 7064
	/* crash recovery should always recover to the end of WAL */
	MemSet(&ControlFile->minRecoveryPoint, 0, sizeof(XLogRecPtr));
7065
	UpdateControlFile();
7066
	LWLockRelease(ControlFileLock);
7067

7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078
	/* Update shared-memory copy of checkpoint XID/epoch */
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		SpinLockAcquire(&xlogctl->info_lck);
		xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
		xlogctl->ckptXid = checkPoint.nextXid;
		SpinLockRelease(&xlogctl->info_lck);
	}

7079
	/*
B
Bruce Momjian 已提交
7080
	 * We are now done with critical updates; no need for system panic if we
7081
	 * have trouble while fooling with old log segments.
7082 7083 7084
	 */
	END_CRIT_SECTION();

7085 7086 7087 7088 7089
	/*
	 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
	 */
	smgrpostckpt();

V
Vadim B. Mikheev 已提交
7090
	/*
B
Bruce Momjian 已提交
7091 7092 7093 7094 7095
	 * If there's connected standby servers doing XLOG streaming, don't delete
	 * XLOG files that have not been streamed to all of them yet. This does
	 * nothing to prevent them from being deleted when the standby is
	 * disconnected (e.g because of network problems), but at least it avoids
	 * an open replication connection from failing because of that.
7096
	 */
7097
	if ((_logId || _logSeg) && max_wal_senders > 0)
7098
	{
B
Bruce Momjian 已提交
7099 7100 7101
		XLogRecPtr	oldest;
		uint32		log;
		uint32		seg;
7102 7103 7104 7105 7106 7107 7108

		oldest = GetOldestWALSendPointer();
		if (oldest.xlogid != 0 || oldest.xrecoff != 0)
		{
			XLByteToSeg(oldest, log, seg);
			if (log < _logId || (log == _logId && seg < _logSeg))
			{
B
Bruce Momjian 已提交
7109 7110
				_logId = log;
				_logSeg = seg;
7111 7112 7113 7114 7115
			}
		}
	}

	/*
B
Bruce Momjian 已提交
7116 7117
	 * Delete old log files (those no longer needed even for previous
	 * checkpoint or the standbys in XLOG streaming).
V
Vadim B. Mikheev 已提交
7118 7119 7120
	 */
	if (_logId || _logSeg)
	{
T
Tom Lane 已提交
7121
		PrevLogSeg(_logId, _logSeg);
7122
		RemoveOldXlogFiles(_logId, _logSeg, recptr);
V
Vadim B. Mikheev 已提交
7123 7124
	}

T
Tom Lane 已提交
7125
	/*
7126 7127
	 * Make more log segments if needed.  (Do this after recycling old log
	 * segments, since that may supply some of the needed files.)
T
Tom Lane 已提交
7128 7129
	 */
	if (!shutdown)
7130
		PreallocXlogFiles(recptr);
T
Tom Lane 已提交
7131

7132
	/*
B
Bruce Momjian 已提交
7133 7134 7135 7136 7137
	 * Truncate pg_subtrans if possible.  We can throw away all data before
	 * the oldest XMIN of any running transaction.	No future transaction will
	 * attempt to reference any pg_subtrans entry older than that (see Asserts
	 * in subtrans.c).	During recovery, though, we mustn't do this because
	 * StartupSUBTRANS hasn't been called yet.
7138
	 */
7139
	if (!RecoveryInProgress())
7140
		TruncateSUBTRANS(GetOldestXmin(true, false));
7141

7142 7143
	/* All real work is done, but log before releasing lock. */
	if (log_checkpoints)
7144
		LogCheckpointEnd(false);
7145

7146 7147 7148 7149 7150
	TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
									 NBuffers,
									 CheckpointStats.ckpt_segs_added,
									 CheckpointStats.ckpt_segs_removed,
									 CheckpointStats.ckpt_segs_recycled);
7151

7152
	LWLockRelease(CheckpointLock);
7153
}
V
WAL  
Vadim B. Mikheev 已提交
7154

7155 7156 7157 7158 7159 7160 7161
/*
 * Flush all data in shared memory to disk, and fsync
 *
 * This is the common code shared between regular checkpoints and
 * recovery restartpoints.
 */
static void
7162
CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
7163 7164 7165 7166
{
	CheckPointCLOG();
	CheckPointSUBTRANS();
	CheckPointMultiXact();
7167
	CheckPointRelationMap();
B
Bruce Momjian 已提交
7168
	CheckPointBuffers(flags);	/* performs all required fsyncs */
7169 7170 7171 7172 7173
	/* We deliberately delay 2PC checkpointing as long as possible */
	CheckPointTwoPhase(checkPointRedo);
}

/*
7174 7175 7176 7177 7178 7179 7180 7181
 * Save a checkpoint for recovery restart if appropriate
 *
 * This function is called each time a checkpoint record is read from XLOG.
 * It must determine whether the checkpoint represents a safe restartpoint or
 * not.  If so, the checkpoint record is stashed in shared memory so that
 * CreateRestartPoint can consult it.  (Note that the latter function is
 * executed by the bgwriter, while this one will be executed by the startup
 * process.)
7182 7183 7184 7185
 */
static void
RecoveryRestartPoint(const CheckPoint *checkPoint)
{
B
Bruce Momjian 已提交
7186
	int			rmid;
7187

7188 7189
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200

	/*
	 * Is it safe to checkpoint?  We must ask each of the resource managers
	 * whether they have any partial state information that might prevent a
	 * correct restart from this point.  If so, we skip this opportunity, but
	 * return at the next checkpoint record for another try.
	 */
	for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
	{
		if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
			if (!(RmgrTable[rmid].rm_safe_restartpoint()))
7201
			{
7202
				elog(trace_recovery(DEBUG2), "RM %d not safe to record restart point at %X/%X",
7203 7204 7205
					 rmid,
					 checkPoint->redo.xlogid,
					 checkPoint->redo.xrecoff);
7206
				return;
7207
			}
7208 7209 7210
	}

	/*
7211 7212
	 * Copy the checkpoint record to shared memory, so that bgwriter can use
	 * it the next time it wants to perform a restartpoint.
7213 7214 7215 7216 7217 7218 7219 7220
	 */
	SpinLockAcquire(&xlogctl->info_lck);
	XLogCtl->lastCheckPointRecPtr = ReadRecPtr;
	memcpy(&XLogCtl->lastCheckPoint, checkPoint, sizeof(CheckPoint));
	SpinLockRelease(&xlogctl->info_lck);
}

/*
7221 7222
 * Establish a restartpoint if possible.
 *
7223 7224 7225 7226 7227
 * This is similar to CreateCheckPoint, but is used during WAL recovery
 * to establish a point from which recovery can roll forward without
 * replaying the entire recovery log.
 *
 * Returns true if a new restartpoint was established. We can only establish
7228
 * a restartpoint if we have replayed a safe checkpoint record since last
7229 7230 7231 7232 7233
 * restartpoint.
 */
bool
CreateRestartPoint(int flags)
{
7234 7235
	XLogRecPtr	lastCheckPointRecPtr;
	CheckPoint	lastCheckPoint;
7236 7237
	uint32		_logId;
	uint32		_logSeg;
7238

7239 7240 7241 7242 7243 7244 7245 7246 7247
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

	/*
	 * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
	 * happens at a time.
	 */
	LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);

7248
	/* Get a local copy of the last safe checkpoint record. */
7249 7250 7251 7252 7253
	SpinLockAcquire(&xlogctl->info_lck);
	lastCheckPointRecPtr = xlogctl->lastCheckPointRecPtr;
	memcpy(&lastCheckPoint, &XLogCtl->lastCheckPoint, sizeof(CheckPoint));
	SpinLockRelease(&xlogctl->info_lck);

7254
	/*
7255 7256 7257 7258 7259 7260
	 * Check that we're still in recovery mode. It's ok if we exit recovery
	 * mode after this check, the restart point is valid anyway.
	 */
	if (!RecoveryInProgress())
	{
		ereport(DEBUG2,
7261
			  (errmsg("skipping restartpoint, recovery has already ended")));
7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276
		LWLockRelease(CheckpointLock);
		return false;
	}

	/*
	 * If the last checkpoint record we've replayed is already our last
	 * restartpoint, we can't perform a new restart point. We still update
	 * minRecoveryPoint in that case, so that if this is a shutdown restart
	 * point, we won't start up earlier than before. That's not strictly
	 * necessary, but when we get hot standby capability, it would be rather
	 * weird if the database opened up for read-only connections at a
	 * point-in-time before the last shutdown. Such time travel is still
	 * possible in case of immediate shutdown, though.
	 *
	 * We don't explicitly advance minRecoveryPoint when we do create a
7277 7278
	 * restartpoint. It's assumed that flushing the buffers will do that as a
	 * side-effect.
7279
	 */
7280 7281 7282
	if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
		XLByteLE(lastCheckPoint.redo, ControlFile->checkPointCopy.redo))
	{
7283 7284
		XLogRecPtr	InvalidXLogRecPtr = {0, 0};

7285 7286
		ereport(DEBUG2,
				(errmsg("skipping restartpoint, already performed at %X/%X",
7287
				  lastCheckPoint.redo.xlogid, lastCheckPoint.redo.xrecoff)));
7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305

		UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
		LWLockRelease(CheckpointLock);
		return false;
	}

	if (log_checkpoints)
	{
		/*
		 * Prepare to accumulate statistics.
		 */
		MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
		CheckpointStats.ckpt_start_t = GetCurrentTimestamp();

		LogCheckpointStart(flags, true);
	}

	CheckPointGuts(lastCheckPoint.redo, flags);
7306

7307 7308 7309 7310 7311 7312
	/*
	 * Select point at which we can truncate the xlog, which we base on the
	 * prior checkpoint's earliest info.
	 */
	XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);

7313
	/*
7314 7315
	 * Update pg_control, using current time.  Check that it still shows
	 * IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
B
Bruce Momjian 已提交
7316 7317
	 * this is a quick hack to make sure nothing really bad happens if somehow
	 * we get here after the end-of-recovery checkpoint.
7318
	 */
7319
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7320 7321 7322 7323 7324 7325 7326 7327 7328
	if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY &&
		XLByteLT(ControlFile->checkPointCopy.redo, lastCheckPoint.redo))
	{
		ControlFile->prevCheckPoint = ControlFile->checkPoint;
		ControlFile->checkPoint = lastCheckPointRecPtr;
		ControlFile->checkPointCopy = lastCheckPoint;
		ControlFile->time = (pg_time_t) time(NULL);
		UpdateControlFile();
	}
7329
	LWLockRelease(ControlFileLock);
7330

7331 7332 7333 7334 7335 7336 7337
	/*
	 * Delete old log files (those no longer needed even for previous
	 * checkpoint/restartpoint) to prevent the disk holding the xlog from
	 * growing full. We don't need do this during normal recovery, but during
	 * streaming recovery we have to or the disk will eventually fill up from
	 * old log files streamed from master.
	 */
7338
	if (WalRcvInProgress() && (_logId || _logSeg))
7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354
	{
		XLogRecPtr	endptr;

		/* Get the current (or recent) end of xlog */
		endptr = GetWalRcvWriteRecPtr();

		PrevLogSeg(_logId, _logSeg);
		RemoveOldXlogFiles(_logId, _logSeg, endptr);

		/*
		 * Make more log segments if needed.  (Do this after recycling old log
		 * segments, since that may supply some of the needed files.)
		 */
		PreallocXlogFiles(endptr);
	}

7355
	/*
7356 7357 7358
	 * Currently, there is no need to truncate pg_subtrans during recovery. If
	 * we did do that, we will need to have called StartupSUBTRANS() already
	 * and then TruncateSUBTRANS() would go here.
7359 7360 7361 7362 7363 7364 7365
	 */

	/* All real work is done, but log before releasing lock. */
	if (log_checkpoints)
		LogCheckpointEnd(true);

	ereport((log_checkpoints ? LOG : DEBUG2),
B
Bruce Momjian 已提交
7366 7367 7368
	 (errmsg("recovery restart point at %X/%X with latest known log time %s",
			 lastCheckPoint.redo.xlogid, lastCheckPoint.redo.xrecoff,
			 timestamptz_to_str(GetLatestXLogTime()))));
7369 7370

	LWLockRelease(CheckpointLock);
7371 7372 7373 7374 7375 7376 7377 7378 7379

	/*
	 * Finally, execute restartpoint_command, if any.
	 */
	if (XLogCtl->restartPointCommand[0])
		ExecuteRecoveryCommand(XLogCtl->restartPointCommand,
							   "restartpoint_command",
							   false);

7380
	return true;
7381 7382
}

T
Tom Lane 已提交
7383 7384 7385
/*
 * Write a NEXTOID log record
 */
7386 7387 7388
void
XLogPutNextOid(Oid nextOid)
{
B
Bruce Momjian 已提交
7389
	XLogRecData rdata;
7390

B
Bruce Momjian 已提交
7391
	rdata.data = (char *) (&nextOid);
7392
	rdata.len = sizeof(Oid);
7393
	rdata.buffer = InvalidBuffer;
7394 7395
	rdata.next = NULL;
	(void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
B
Bruce Momjian 已提交
7396

7397 7398
	/*
	 * We need not flush the NEXTOID record immediately, because any of the
B
Bruce Momjian 已提交
7399 7400 7401 7402 7403
	 * just-allocated OIDs could only reach disk as part of a tuple insert or
	 * update that would have its own XLOG record that must follow the NEXTOID
	 * record.	Therefore, the standard buffer LSN interlock applied to those
	 * records will ensure no such OID reaches disk before the NEXTOID record
	 * does.
7404 7405
	 *
	 * Note, however, that the above statement only covers state "within" the
B
Bruce Momjian 已提交
7406 7407
	 * database.  When we use a generated OID as a file or directory name, we
	 * are in a sense violating the basic WAL rule, because that filesystem
7408
	 * change may reach disk before the NEXTOID WAL record does.  The impact
B
Bruce Momjian 已提交
7409 7410 7411 7412 7413
	 * of this is that if a database crash occurs immediately afterward, we
	 * might after restart re-generate the same OID and find that it conflicts
	 * with the leftover file or directory.  But since for safety's sake we
	 * always loop until finding a nonconflicting filename, this poses no real
	 * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
7414 7415 7416
	 */
}

7417 7418 7419 7420 7421 7422 7423 7424 7425 7426
/*
 * Write an XLOG SWITCH record.
 *
 * Here we just blindly issue an XLogInsert request for the record.
 * All the magic happens inside XLogInsert.
 *
 * The return value is either the end+1 address of the switch record,
 * or the end+1 address of the prior segment if we did not need to
 * write a switch record because we are already at segment start.
 */
7427
XLogRecPtr
7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443
RequestXLogSwitch(void)
{
	XLogRecPtr	RecPtr;
	XLogRecData rdata;

	/* XLOG SWITCH, alone among xlog record types, has no data */
	rdata.buffer = InvalidBuffer;
	rdata.data = NULL;
	rdata.len = 0;
	rdata.next = NULL;

	RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);

	return RecPtr;
}

7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468
/*
 * Write an XLOG UNLOGGED record, indicating that some operation was
 * performed on data that we fsync()'d directly to disk, skipping
 * WAL-logging.
 *
 * Such operations screw up archive recovery, so we complain if we see
 * these records during archive recovery. That shouldn't happen in a
 * correctly configured server, but you can induce it by temporarily
 * disabling archiving and restarting, so it's good to at least get a
 * warning of silent data loss in such cases. These records serve no
 * other purpose and are simply ignored during crash recovery.
 */
void
XLogReportUnloggedStatement(char *reason)
{
	XLogRecData rdata;

	rdata.buffer = InvalidBuffer;
	rdata.data = reason;
	rdata.len = strlen(reason) + 1;
	rdata.next = NULL;

	XLogInsert(RM_XLOG_ID, XLOG_UNLOGGED, &rdata);
}

T
Tom Lane 已提交
7469 7470
/*
 * XLOG resource manager's routines
7471 7472
 *
 * Definitions of info values are in include/catalog/pg_control.h, though
7473
 * not all record types are related to control file updates.
T
Tom Lane 已提交
7474
 */
V
WAL  
Vadim B. Mikheev 已提交
7475 7476 7477
void
xlog_redo(XLogRecPtr lsn, XLogRecord *record)
{
B
Bruce Momjian 已提交
7478
	uint8		info = record->xl_info & ~XLR_INFO_MASK;
7479

7480 7481 7482
	/* Backup blocks are not used in xlog records */
	Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));

7483
	if (info == XLOG_NEXTOID)
7484
	{
B
Bruce Momjian 已提交
7485
		Oid			nextOid;
7486 7487 7488

		memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
		if (ShmemVariableCache->nextOid < nextOid)
T
Tom Lane 已提交
7489
		{
7490
			ShmemVariableCache->nextOid = nextOid;
T
Tom Lane 已提交
7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502
			ShmemVariableCache->oidCount = 0;
		}
	}
	else if (info == XLOG_CHECKPOINT_SHUTDOWN)
	{
		CheckPoint	checkPoint;

		memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
		/* In a SHUTDOWN checkpoint, believe the counters exactly */
		ShmemVariableCache->nextXid = checkPoint.nextXid;
		ShmemVariableCache->nextOid = checkPoint.nextOid;
		ShmemVariableCache->oidCount = 0;
7503 7504
		MultiXactSetNextMXact(checkPoint.nextMulti,
							  checkPoint.nextMultiOffset);
7505
		SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
B
Bruce Momjian 已提交
7506

7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519
		/* Check to see if any changes to max_connections give problems */
		if (standbyState != STANDBY_DISABLED)
			CheckRequiredParameterValues(checkPoint);

		if (standbyState >= STANDBY_INITIALIZED)
		{
			/*
			 * Remove stale transactions, if any.
			 */
			ExpireOldKnownAssignedTransactionIds(checkPoint.nextXid);
			StandbyReleaseOldLocks(checkPoint.nextXid);
		}

7520 7521 7522 7523
		/* ControlFile->checkPointCopy always tracks the latest ckpt XID */
		ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
		ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;

7524
		/*
B
Bruce Momjian 已提交
7525
		 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
7526 7527 7528 7529 7530 7531 7532 7533
		 */
		if (checkPoint.ThisTimeLineID != ThisTimeLineID)
		{
			if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
				!list_member_int(expectedTLIs,
								 (int) checkPoint.ThisTimeLineID))
				ereport(PANIC,
						(errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
7534 7535 7536
								checkPoint.ThisTimeLineID, ThisTimeLineID)));
			/* Following WAL records should be run with new TLI */
			ThisTimeLineID = checkPoint.ThisTimeLineID;
7537
		}
7538 7539

		RecoveryRestartPoint(&checkPoint);
T
Tom Lane 已提交
7540 7541 7542 7543 7544 7545
	}
	else if (info == XLOG_CHECKPOINT_ONLINE)
	{
		CheckPoint	checkPoint;

		memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
7546
		/* In an ONLINE checkpoint, treat the counters like NEXTOID */
7547 7548
		if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
								  checkPoint.nextXid))
T
Tom Lane 已提交
7549 7550 7551 7552 7553 7554
			ShmemVariableCache->nextXid = checkPoint.nextXid;
		if (ShmemVariableCache->nextOid < checkPoint.nextOid)
		{
			ShmemVariableCache->nextOid = checkPoint.nextOid;
			ShmemVariableCache->oidCount = 0;
		}
7555 7556
		MultiXactAdvanceNextMXact(checkPoint.nextMulti,
								  checkPoint.nextMultiOffset);
7557 7558
		if (TransactionIdPrecedes(ShmemVariableCache->oldestXid,
								  checkPoint.oldestXid))
7559 7560
			SetTransactionIdLimit(checkPoint.oldestXid,
								  checkPoint.oldestXidDB);
7561 7562 7563 7564 7565

		/* ControlFile->checkPointCopy always tracks the latest ckpt XID */
		ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
		ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;

7566 7567
		/* TLI should not change in an on-line checkpoint */
		if (checkPoint.ThisTimeLineID != ThisTimeLineID)
7568
			ereport(PANIC,
7569 7570
					(errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
							checkPoint.ThisTimeLineID, ThisTimeLineID)));
7571 7572

		RecoveryRestartPoint(&checkPoint);
7573
	}
7574 7575 7576 7577
	else if (info == XLOG_NOOP)
	{
		/* nothing to do here */
	}
7578 7579 7580 7581
	else if (info == XLOG_SWITCH)
	{
		/* nothing to do here */
	}
7582 7583 7584
	else if (info == XLOG_BACKUP_END)
	{
		XLogRecPtr	startpoint;
B
Bruce Momjian 已提交
7585

7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608
		memcpy(&startpoint, XLogRecGetData(record), sizeof(startpoint));

		if (XLByteEQ(ControlFile->backupStartPoint, startpoint))
		{
			/*
			 * We have reached the end of base backup, the point where
			 * pg_stop_backup() was done. The data on disk is now consistent.
			 * Reset backupStartPoint, and update minRecoveryPoint to make
			 * sure we don't allow starting up at an earlier point even if
			 * recovery is stopped and restarted soon after this.
			 */
			elog(DEBUG1, "end of backup reached");

			LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);

			if (XLByteLT(ControlFile->minRecoveryPoint, lsn))
				ControlFile->minRecoveryPoint = lsn;
			MemSet(&ControlFile->backupStartPoint, 0, sizeof(XLogRecPtr));
			UpdateControlFile();

			LWLockRelease(ControlFileLock);
		}
	}
7609 7610 7611 7612 7613
	else if (info == XLOG_UNLOGGED)
	{
		if (InArchiveRecovery)
		{
			/*
B
Bruce Momjian 已提交
7614 7615
			 * Note: We don't print the reason string from the record, because
			 * that gets added as a line using xlog_desc()
7616 7617
			 */
			ereport(WARNING,
B
Bruce Momjian 已提交
7618 7619
				(errmsg("unlogged operation performed, data may be missing"),
				 errhint("This can happen if you temporarily disable archive_mode without taking a new base backup.")));
7620 7621
		}
	}
V
WAL  
Vadim B. Mikheev 已提交
7622
}
B
Bruce Momjian 已提交
7623

V
WAL  
Vadim B. Mikheev 已提交
7624
void
7625
xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
V
WAL  
Vadim B. Mikheev 已提交
7626
{
B
Bruce Momjian 已提交
7627
	uint8		info = xl_info & ~XLR_INFO_MASK;
V
WAL  
Vadim B. Mikheev 已提交
7628

T
Tom Lane 已提交
7629 7630
	if (info == XLOG_CHECKPOINT_SHUTDOWN ||
		info == XLOG_CHECKPOINT_ONLINE)
V
WAL  
Vadim B. Mikheev 已提交
7631
	{
B
Bruce Momjian 已提交
7632 7633
		CheckPoint *checkpoint = (CheckPoint *) rec;

7634
		appendStringInfo(buf, "checkpoint: redo %X/%X; "
7635
						 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; "
7636
						 "oldest xid %u in DB %u; oldest running xid %u; %s",
B
Bruce Momjian 已提交
7637 7638 7639 7640 7641 7642
						 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
						 checkpoint->ThisTimeLineID,
						 checkpoint->nextXidEpoch, checkpoint->nextXid,
						 checkpoint->nextOid,
						 checkpoint->nextMulti,
						 checkpoint->nextMultiOffset,
7643 7644
						 checkpoint->oldestXid,
						 checkpoint->oldestXidDB,
7645
						 checkpoint->oldestActiveXid,
B
Bruce Momjian 已提交
7646
				 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
T
Tom Lane 已提交
7647
	}
7648 7649 7650 7651
	else if (info == XLOG_NOOP)
	{
		appendStringInfo(buf, "xlog no-op");
	}
7652 7653
	else if (info == XLOG_NEXTOID)
	{
B
Bruce Momjian 已提交
7654
		Oid			nextOid;
7655 7656

		memcpy(&nextOid, rec, sizeof(Oid));
7657
		appendStringInfo(buf, "nextOid: %u", nextOid);
7658
	}
7659 7660 7661 7662
	else if (info == XLOG_SWITCH)
	{
		appendStringInfo(buf, "xlog switch");
	}
7663 7664
	else if (info == XLOG_BACKUP_END)
	{
B
Bruce Momjian 已提交
7665
		XLogRecPtr	startpoint;
7666 7667 7668 7669 7670

		memcpy(&startpoint, rec, sizeof(XLogRecPtr));
		appendStringInfo(buf, "backup end: %X/%X",
						 startpoint.xlogid, startpoint.xrecoff);
	}
7671 7672
	else if (info == XLOG_UNLOGGED)
	{
B
Bruce Momjian 已提交
7673
		char	   *reason = rec;
7674 7675 7676

		appendStringInfo(buf, "unlogged operation: %s", reason);
	}
V
WAL  
Vadim B. Mikheev 已提交
7677
	else
7678
		appendStringInfo(buf, "UNKNOWN");
V
WAL  
Vadim B. Mikheev 已提交
7679 7680
}

7681
#ifdef WAL_DEBUG
7682

V
WAL  
Vadim B. Mikheev 已提交
7683
static void
7684
xlog_outrec(StringInfo buf, XLogRecord *record)
V
WAL  
Vadim B. Mikheev 已提交
7685
{
B
Bruce Momjian 已提交
7686
	int			i;
7687

7688
	appendStringInfo(buf, "prev %X/%X; xid %u",
7689 7690
					 record->xl_prev.xlogid, record->xl_prev.xrecoff,
					 record->xl_xid);
7691

7692 7693 7694
	appendStringInfo(buf, "; len %u",
					 record->xl_len);

7695
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
7696
	{
7697
		if (record->xl_info & XLR_SET_BKP_BLOCK(i))
B
Bruce Momjian 已提交
7698
			appendStringInfo(buf, "; bkpb%d", i + 1);
7699 7700
	}

7701
	appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
V
WAL  
Vadim B. Mikheev 已提交
7702
}
B
Bruce Momjian 已提交
7703
#endif   /* WAL_DEBUG */
7704 7705 7706


/*
7707 7708
 * Return the (possible) sync flag used for opening a file, depending on the
 * value of the GUC wal_sync_method.
7709
 */
7710 7711
static int
get_sync_bit(int method)
7712
{
B
Bruce Momjian 已提交
7713
	int			o_direct_flag = 0;
7714

7715 7716 7717
	/* If fsync is disabled, never open in sync mode */
	if (!enableFsync)
		return 0;
7718

7719 7720 7721
	/*
	 * Optimize writes by bypassing kernel cache with O_DIRECT when using
	 * O_SYNC, O_DSYNC or O_FSYNC. But only if archiving and streaming are
B
Bruce Momjian 已提交
7722 7723 7724 7725 7726
	 * disabled, otherwise the archive command or walsender process will read
	 * the WAL soon after writing it, which is guaranteed to cause a physical
	 * read if we bypassed the kernel cache. We also skip the
	 * posix_fadvise(POSIX_FADV_DONTNEED) call in XLogFileClose() for the same
	 * reason.
7727 7728 7729 7730 7731 7732 7733 7734 7735
	 *
	 * Never use O_DIRECT in walreceiver process for similar reasons; the WAL
	 * written by walreceiver is normally read by the startup process soon
	 * after its written. Also, walreceiver performs unaligned writes, which
	 * don't work with O_DIRECT, so it is required for correctness too.
	 */
	if (!XLogIsNeeded() && !am_walreceiver)
		o_direct_flag = PG_O_DIRECT;

7736
	switch (method)
7737
	{
7738 7739 7740 7741 7742 7743
			/*
			 * enum values for all sync options are defined even if they are
			 * not supported on the current platform.  But if not, they are
			 * not included in the enum option array, and therefore will never
			 * be seen here.
			 */
7744 7745 7746
		case SYNC_METHOD_FSYNC:
		case SYNC_METHOD_FSYNC_WRITETHROUGH:
		case SYNC_METHOD_FDATASYNC:
7747
			return 0;
7748
#ifdef OPEN_SYNC_FLAG
7749
		case SYNC_METHOD_OPEN:
7750
			return OPEN_SYNC_FLAG | o_direct_flag;
7751 7752
#endif
#ifdef OPEN_DATASYNC_FLAG
7753
		case SYNC_METHOD_OPEN_DSYNC:
7754
			return OPEN_DATASYNC_FLAG | o_direct_flag;
7755
#endif
7756
		default:
7757 7758
			/* can't happen (unless we are out of sync with option array) */
			elog(ERROR, "unrecognized wal_sync_method: %d", method);
7759
			return 0;			/* silence warning */
7760
	}
7761
}
7762

7763 7764 7765 7766 7767 7768
/*
 * GUC support
 */
bool
assign_xlog_sync_method(int new_sync_method, bool doit, GucSource source)
{
7769
	if (!doit)
7770
		return true;
7771

7772
	if (sync_method != new_sync_method)
7773 7774
	{
		/*
B
Bruce Momjian 已提交
7775 7776
		 * To ensure that no blocks escape unsynced, force an fsync on the
		 * currently open log segment (if any).  Also, if the open flag is
B
Bruce Momjian 已提交
7777 7778
		 * changing, close the log file so it will be reopened (with new flag
		 * bit) at next use.
7779 7780 7781 7782
		 */
		if (openLogFile >= 0)
		{
			if (pg_fsync(openLogFile) != 0)
7783 7784
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
7785 7786
						 errmsg("could not fsync log file %u, segment %u: %m",
								openLogId, openLogSeg)));
7787
			if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
7788
				XLogFileClose();
7789 7790
		}
	}
7791

7792
	return true;
7793 7794 7795 7796
}


/*
7797 7798 7799 7800
 * Issue appropriate kind of fsync (if any) for an XLOG output file.
 *
 * 'fd' is a file descriptor for the XLOG file to be fsync'd.
 * 'log' and 'seg' are for error reporting purposes.
7801
 */
7802 7803
void
issue_xlog_fsync(int fd, uint32 log, uint32 seg)
7804 7805 7806
{
	switch (sync_method)
	{
7807
		case SYNC_METHOD_FSYNC:
7808
			if (pg_fsync_no_writethrough(fd) != 0)
7809 7810
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
7811
						 errmsg("could not fsync log file %u, segment %u: %m",
7812
								log, seg)));
7813
			break;
7814 7815
#ifdef HAVE_FSYNC_WRITETHROUGH
		case SYNC_METHOD_FSYNC_WRITETHROUGH:
7816
			if (pg_fsync_writethrough(fd) != 0)
7817 7818
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
7819
						 errmsg("could not fsync write-through log file %u, segment %u: %m",
7820
								log, seg)));
7821 7822
			break;
#endif
7823 7824
#ifdef HAVE_FDATASYNC
		case SYNC_METHOD_FDATASYNC:
7825
			if (pg_fdatasync(fd) != 0)
7826 7827
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
7828
					errmsg("could not fdatasync log file %u, segment %u: %m",
7829
						   log, seg)));
7830 7831 7832
			break;
#endif
		case SYNC_METHOD_OPEN:
7833
		case SYNC_METHOD_OPEN_DSYNC:
7834 7835 7836
			/* write synced it already */
			break;
		default:
7837
			elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
7838 7839 7840
			break;
	}
}
7841 7842 7843 7844 7845 7846 7847 7848 7849


/*
 * pg_start_backup: set up for taking an on-line backup dump
 *
 * Essentially what this does is to create a backup label file in $PGDATA,
 * where it will be archived as part of the backup dump.  The label file
 * contains the user-supplied label string (typically this would be used
 * to tell where the backup dump will be stored) and the starting time and
7850
 * starting WAL location for the dump.
7851 7852 7853 7854 7855
 */
Datum
pg_start_backup(PG_FUNCTION_ARGS)
{
	text	   *backupid = PG_GETARG_TEXT_P(0);
7856
	bool		fast = PG_GETARG_BOOL(1);
7857
	char	   *backupidstr;
7858
	XLogRecPtr	checkpointloc;
7859
	XLogRecPtr	startpoint;
7860
	pg_time_t	stamp_time;
7861 7862 7863 7864 7865 7866 7867
	char		strfbuf[128];
	char		xlogfilename[MAXFNAMELEN];
	uint32		_logId;
	uint32		_logSeg;
	struct stat stat_buf;
	FILE	   *fp;

B
Bruce Momjian 已提交
7868
	if (!superuser())
7869 7870
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7871
				 errmsg("must be superuser to run a backup")));
7872

7873 7874 7875 7876 7877 7878
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

7879 7880 7881
	if (!XLogArchivingActive())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7882 7883 7884 7885 7886 7887 7888 7889 7890
				 errmsg("WAL archiving is not active"),
				 errhint("archive_mode must be enabled at server start.")));

	if (!XLogArchiveCommandSet())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("WAL archiving is not active"),
				 errhint("archive_command must be defined before "
						 "online backups can be made safely.")));
7891

7892
	backupidstr = text_to_cstring(backupid);
B
Bruce Momjian 已提交
7893

7894
	/*
7895 7896 7897
	 * Mark backup active in shared memory.  We must do full-page WAL writes
	 * during an on-line backup even if not doing so at other times, because
	 * it's quite possible for the backup dump to obtain a "torn" (partially
B
Bruce Momjian 已提交
7898 7899 7900 7901 7902 7903 7904 7905 7906
	 * written) copy of a database page if it reads the page concurrently with
	 * our write to the same page.	This can be fixed as long as the first
	 * write to the page in the WAL sequence is a full-page write. Hence, we
	 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
	 * are no dirty pages in shared memory that might get dumped while the
	 * backup is in progress without having a corresponding WAL record.  (Once
	 * the backup is complete, we need not force full-page writes anymore,
	 * since we expect that any pages not modified during the backup interval
	 * must have been correctly captured by the backup.)
7907
	 *
B
Bruce Momjian 已提交
7908 7909
	 * We must hold WALInsertLock to change the value of forcePageWrites, to
	 * ensure adequate interlocking against XLogInsert().
7910
	 */
7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
	if (XLogCtl->Insert.forcePageWrites)
	{
		LWLockRelease(WALInsertLock);
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("a backup is already in progress"),
				 errhint("Run pg_stop_backup() and try again.")));
	}
	XLogCtl->Insert.forcePageWrites = true;
	LWLockRelease(WALInsertLock);
B
Bruce Momjian 已提交
7922

7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935
	/*
	 * Force an XLOG file switch before the checkpoint, to ensure that the WAL
	 * segment the checkpoint is written to doesn't contain pages with old
	 * timeline IDs. That would otherwise happen if you called
	 * pg_start_backup() right after restoring from a PITR archive: the first
	 * WAL segment containing the startup checkpoint has pages in the
	 * beginning with the old timeline ID. That can cause trouble at recovery:
	 * we won't have a history file covering the old timeline if pg_xlog
	 * directory was not included in the base backup and the WAL archive was
	 * cleared too before starting the backup.
	 */
	RequestXLogSwitch();

7936 7937
	/* Ensure we release forcePageWrites if fail below */
	PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
7938 7939
	{
		/*
B
Bruce Momjian 已提交
7940
		 * Force a CHECKPOINT.	Aside from being necessary to prevent torn
7941 7942 7943
		 * page problems, this guarantees that two successive backup runs will
		 * have different checkpoint positions and hence different history
		 * file names, even if nothing happened in between.
7944
		 *
7945 7946
		 * We use CHECKPOINT_IMMEDIATE only if requested by user (via passing
		 * fast = true).  Otherwise this can take awhile.
7947
		 */
7948 7949
		RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT |
						  (fast ? CHECKPOINT_IMMEDIATE : 0));
7950

7951 7952 7953 7954 7955
		/*
		 * Now we need to fetch the checkpoint record location, and also its
		 * REDO pointer.  The oldest point in WAL that would be needed to
		 * restore starting from the checkpoint is precisely the REDO pointer.
		 */
7956
		LWLockAcquire(ControlFileLock, LW_SHARED);
7957 7958 7959
		checkpointloc = ControlFile->checkPoint;
		startpoint = ControlFile->checkPointCopy.redo;
		LWLockRelease(ControlFileLock);
B
Bruce Momjian 已提交
7960

7961 7962
		XLByteToSeg(startpoint, _logId, _logSeg);
		XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
B
Bruce Momjian 已提交
7963

7964 7965 7966 7967 7968
		/* Use the log timezone here, not the session timezone */
		stamp_time = (pg_time_t) time(NULL);
		pg_strftime(strfbuf, sizeof(strfbuf),
					"%Y-%m-%d %H:%M:%S %Z",
					pg_localtime(&stamp_time, log_timezone));
7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994

		/*
		 * Check for existing backup label --- implies a backup is already
		 * running.  (XXX given that we checked forcePageWrites above, maybe
		 * it would be OK to just unlink any such label file?)
		 */
		if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
		{
			if (errno != ENOENT)
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not stat file \"%s\": %m",
								BACKUP_LABEL_FILE)));
		}
		else
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
					 errmsg("a backup is already in progress"),
					 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
							 BACKUP_LABEL_FILE)));

		/*
		 * Okay, write the file
		 */
		fp = AllocateFile(BACKUP_LABEL_FILE, "w");
		if (!fp)
7995 7996
			ereport(ERROR,
					(errcode_for_file_access(),
7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008
					 errmsg("could not create file \"%s\": %m",
							BACKUP_LABEL_FILE)));
		fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
				startpoint.xlogid, startpoint.xrecoff, xlogfilename);
		fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
				checkpointloc.xlogid, checkpointloc.xrecoff);
		fprintf(fp, "START TIME: %s\n", strfbuf);
		fprintf(fp, "LABEL: %s\n", backupidstr);
		if (fflush(fp) || ferror(fp) || FreeFile(fp))
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not write file \"%s\": %m",
8009
							BACKUP_LABEL_FILE)));
8010
	}
8011
	PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
B
Bruce Momjian 已提交
8012

8013
	/*
8014
	 * We're done.  As a convenience, return the starting WAL location.
8015 8016 8017
	 */
	snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
			 startpoint.xlogid, startpoint.xrecoff);
8018
	PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
8019 8020
}

8021 8022 8023 8024 8025 8026 8027 8028 8029 8030
/* Error cleanup callback for pg_start_backup */
static void
pg_start_backup_callback(int code, Datum arg)
{
	/* Turn off forcePageWrites on failure */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
	XLogCtl->Insert.forcePageWrites = false;
	LWLockRelease(WALInsertLock);
}

8031 8032 8033
/*
 * pg_stop_backup: finish taking an on-line backup dump
 *
8034 8035 8036 8037
 * We write an end-of-backup WAL record, and remove the backup label file
 * created by pg_start_backup, creating a backup history file in pg_xlog
 * instead (whence it will immediately be archived). The backup history file
 * contains the same info found in the label file, plus the backup-end time
8038
 * and WAL location. Before 9.0, the backup-end time was read from the backup
8039 8040 8041
 * history file at the beginning of archive recovery, but we now use the WAL
 * record for that and the file is for informational and debug purposes only.
 *
8042
 * Note: different from CancelBackup which just cancels online backup mode.
8043 8044 8045 8046 8047 8048
 */
Datum
pg_stop_backup(PG_FUNCTION_ARGS)
{
	XLogRecPtr	startpoint;
	XLogRecPtr	stoppoint;
B
Bruce Momjian 已提交
8049
	XLogRecData rdata;
8050
	pg_time_t	stamp_time;
8051
	char		strfbuf[128];
8052
	char		histfilepath[MAXPGPATH];
8053 8054
	char		startxlogfilename[MAXFNAMELEN];
	char		stopxlogfilename[MAXFNAMELEN];
8055 8056
	char		lastxlogfilename[MAXFNAMELEN];
	char		histfilename[MAXFNAMELEN];
8057 8058 8059 8060 8061 8062
	uint32		_logId;
	uint32		_logSeg;
	FILE	   *lfp;
	FILE	   *fp;
	char		ch;
	int			ich;
8063 8064
	int			seconds_before_warning;
	int			waits = 0;
8065

B
Bruce Momjian 已提交
8066
	if (!superuser())
8067 8068 8069
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 (errmsg("must be superuser to run a backup"))));
B
Bruce Momjian 已提交
8070

8071 8072 8073 8074 8075 8076
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

8077 8078 8079 8080 8081 8082
	if (!XLogArchivingActive())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("WAL archiving is not active"),
				 errhint("archive_mode must be enabled at server start.")));

8083
	/*
8084
	 * OK to clear forcePageWrites
8085 8086
	 */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
8087
	XLogCtl->Insert.forcePageWrites = false;
8088 8089 8090 8091 8092
	LWLockRelease(WALInsertLock);

	/*
	 * Open the existing label file
	 */
8093
	lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
8094 8095 8096 8097 8098 8099
	if (!lfp)
	{
		if (errno != ENOENT)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
8100
							BACKUP_LABEL_FILE)));
8101 8102 8103 8104
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("a backup is not in progress")));
	}
B
Bruce Momjian 已提交
8105

8106
	/*
B
Bruce Momjian 已提交
8107 8108
	 * Read and parse the START WAL LOCATION line (this code is pretty crude,
	 * but we are not expecting any variability in the file format).
8109 8110 8111 8112 8113 8114
	 */
	if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
			   &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
			   &ch) != 4 || ch != '\n')
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8115
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
8116

8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131
	/*
	 * Write the backup-end xlog record
	 */
	rdata.data = (char *) (&startpoint);
	rdata.len = sizeof(startpoint);
	rdata.buffer = InvalidBuffer;
	rdata.next = NULL;
	stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END, &rdata);

	/*
	 * Force a switch to a new xlog segment file, so that the backup is valid
	 * as soon as archiver moves out the current segment file.
	 */
	RequestXLogSwitch();

8132
	XLByteToPrevSeg(stoppoint, _logId, _logSeg);
8133 8134 8135 8136 8137 8138 8139 8140
	XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);

	/* Use the log timezone here, not the session timezone */
	stamp_time = (pg_time_t) time(NULL);
	pg_strftime(strfbuf, sizeof(strfbuf),
				"%Y-%m-%d %H:%M:%S %Z",
				pg_localtime(&stamp_time, log_timezone));

8141 8142 8143 8144
	/*
	 * Write the backup history file
	 */
	XLByteToSeg(startpoint, _logId, _logSeg);
8145
	BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
8146
						  startpoint.xrecoff % XLogSegSize);
8147
	fp = AllocateFile(histfilepath, "w");
8148 8149 8150 8151
	if (!fp)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m",
8152
						histfilepath)));
8153 8154 8155 8156
	fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
			startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
	fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
			stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
8157
	/* transfer remaining lines from label to history file */
8158 8159 8160 8161 8162 8163 8164
	while ((ich = fgetc(lfp)) != EOF)
		fputc(ich, fp);
	fprintf(fp, "STOP TIME: %s\n", strfbuf);
	if (fflush(fp) || ferror(fp) || FreeFile(fp))
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not write file \"%s\": %m",
8165
						histfilepath)));
B
Bruce Momjian 已提交
8166

8167 8168 8169 8170 8171 8172 8173
	/*
	 * Close and remove the backup label file
	 */
	if (ferror(lfp) || FreeFile(lfp))
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not read file \"%s\": %m",
8174 8175
						BACKUP_LABEL_FILE)));
	if (unlink(BACKUP_LABEL_FILE) != 0)
8176 8177 8178
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not remove file \"%s\": %m",
8179
						BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
8180

8181
	/*
B
Bruce Momjian 已提交
8182 8183 8184
	 * Clean out any no-longer-needed history files.  As a side effect, this
	 * will post a .ready file for the newly created history file, notifying
	 * the archiver that history file may be archived immediately.
8185
	 */
8186
	CleanupBackupHistory();
B
Bruce Momjian 已提交
8187

8188
	/*
8189 8190 8191 8192
	 * Wait until both the last WAL file filled during backup and the history
	 * file have been archived.  We assume that the alphabetic sorting
	 * property of the WAL files ensures any earlier WAL files are safely
	 * archived as well.
8193
	 *
8194 8195
	 * We wait forever, since archive_command is supposed to work and we
	 * assume the admin wanted his backup to work completely. If you don't
B
Bruce Momjian 已提交
8196 8197
	 * wish to wait, you can set statement_timeout.  Also, some notices are
	 * issued to clue in anyone who might be doing this interactively.
8198
	 */
8199 8200 8201 8202 8203
	XLByteToPrevSeg(stoppoint, _logId, _logSeg);
	XLogFileName(lastxlogfilename, ThisTimeLineID, _logId, _logSeg);

	XLByteToSeg(startpoint, _logId, _logSeg);
	BackupHistoryFileName(histfilename, ThisTimeLineID, _logId, _logSeg,
8204 8205
						  startpoint.xrecoff % XLogSegSize);

8206 8207 8208
	ereport(NOTICE,
			(errmsg("pg_stop_backup cleanup done, waiting for required WAL segments to be archived")));

8209 8210 8211
	seconds_before_warning = 60;
	waits = 0;

8212 8213
	while (XLogArchiveIsBusy(lastxlogfilename) ||
		   XLogArchiveIsBusy(histfilename))
8214 8215 8216 8217 8218 8219 8220
	{
		CHECK_FOR_INTERRUPTS();

		pg_usleep(1000000L);

		if (++waits >= seconds_before_warning)
		{
8221
			seconds_before_warning *= 2;		/* This wraps in >10 years... */
8222
			ereport(WARNING,
8223 8224
					(errmsg("pg_stop_backup still waiting for all required WAL segments to be archived (%d seconds elapsed)",
							waits),
P
Peter Eisentraut 已提交
8225
			errhint("Check that your archive_command is executing properly.  "
B
Bruce Momjian 已提交
8226 8227
					"pg_stop_backup can be cancelled safely, "
					"but the database backup will not be usable without all the WAL segments.")));
8228 8229 8230
		}
	}

8231
	/*
8232
	 * We're done.  As a convenience, return the ending WAL location.
8233 8234 8235
	 */
	snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
			 stoppoint.xlogid, stoppoint.xrecoff);
8236
	PG_RETURN_TEXT_P(cstring_to_text(stopxlogfilename));
8237
}
8238

8239 8240 8241 8242 8243 8244
/*
 * pg_switch_xlog: switch to next xlog file
 */
Datum
pg_switch_xlog(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
8245
	XLogRecPtr	switchpoint;
8246 8247 8248 8249 8250
	char		location[MAXFNAMELEN];

	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
B
Bruce Momjian 已提交
8251
			 (errmsg("must be superuser to switch transaction log files"))));
8252

8253 8254 8255 8256 8257 8258
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

8259 8260 8261 8262 8263 8264 8265
	switchpoint = RequestXLogSwitch();

	/*
	 * As a convenience, return the WAL location of the switch record
	 */
	snprintf(location, sizeof(location), "%X/%X",
			 switchpoint.xlogid, switchpoint.xrecoff);
8266
	PG_RETURN_TEXT_P(cstring_to_text(location));
8267 8268 8269
}

/*
8270 8271 8272 8273 8274
 * Report the current WAL write location (same format as pg_start_backup etc)
 *
 * This is useful for determining how much of WAL is visible to an external
 * archiving process.  Note that the data before this point is written out
 * to the kernel, but is not necessarily synced to disk.
8275 8276 8277
 */
Datum
pg_current_xlog_location(PG_FUNCTION_ARGS)
8278 8279 8280
{
	char		location[MAXFNAMELEN];

8281 8282 8283 8284 8285 8286
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298
	/* Make sure we have an up-to-date local LogwrtResult */
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		SpinLockAcquire(&xlogctl->info_lck);
		LogwrtResult = xlogctl->LogwrtResult;
		SpinLockRelease(&xlogctl->info_lck);
	}

	snprintf(location, sizeof(location), "%X/%X",
			 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
8299
	PG_RETURN_TEXT_P(cstring_to_text(location));
8300 8301 8302 8303 8304 8305 8306 8307 8308
}

/*
 * Report the current WAL insert location (same format as pg_start_backup etc)
 *
 * This function is mostly for debugging purposes.
 */
Datum
pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
8309 8310 8311 8312 8313
{
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecPtr	current_recptr;
	char		location[MAXFNAMELEN];

8314 8315 8316 8317 8318 8319
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

8320 8321 8322 8323 8324 8325 8326 8327 8328
	/*
	 * Get the current end-of-WAL position ... shared lock is sufficient
	 */
	LWLockAcquire(WALInsertLock, LW_SHARED);
	INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
	LWLockRelease(WALInsertLock);

	snprintf(location, sizeof(location), "%X/%X",
			 current_recptr.xlogid, current_recptr.xrecoff);
8329
	PG_RETURN_TEXT_P(cstring_to_text(location));
8330 8331
}

8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373
/*
 * Report the last WAL receive location (same format as pg_start_backup etc)
 *
 * This is useful for determining how much of WAL is guaranteed to be received
 * and synced to disk by walreceiver.
 */
Datum
pg_last_xlog_receive_location(PG_FUNCTION_ARGS)
{
	XLogRecPtr	recptr;
	char		location[MAXFNAMELEN];

	recptr = GetWalRcvWriteRecPtr();

	snprintf(location, sizeof(location), "%X/%X",
			 recptr.xlogid, recptr.xrecoff);
	PG_RETURN_TEXT_P(cstring_to_text(location));
}

/*
 * Report the last WAL replay location (same format as pg_start_backup etc)
 *
 * This is useful for determining how much of WAL is visible to read-only
 * connections during recovery.
 */
Datum
pg_last_xlog_replay_location(PG_FUNCTION_ARGS)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	XLogRecPtr	recptr;
	char		location[MAXFNAMELEN];

	SpinLockAcquire(&xlogctl->info_lck);
	recptr = xlogctl->recoveryLastRecPtr;
	SpinLockRelease(&xlogctl->info_lck);

	snprintf(location, sizeof(location), "%X/%X",
			 recptr.xlogid, recptr.xrecoff);
	PG_RETURN_TEXT_P(cstring_to_text(location));
}

8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393
/*
 * Compute an xlog file name and decimal byte offset given a WAL location,
 * such as is returned by pg_stop_backup() or pg_xlog_switch().
 *
 * Note that a location exactly at a segment boundary is taken to be in
 * the previous segment.  This is usually the right thing, since the
 * expected usage is to determine which xlog file(s) are ready to archive.
 */
Datum
pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
{
	text	   *location = PG_GETARG_TEXT_P(0);
	char	   *locationstr;
	unsigned int uxlogid;
	unsigned int uxrecoff;
	uint32		xlogid;
	uint32		xlogseg;
	uint32		xrecoff;
	XLogRecPtr	locationpoint;
	char		xlogfilename[MAXFNAMELEN];
B
Bruce Momjian 已提交
8394 8395 8396 8397 8398
	Datum		values[2];
	bool		isnull[2];
	TupleDesc	resultTupleDesc;
	HeapTuple	resultHeapTuple;
	Datum		result;
8399

8400 8401 8402
	/*
	 * Read input and parse
	 */
8403
	locationstr = text_to_cstring(location);
8404 8405 8406 8407

	if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
P
Peter Eisentraut 已提交
8408
				 errmsg("could not parse transaction log location \"%s\"",
8409 8410 8411 8412 8413
						locationstr)));

	locationpoint.xlogid = uxlogid;
	locationpoint.xrecoff = uxrecoff;

8414
	/*
B
Bruce Momjian 已提交
8415 8416
	 * Construct a tuple descriptor for the result row.  This must match this
	 * function's pg_proc entry!
8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428
	 */
	resultTupleDesc = CreateTemplateTupleDesc(2, false);
	TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
					   TEXTOID, -1, 0);
	TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
					   INT4OID, -1, 0);

	resultTupleDesc = BlessTupleDesc(resultTupleDesc);

	/*
	 * xlogfilename
	 */
8429 8430 8431
	XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
	XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);

8432
	values[0] = CStringGetTextDatum(xlogfilename);
8433 8434 8435 8436 8437
	isnull[0] = false;

	/*
	 * offset
	 */
8438 8439
	xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;

8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450
	values[1] = UInt32GetDatum(xrecoff);
	isnull[1] = false;

	/*
	 * Tuple jam: Having first prepared your Datums, then squash together
	 */
	resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);

	result = HeapTupleGetDatum(resultHeapTuple);

	PG_RETURN_DATUM(result);
8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468
}

/*
 * Compute an xlog file name given a WAL location,
 * such as is returned by pg_stop_backup() or pg_xlog_switch().
 */
Datum
pg_xlogfile_name(PG_FUNCTION_ARGS)
{
	text	   *location = PG_GETARG_TEXT_P(0);
	char	   *locationstr;
	unsigned int uxlogid;
	unsigned int uxrecoff;
	uint32		xlogid;
	uint32		xlogseg;
	XLogRecPtr	locationpoint;
	char		xlogfilename[MAXFNAMELEN];

8469
	locationstr = text_to_cstring(location);
8470 8471 8472 8473

	if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
P
Peter Eisentraut 已提交
8474
				 errmsg("could not parse transaction log location \"%s\"",
8475 8476 8477 8478 8479 8480 8481 8482
						locationstr)));

	locationpoint.xlogid = uxlogid;
	locationpoint.xrecoff = uxrecoff;

	XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
	XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);

8483
	PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
8484 8485
}

8486 8487 8488 8489 8490
/*
 * read_backup_label: check to see if a backup_label file is present
 *
 * If we see a backup_label during recovery, we assume that we are recovering
 * from a backup dump file, and we therefore roll forward from the checkpoint
B
Bruce Momjian 已提交
8491
 * identified by the label file, NOT what pg_control says.	This avoids the
8492 8493 8494 8495 8496
 * problem that pg_control might have been archived one or more checkpoints
 * later than the start of the dump, and so if we rely on it as the start
 * point, we will fail to restore a consistent database state.
 *
 * Returns TRUE if a backup_label was found (and fills the checkpoint
8497 8498
 * location and its REDO location into *checkPointLoc and RedoStartLSN,
 * respectively); returns FALSE if not.
8499 8500
 */
static bool
8501
read_backup_label(XLogRecPtr *checkPointLoc)
8502 8503 8504 8505 8506 8507 8508 8509 8510
{
	char		startxlogfilename[MAXFNAMELEN];
	TimeLineID	tli;
	FILE	   *lfp;
	char		ch;

	/*
	 * See if label file is present
	 */
8511
	lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
8512 8513 8514 8515 8516 8517
	if (!lfp)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
8518
							BACKUP_LABEL_FILE)));
8519 8520
		return false;			/* it's not there, all is fine */
	}
B
Bruce Momjian 已提交
8521

8522
	/*
B
Bruce Momjian 已提交
8523 8524 8525
	 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
	 * is pretty crude, but we are not expecting any variability in the file
	 * format).
8526 8527
	 */
	if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
8528
			   &RedoStartLSN.xlogid, &RedoStartLSN.xrecoff, &tli,
8529 8530 8531
			   startxlogfilename, &ch) != 5 || ch != '\n')
		ereport(FATAL,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8532
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
8533 8534 8535 8536 8537
	if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
			   &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
			   &ch) != 3 || ch != '\n')
		ereport(FATAL,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8538
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
8539 8540 8541 8542
	if (ferror(lfp) || FreeFile(lfp))
		ereport(FATAL,
				(errcode_for_file_access(),
				 errmsg("could not read file \"%s\": %m",
8543
						BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
8544

8545 8546 8547
	return true;
}

8548 8549 8550 8551 8552 8553
/*
 * Error context callback for errors occurring during rm_redo().
 */
static void
rm_redo_error_callback(void *arg)
{
B
Bruce Momjian 已提交
8554 8555
	XLogRecord *record = (XLogRecord *) arg;
	StringInfoData buf;
8556 8557

	initStringInfo(&buf);
8558 8559
	RmgrTable[record->xl_rmid].rm_desc(&buf,
									   record->xl_info,
8560 8561 8562 8563 8564 8565 8566 8567
									   XLogRecGetData(record));

	/* don't bother emitting empty description */
	if (buf.len > 0)
		errcontext("xlog redo %s", buf.data);

	pfree(buf.data);
}
8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604

/*
 * BackupInProgress: check if online backup mode is active
 *
 * This is done by checking for existence of the "backup_label" file.
 */
bool
BackupInProgress(void)
{
	struct stat stat_buf;

	return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
}

/*
 * CancelBackup: rename the "backup_label" file to cancel backup mode
 *
 * If the "backup_label" file exists, it will be renamed to "backup_label.old".
 * Note that this will render an online backup in progress useless.
 * To correctly finish an online backup, pg_stop_backup must be called.
 */
void
CancelBackup(void)
{
	struct stat stat_buf;

	/* if the file is not there, return */
	if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
		return;

	/* remove leftover file from previously cancelled backup if it exists */
	unlink(BACKUP_LABEL_OLD);

	if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) == 0)
	{
		ereport(LOG,
				(errmsg("online backup mode cancelled"),
8605
				 errdetail("\"%s\" was renamed to \"%s\".",
8606
						   BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
8607 8608 8609 8610 8611
	}
	else
	{
		ereport(WARNING,
				(errcode_for_file_access(),
8612 8613
				 errmsg("online backup mode was not cancelled"),
				 errdetail("Could not rename \"%s\" to \"%s\": %m.",
8614
						   BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
8615 8616 8617
	}
}

8618
/* ------------------------------------------------------
8619
 *	Startup Process main entry point and signal handlers
8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634
 * ------------------------------------------------------
 */

/*
 * startupproc_quickdie() occurs when signalled SIGQUIT by the postmaster.
 *
 * Some backend has bought the farm,
 * so we need to stop what we're doing and exit.
 */
static void
startupproc_quickdie(SIGNAL_ARGS)
{
	PG_SETMASK(&BlockSig);

	/*
8635 8636 8637 8638 8639 8640 8641 8642 8643 8644
	 * We DO NOT want to run proc_exit() callbacks -- we're here because
	 * shared memory may be corrupted, so we don't want to try to clean up our
	 * transaction.  Just nail the windows shut and get out of town.  Now that
	 * there's an atexit callback to prevent third-party code from breaking
	 * things by calling exit() directly, we have to reset the callbacks
	 * explicitly to make this work as intended.
	 */
	on_exit_reset();

	/*
8645 8646 8647
	 * Note we do exit(2) not exit(0).	This is to force the postmaster into a
	 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
	 * backend.  This is necessary precisely because we don't clean up our
8648
	 * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
8649 8650
	 * should ensure the postmaster sees this as a crash, too, but no harm in
	 * being doubly sure.)
8651 8652 8653 8654 8655
	 */
	exit(2);
}


8656 8657 8658 8659 8660 8661 8662
/* SIGHUP: set flag to re-read config file at next convenient time */
static void
StartupProcSigHupHandler(SIGNAL_ARGS)
{
	got_SIGHUP = true;
}

8663 8664 8665 8666 8667
/* SIGTERM: set flag to abort redo and exit */
static void
StartupProcShutdownHandler(SIGNAL_ARGS)
{
	if (in_restore_command)
8668
		proc_exit(1);
8669 8670 8671 8672
	else
		shutdown_requested = true;
}

8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684
/* Handle SIGHUP and SIGTERM signals of startup process */
void
HandleStartupProcInterrupts(void)
{
	/*
	 * Check if we were requested to re-read config file.
	 */
	if (got_SIGHUP)
	{
		got_SIGHUP = false;
		ProcessConfigFile(PGC_SIGHUP);
	}
B
Bruce Momjian 已提交
8685

8686 8687 8688 8689 8690
	/*
	 * Check if we were requested to exit without finishing recovery.
	 */
	if (shutdown_requested)
		proc_exit(1);
8691 8692 8693 8694 8695 8696 8697

	/*
	 * Emergency bailout if postmaster has died.  This is to avoid the
	 * necessity for manual cleanup of all postmaster children.
	 */
	if (IsUnderPostmaster && !PostmasterIsAlive(true))
		exit(1);
8698 8699
}

8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715
/* Main entry point for startup process */
void
StartupProcessMain(void)
{
	/*
	 * If possible, make this process a group leader, so that the postmaster
	 * can signal any child processes too.
	 */
#ifdef HAVE_SETSID
	if (setsid() < 0)
		elog(FATAL, "setsid() failed: %m");
#endif

	/*
	 * Properly accept or ignore signals the postmaster might send us
	 */
8716 8717
	pqsignal(SIGHUP, StartupProcSigHupHandler); /* reload config file */
	pqsignal(SIGINT, SIG_IGN);	/* ignore query cancel */
B
Bruce Momjian 已提交
8718 8719
	pqsignal(SIGTERM, StartupProcShutdownHandler);		/* request shutdown */
	pqsignal(SIGQUIT, startupproc_quickdie);	/* hard crash time */
8720
	if (XLogRequestRecoveryConnections)
B
Bruce Momjian 已提交
8721 8722
		pqsignal(SIGALRM, handle_standby_sig_alarm);	/* ignored unless
														 * InHotStandby */
8723 8724
	else
		pqsignal(SIGALRM, SIG_IGN);
8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, SIG_IGN);
	pqsignal(SIGUSR2, SIG_IGN);

	/*
	 * Reset some signals that are accepted by postmaster but not here
	 */
	pqsignal(SIGCHLD, SIG_DFL);
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);
	pqsignal(SIGWINCH, SIG_DFL);

	/*
	 * Unblock signals (they were blocked when the postmaster forked us)
	 */
	PG_SETMASK(&UnBlockSig);

8743
	StartupXLOG();
8744

8745
	/*
8746 8747
	 * Exit normally. Exit code 0 tells postmaster that we completed recovery
	 * successfully.
8748
	 */
8749 8750
	proc_exit(0);
}
8751 8752 8753

/*
 * Read the XLOG page containing RecPtr into readBuf (if not read already).
8754
 * Returns true if the page is read successfully.
8755 8756 8757
 *
 * This is responsible for restoring files from archive as needed, as well
 * as for waiting for the requested WAL record to arrive in standby mode.
8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771
 *
 * 'emode' specifies the log level used for reporting "file not found" or
 * "end of WAL" situations in archive recovery, or in standby mode when a
 * trigger file is found. If set to WARNING or below, XLogPageRead() returns
 * false in those situations, on higher log levels the ereport() won't
 * return.
 *
 * In standby mode, if after a successful return of XLogPageRead() the
 * caller finds the record it's interested in to be broken, it should
 * ereport the error with the level determined by
 * emode_for_corrupt_record(), and then set "failedSources |= readSource"
 * and call XLogPageRead() again with the same arguments. This lets
 * XLogPageRead() to try fetching the record from another source, or to
 * sleep and retry.
8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782
 */
static bool
XLogPageRead(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt,
			 bool randAccess)
{
	static XLogRecPtr receivedUpto = {0, 0};
	bool		switched_segment = false;
	uint32		targetPageOff;
	uint32		targetRecOff;
	uint32		targetId;
	uint32		targetSeg;
8783
	static pg_time_t last_fail_time = 0;
8784 8785 8786 8787 8788 8789

	XLByteToSeg(*RecPtr, targetId, targetSeg);
	targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
	targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;

	/* Fast exit if we have read the record in the current buffer already */
8790
	if (failedSources == 0 && targetId == readId && targetSeg == readSeg &&
8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801
		targetPageOff == readOff && targetRecOff < readLen)
		return true;

	/*
	 * See if we need to switch to a new segment because the requested record
	 * is not in the currently open one.
	 */
	if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
	{
		close(readFile);
		readFile = -1;
8802
		readSource = 0;
8803 8804 8805 8806
	}

	XLByteToSeg(*RecPtr, readId, readSeg);

8807
retry:
8808 8809
	/* See if we need to retrieve more data */
	if (readFile < 0 ||
8810
		(readSource == XLOG_FROM_STREAM && !XLByteLT(*RecPtr, receivedUpto)))
8811 8812 8813 8814 8815
	{
		if (StandbyMode)
		{
			/*
			 * In standby mode, wait for the requested record to become
B
Bruce Momjian 已提交
8816 8817
			 * available, either via restore_command succeeding to restore the
			 * segment, or via walreceiver having streamed the record.
8818 8819 8820 8821 8822 8823
			 */
			for (;;)
			{
				if (WalRcvInProgress())
				{
					/*
B
Bruce Momjian 已提交
8824 8825
					 * While walreceiver is active, wait for new WAL to arrive
					 * from primary.
8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837
					 */
					receivedUpto = GetWalRcvWriteRecPtr();
					if (XLByteLT(*RecPtr, receivedUpto))
					{
						/*
						 * Great, streamed far enough. Open the file if it's
						 * not open already.
						 */
						if (readFile < 0)
						{
							readFile =
								XLogFileRead(readId, readSeg, PANIC,
8838 8839
											 recoveryTargetTLI,
											 XLOG_FROM_PG_XLOG, false);
8840
							switched_segment = true;
8841
							readSource = XLOG_FROM_STREAM;
8842 8843 8844 8845 8846
						}
						break;
					}

					if (CheckForStandbyTrigger())
8847
						goto triggered;
8848 8849 8850 8851 8852 8853 8854 8855 8856

					/*
					 * When streaming is active, we want to react quickly when
					 * the next WAL record arrives, so sleep only a bit.
					 */
					pg_usleep(100000L); /* 100ms */
				}
				else
				{
8857 8858 8859
					int sources;
					pg_time_t now;

8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873
					/*
					 * Until walreceiver manages to reconnect, poll the
					 * archive.
					 */
					if (readFile >= 0)
					{
						close(readFile);
						readFile = -1;
					}
					/* Reset curFileTLI if random fetch. */
					if (randAccess)
						curFileTLI = 0;

					/*
8874 8875
					 * Try to restore the file from archive, or read an
					 * existing file from pg_xlog.
8876
					 */
8877 8878
					sources = XLOG_FROM_ARCHIVE | XLOG_FROM_PG_XLOG;
					if (!(sources & ~failedSources))
8879 8880
					{
						/*
8881 8882 8883 8884 8885 8886 8887 8888
						 * We've exhausted all options for retrieving the
						 * file. Retry ...
						 */
						failedSources = 0;

						/*
						 * ... but sleep first if it hasn't been long since
						 * last attempt.
8889
						 */
8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916
						now = (pg_time_t) time(NULL);
						if ((now - last_fail_time) < 5)
						{
							pg_usleep(1000000L * (5 - (now - last_fail_time)));
							now = (pg_time_t) time(NULL);
						}
						last_fail_time = now;

						/*
						 * If primary_conninfo is set, launch walreceiver to
						 * try to stream the missing WAL, before retrying
						 * to restore from archive/pg_xlog.
						 *
						 * If fetching_ckpt is TRUE, RecPtr points to the
						 * initial checkpoint location. In that case, we use
						 * RedoStartLSN as the streaming start position instead
						 * of RecPtr, so that when we later jump backwards to
						 * start redo at RedoStartLSN, we will have the logs
						 * streamed already.
						 */
						if (PrimaryConnInfo)
						{
							RequestXLogStreaming(
								fetching_ckpt ? RedoStartLSN : *RecPtr,
								PrimaryConnInfo);
							continue;
						}
8917
					}
8918 8919 8920 8921 8922 8923 8924
					/* Don't try to read from a source that just failed */
					sources &= ~failedSources;
					readFile = XLogFileReadAnyTLI(readId, readSeg, DEBUG2,
												  sources);
					switched_segment = true;
					if (readFile != -1)
						break;
8925 8926

					/*
8927 8928 8929 8930 8931 8932 8933 8934 8935
					 * Nope, not found in archive and/or pg_xlog.
					 */
					failedSources |= sources;

					/*
					 * Check to see if the trigger file exists. Note that
					 * we do this only after failure, so when you create
					 * the trigger file, we still finish replaying as much
					 * as we can from archive and pg_xlog before failover.
8936
					 */
8937 8938
					if (CheckForStandbyTrigger())
						goto triggered;
8939 8940 8941
				}

				/*
B
Bruce Momjian 已提交
8942 8943
				 * This possibly-long loop needs to handle interrupts of
				 * startup process.
8944 8945 8946 8947 8948 8949 8950 8951 8952
				 */
				HandleStartupProcInterrupts();
			}
		}
		else
		{
			/* In archive or crash recovery. */
			if (readFile < 0)
			{
8953 8954
				int sources;

8955 8956 8957
				/* Reset curFileTLI if random fetch. */
				if (randAccess)
					curFileTLI = 0;
8958 8959 8960 8961 8962

				sources = XLOG_FROM_PG_XLOG;
				if (InArchiveRecovery)
					sources |= XLOG_FROM_ARCHIVE;

8963
				readFile = XLogFileReadAnyTLI(readId, readSeg, emode,
8964
											  sources);
8965 8966 8967 8968 8969 8970 8971 8972
				switched_segment = true;
				if (readFile < 0)
					return false;
			}
		}
	}

	/*
8973 8974
	 * At this point, we have the right segment open and if we're streaming
	 * we know the requested record is in it.
8975 8976 8977 8978
	 */
	Assert(readFile != -1);

	/*
B
Bruce Momjian 已提交
8979 8980 8981 8982
	 * If the current segment is being streamed from master, calculate how
	 * much of the current page we have received already. We know the
	 * requested record has been received, but this is for the benefit of
	 * future calls, to allow quick exit at the top of this function.
8983
	 */
8984
	if (readSource == XLOG_FROM_STREAM)
8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008
	{
		if (RecPtr->xlogid != receivedUpto.xlogid ||
			(RecPtr->xrecoff / XLOG_BLCKSZ) != (receivedUpto.xrecoff / XLOG_BLCKSZ))
		{
			readLen = XLOG_BLCKSZ;
		}
		else
			readLen = receivedUpto.xrecoff % XLogSegSize - targetPageOff;
	}
	else
		readLen = XLOG_BLCKSZ;

	if (switched_segment && targetPageOff != 0)
	{
		/*
		 * Whenever switching to a new WAL segment, we read the first page of
		 * the file and validate its header, even if that's not where the
		 * target record is.  This is so that we can check the additional
		 * identification info that is present in the first page's "long"
		 * header.
		 */
		readOff = 0;
		if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
		{
9009
			ereport(emode_for_corrupt_record(emode),
9010 9011 9012 9013 9014
					(errcode_for_file_access(),
					 errmsg("could not read from log file %u, segment %u, offset %u: %m",
							readId, readSeg, readOff)));
			goto next_record_is_invalid;
		}
9015 9016
		if (!ValidXLOGHeader((XLogPageHeader) readBuf,
							 emode_for_corrupt_record(emode)))
9017 9018 9019 9020 9021 9022 9023
			goto next_record_is_invalid;
	}

	/* Read the requested page */
	readOff = targetPageOff;
	if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
	{
9024
		ereport(emode_for_corrupt_record(emode),
9025
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
9026 9027
		 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
				readId, readSeg, readOff)));
9028 9029 9030 9031
		goto next_record_is_invalid;
	}
	if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
	{
9032
		ereport(emode_for_corrupt_record(emode),
9033
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
9034 9035
		 errmsg("could not read from log file %u, segment %u, offset %u: %m",
				readId, readSeg, readOff)));
9036 9037
		goto next_record_is_invalid;
	}
9038
	if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode_for_corrupt_record(emode)))
9039 9040 9041 9042 9043 9044 9045 9046 9047 9048
		goto next_record_is_invalid;

	Assert(targetId == readId);
	Assert(targetSeg == readSeg);
	Assert(targetPageOff == readOff);
	Assert(targetRecOff < readLen);

	return true;

next_record_is_invalid:
9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063
	failedSources |= readSource;

	if (readFile >= 0)
		close(readFile);
	readFile = -1;
	readLen = 0;
	readSource = 0;

	/* In standby-mode, keep trying */
	if (StandbyMode)
		goto retry;
	else
		return false;

triggered:
9064 9065 9066 9067
	if (readFile >= 0)
		close(readFile);
	readFile = -1;
	readLen = 0;
9068
	readSource = 0;
9069 9070 9071 9072

	return false;
}

9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106
/*
 * Determine what log level should be used to report a corrupt WAL record
 * in the current WAL page, previously read by XLogPageRead().
 *
 * 'emode' is the error mode that would be used to report a file-not-found
 * or legitimate end-of-WAL situation. It is upgraded to WARNING or PANIC
 * if a corrupt record is not expected at this point.
 */
static int
emode_for_corrupt_record(int emode)
{
	/*
	 * We don't expect any invalid records in archive or in records streamed
	 * from master. Files in the archive should be complete, and we should
	 * never hit the end of WAL because we stop and wait for more WAL to
	 * arrive before replaying it.
	 *
	 * In standby mode, throw a WARNING and keep retrying. If we're lucky
	 * it's a transient error and will go away by itself, and in any case
	 * it's better to keep the standby open for any possible read-only
	 * queries. We throw WARNING in PITR as well, which causes the recovery
	 * to end. That's questionable, you probably would want to abort the
	 * recovery if the archive is corrupt and investigate the situation.
	 * But that's the behavior we've always had, and it does make sense
	 * for tools like pg_standby that implement a standby mode externally.
	 */
	if (readSource == XLOG_FROM_STREAM || readSource == XLOG_FROM_ARCHIVE)
	{
		if (emode < WARNING)
			emode = WARNING;
	}
	return emode;
}

9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129
/*
 * Check to see if the trigger file exists. If it does, request postmaster
 * to shut down walreceiver, wait for it to exit, remove the trigger
 * file, and return true.
 */
static bool
CheckForStandbyTrigger(void)
{
	struct stat stat_buf;

	if (TriggerFile == NULL)
		return false;

	if (stat(TriggerFile, &stat_buf) == 0)
	{
		ereport(LOG,
				(errmsg("trigger file found: %s", TriggerFile)));
		ShutdownWalRcv();
		unlink(TriggerFile);
		return true;
	}
	return false;
}