xlog.c 205.5 KB
Newer Older
1
/*-------------------------------------------------------------------------
2 3
 *
 * xlog.c
4
 *		PostgreSQL transaction log manager
5 6
 *
 *
7
 * Portions Copyright (c) 1996-2007, 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.290 2007/11/15 22:25:15 momjian Exp $
11 12 13
 *
 *-------------------------------------------------------------------------
 */
14

15 16
#include "postgres.h"

17
#include <ctype.h>
18
#include <fcntl.h>
T
Tom Lane 已提交
19
#include <signal.h>
20
#include <time.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/heapam.h"
28
#include "access/multixact.h"
29
#include "access/subtrans.h"
30
#include "access/transam.h"
31
#include "access/tuptoaster.h"
32
#include "access/twophase.h"
33
#include "access/xact.h"
34
#include "access/xlog_internal.h"
35
#include "access/xlogdefs.h"
36
#include "access/xlogutils.h"
37
#include "catalog/catversion.h"
T
Tom Lane 已提交
38
#include "catalog/pg_control.h"
39 40
#include "catalog/pg_type.h"
#include "funcapi.h"
41
#include "miscadmin.h"
42
#include "pgstat.h"
43
#include "postmaster/bgwriter.h"
44
#include "storage/bufpage.h"
45
#include "storage/fd.h"
46
#include "storage/pmsignal.h"
47
#include "storage/procarray.h"
48
#include "storage/smgr.h"
49
#include "storage/spin.h"
50
#include "utils/builtins.h"
51
#include "utils/pg_locale.h"
52
#include "utils/ps_status.h"
53

54

55 56
/* File path names (all relative to $PGDATA) */
#define BACKUP_LABEL_FILE		"backup_label"
57
#define BACKUP_LABEL_OLD		"backup_label.old"
58 59 60 61
#define RECOVERY_COMMAND_FILE	"recovery.conf"
#define RECOVERY_COMMAND_DONE	"recovery.done"


T
Tom Lane 已提交
62 63
/* User-settable parameters */
int			CheckPointSegments = 3;
V
Vadim B. Mikheev 已提交
64
int			XLOGbuffers = 8;
65
int			XLogArchiveTimeout = 0;
66
bool		XLogArchiveMode = false;
67
char	   *XLogArchiveCommand = NULL;
68 69
char	   *XLOG_sync_method = NULL;
const char	XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
70
bool		fullPageWrites = true;
71
bool		log_checkpoints = false;
T
Tom Lane 已提交
72

73 74 75 76
#ifdef WAL_DEBUG
bool		XLOG_DEBUG = false;
#endif

77
/*
78 79 80 81 82
 * 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 已提交
83
 * 2*CheckPointSegments+1.	Under normal conditions, a checkpoint will free
84 85 86
 * 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.
87 88 89 90
 */
#define XLOGfileslop	(2*CheckPointSegments + 1)


91
/* these are derived from XLOG_sync_method by assign_xlog_sync_method */
B
Bruce Momjian 已提交
92
int			sync_method = DEFAULT_SYNC_METHOD;
93 94 95 96
static int	open_sync_bit = DEFAULT_SYNC_FLAGBIT;

#define XLOG_SYNC_BIT  (enableFsync ? open_sync_bit : 0)

T
Tom Lane 已提交
97

98 99 100 101 102 103 104
/*
 * 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 已提交
105
/*
106 107
 * ThisTimeLineID will be same in all backends --- it identifies current
 * WAL timeline for the database system.
T
Tom Lane 已提交
108
 */
109
TimeLineID	ThisTimeLineID = 0;
V
WAL  
Vadim B. Mikheev 已提交
110

111
/* Are we doing recovery from XLOG? */
T
Tom Lane 已提交
112
bool		InRecovery = false;
B
Bruce Momjian 已提交
113

114
/* Are we recovering using offline XLOG archives? */
B
Bruce Momjian 已提交
115 116
static bool InArchiveRecovery = false;

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

120 121
/* options taken from recovery.conf */
static char *recoveryRestoreCommand = NULL;
122 123 124
static bool recoveryTarget = false;
static bool recoveryTargetExact = false;
static bool recoveryTargetInclusive = true;
125
static bool recoveryLogRestartpoints = false;
B
Bruce Momjian 已提交
126
static TransactionId recoveryTargetXid;
127
static TimestampTz recoveryTargetTime;
128
static TimestampTz recoveryLastXTime = 0;
129

130
/* if recoveryStopsHere returns true, it saves actual stop xid/time here */
B
Bruce Momjian 已提交
131
static TransactionId recoveryStopXid;
132
static TimestampTz recoveryStopTime;
B
Bruce Momjian 已提交
133
static bool recoveryStopAfter;
134 135 136 137 138 139 140 141 142 143 144 145 146

/*
 * 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 已提交
147
 * first list member).	Only these TLIs are expected to be seen in the WAL
148 149 150 151 152 153 154 155 156
 * 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 已提交
157 158 159
static TimeLineID recoveryTargetTLI;
static List *expectedTLIs;
static TimeLineID curFileTLI;
160

T
Tom Lane 已提交
161 162
/*
 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
163 164 165 166
 * 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 已提交
167 168
 */
static XLogRecPtr ProcLastRecPtr = {0, 0};
169

170
XLogRecPtr	XactLastRecEnd = {0, 0};
171

T
Tom Lane 已提交
172 173 174
/*
 * 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 已提交
175
 * CHECKPOINT record).	We update this from the shared-memory copy,
T
Tom Lane 已提交
176
 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
B
Bruce Momjian 已提交
177
 * hold the Insert lock).  See XLogInsert for details.	We are also allowed
178
 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
179 180
 * see GetRedoRecPtr.  A freshly spawned backend obtains the value during
 * InitXLOGAccess.
T
Tom Lane 已提交
181
 */
182
static XLogRecPtr RedoRecPtr;
183

T
Tom Lane 已提交
184 185 186 187 188 189 190 191 192
/*----------
 * 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.
 *
193
 * We do a lot of pushups to minimize the amount of access to lockable
T
Tom Lane 已提交
194 195 196
 * 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
197 198 199 200
 *		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 已提交
201 202 203
 *
 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
 * right", since both are updated by a write or flush operation before
204 205
 * 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 已提交
206 207 208
 * without needing to grab info_lck as well.
 *
 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
B
Bruce Momjian 已提交
209
 * but is updated when convenient.	Again, it exists for the convenience of
210
 * code that is already holding WALInsertLock but not the other locks.
T
Tom Lane 已提交
211 212 213 214 215 216 217 218 219 220
 *
 * 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".
221 222 223 224 225 226 227 228 229 230 231 232 233 234
 *
 * 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.
 *
 * CheckpointLock: must be held to do a checkpoint (ensures only one
235 236
 * checkpointer at a time; currently, with all checkpoints done by the
 * bgwriter, this is just pro forma).
237
 *
T
Tom Lane 已提交
238 239
 *----------
 */
240

T
Tom Lane 已提交
241
typedef struct XLogwrtRqst
242
{
T
Tom Lane 已提交
243 244
	XLogRecPtr	Write;			/* last byte + 1 to write out */
	XLogRecPtr	Flush;			/* last byte + 1 to flush */
245
} XLogwrtRqst;
246

247 248 249 250 251 252
typedef struct XLogwrtResult
{
	XLogRecPtr	Write;			/* last byte + 1 written out */
	XLogRecPtr	Flush;			/* last byte + 1 flushed */
} XLogwrtResult;

T
Tom Lane 已提交
253 254 255
/*
 * Shared state data for XLogInsert.
 */
256 257
typedef struct XLogCtlInsert
{
B
Bruce Momjian 已提交
258 259
	XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
	XLogRecPtr	PrevRecord;		/* start of previously-inserted record */
260
	int			curridx;		/* current block index in cache */
B
Bruce Momjian 已提交
261 262 263
	XLogPageHeader currpage;	/* points to header of block in cache */
	char	   *currpos;		/* current insertion point in cache */
	XLogRecPtr	RedoRecPtr;		/* current redo point for insertions */
264
	bool		forcePageWrites;	/* forcing full-page writes for PITR? */
265 266
} XLogCtlInsert;

T
Tom Lane 已提交
267 268 269
/*
 * Shared state data for XLogWrite/XLogFlush.
 */
270 271
typedef struct XLogCtlWrite
{
B
Bruce Momjian 已提交
272 273 274
	XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
	int			curridx;		/* cache index of next block to write */
	time_t		lastSegSwitchTime;		/* time of last xlog segment switch */
275 276
} XLogCtlWrite;

T
Tom Lane 已提交
277 278 279
/*
 * Total shared-memory state for XLOG.
 */
280 281
typedef struct XLogCtlData
{
282
	/* Protected by WALInsertLock: */
B
Bruce Momjian 已提交
283
	XLogCtlInsert Insert;
284

T
Tom Lane 已提交
285
	/* Protected by info_lck: */
B
Bruce Momjian 已提交
286 287
	XLogwrtRqst LogwrtRqst;
	XLogwrtResult LogwrtResult;
288 289
	uint32		ckptXidEpoch;	/* nextXID & epoch of latest checkpoint */
	TransactionId ckptXid;
B
Bruce Momjian 已提交
290
	XLogRecPtr	asyncCommitLSN; /* LSN of newest async commit */
291

292
	/* Protected by WALWriteLock: */
B
Bruce Momjian 已提交
293 294
	XLogCtlWrite Write;

T
Tom Lane 已提交
295
	/*
B
Bruce Momjian 已提交
296 297 298
	 * 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 已提交
299
	 */
B
Bruce Momjian 已提交
300
	char	   *pages;			/* buffers for unwritten XLOG pages */
301
	XLogRecPtr *xlblocks;		/* 1st byte ptr-s + XLOG_BLCKSZ */
302 303
	Size		XLogCacheByte;	/* # bytes in xlog buffers */
	int			XLogCacheBlck;	/* highest allocated xlog buffer index */
304
	TimeLineID	ThisTimeLineID;
T
Tom Lane 已提交
305

306
	slock_t		info_lck;		/* locks shared variables shown above */
307 308
} XLogCtlData;

309
static XLogCtlData *XLogCtl = NULL;
310

311
/*
T
Tom Lane 已提交
312
 * We maintain an image of pg_control in shared memory.
313
 */
314
static ControlFileData *ControlFile = NULL;
315

T
Tom Lane 已提交
316 317 318 319 320
/*
 * 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.
 */
321

T
Tom Lane 已提交
322 323
/* Free space remaining in the current xlog page buffer */
#define INSERT_FREESPACE(Insert)  \
324
	(XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
T
Tom Lane 已提交
325 326 327 328 329 330

/* Construct XLogRecPtr value for current insertion point */
#define INSERT_RECPTR(recptr,Insert,curridx)  \
	( \
	  (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
	  (recptr).xrecoff = \
B
Bruce Momjian 已提交
331
		XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
T
Tom Lane 已提交
332 333 334 335 336 337 338
	)

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

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

T
Tom Lane 已提交
340 341 342 343
/*
 * Private, possibly out-of-date copy of shared LogwrtResult.
 * See discussion above.
 */
344
static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
345

T
Tom Lane 已提交
346 347 348 349 350 351 352 353 354 355
/*
 * 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;
356

T
Tom Lane 已提交
357 358 359 360 361 362
/*
 * 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
 * will be just past that page.
 */
363 364 365 366
static int	readFile = -1;
static uint32 readId = 0;
static uint32 readSeg = 0;
static uint32 readOff = 0;
B
Bruce Momjian 已提交
367

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

371 372 373 374
/* Buffer for current ReadRecord result (expandable) */
static char *readRecordBuf = NULL;
static uint32 readRecordBufSize = 0;

T
Tom Lane 已提交
375
/* State information for XLOG reading */
B
Bruce Momjian 已提交
376 377
static XLogRecPtr ReadRecPtr;	/* start of last record read */
static XLogRecPtr EndRecPtr;	/* end+1 of last record read */
378
static XLogRecord *nextRecord = NULL;
379
static TimeLineID lastPageTLI = 0;
380

V
WAL  
Vadim B. Mikheev 已提交
381 382
static bool InRedo = false;

383

384 385
static void XLogArchiveNotify(const char *xlog);
static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
386
static bool XLogArchiveCheckDone(const char *xlog);
387 388
static void XLogArchiveCleanup(const char *xlog);
static void readRecoveryCommandFile(void);
389
static void exitArchiveRecovery(TimeLineID endTLI,
B
Bruce Momjian 已提交
390
					uint32 endLogId, uint32 endLogSeg);
391
static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
392
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
T
Tom Lane 已提交
393

394
static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
B
Bruce Momjian 已提交
395
				XLogRecPtr *lsn, BkpBlock *bkpb);
396 397
static bool AdvanceXLInsertBuffer(bool new_segment);
static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
B
Bruce Momjian 已提交
398 399
static int XLogFileInit(uint32 log, uint32 seg,
			 bool *use_existent, bool use_lock);
400 401
static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
402
					   bool use_lock);
403 404
static int	XLogFileOpen(uint32 log, uint32 seg);
static int	XLogFileRead(uint32 log, uint32 seg, int emode);
B
Bruce Momjian 已提交
405
static void XLogFileClose(void);
406
static bool RestoreArchivedFile(char *path, const char *xlogfname,
B
Bruce Momjian 已提交
407
					const char *recovername, off_t expectedSize);
408 409
static void PreallocXlogFiles(XLogRecPtr endptr);
static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
410
static void CleanupBackupHistory(void);
411
static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
412
static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
413
static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
414 415 416 417
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 已提交
418 419
					 TimeLineID endTLI,
					 uint32 endLogId, uint32 endLogSeg);
T
Tom Lane 已提交
420 421
static void WriteControlFile(void);
static void ReadControlFile(void);
422
static char *str_time(pg_time_t tnow);
423
static void issue_xlog_fsync(void);
B
Bruce Momjian 已提交
424

425
#ifdef WAL_DEBUG
426
static void xlog_outrec(StringInfo buf, XLogRecord *record);
427
#endif
428
static bool read_backup_label(XLogRecPtr *checkPointLoc,
B
Bruce Momjian 已提交
429
				  XLogRecPtr *minRecoveryLoc);
430
static void rm_redo_error_callback(void *arg);
T
Tom Lane 已提交
431 432 433 434 435


/*
 * Insert an XLOG record having the specified RMID and info bytes,
 * with the body of the record being the data chunk(s) described by
436
 * the rdata chain (see xlog.h for notes about rdata).
T
Tom Lane 已提交
437 438 439 440 441 442 443 444 445 446 447
 *
 * 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.
 */
448
XLogRecPtr
449
XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
450
{
B
Bruce Momjian 已提交
451 452
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecord *record;
T
Tom Lane 已提交
453
	XLogContRecord *contrecord;
B
Bruce Momjian 已提交
454 455 456
	XLogRecPtr	RecPtr;
	XLogRecPtr	WriteRqst;
	uint32		freespace;
457
	int			curridx;
B
Bruce Momjian 已提交
458 459 460 461 462
	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];
463 464 465 466
	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 已提交
467 468 469 470
	uint32		len,
				write_len;
	unsigned	i;
	bool		updrqst;
471
	bool		doPageWrites;
472
	bool		isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
V
Vadim B. Mikheev 已提交
473

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

T
Tom Lane 已提交
478
	/*
B
Bruce Momjian 已提交
479 480
	 * In bootstrap mode, we don't actually log anything but XLOG resources;
	 * return a phony record pointer.
T
Tom Lane 已提交
481
	 */
V
Vadim B. Mikheev 已提交
482
	if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
V
WAL  
Vadim B. Mikheev 已提交
483 484
	{
		RecPtr.xlogid = 0;
B
Bruce Momjian 已提交
485
		RecPtr.xrecoff = SizeOfXLogLongPHD;		/* start of 1st chkpt record */
486
		return RecPtr;
V
WAL  
Vadim B. Mikheev 已提交
487 488
	}

T
Tom Lane 已提交
489
	/*
490
	 * Here we scan the rdata chain, determine which buffers must be backed
T
Tom Lane 已提交
491
	 * up, and compute the CRC values for the data.  Note that the record
B
Bruce Momjian 已提交
492 493 494 495
	 * 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 已提交
496
	 *
497 498 499 500 501
	 * 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 已提交
502 503 504 505 506
	 * 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 已提交
507
	 */
508
begin:;
T
Tom Lane 已提交
509 510 511 512 513 514
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
	{
		dtbuf[i] = InvalidBuffer;
		dtbuf_bkp[i] = false;
	}

515 516 517 518 519 520 521 522
	/*
	 * 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;

523
	INIT_CRC32(rdata_crc);
T
Tom Lane 已提交
524
	len = 0;
B
Bruce Momjian 已提交
525
	for (rdt = rdata;;)
526 527 528
	{
		if (rdt->buffer == InvalidBuffer)
		{
T
Tom Lane 已提交
529
			/* Simple data, just include it */
530
			len += rdt->len;
531
			COMP_CRC32(rdata_crc, rdt->data, rdt->len);
532
		}
T
Tom Lane 已提交
533
		else
534
		{
T
Tom Lane 已提交
535 536
			/* Find info for buffer */
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
537
			{
T
Tom Lane 已提交
538
				if (rdt->buffer == dtbuf[i])
539
				{
540
					/* Buffer already referenced by earlier chain item */
T
Tom Lane 已提交
541 542 543 544 545
					if (dtbuf_bkp[i])
						rdt->data = NULL;
					else if (rdt->data)
					{
						len += rdt->len;
546
						COMP_CRC32(rdata_crc, rdt->data, rdt->len);
T
Tom Lane 已提交
547 548
					}
					break;
549
				}
T
Tom Lane 已提交
550
				if (dtbuf[i] == InvalidBuffer)
551
				{
T
Tom Lane 已提交
552 553
					/* OK, put it in this slot */
					dtbuf[i] = rdt->buffer;
554 555
					if (XLogCheckBuffer(rdt, doPageWrites,
										&(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
T
Tom Lane 已提交
556 557 558 559 560 561 562
					{
						dtbuf_bkp[i] = true;
						rdt->data = NULL;
					}
					else if (rdt->data)
					{
						len += rdt->len;
563
						COMP_CRC32(rdata_crc, rdt->data, rdt->len);
T
Tom Lane 已提交
564 565
					}
					break;
566 567
				}
			}
T
Tom Lane 已提交
568
			if (i >= XLR_MAX_BKP_BLOCKS)
569
				elog(PANIC, "can backup at most %d blocks per xlog record",
T
Tom Lane 已提交
570
					 XLR_MAX_BKP_BLOCKS);
571
		}
572
		/* Break out of loop when rdt points to last chain item */
573 574 575 576 577
		if (rdt->next == NULL)
			break;
		rdt = rdt->next;
	}

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
	/*
	 * 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 已提交
611
	/*
612 613
	 * 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 已提交
614 615 616
	 * 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 已提交
617
	 */
618
	if (len == 0 && !isLogSwitch)
619
		elog(PANIC, "invalid xlog record length %u", len);
620

621
	START_CRIT_SECTION();
622

623 624 625
	/* Now wait to get insert lock */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);

T
Tom Lane 已提交
626
	/*
B
Bruce Momjian 已提交
627 628 629
	 * 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.
630 631
	 *
	 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
B
Bruce Momjian 已提交
632 633
	 * affect the contents of the XLOG record, so we'll update our local copy
	 * but not force a recomputation.
T
Tom Lane 已提交
634 635
	 */
	if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
636
	{
T
Tom Lane 已提交
637 638 639
		Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
		RedoRecPtr = Insert->RedoRecPtr;

640
		if (doPageWrites)
641
		{
642
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
T
Tom Lane 已提交
643
			{
644 645 646 647 648 649 650 651 652 653 654 655 656
				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 已提交
657
			}
658 659 660
		}
	}

661
	/*
B
Bruce Momjian 已提交
662 663 664 665
	 * 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.)
666 667 668 669 670 671 672 673 674
	 */
	if (Insert->forcePageWrites && !doPageWrites)
	{
		/* Oops, must redo it with full-page data */
		LWLockRelease(WALInsertLock);
		END_CRIT_SECTION();
		goto begin;
	}

T
Tom Lane 已提交
675
	/*
B
Bruce Momjian 已提交
676 677 678 679
	 * 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 已提交
680
	 *
681 682 683
	 * 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 已提交
684 685 686
	 */
	write_len = len;
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
687
	{
688 689 690
		BkpBlock   *bkpb;
		char	   *page;

691
		if (!dtbuf_bkp[i])
692 693
			continue;

T
Tom Lane 已提交
694
		info |= XLR_SET_BKP_BLOCK(i);
695

696 697 698 699 700
		bkpb = &(dtbuf_xlg[i]);
		page = (char *) BufferGetBlock(dtbuf[i]);

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

702 703
		rdt->data = (char *) bkpb;
		rdt->len = sizeof(BkpBlock);
T
Tom Lane 已提交
704
		write_len += sizeof(BkpBlock);
705

706 707
		rdt->next = &(dtbuf_rdt2[i]);
		rdt = rdt->next;
708

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
		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;
		}
731 732
	}

733 734 735 736 737 738 739
	/*
	 * 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 已提交
740 741
	 * defining it like this leaves the info bit free for some potential other
	 * use in records without any backup blocks.
742 743 744 745
	 */
	if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
		info |= XLR_BKP_REMOVABLE;

746
	/*
747
	 * If there isn't enough space on the current XLOG page for a record
B
Bruce Momjian 已提交
748
	 * header, advance to the next page (leaving the unused space as zeroes).
749
	 */
T
Tom Lane 已提交
750 751
	updrqst = false;
	freespace = INSERT_FREESPACE(Insert);
752 753
	if (freespace < SizeOfXLogRecord)
	{
754
		updrqst = AdvanceXLInsertBuffer(false);
755 756 757
		freespace = INSERT_FREESPACE(Insert);
	}

758
	/* Compute record's XLOG location */
T
Tom Lane 已提交
759
	curridx = Insert->curridx;
760 761 762
	INSERT_RECPTR(RecPtr, Insert, curridx);

	/*
B
Bruce Momjian 已提交
763 764 765 766 767
	 * 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.
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
	 */
	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 已提交
799

800 801
	/* Insert record header */

802
	record = (XLogRecord *) Insert->currpos;
803
	record->xl_prev = Insert->PrevRecord;
804
	record->xl_xid = GetCurrentTransactionIdIfAny();
805
	record->xl_tot_len = SizeOfXLogRecord + write_len;
T
Tom Lane 已提交
806
	record->xl_len = len;		/* doesn't include backup blocks */
807
	record->xl_info = info;
808
	record->xl_rmid = rmid;
809

810 811 812 813
	/* 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);
814 815
	record->xl_crc = rdata_crc;

816
#ifdef WAL_DEBUG
V
WAL  
Vadim B. Mikheev 已提交
817 818
	if (XLOG_DEBUG)
	{
B
Bruce Momjian 已提交
819
		StringInfoData buf;
V
WAL  
Vadim B. Mikheev 已提交
820

821
		initStringInfo(&buf);
822 823
		appendStringInfo(&buf, "INSERT @ %X/%X: ",
						 RecPtr.xlogid, RecPtr.xrecoff);
824
		xlog_outrec(&buf, record);
825
		if (rdata->data != NULL)
V
WAL  
Vadim B. Mikheev 已提交
826
		{
827 828
			appendStringInfo(&buf, " - ");
			RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
V
WAL  
Vadim B. Mikheev 已提交
829
		}
830 831
		elog(LOG, "%s", buf.data);
		pfree(buf.data);
V
WAL  
Vadim B. Mikheev 已提交
832
	}
833
#endif
V
WAL  
Vadim B. Mikheev 已提交
834

T
Tom Lane 已提交
835 836 837 838
	/* Record begin of record in appropriate places */
	ProcLastRecPtr = RecPtr;
	Insert->PrevRecord = RecPtr;

839
	Insert->currpos += SizeOfXLogRecord;
T
Tom Lane 已提交
840
	freespace -= SizeOfXLogRecord;
841

T
Tom Lane 已提交
842 843 844 845
	/*
	 * Append the data, including backup blocks if any
	 */
	while (write_len)
846
	{
847 848 849 850
		while (rdata->data == NULL)
			rdata = rdata->next;

		if (freespace > 0)
851
		{
852 853 854 855 856
			if (rdata->len > freespace)
			{
				memcpy(Insert->currpos, rdata->data, freespace);
				rdata->data += freespace;
				rdata->len -= freespace;
T
Tom Lane 已提交
857
				write_len -= freespace;
858 859 860 861 862
			}
			else
			{
				memcpy(Insert->currpos, rdata->data, rdata->len);
				freespace -= rdata->len;
T
Tom Lane 已提交
863
				write_len -= rdata->len;
864 865 866 867
				Insert->currpos += rdata->len;
				rdata = rdata->next;
				continue;
			}
868 869
		}

870
		/* Use next buffer */
871
		updrqst = AdvanceXLInsertBuffer(false);
T
Tom Lane 已提交
872 873 874 875 876 877
		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;
878
		freespace = INSERT_FREESPACE(Insert);
879
	}
880

T
Tom Lane 已提交
881 882
	/* Ensure next record will be properly aligned */
	Insert->currpos = (char *) Insert->currpage +
B
Bruce Momjian 已提交
883
		MAXALIGN(Insert->currpos - (char *) Insert->currpage);
T
Tom Lane 已提交
884
	freespace = INSERT_FREESPACE(Insert);
885

V
Vadim B. Mikheev 已提交
886
	/*
B
Bruce Momjian 已提交
887 888
	 * 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 已提交
889
	 */
T
Tom Lane 已提交
890
	INSERT_RECPTR(RecPtr, Insert, curridx);
V
Vadim B. Mikheev 已提交
891

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
	/*
	 * 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;

		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);

		/*
B
Bruce Momjian 已提交
909 910
		 * Flush through the end of the page containing XLOG_SWITCH, and
		 * perform end-of-segment actions (eg, notifying archiver).
911 912 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 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
		 */
		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 */
	}
961
	else
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
	{
		/* 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];
	}
978

979
	LWLockRelease(WALInsertLock);
980 981 982

	if (updrqst)
	{
983 984 985
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

986
		SpinLockAcquire(&xlogctl->info_lck);
T
Tom Lane 已提交
987
		/* advance global request to include new block(s) */
988 989
		if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
			xlogctl->LogwrtRqst.Write = WriteRqst;
T
Tom Lane 已提交
990
		/* update local result copy while I have the chance */
991
		LogwrtResult = xlogctl->LogwrtResult;
992
		SpinLockRelease(&xlogctl->info_lck);
993 994
	}

995
	XactLastRecEnd = RecPtr;
996

997
	END_CRIT_SECTION();
998

999
	return RecPtr;
1000
}
1001

1002
/*
1003 1004 1005
 * 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.
1006
 */
1007
static bool
1008
XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1009
				XLogRecPtr *lsn, BkpBlock *bkpb)
1010 1011
{
	PageHeader	page;
1012 1013 1014 1015

	page = (PageHeader) BufferGetBlock(rdata->buffer);

	/*
B
Bruce Momjian 已提交
1016 1017 1018
	 * 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.
1019 1020 1021
	 */
	*lsn = page->pd_lsn;

1022
	if (doPageWrites &&
1023
		XLByteLE(page->pd_lsn, RedoRecPtr))
1024
	{
1025 1026 1027 1028 1029
		/*
		 * The page needs to be backed up, so set up *bkpb
		 */
		bkpb->node = BufferGetFileNode(rdata->buffer);
		bkpb->block = BufferGetBlockNumber(rdata->buffer);
1030

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
		if (rdata->buffer_std)
		{
			/* Assume we can omit data between pd_lower and pd_upper */
			uint16		lower = page->pd_lower;
			uint16		upper = page->pd_upper;

			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;
		}
1057

1058
		return true;			/* buffer requires backup */
1059
	}
1060 1061

	return false;				/* buffer does not need to be backed up */
1062 1063
}

1064 1065 1066 1067 1068 1069
/*
 * XLogArchiveNotify
 *
 * Create an archive notification file
 *
 * The name of the notification file is the message that will be picked up
1070
 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1071
 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1072
 * then when complete, rename it to 0000000100000001000000C6.done
1073 1074 1075 1076 1077
 */
static void
XLogArchiveNotify(const char *xlog)
{
	char		archiveStatusPath[MAXPGPATH];
B
Bruce Momjian 已提交
1078
	FILE	   *fd;
1079 1080 1081 1082

	/* insert an otherwise empty file called <XLOG>.ready */
	StatusFilePath(archiveStatusPath, xlog, ".ready");
	fd = AllocateFile(archiveStatusPath, "w");
B
Bruce Momjian 已提交
1083 1084
	if (fd == NULL)
	{
1085 1086 1087 1088 1089 1090
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not create archive status file \"%s\": %m",
						archiveStatusPath)));
		return;
	}
B
Bruce Momjian 已提交
1091 1092
	if (FreeFile(fd))
	{
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
		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];

1113
	XLogFileName(xlog, ThisTimeLineID, log, seg);
1114 1115 1116 1117
	XLogArchiveNotify(xlog);
}

/*
1118
 * XLogArchiveCheckDone
1119
 *
1120 1121 1122 1123
 * 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.
1124 1125
 *
 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1126 1127 1128 1129
 * 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.
1130 1131
 */
static bool
1132
XLogArchiveCheckDone(const char *xlog)
1133 1134 1135 1136
{
	char		archiveStatusPath[MAXPGPATH];
	struct stat stat_buf;

1137 1138 1139 1140 1141
	/* Always deletable if archiving is off */
	if (!XLogArchivingActive())
		return true;

	/* First check for .done --- this means archiver is done with it */
1142 1143 1144 1145 1146 1147 1148
	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 已提交
1149
		return false;
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163

	/* 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 */
	XLogArchiveNotify(xlog);
	return false;
}

/*
 * XLogArchiveCleanup
 *
1164
 * Cleanup archive notification file(s) for a particular xlog segment
1165 1166 1167 1168
 */
static void
XLogArchiveCleanup(const char *xlog)
{
B
Bruce Momjian 已提交
1169
	char		archiveStatusPath[MAXPGPATH];
1170

1171
	/* Remove the .done file */
1172 1173 1174
	StatusFilePath(archiveStatusPath, xlog, ".done");
	unlink(archiveStatusPath);
	/* should we complain about failure? */
1175 1176 1177 1178 1179

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

T
Tom Lane 已提交
1182 1183 1184 1185
/*
 * Advance the Insert state to the next buffer page, writing out the next
 * buffer if it still contains unwritten data.
 *
1186 1187 1188 1189
 * 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 已提交
1190
 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1191
 * just-filled page.  If we can do this for free (without an extra lock),
T
Tom Lane 已提交
1192 1193 1194
 * 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.
 *
1195
 * Must be called with WALInsertLock held.
T
Tom Lane 已提交
1196 1197
 */
static bool
1198
AdvanceXLInsertBuffer(bool new_segment)
1199
{
T
Tom Lane 已提交
1200 1201
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogCtlWrite *Write = &XLogCtl->Write;
1202
	int			nextidx = NextBufIdx(Insert->curridx);
T
Tom Lane 已提交
1203 1204 1205
	bool		update_needed = true;
	XLogRecPtr	OldPageRqstPtr;
	XLogwrtRqst WriteRqst;
1206 1207
	XLogRecPtr	NewPageEndPtr;
	XLogPageHeader NewPage;
1208

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

T
Tom Lane 已提交
1213
	/*
B
Bruce Momjian 已提交
1214 1215 1216
	 * 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 已提交
1217 1218 1219 1220 1221 1222
	 */
	OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
	if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
	{
		/* nope, got work to do... */
		XLogRecPtr	FinishedPageRqstPtr;
1223

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

1226
		/* Before waiting, get info_lck and update LogwrtResult */
1227 1228 1229 1230
		{
			/* use volatile pointer to prevent code rearrangement */
			volatile XLogCtlData *xlogctl = XLogCtl;

1231
			SpinLockAcquire(&xlogctl->info_lck);
1232 1233 1234
			if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
				xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
			LogwrtResult = xlogctl->LogwrtResult;
1235
			SpinLockRelease(&xlogctl->info_lck);
1236
		}
1237 1238 1239 1240 1241 1242 1243 1244 1245

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

		if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
		{
			/* OK, someone wrote it already */
			Insert->LogwrtResult = LogwrtResult;
		}
		else
1246
		{
1247 1248 1249 1250
			/* Must acquire write lock */
			LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
			LogwrtResult = Write->LogwrtResult;
			if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1251
			{
1252 1253 1254
				/* OK, someone wrote it already */
				LWLockRelease(WALWriteLock);
				Insert->LogwrtResult = LogwrtResult;
T
Tom Lane 已提交
1255
			}
1256
			else
T
Tom Lane 已提交
1257 1258
			{
				/*
B
Bruce Momjian 已提交
1259 1260
				 * Have to write buffers while holding insert lock. This is
				 * not good, so only write as much as we absolutely must.
T
Tom Lane 已提交
1261 1262 1263 1264
				 */
				WriteRqst.Write = OldPageRqstPtr;
				WriteRqst.Flush.xlogid = 0;
				WriteRqst.Flush.xrecoff = 0;
1265
				XLogWrite(WriteRqst, false, false);
1266
				LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
1267
				Insert->LogwrtResult = LogwrtResult;
1268 1269 1270 1271
			}
		}
	}

T
Tom Lane 已提交
1272
	/*
B
Bruce Momjian 已提交
1273 1274
	 * Now the next buffer slot is free and we can set it up to be the next
	 * output page.
T
Tom Lane 已提交
1275
	 */
1276
	NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1277 1278 1279 1280 1281 1282 1283 1284

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

1285
	if (NewPageEndPtr.xrecoff >= XLogFileSize)
1286
	{
T
Tom Lane 已提交
1287
		/* crossing a logid boundary */
1288
		NewPageEndPtr.xlogid += 1;
1289
		NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1290
	}
T
Tom Lane 已提交
1291
	else
1292
		NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1293
	XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1294
	NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
B
Bruce Momjian 已提交
1295

T
Tom Lane 已提交
1296
	Insert->curridx = nextidx;
1297
	Insert->currpage = NewPage;
B
Bruce Momjian 已提交
1298 1299

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

T
Tom Lane 已提交
1301
	/*
B
Bruce Momjian 已提交
1302 1303
	 * 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 已提交
1304
	 */
1305
	MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1306

1307 1308 1309
	/*
	 * Fill the new page's header
	 */
B
Bruce Momjian 已提交
1310 1311
	NewPage   ->xlp_magic = XLOG_PAGE_MAGIC;

1312
	/* NewPage->xlp_info = 0; */	/* done by memset */
B
Bruce Momjian 已提交
1313 1314
	NewPage   ->xlp_tli = ThisTimeLineID;
	NewPage   ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1315
	NewPage   ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
T
Tom Lane 已提交
1316

1317
	/*
1318
	 * If first page of an XLOG segment file, make it a long header.
1319 1320 1321
	 */
	if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
	{
1322
		XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1323

1324 1325
		NewLongPage->xlp_sysid = ControlFile->system_identifier;
		NewLongPage->xlp_seg_size = XLogSegSize;
1326
		NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
B
Bruce Momjian 已提交
1327 1328 1329
		NewPage   ->xlp_info |= XLP_LONG_HEADER;

		Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1330 1331
	}

T
Tom Lane 已提交
1332
	return update_needed;
1333 1334
}

1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
/*
 * 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)
{
	/*
1348 1349
	 * 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 已提交
1350 1351
	 * highest-order bits separately, and force a checkpoint immediately when
	 * they change.
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
	 */
	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 已提交
1364
		new_segno >= old_segno + (uint32) (CheckPointSegments - 1))
1365 1366 1367 1368
		return true;
	return false;
}

T
Tom Lane 已提交
1369 1370 1371
/*
 * Write and/or fsync the log at least as far as WriteRqst indicates.
 *
1372 1373 1374 1375 1376
 * 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.
 *
1377 1378 1379 1380 1381 1382
 * 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.)
 *
1383
 * Must be called with WALWriteLock held.
T
Tom Lane 已提交
1384
 */
1385
static void
1386
XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1387
{
1388
	XLogCtlWrite *Write = &XLogCtl->Write;
T
Tom Lane 已提交
1389
	bool		ispartialpage;
1390
	bool		last_iteration;
1391
	bool		finishing_seg;
1392
	bool		use_existent;
1393 1394 1395 1396
	int			curridx;
	int			npages;
	int			startidx;
	uint32		startoffset;
1397

1398 1399 1400
	/* We should always be inside a critical section here */
	Assert(CritSectionCount > 0);

B
Bruce Momjian 已提交
1401
	/*
B
Bruce Momjian 已提交
1402
	 * Update local LogwrtResult (caller probably did this already, but...)
B
Bruce Momjian 已提交
1403
	 */
T
Tom Lane 已提交
1404 1405
	LogwrtResult = Write->LogwrtResult;

1406 1407 1408
	/*
	 * Since successive pages in the xlog cache are consecutively allocated,
	 * we can usually gather multiple pages together and issue just one
B
Bruce Momjian 已提交
1409 1410 1411 1412 1413
	 * 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.
1414 1415 1416 1417 1418 1419 1420 1421 1422
	 */
	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 已提交
1423 1424
	 * going to PANIC if any error occurs anyway; but someday it may come in
	 * useful.)
1425 1426
	 */
	curridx = Write->curridx;
B
 
Bruce Momjian 已提交
1427

T
Tom Lane 已提交
1428
	while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1429
	{
1430
		/*
B
Bruce Momjian 已提交
1431 1432 1433
		 * 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.
1434
		 */
1435
		if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1436
			elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1437
				 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1438 1439
				 XLogCtl->xlblocks[curridx].xlogid,
				 XLogCtl->xlblocks[curridx].xrecoff);
1440

T
Tom Lane 已提交
1441
		/* Advance LogwrtResult.Write to end of current buffer page */
1442
		LogwrtResult.Write = XLogCtl->xlblocks[curridx];
T
Tom Lane 已提交
1443 1444 1445
		ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);

		if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1446
		{
T
Tom Lane 已提交
1447
			/*
1448 1449
			 * Switch to new logfile segment.  We cannot have any pending
			 * pages here (since we dump what we have at segment end).
T
Tom Lane 已提交
1450
			 */
1451
			Assert(npages == 0);
T
Tom Lane 已提交
1452
			if (openLogFile >= 0)
1453
				XLogFileClose();
T
Tom Lane 已提交
1454 1455
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);

1456 1457 1458 1459
			/* create/use new log file */
			use_existent = true;
			openLogFile = XLogFileInit(openLogId, openLogSeg,
									   &use_existent, true);
T
Tom Lane 已提交
1460
			openLogOff = 0;
1461 1462
		}

1463
		/* Make sure we have the current logfile open */
T
Tom Lane 已提交
1464
		if (openLogFile < 0)
1465
		{
T
Tom Lane 已提交
1466
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1467
			openLogFile = XLogFileOpen(openLogId, openLogSeg);
T
Tom Lane 已提交
1468
			openLogOff = 0;
1469 1470
		}

1471 1472 1473 1474 1475
		/* Add current page to the set of pending pages-to-dump */
		if (npages == 0)
		{
			/* first of group */
			startidx = curridx;
1476
			startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1477 1478
		}
		npages++;
1479

T
Tom Lane 已提交
1480
		/*
B
Bruce Momjian 已提交
1481 1482 1483 1484
		 * 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 已提交
1485
		 */
1486 1487
		last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);

1488
		finishing_seg = !ispartialpage &&
1489
			(startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1490

1491
		if (last_iteration ||
1492 1493
			curridx == XLogCtl->XLogCacheBlck ||
			finishing_seg)
T
Tom Lane 已提交
1494
		{
1495 1496
			char	   *from;
			Size		nbytes;
1497

1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
			/* 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) */
1511 1512
			from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
			nbytes = npages * (Size) XLOG_BLCKSZ;
1513 1514 1515 1516 1517 1518 1519 1520 1521
			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 已提交
1522
								"at offset %u, length %lu: %m",
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
								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.
			 *
1539 1540 1541
			 * We also do this if this is the last page written for an xlog
			 * switch.
			 *
1542
			 * This is also the right place to notify the Archiver that the
B
Bruce Momjian 已提交
1543
			 * segment is ready to copy to archival storage, and to update the
1544 1545 1546
			 * timer for archive_timeout, and to signal for a checkpoint if
			 * too many logfile segments have been used since the last
			 * checkpoint.
1547
			 */
1548
			if (finishing_seg || (xlog_switch && last_iteration))
1549 1550
			{
				issue_xlog_fsync();
B
Bruce Momjian 已提交
1551
				LogwrtResult.Flush = LogwrtResult.Write;		/* end of page */
1552 1553 1554

				if (XLogArchivingActive())
					XLogArchiveNotifySeg(openLogId, openLogSeg);
1555 1556

				Write->lastSegSwitchTime = time(NULL);
1557 1558

				/*
1559
				 * Signal bgwriter to start a checkpoint if we've consumed too
1560
				 * much xlog since the last one.  For speed, we first check
B
Bruce Momjian 已提交
1561 1562 1563
				 * 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.
1564
				 */
1565 1566
				if (IsUnderPostmaster &&
					XLogCheckpointNeeded())
1567
				{
1568 1569
					(void) GetRedoRecPtr();
					if (XLogCheckpointNeeded())
1570
						RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1571
				}
1572
			}
T
Tom Lane 已提交
1573
		}
1574

T
Tom Lane 已提交
1575 1576 1577 1578 1579 1580
		if (ispartialpage)
		{
			/* Only asked to write a partial page */
			LogwrtResult.Write = WriteRqst.Write;
			break;
		}
1581 1582 1583 1584 1585
		curridx = NextBufIdx(curridx);

		/* If flexible, break out of loop as soon as we wrote something */
		if (flexible && npages == 0)
			break;
1586
	}
1587 1588 1589

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

T
Tom Lane 已提交
1591 1592 1593 1594 1595
	/*
	 * If asked to flush, do so
	 */
	if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
		XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1596
	{
T
Tom Lane 已提交
1597
		/*
B
Bruce Momjian 已提交
1598 1599 1600
		 * 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 已提交
1601
		 */
1602
		if (sync_method != SYNC_METHOD_OPEN)
T
Tom Lane 已提交
1603
		{
1604
			if (openLogFile >= 0 &&
B
Bruce Momjian 已提交
1605
				!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1606
				XLogFileClose();
1607 1608 1609
			if (openLogFile < 0)
			{
				XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1610
				openLogFile = XLogFileOpen(openLogId, openLogSeg);
1611 1612 1613
				openLogOff = 0;
			}
			issue_xlog_fsync();
T
Tom Lane 已提交
1614 1615
		}
		LogwrtResult.Flush = LogwrtResult.Write;
1616 1617
	}

T
Tom Lane 已提交
1618 1619 1620
	/*
	 * Update shared-memory status
	 *
B
Bruce Momjian 已提交
1621
	 * We make sure that the shared 'request' values do not fall behind the
B
Bruce Momjian 已提交
1622 1623
	 * 'result' values.  This is not absolutely essential, but it saves some
	 * code in a couple of places.
T
Tom Lane 已提交
1624
	 */
1625 1626 1627 1628
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

1629
		SpinLockAcquire(&xlogctl->info_lck);
1630 1631 1632 1633 1634
		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;
1635
		SpinLockRelease(&xlogctl->info_lck);
1636
	}
1637

T
Tom Lane 已提交
1638 1639 1640
	Write->LogwrtResult = LogwrtResult;
}

1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
/*
 * 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);
}

T
Tom Lane 已提交
1657 1658 1659
/*
 * Ensure that all XLOG data through the given position is flushed to disk.
 *
1660
 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
T
Tom Lane 已提交
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
 * already held, and we try to avoid acquiring it if possible.
 */
void
XLogFlush(XLogRecPtr record)
{
	XLogRecPtr	WriteRqstPtr;
	XLogwrtRqst WriteRqst;

	/* Disabled during REDO */
	if (InRedo)
		return;

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

1677
#ifdef WAL_DEBUG
1678
	if (XLOG_DEBUG)
1679
		elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1680 1681 1682
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1683
#endif
1684

T
Tom Lane 已提交
1685 1686 1687 1688
	START_CRIT_SECTION();

	/*
	 * Since fsync is usually a horribly expensive operation, we try to
B
Bruce Momjian 已提交
1689 1690 1691 1692
	 * 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 已提交
1693 1694 1695 1696 1697
	 */

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

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

1703
		SpinLockAcquire(&xlogctl->info_lck);
1704 1705 1706
		if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
			WriteRqstPtr = xlogctl->LogwrtRqst.Write;
		LogwrtResult = xlogctl->LogwrtResult;
1707
		SpinLockRelease(&xlogctl->info_lck);
1708
	}
1709 1710 1711

	/* done already? */
	if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
1712
	{
1713 1714 1715 1716
		/* now wait for the write lock */
		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
		LogwrtResult = XLogCtl->Write.LogwrtResult;
		if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
1717
		{
1718 1719 1720 1721 1722 1723
			/* 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 已提交
1724
				if (freespace < SizeOfXLogRecord)		/* buffer is full */
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
					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;
			}
1740
			XLogWrite(WriteRqst, false, false);
T
Tom Lane 已提交
1741
		}
1742
		LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
1743 1744 1745
	}

	END_CRIT_SECTION();
1746 1747 1748

	/*
	 * If we still haven't flushed to the request point then we have a
B
Bruce Momjian 已提交
1749 1750
	 * 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.
1751
	 *
1752 1753 1754 1755 1756 1757 1758 1759 1760
	 * 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
	 * unable to restart the database at all!  (This scenario has actually
	 * happened in the field several times with 7.1 releases. Note that we
	 * cannot get here while InRedo is true, but if the bad page is brought in
	 * and marked dirty during recovery then CreateCheckPoint will try to
	 * flush it at the end of recovery.)
1761
	 *
1762 1763 1764 1765
	 * The current approach is to ERROR under normal conditions, but only
	 * WARNING during recovery, so that the system can be brought up even if
	 * there's a corrupt LSN.  Note that for calls from xact.c, the ERROR will
	 * be promoted to PANIC since xact.c calls this routine inside a critical
B
Bruce Momjian 已提交
1766 1767
	 * 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.
1768 1769
	 */
	if (XLByteLT(LogwrtResult.Flush, record))
B
Bruce Momjian 已提交
1770
		elog(InRecovery ? WARNING : ERROR,
B
Bruce Momjian 已提交
1771
		"xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1772 1773
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1774 1775
}

1776 1777 1778 1779 1780 1781
/*
 * 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 已提交
1782
 * are not being used, we will flush complete blocks only.	We can guarantee
1783
 * that async commits reach disk after at most three cycles; normally only
B
Bruce Momjian 已提交
1784
 * one or two.	(We allow XLogWrite to write "flexibly", meaning it can stop
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
 * 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;

	/* 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;

1817
		SpinLockAcquire(&xlogctl->info_lck);
1818
		WriteRqstPtr = xlogctl->asyncCommitLSN;
1819
		SpinLockRelease(&xlogctl->info_lck);
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
		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();
}

1853 1854
/*
 * Flush any previous asynchronously-committed transactions' commit records.
1855 1856 1857 1858
 *
 * NOTE: it is unwise to assume that this provides any strong guarantees.
 * In particular, because of the inexact LSN bookkeeping used by clog.c,
 * we cannot assume that hint bits will be settable for these transactions.
1859 1860 1861 1862 1863
 */
void
XLogAsyncCommitFlush(void)
{
	XLogRecPtr	WriteRqstPtr;
B
Bruce Momjian 已提交
1864

1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

	SpinLockAcquire(&xlogctl->info_lck);
	WriteRqstPtr = xlogctl->asyncCommitLSN;
	SpinLockRelease(&xlogctl->info_lck);

	XLogFlush(WriteRqstPtr);
}

1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
/*
 * 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)
{
	/* 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 已提交
1905 1906 1907
/*
 * Create a new XLOG file segment, or open a pre-existing one.
 *
1908 1909 1910
 * log, seg: identify segment to be created/opened.
 *
 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
B
Bruce Momjian 已提交
1911
 * pre-existing file will be deleted).	On return, TRUE if a pre-existing
1912 1913
 * file was used.
 *
1914
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1915
 * place.  This should be TRUE except during bootstrap log creation.  The
1916
 * caller must *not* hold the lock at call.
1917
 *
T
Tom Lane 已提交
1918
 * Returns FD of opened file.
1919 1920 1921 1922 1923
 *
 * 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 已提交
1924
 */
1925
static int
1926 1927
XLogFileInit(uint32 log, uint32 seg,
			 bool *use_existent, bool use_lock)
1928
{
1929
	char		path[MAXPGPATH];
1930
	char		tmppath[MAXPGPATH];
1931
	char	   *zbuffer;
1932 1933 1934
	uint32		installed_log;
	uint32		installed_seg;
	int			max_advance;
1935
	int			fd;
1936
	int			nbytes;
1937

1938
	XLogFilePath(path, ThisTimeLineID, log, seg);
V
Vadim B. Mikheev 已提交
1939 1940

	/*
B
Bruce Momjian 已提交
1941
	 * Try to use existent file (checkpoint maker may have created it already)
V
Vadim B. Mikheev 已提交
1942
	 */
1943
	if (*use_existent)
V
Vadim B. Mikheev 已提交
1944
	{
1945 1946
		fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
						   S_IRUSR | S_IWUSR);
V
Vadim B. Mikheev 已提交
1947 1948 1949
		if (fd < 0)
		{
			if (errno != ENOENT)
1950
				ereport(ERROR,
1951
						(errcode_for_file_access(),
1952
						 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1953
								path, log, seg)));
V
Vadim B. Mikheev 已提交
1954 1955
		}
		else
1956
			return fd;
V
Vadim B. Mikheev 已提交
1957 1958
	}

1959
	/*
B
Bruce Momjian 已提交
1960 1961 1962 1963
	 * 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.
1964
	 */
1965 1966
	elog(DEBUG2, "creating and filling new WAL file");

1967
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1968 1969

	unlink(tmppath);
1970

1971
	/* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1972
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
T
Tom Lane 已提交
1973
					   S_IRUSR | S_IWUSR);
1974
	if (fd < 0)
1975
		ereport(ERROR,
1976
				(errcode_for_file_access(),
1977
				 errmsg("could not create file \"%s\": %m", tmppath)));
1978

1979
	/*
B
Bruce Momjian 已提交
1980 1981 1982 1983 1984 1985 1986
	 * 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.
1987 1988 1989 1990
	 *
	 * 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.
1991
	 */
1992 1993
	zbuffer = (char *) palloc0(XLOG_BLCKSZ);
	for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
1994
	{
1995
		errno = 0;
1996
		if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
T
Tom Lane 已提交
1997
		{
B
Bruce Momjian 已提交
1998
			int			save_errno = errno;
T
Tom Lane 已提交
1999

B
Bruce Momjian 已提交
2000
			/*
B
Bruce Momjian 已提交
2001
			 * If we fail to make the file, delete it to release disk space
B
Bruce Momjian 已提交
2002
			 */
2003
			unlink(tmppath);
2004 2005
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;
T
Tom Lane 已提交
2006

2007
			ereport(ERROR,
2008
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2009
					 errmsg("could not write to file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2010
		}
2011
	}
2012
	pfree(zbuffer);
2013

2014
	if (pg_fsync(fd) != 0)
2015
		ereport(ERROR,
2016
				(errcode_for_file_access(),
2017
				 errmsg("could not fsync file \"%s\": %m", tmppath)));
2018

2019
	if (close(fd))
2020
		ereport(ERROR,
2021 2022
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2023

2024
	/*
2025 2026
	 * Now move the segment into place with its final name.
	 *
2027
	 * If caller didn't want to use a pre-existing file, get rid of any
B
Bruce Momjian 已提交
2028 2029 2030
	 * 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.
2031
	 */
2032 2033 2034 2035 2036
	installed_log = log;
	installed_seg = seg;
	max_advance = XLOGfileslop;
	if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
								*use_existent, &max_advance,
2037 2038 2039 2040 2041 2042
								use_lock))
	{
		/* No need for any more future segments... */
		unlink(tmppath);
	}

2043 2044
	elog(DEBUG2, "done creating and filling new WAL file");

2045 2046 2047 2048 2049 2050 2051
	/* 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) */
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
2052
		ereport(ERROR,
2053
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2054 2055
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2056

2057
	return fd;
2058 2059
}

2060 2061 2062 2063 2064 2065 2066 2067 2068
/*
 * 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 已提交
2069
 * considerations.	But we should be just as tense as XLogFileInit to avoid
2070 2071 2072 2073 2074 2075 2076 2077
 * emplacing a bogus file.
 */
static void
XLogFileCopy(uint32 log, uint32 seg,
			 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
{
	char		path[MAXPGPATH];
	char		tmppath[MAXPGPATH];
2078
	char		buffer[XLOG_BLCKSZ];
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
	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)
2089
		ereport(ERROR,
2090 2091 2092 2093 2094 2095
				(errcode_for_file_access(),
				 errmsg("could not open file \"%s\": %m", path)));

	/*
	 * Copy into a temp file name.
	 */
2096
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2097 2098 2099 2100 2101 2102 2103

	unlink(tmppath);

	/* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
2104
		ereport(ERROR,
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
				(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)
2117
				ereport(ERROR,
2118 2119 2120
						(errcode_for_file_access(),
						 errmsg("could not read file \"%s\": %m", path)));
			else
2121
				ereport(ERROR,
B
Bruce Momjian 已提交
2122
						(errmsg("not enough data in file \"%s\"", path)));
2123 2124 2125 2126 2127 2128 2129
		}
		errno = 0;
		if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
		{
			int			save_errno = errno;

			/*
B
Bruce Momjian 已提交
2130
			 * If we fail to make the file, delete it to release disk space
2131 2132 2133 2134 2135
			 */
			unlink(tmppath);
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;

2136
			ereport(ERROR,
2137
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2138
					 errmsg("could not write to file \"%s\": %m", tmppath)));
2139 2140 2141 2142
		}
	}

	if (pg_fsync(fd) != 0)
2143
		ereport(ERROR,
2144 2145 2146 2147
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
2148
		ereport(ERROR,
2149 2150 2151 2152 2153 2154 2155 2156
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));

	close(srcfd);

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

2161 2162 2163 2164 2165 2166
/*
 * 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.
 *
2167 2168 2169
 * *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.
2170 2171 2172 2173 2174 2175 2176
 *
 * 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.
 *
2177 2178 2179 2180
 * *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.)
2181
 *
2182
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2183
 * place.  This should be TRUE except during bootstrap log creation.  The
2184
 * caller must *not* hold the lock at call.
2185 2186
 *
 * Returns TRUE if file installed, FALSE if not installed because of
2187 2188 2189
 * exceeding max_advance limit.  On Windows, we also return FALSE if we
 * can't rename the file into place because someone's got it open.
 * (Any other kind of failure causes ereport().)
2190 2191
 */
static bool
2192 2193
InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
2194 2195 2196
					   bool use_lock)
{
	char		path[MAXPGPATH];
2197
	struct stat stat_buf;
2198

2199
	XLogFilePath(path, ThisTimeLineID, *log, *seg);
2200 2201 2202 2203 2204

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

2207 2208 2209 2210 2211
	if (!find_free)
	{
		/* Force installation: get rid of any pre-existing segment file */
		unlink(path);
	}
2212 2213
	else
	{
2214
		/* Find a free slot to put it in */
2215
		while (stat(path, &stat_buf) == 0)
2216
		{
2217
			if (*max_advance <= 0)
2218 2219 2220
			{
				/* Failed to find a free slot within specified range */
				if (use_lock)
2221
					LWLockRelease(ControlFileLock);
2222 2223
				return false;
			}
2224 2225 2226
			NextLogSeg(*log, *seg);
			(*max_advance)--;
			XLogFilePath(path, ThisTimeLineID, *log, *seg);
2227 2228 2229 2230 2231 2232 2233
		}
	}

	/*
	 * 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.
2234
	 */
2235
#if HAVE_WORKING_LINK
2236
	if (link(tmppath, path) < 0)
2237
		ereport(ERROR,
2238
				(errcode_for_file_access(),
2239
				 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2240
						tmppath, path, *log, *seg)));
2241
	unlink(tmppath);
2242
#else
2243
	if (rename(tmppath, path) < 0)
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
	{
#ifdef WIN32
#if !defined(__CYGWIN__)
		if (GetLastError() == ERROR_ACCESS_DENIED)
#else
		if (errno == EACCES)
#endif
		{
			if (use_lock)
				LWLockRelease(ControlFileLock);
			return false;
		}
B
Bruce Momjian 已提交
2256
#endif   /* WIN32 */
2257

2258
		ereport(ERROR,
2259
				(errcode_for_file_access(),
2260
				 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2261
						tmppath, path, *log, *seg)));
2262
	}
2263
#endif
V
Vadim B. Mikheev 已提交
2264

2265
	if (use_lock)
2266
		LWLockRelease(ControlFileLock);
2267

2268
	return true;
2269 2270
}

T
Tom Lane 已提交
2271
/*
2272
 * Open a pre-existing logfile segment for writing.
T
Tom Lane 已提交
2273
 */
2274
static int
2275
XLogFileOpen(uint32 log, uint32 seg)
2276
{
2277 2278
	char		path[MAXPGPATH];
	int			fd;
2279

2280
	XLogFilePath(path, ThisTimeLineID, log, seg);
2281

2282 2283
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
					   S_IRUSR | S_IWUSR);
2284
	if (fd < 0)
2285 2286
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2287 2288
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300

	return fd;
}

/*
 * Open a logfile segment for reading (during recovery).
 */
static int
XLogFileRead(uint32 log, uint32 seg, int emode)
{
	char		path[MAXPGPATH];
	char		xlogfname[MAXFNAMELEN];
2301
	char		activitymsg[MAXFNAMELEN + 16];
2302 2303
	ListCell   *cell;
	int			fd;
2304

2305
	/*
B
Bruce Momjian 已提交
2306 2307
	 * Loop looking for a suitable timeline ID: we might need to read any of
	 * the timelines listed in expectedTLIs.
2308
	 *
B
Bruce Momjian 已提交
2309
	 * We expect curFileTLI on entry to be the TLI of the preceding file in
B
Bruce Momjian 已提交
2310 2311 2312 2313
	 * 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.
2314
	 */
2315 2316 2317
	foreach(cell, expectedTLIs)
	{
		TimeLineID	tli = (TimeLineID) lfirst_int(cell);
2318

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

2322 2323
		XLogFileName(xlogfname, tli, log, seg);

2324 2325
		if (InArchiveRecovery)
		{
2326 2327 2328 2329 2330
			/* Report recovery progress in PS display */
			snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
					 xlogfname);
			set_ps_display(activitymsg, false);

2331
			restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2332 2333
													  "RECOVERYXLOG",
													  XLogSegSize);
2334 2335 2336 2337 2338 2339 2340 2341 2342
		}
		else
			XLogFilePath(path, tli, log, seg);

		fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
		if (fd >= 0)
		{
			/* Success! */
			curFileTLI = tli;
2343 2344

			/* Report recovery progress in PS display */
2345 2346
			snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
					 xlogfname);
2347 2348
			set_ps_display(activitymsg, false);

2349 2350 2351 2352 2353
			return fd;
		}
		if (errno != ENOENT)	/* unexpected failure? */
			ereport(PANIC,
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2354 2355
			errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				   path, log, seg)));
2356 2357 2358 2359 2360 2361 2362
	}

	/* 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 已提交
2363 2364
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2365
	return -1;
2366 2367
}

2368 2369 2370 2371 2372 2373 2374 2375
/*
 * Close the current logfile segment for writing.
 */
static void
XLogFileClose(void)
{
	Assert(openLogFile >= 0);

2376
	/*
B
Bruce Momjian 已提交
2377 2378 2379 2380 2381 2382
	 * posix_fadvise is problematic on many platforms: on older x86 Linux it
	 * just dumps core, and there are reports of problems on PPC platforms as
	 * well.  The following is therefore disabled for the time being. We could
	 * consider some kind of configure test to see if it's safe to use, but
	 * since we lack hard evidence that there's any useful performance gain to
	 * be had, spending time on that seems unprofitable for now.
2383 2384 2385
	 */
#ifdef NOT_USED

2386
	/*
2387
	 * WAL segment files will not be re-read in normal operation, so we advise
B
Bruce Momjian 已提交
2388
	 * OS to release any cached pages.	But do not do so if WAL archiving is
2389 2390 2391
	 * active, because archiver process could use the cache to read the WAL
	 * segment.
	 *
B
Bruce Momjian 已提交
2392 2393
	 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
	 * O_SYNC, and some platforms only have posix_fadvise().
2394
	 */
2395
#if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2396 2397 2398
	if (!XLogArchivingActive())
		posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
#endif
B
Bruce Momjian 已提交
2399
#endif   /* NOT_USED */
2400

2401 2402
	if (close(openLogFile))
		ereport(PANIC,
B
Bruce Momjian 已提交
2403 2404 2405
				(errcode_for_file_access(),
				 errmsg("could not close log file %u, segment %u: %m",
						openLogId, openLogSeg)));
2406 2407 2408
	openLogFile = -1;
}

2409
/*
2410
 * Attempt to retrieve the specified file from off-line archival storage.
2411
 * If successful, fill "path" with its complete path (note that this will be
2412 2413
 * a temp file name that doesn't follow the normal naming convention), and
 * return TRUE.
2414
 *
2415 2416 2417
 * 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.
2418 2419 2420 2421
 *
 * 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.
2422
 */
2423 2424
static bool
RestoreArchivedFile(char *path, const char *xlogfname,
2425
					const char *recovername, off_t expectedSize)
2426
{
B
Bruce Momjian 已提交
2427 2428
	char		xlogpath[MAXPGPATH];
	char		xlogRestoreCmd[MAXPGPATH];
2429
	char		lastRestartPointFname[MAXPGPATH];
B
Bruce Momjian 已提交
2430 2431
	char	   *dp;
	char	   *endp;
2432
	const char *sp;
B
Bruce Momjian 已提交
2433
	int			rc;
2434
	bool		signaled;
2435
	struct stat stat_buf;
B
Bruce Momjian 已提交
2436 2437
	uint32		restartLog;
	uint32		restartSeg;
2438 2439

	/*
B
Bruce Momjian 已提交
2440 2441 2442 2443
	 * 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.
2444
	 *
B
Bruce Momjian 已提交
2445
	 * We could try to optimize this slightly by checking the local copy
B
Bruce Momjian 已提交
2446 2447 2448 2449
	 * 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.
2450
	 *
2451 2452 2453
	 * 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.
2454
	 *
2455 2456 2457 2458
	 * 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 已提交
2459 2460
	 * copy-from-archive filename is always the same, ensuring that we don't
	 * run out of disk space on long recoveries.
2461
	 */
2462
	snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2463 2464

	/*
2465
	 * Make sure there is no existing file named recovername.
2466 2467 2468 2469 2470 2471
	 */
	if (stat(xlogpath, &stat_buf) != 0)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
2472
					 errmsg("could not stat file \"%s\": %m",
2473 2474 2475 2476 2477 2478 2479
							xlogpath)));
	}
	else
	{
		if (unlink(xlogpath) != 0)
			ereport(FATAL,
					(errcode_for_file_access(),
2480
					 errmsg("could not remove file \"%s\": %m",
2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
							xlogpath)));
	}

	/*
	 * 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':
2498
					/* %p: relative path of target file */
2499
					sp++;
B
Bruce Momjian 已提交
2500
					StrNCpy(dp, xlogpath, endp - dp);
2501
					make_native_path(dp);
2502 2503 2504 2505 2506
					dp += strlen(dp);
					break;
				case 'f':
					/* %f: filename of desired file */
					sp++;
B
Bruce Momjian 已提交
2507
					StrNCpy(dp, xlogfname, endp - dp);
2508 2509
					dp += strlen(dp);
					break;
2510 2511 2512 2513 2514
				case 'r':
					/* %r: filename of last restartpoint */
					sp++;
					XLByteToSeg(ControlFile->checkPointCopy.redo,
								restartLog, restartSeg);
B
Bruce Momjian 已提交
2515 2516
					XLogFileName(lastRestartPointFname,
								 ControlFile->checkPointCopy.ThisTimeLineID,
2517 2518 2519 2520
								 restartLog, restartSeg);
					StrNCpy(dp, lastRestartPointFname, endp - dp);
					dp += strlen(dp);
					break;
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542
				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 已提交
2543
			(errmsg_internal("executing restore command \"%s\"",
2544 2545 2546
							 xlogRestoreCmd)));

	/*
2547
	 * Copy xlog from archival storage to XLOGDIR
2548 2549 2550 2551
	 */
	rc = system(xlogRestoreCmd);
	if (rc == 0)
	{
2552 2553 2554 2555
		/*
		 * command apparently succeeded, but let's make sure the file is
		 * really there now and has the correct size.
		 *
2556 2557 2558 2559 2560
		 * XXX I made wrong-size a fatal error to ensure the DBA would notice
		 * it, but is that too strong?	We could try to plow ahead with a
		 * local copy of the file ... but the problem is that there probably
		 * isn't one, and we'd incorrectly conclude we've reached the end of
		 * WAL and we're done recovering ...
2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
		 */
		if (stat(xlogpath, &stat_buf) == 0)
		{
			if (expectedSize > 0 && stat_buf.st_size != expectedSize)
				ereport(FATAL,
						(errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
								xlogfname,
								(unsigned long) stat_buf.st_size,
								(unsigned long) expectedSize)));
			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 已提交
2585
						 errmsg("could not stat file \"%s\": %m",
2586
								xlogpath)));
2587 2588 2589 2590
		}
	}

	/*
2591
	 * Remember, we rollforward UNTIL the restore fails so failure here is
B
Bruce Momjian 已提交
2592
	 * just part of the process... that makes it difficult to determine
B
Bruce Momjian 已提交
2593 2594 2595
	 * 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.
2596 2597
	 *
	 * However, if the failure was due to any sort of signal, it's best to
B
Bruce Momjian 已提交
2598 2599 2600
	 * 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
2601 2602 2603 2604
	 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
	 * those it's a good bet we should have gotten it too.  Aborting on other
	 * signals such as SIGTERM seems a good idea as well.
	 *
B
Bruce Momjian 已提交
2605 2606 2607 2608
	 * 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.
2609
	 */
2610 2611 2612
	signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;

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

	/*
B
Bruce Momjian 已提交
2617 2618
	 * 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.
2619
	 *
B
Bruce Momjian 已提交
2620 2621
	 * In many recovery scenarios we expect this to fail also, but if so that
	 * just means we've reached the end of WAL.
2622
	 */
2623
	snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2624
	return false;
2625 2626
}

V
Vadim B. Mikheev 已提交
2627
/*
2628 2629 2630 2631 2632 2633 2634 2635
 * 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 已提交
2636
 */
2637
static void
T
Tom Lane 已提交
2638 2639 2640 2641 2642
PreallocXlogFiles(XLogRecPtr endptr)
{
	uint32		_logId;
	uint32		_logSeg;
	int			lf;
2643
	bool		use_existent;
T
Tom Lane 已提交
2644 2645

	XLByteToPrevSeg(endptr, _logId, _logSeg);
B
Bruce Momjian 已提交
2646
	if ((endptr.xrecoff - 1) % XLogSegSize >=
B
Bruce Momjian 已提交
2647
		(uint32) (0.75 * XLogSegSize))
T
Tom Lane 已提交
2648 2649
	{
		NextLogSeg(_logId, _logSeg);
2650 2651
		use_existent = true;
		lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
T
Tom Lane 已提交
2652
		close(lf);
2653
		if (!use_existent)
2654
			CheckpointStats.ckpt_segs_added++;
T
Tom Lane 已提交
2655 2656 2657 2658
	}
}

/*
2659
 * Recycle or remove all log files older or equal to passed log/seg#
2660 2661 2662
 *
 * 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 已提交
2663 2664
 */
static void
2665
RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
V
Vadim B. Mikheev 已提交
2666
{
2667 2668
	uint32		endlogId;
	uint32		endlogSeg;
2669
	int			max_advance;
B
Bruce Momjian 已提交
2670 2671
	DIR		   *xldir;
	struct dirent *xlde;
2672
	char		lastoff[MAXFNAMELEN];
B
Bruce Momjian 已提交
2673
	char		path[MAXPGPATH];
V
Vadim B. Mikheev 已提交
2674

2675 2676 2677 2678
	/*
	 * Initialize info about where to try to recycle to.  We allow recycling
	 * segments up to XLOGfileslop segments beyond the current XLOG location.
	 */
2679
	XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2680
	max_advance = XLOGfileslop;
V
Vadim B. Mikheev 已提交
2681

2682
	xldir = AllocateDir(XLOGDIR);
V
Vadim B. Mikheev 已提交
2683
	if (xldir == NULL)
2684
		ereport(ERROR,
2685
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2686 2687
				 errmsg("could not open transaction log directory \"%s\": %m",
						XLOGDIR)));
V
Vadim B. Mikheev 已提交
2688

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

2691
	while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
V
Vadim B. Mikheev 已提交
2692
	{
2693
		/*
2694
		 * We ignore the timeline part of the XLOG segment identifiers in
B
Bruce Momjian 已提交
2695 2696 2697 2698 2699
		 * 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.
2700
		 *
B
Bruce Momjian 已提交
2701 2702
		 * We use the alphanumeric sorting property of the filenames to decide
		 * which ones are earlier than the lastoff segment.
2703
		 */
2704 2705 2706
		if (strlen(xlde->d_name) == 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
V
Vadim B. Mikheev 已提交
2707
		{
2708
			if (XLogArchiveCheckDone(xlde->d_name))
2709
			{
2710
				snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2711

2712
				/*
B
Bruce Momjian 已提交
2713 2714
				 * Before deleting the file, see if it can be recycled as a
				 * future log segment.
2715
				 */
2716 2717
				if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
										   true, &max_advance,
2718 2719
										   true))
				{
2720
					ereport(DEBUG2,
B
Bruce Momjian 已提交
2721 2722
							(errmsg("recycled transaction log file \"%s\"",
									xlde->d_name)));
2723
					CheckpointStats.ckpt_segs_recycled++;
2724 2725 2726 2727 2728 2729
					/* Needn't recheck that slot on future iterations */
					if (max_advance > 0)
					{
						NextLogSeg(endlogId, endlogSeg);
						max_advance--;
					}
2730 2731 2732 2733
				}
				else
				{
					/* No need for any more future segments... */
2734
					ereport(DEBUG2,
B
Bruce Momjian 已提交
2735 2736
							(errmsg("removing transaction log file \"%s\"",
									xlde->d_name)));
2737
					unlink(path);
2738
					CheckpointStats.ckpt_segs_removed++;
2739
				}
2740 2741

				XLogArchiveCleanup(xlde->d_name);
2742
			}
V
Vadim B. Mikheev 已提交
2743 2744
		}
	}
B
Bruce Momjian 已提交
2745

2746
	FreeDir(xldir);
V
Vadim B. Mikheev 已提交
2747 2748
}

2749
/*
2750 2751 2752
 * Remove previous backup history files.  This also retries creation of
 * .ready files for any backup history files for which XLogArchiveNotify
 * failed earlier.
2753 2754
 */
static void
2755
CleanupBackupHistory(void)
2756 2757 2758 2759 2760
{
	DIR		   *xldir;
	struct dirent *xlde;
	char		path[MAXPGPATH];

2761
	xldir = AllocateDir(XLOGDIR);
2762 2763 2764
	if (xldir == NULL)
		ereport(ERROR,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2765 2766
				 errmsg("could not open transaction log directory \"%s\": %m",
						XLOGDIR)));
2767

2768
	while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2769 2770 2771 2772 2773 2774
	{
		if (strlen(xlde->d_name) > 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
				   ".backup") == 0)
		{
2775
			if (XLogArchiveCheckDone(xlde->d_name))
2776 2777
			{
				ereport(DEBUG2,
B
Bruce Momjian 已提交
2778 2779
				(errmsg("removing transaction log backup history file \"%s\"",
						xlde->d_name)));
2780
				snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2781 2782 2783 2784 2785 2786 2787 2788 2789
				unlink(path);
				XLogArchiveCleanup(xlde->d_name);
			}
		}
	}

	FreeDir(xldir);
}

T
Tom Lane 已提交
2790 2791 2792 2793
/*
 * Restore the backup blocks present in an XLOG record, if any.
 *
 * We assume all of the record has been read into memory at *record.
2794 2795 2796 2797 2798 2799 2800 2801 2802
 *
 * 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.
T
Tom Lane 已提交
2803
 */
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
static void
RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
{
	Relation	reln;
	Buffer		buffer;
	Page		page;
	BkpBlock	bkpb;
	char	   *blk;
	int			i;

B
Bruce Momjian 已提交
2814
	blk = (char *) XLogRecGetData(record) + record->xl_len;
T
Tom Lane 已提交
2815
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2816
	{
T
Tom Lane 已提交
2817
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2818 2819
			continue;

2820
		memcpy(&bkpb, blk, sizeof(BkpBlock));
2821 2822
		blk += sizeof(BkpBlock);

2823
		reln = XLogOpenRelation(bkpb.node);
2824 2825 2826
		buffer = XLogReadBuffer(reln, bkpb.block, true);
		Assert(BufferIsValid(buffer));
		page = (Page) BufferGetPage(buffer);
2827

2828
		if (bkpb.hole_length == 0)
2829
		{
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
			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));
2840 2841
		}

2842 2843
		PageSetLSN(page, lsn);
		PageSetTLI(page, ThisTimeLineID);
2844 2845
		MarkBufferDirty(buffer);
		UnlockReleaseBuffer(buffer);
2846

2847
		blk += BLCKSZ - bkpb.hole_length;
2848 2849 2850
	}
}

T
Tom Lane 已提交
2851 2852 2853 2854 2855 2856 2857
/*
 * 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.
 */
2858 2859 2860
static bool
RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
{
2861
	pg_crc32	crc;
2862 2863
	int			i;
	uint32		len = record->xl_len;
2864
	BkpBlock	bkpb;
2865 2866
	char	   *blk;

2867 2868 2869
	/* First the rmgr data */
	INIT_CRC32(crc);
	COMP_CRC32(crc, XLogRecGetData(record), len);
2870

2871
	/* Add in the backup blocks, if any */
B
Bruce Momjian 已提交
2872
	blk = (char *) XLogRecGetData(record) + len;
T
Tom Lane 已提交
2873
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2874
	{
B
Bruce Momjian 已提交
2875
		uint32		blen;
2876

T
Tom Lane 已提交
2877
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2878 2879
			continue;

2880 2881
		memcpy(&bkpb, blk, sizeof(BkpBlock));
		if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2882
		{
2883
			ereport(emode,
2884 2885 2886
					(errmsg("incorrect hole size in record at %X/%X",
							recptr.xlogid, recptr.xrecoff)));
			return false;
2887
		}
2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
		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 已提交
2910 2911
		(errmsg("incorrect resource manager data checksum in record at %X/%X",
				recptr.xlogid, recptr.xrecoff)));
2912
		return false;
2913 2914
	}

2915
	return true;
2916 2917
}

T
Tom Lane 已提交
2918 2919 2920 2921 2922 2923
/*
 * 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.
 *
2924 2925
 * If no valid record is available, returns NULL, or fails if emode is PANIC.
 * (emode must be either PANIC or LOG.)
T
Tom Lane 已提交
2926
 *
2927 2928
 * The record is copied into readRecordBuf, so that on successful return,
 * the returned record pointer always points there.
T
Tom Lane 已提交
2929
 */
2930
static XLogRecord *
2931
ReadRecord(XLogRecPtr *RecPtr, int emode)
2932
{
2933
	XLogRecord *record;
2934
	char	   *buffer;
2935
	XLogRecPtr	tmpRecPtr = EndRecPtr;
2936
	bool		randAccess = false;
T
Tom Lane 已提交
2937 2938 2939
	uint32		len,
				total_len;
	uint32		targetPageOff;
2940 2941
	uint32		targetRecOff;
	uint32		pageHeaderSize;
T
Tom Lane 已提交
2942 2943 2944 2945

	if (readBuf == NULL)
	{
		/*
B
Bruce Momjian 已提交
2946 2947 2948 2949 2950
		 * 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 已提交
2951
		 */
2952
		readBuf = (char *) malloc(XLOG_BLCKSZ);
T
Tom Lane 已提交
2953 2954
		Assert(readBuf != NULL);
	}
2955

T
Tom Lane 已提交
2956
	if (RecPtr == NULL)
2957
	{
2958
		RecPtr = &tmpRecPtr;
T
Tom Lane 已提交
2959
		/* fast case if next record is on same page */
2960 2961 2962 2963 2964
		if (nextRecord != NULL)
		{
			record = nextRecord;
			goto got_record;
		}
T
Tom Lane 已提交
2965
		/* align old recptr to next page */
2966 2967
		if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
			tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2968 2969 2970 2971 2972
		if (tmpRecPtr.xrecoff >= XLogFileSize)
		{
			(tmpRecPtr.xlogid)++;
			tmpRecPtr.xrecoff = 0;
		}
2973 2974 2975 2976 2977 2978 2979 2980
		/* We will account for page header size below */
	}
	else
	{
		if (!XRecOffIsValid(RecPtr->xrecoff))
			ereport(PANIC,
					(errmsg("invalid record offset at %X/%X",
							RecPtr->xlogid, RecPtr->xrecoff)));
B
Bruce Momjian 已提交
2981

2982
		/*
B
Bruce Momjian 已提交
2983 2984 2985 2986 2987
		 * 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).
2988 2989 2990
		 */
		lastPageTLI = 0;		/* see comment in ValidXLOGHeader */
		randAccess = true;		/* allow curFileTLI to go backwards too */
2991 2992
	}

T
Tom Lane 已提交
2993
	if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2994
	{
2995 2996
		close(readFile);
		readFile = -1;
2997
	}
T
Tom Lane 已提交
2998
	XLByteToSeg(*RecPtr, readId, readSeg);
2999
	if (readFile < 0)
3000
	{
3001 3002 3003 3004 3005
		/* Now it's okay to reset curFileTLI if random fetch */
		if (randAccess)
			curFileTLI = 0;

		readFile = XLogFileRead(readId, readSeg, emode);
3006 3007
		if (readFile < 0)
			goto next_record_is_invalid;
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026

		/*
		 * 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)
		{
			ereport(emode,
					(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;
		}
		if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
			goto next_record_is_invalid;
3027 3028
	}

3029
	targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
T
Tom Lane 已提交
3030
	if (readOff != targetPageOff)
3031
	{
T
Tom Lane 已提交
3032 3033 3034
		readOff = targetPageOff;
		if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
		{
3035 3036
			ereport(emode,
					(errcode_for_file_access(),
3037
					 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
3038
							readId, readSeg, readOff)));
T
Tom Lane 已提交
3039 3040
			goto next_record_is_invalid;
		}
3041
		if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
T
Tom Lane 已提交
3042
		{
3043 3044
			ereport(emode,
					(errcode_for_file_access(),
3045
					 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3046
							readId, readSeg, readOff)));
T
Tom Lane 已提交
3047 3048
			goto next_record_is_invalid;
		}
3049
		if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3050 3051
			goto next_record_is_invalid;
	}
3052
	pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3053
	targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
3054 3055 3056
	if (targetRecOff == 0)
	{
		/*
B
Bruce Momjian 已提交
3057 3058 3059
		 * 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.
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
		 */
		tmpRecPtr.xrecoff += pageHeaderSize;
		targetRecOff = pageHeaderSize;
	}
	else if (targetRecOff < pageHeaderSize)
	{
		ereport(emode,
				(errmsg("invalid record offset at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
		goto next_record_is_invalid;
	}
T
Tom Lane 已提交
3071
	if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3072
		targetRecOff == pageHeaderSize)
3073
	{
3074 3075 3076
		ereport(emode,
				(errmsg("contrecord is requested by %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
3077 3078
		goto next_record_is_invalid;
	}
3079
	record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3080 3081

got_record:;
B
Bruce Momjian 已提交
3082

T
Tom Lane 已提交
3083
	/*
B
Bruce Momjian 已提交
3084 3085
	 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
	 * required.
T
Tom Lane 已提交
3086
	 */
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
	if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
	{
		if (record->xl_len != 0)
		{
			ereport(emode,
					(errmsg("invalid xlog switch record at %X/%X",
							RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
	}
	else if (record->xl_len == 0)
3098
	{
3099 3100 3101
		ereport(emode,
				(errmsg("record with zero length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
3102 3103
		goto next_record_is_invalid;
	}
3104 3105 3106 3107 3108 3109 3110 3111 3112
	if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
		record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
		XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
	{
		ereport(emode,
				(errmsg("invalid record length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
		goto next_record_is_invalid;
	}
3113 3114 3115 3116
	if (record->xl_rmid > RM_MAX_ID)
	{
		ereport(emode,
				(errmsg("invalid resource manager ID %u at %X/%X",
B
Bruce Momjian 已提交
3117
						record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3118 3119
		goto next_record_is_invalid;
	}
3120 3121 3122
	if (randAccess)
	{
		/*
B
Bruce Momjian 已提交
3123 3124
		 * We can't exactly verify the prev-link, but surely it should be less
		 * than the record's own address.
3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
		 */
		if (!XLByteLT(record->xl_prev, *RecPtr))
		{
			ereport(emode,
					(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 已提交
3138 3139 3140
		 * 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.
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150
		 */
		if (!XLByteEQ(record->xl_prev, ReadRecPtr))
		{
			ereport(emode,
					(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 已提交
3151

T
Tom Lane 已提交
3152
	/*
B
Bruce Momjian 已提交
3153
	 * Allocate or enlarge readRecordBuf as needed.  To avoid useless small
3154 3155 3156 3157
	 * 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 已提交
3158
	 */
3159
	total_len = record->xl_tot_len;
3160
	if (total_len > readRecordBufSize)
3161
	{
3162 3163
		uint32		newSize = total_len;

3164 3165
		newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
		newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
		if (readRecordBuf)
			free(readRecordBuf);
		readRecordBuf = (char *) malloc(newSize);
		if (!readRecordBuf)
		{
			readRecordBufSize = 0;
			/* We treat this as a "bogus data" condition */
			ereport(emode,
					(errmsg("record length %u at %X/%X too long",
							total_len, RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
		readRecordBufSize = newSize;
3179
	}
3180 3181

	buffer = readRecordBuf;
3182
	nextRecord = NULL;
3183
	len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
T
Tom Lane 已提交
3184
	if (total_len > len)
3185
	{
T
Tom Lane 已提交
3186 3187
		/* Need to reassemble record */
		XLogContRecord *contrecord;
B
Bruce Momjian 已提交
3188
		uint32		gotlen = len;
3189

T
Tom Lane 已提交
3190
		memcpy(buffer, record, len);
3191
		record = (XLogRecord *) buffer;
T
Tom Lane 已提交
3192
		buffer += len;
3193
		for (;;)
3194
		{
3195
			readOff += XLOG_BLCKSZ;
T
Tom Lane 已提交
3196
			if (readOff >= XLogSegSize)
3197 3198
			{
				close(readFile);
T
Tom Lane 已提交
3199 3200
				readFile = -1;
				NextLogSeg(readId, readSeg);
3201
				readFile = XLogFileRead(readId, readSeg, emode);
3202 3203
				if (readFile < 0)
					goto next_record_is_invalid;
T
Tom Lane 已提交
3204
				readOff = 0;
3205
			}
3206
			if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
T
Tom Lane 已提交
3207
			{
3208 3209
				ereport(emode,
						(errcode_for_file_access(),
T
Tom Lane 已提交
3210
						 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3211
								readId, readSeg, readOff)));
T
Tom Lane 已提交
3212 3213
				goto next_record_is_invalid;
			}
3214
			if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3215
				goto next_record_is_invalid;
T
Tom Lane 已提交
3216
			if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3217
			{
3218 3219 3220
				ereport(emode,
						(errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
								readId, readSeg, readOff)));
3221 3222
				goto next_record_is_invalid;
			}
3223 3224
			pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
			contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
B
Bruce Momjian 已提交
3225
			if (contrecord->xl_rem_len == 0 ||
T
Tom Lane 已提交
3226
				total_len != (contrecord->xl_rem_len + gotlen))
3227
			{
3228 3229 3230 3231
				ereport(emode,
						(errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
								contrecord->xl_rem_len,
								readId, readSeg, readOff)));
3232 3233
				goto next_record_is_invalid;
			}
3234
			len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
T
Tom Lane 已提交
3235
			if (contrecord->xl_rem_len > len)
3236
			{
B
Bruce Momjian 已提交
3237
				memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
T
Tom Lane 已提交
3238 3239 3240 3241 3242 3243 3244 3245 3246 3247
				gotlen += len;
				buffer += len;
				continue;
			}
			memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
				   contrecord->xl_rem_len);
			break;
		}
		if (!RecordIsValid(record, *RecPtr, emode))
			goto next_record_is_invalid;
3248
		pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3249
		if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3250
			MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
T
Tom Lane 已提交
3251
		{
B
Bruce Momjian 已提交
3252
			nextRecord = (XLogRecord *) ((char *) contrecord +
B
Bruce Momjian 已提交
3253
					MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
T
Tom Lane 已提交
3254 3255 3256
		}
		EndRecPtr.xlogid = readId;
		EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3257 3258
			pageHeaderSize +
			MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
T
Tom Lane 已提交
3259
		ReadRecPtr = *RecPtr;
3260
		/* needn't worry about XLOG SWITCH, it can't cross page boundaries */
T
Tom Lane 已提交
3261
		return record;
3262 3263
	}

T
Tom Lane 已提交
3264 3265 3266
	/* Record does not cross a page boundary */
	if (!RecordIsValid(record, *RecPtr, emode))
		goto next_record_is_invalid;
3267
	if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
T
Tom Lane 已提交
3268 3269 3270 3271 3272 3273
		MAXALIGN(total_len))
		nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
	EndRecPtr.xlogid = RecPtr->xlogid;
	EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
	ReadRecPtr = *RecPtr;
	memcpy(buffer, record, total_len);
B
Bruce Momjian 已提交
3274

3275 3276 3277 3278 3279 3280 3281 3282 3283
	/*
	 * 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;
		nextRecord = NULL;		/* definitely not on same page */
B
Bruce Momjian 已提交
3284

3285
		/*
B
Bruce Momjian 已提交
3286 3287 3288
		 * 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.
3289 3290 3291
		 */
		readOff = XLogSegSize - XLOG_BLCKSZ;
	}
T
Tom Lane 已提交
3292
	return (XLogRecord *) buffer;
3293

T
Tom Lane 已提交
3294 3295 3296 3297 3298
next_record_is_invalid:;
	close(readFile);
	readFile = -1;
	nextRecord = NULL;
	return NULL;
3299 3300
}

3301 3302 3303 3304
/*
 * 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 已提交
3305
 * ReadRecord.	It's not intended for use from anywhere else.
3306 3307
 */
static bool
3308
ValidXLOGHeader(XLogPageHeader hdr, int emode)
3309
{
3310 3311
	XLogRecPtr	recaddr;

3312 3313
	if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
	{
3314 3315 3316
		ereport(emode,
				(errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
						hdr->xlp_magic, readId, readSeg, readOff)));
3317 3318 3319 3320
		return false;
	}
	if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
	{
3321 3322 3323
		ereport(emode,
				(errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
						hdr->xlp_info, readId, readSeg, readOff)));
3324 3325
		return false;
	}
3326
	if (hdr->xlp_info & XLP_LONG_HEADER)
3327
	{
3328
		XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
B
Bruce Momjian 已提交
3329

3330
		if (longhdr->xlp_sysid != ControlFile->system_identifier)
3331
		{
3332 3333
			char		fhdrident_str[32];
			char		sysident_str[32];
3334

3335
			/*
B
Bruce Momjian 已提交
3336 3337
			 * Format sysids separately to keep platform-dependent format code
			 * out of the translatable message string.
3338 3339 3340 3341 3342 3343 3344
			 */
			snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
					 longhdr->xlp_sysid);
			snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
					 ControlFile->system_identifier);
			ereport(emode,
					(errmsg("WAL file is from different system"),
B
Bruce Momjian 已提交
3345 3346
					 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
							   fhdrident_str, sysident_str)));
3347 3348 3349 3350 3351 3352
			return false;
		}
		if (longhdr->xlp_seg_size != XLogSegSize)
		{
			ereport(emode,
					(errmsg("WAL file is from different system"),
B
Bruce Momjian 已提交
3353
					 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3354 3355
			return false;
		}
3356 3357 3358 3359 3360 3361 3362
		if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
		{
			ereport(emode,
					(errmsg("WAL file is from different system"),
					 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
			return false;
		}
3363
	}
3364 3365 3366 3367 3368 3369 3370 3371 3372
	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;
	}

3373 3374 3375 3376 3377 3378
	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 已提交
3379
						hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400
						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 已提交
3401 3402 3403
	 * 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.
3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420
	 */
	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 已提交
3421
 * its ancestor TLIs).	If we can't find the history file, assume that the
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
 * 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 已提交
3432
	FILE	   *fd;
3433 3434 3435 3436

	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, targetTLI);
3437
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3438 3439 3440 3441
	}
	else
		TLHistoryFilePath(path, targetTLI);

B
Bruce Momjian 已提交
3442
	fd = AllocateFile(path, "r");
3443 3444 3445 3446 3447
	if (fd == NULL)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
3448
					 errmsg("could not open file \"%s\": %m", path)));
3449 3450 3451 3452 3453 3454
		/* Not there, so assume no parents */
		return list_make1_int((int) targetTLI);
	}

	result = NIL;

B
Bruce Momjian 已提交
3455 3456 3457
	/*
	 * Parse the file...
	 */
3458
	while (fgets(fline, sizeof(fline), fd) != NULL)
3459 3460
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
3461 3462 3463
		char	   *ptr;
		char	   *endptr;
		TimeLineID	tli;
3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483

		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 已提交
3484
				   errhint("Timeline IDs must be in increasing sequence.")));
3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497

		/* 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 已提交
3498
			errhint("Timeline IDs must be less than child timeline's ID.")));
3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516

	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 已提交
3517
	FILE	   *fd;
3518 3519 3520 3521

	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, probeTLI);
3522
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537
	}
	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 已提交
3538
					 errmsg("could not open file \"%s\": %m", path)));
3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
		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 已提交
3557 3558
	 * The algorithm is just to probe for the existence of timeline history
	 * files.  XXX is it useful to allow gaps in the sequence?
3559 3560 3561
	 */
	newestTLI = startTLI;

B
Bruce Momjian 已提交
3562
	for (probeTLI = startTLI + 1;; probeTLI++)
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
	{
		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 已提交
3586
 * considerations.	But we should be just as tense as XLogFileInit to avoid
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601
 * 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 已提交
3602
	Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3603 3604 3605 3606

	/*
	 * Write into a temp file name.
	 */
3607
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3608 3609 3610 3611 3612 3613 3614

	unlink(tmppath);

	/* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
3615
		ereport(ERROR,
3616 3617 3618 3619 3620 3621 3622 3623 3624
				(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);
3625
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3626 3627 3628 3629 3630 3631 3632 3633
	}
	else
		TLHistoryFilePath(path, parentTLI);

	srcfd = BasicOpenFile(path, O_RDONLY, 0);
	if (srcfd < 0)
	{
		if (errno != ENOENT)
3634
			ereport(ERROR,
3635
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
3636
					 errmsg("could not open file \"%s\": %m", path)));
3637 3638 3639 3640 3641 3642 3643 3644 3645
		/* Not there, so assume parent has no parents */
	}
	else
	{
		for (;;)
		{
			errno = 0;
			nbytes = (int) read(srcfd, buffer, sizeof(buffer));
			if (nbytes < 0 || errno != 0)
3646
				ereport(ERROR,
3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660
						(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 已提交
3661 3662

				/*
B
Bruce Momjian 已提交
3663
				 * if write didn't set errno, assume problem is no disk space
B
Bruce Momjian 已提交
3664
				 */
3665 3666
				errno = save_errno ? save_errno : ENOSPC;

3667
				ereport(ERROR,
3668
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
3669
					 errmsg("could not write to file \"%s\": %m", tmppath)));
3670 3671 3672 3673 3674 3675 3676 3677
			}
		}
		close(srcfd);
	}

	/*
	 * Append one line with the details of this timeline split.
	 *
B
Bruce Momjian 已提交
3678 3679
	 * If we did have a parent file, insert an extra newline just in case the
	 * parent file failed to end with one.
3680 3681 3682 3683 3684 3685 3686 3687 3688 3689
	 */
	XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);

	snprintf(buffer, sizeof(buffer),
			 "%s%u\t%s\t%s transaction %u at %s\n",
			 (srcfd < 0) ? "" : "\n",
			 parentTLI,
			 xlogfname,
			 recoveryStopAfter ? "after" : "before",
			 recoveryStopXid,
3690
			 timestamptz_to_str(recoveryStopTime));
3691 3692 3693 3694 3695 3696 3697 3698

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

		/*
B
Bruce Momjian 已提交
3699
		 * If we fail to make the file, delete it to release disk space
3700 3701 3702 3703 3704
		 */
		unlink(tmppath);
		/* if write didn't set errno, assume problem is no disk space */
		errno = save_errno ? save_errno : ENOSPC;

3705
		ereport(ERROR,
3706 3707 3708 3709 3710
				(errcode_for_file_access(),
				 errmsg("could not write to file \"%s\": %m", tmppath)));
	}

	if (pg_fsync(fd) != 0)
3711
		ereport(ERROR,
3712 3713 3714 3715
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
3716
		ereport(ERROR,
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732
				(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)
3733
		ereport(ERROR,
3734 3735 3736 3737 3738 3739
				(errcode_for_file_access(),
				 errmsg("could not link file \"%s\" to \"%s\": %m",
						tmppath, path)));
	unlink(tmppath);
#else
	if (rename(tmppath, path) < 0)
3740
		ereport(ERROR,
3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752
				(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
3753 3754
 *
 * *ControlFile is a buffer in shared memory that holds an image of the
B
Bruce Momjian 已提交
3755
 * contents of pg_control.	WriteControlFile() initializes pg_control
3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768
 * 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 已提交
3769
	char		buffer[PG_CONTROL_SIZE];		/* need not be aligned */
3770 3771 3772
	char	   *localeptr;

	/*
T
Tom Lane 已提交
3773
	 * Initialize version and compatibility-check fields
3774
	 */
T
Tom Lane 已提交
3775 3776
	ControlFile->pg_control_version = PG_CONTROL_VERSION;
	ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3777 3778 3779 3780

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

3781 3782
	ControlFile->blcksz = BLCKSZ;
	ControlFile->relseg_size = RELSEG_SIZE;
3783
	ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3784
	ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3785 3786

	ControlFile->nameDataLen = NAMEDATALEN;
3787
	ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3788

3789 3790
	ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;

3791 3792 3793 3794 3795 3796 3797
#ifdef HAVE_INT64_TIMESTAMP
	ControlFile->enableIntTimes = TRUE;
#else
	ControlFile->enableIntTimes = FALSE;
#endif

	ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3798 3799
	localeptr = setlocale(LC_COLLATE, NULL);
	if (!localeptr)
3800 3801
		ereport(PANIC,
				(errmsg("invalid LC_COLLATE setting")));
3802 3803 3804
	StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
	localeptr = setlocale(LC_CTYPE, NULL);
	if (!localeptr)
3805 3806
		ereport(PANIC,
				(errmsg("invalid LC_CTYPE setting")));
3807
	StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
B
Bruce Momjian 已提交
3808

T
Tom Lane 已提交
3809
	/* Contents are protected with a CRC */
3810 3811 3812 3813 3814
	INIT_CRC32(ControlFile->crc);
	COMP_CRC32(ControlFile->crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(ControlFile->crc);
T
Tom Lane 已提交
3815

3816
	/*
3817 3818 3819 3820 3821
	 * 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".
3822
	 */
3823 3824
	if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
		elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3825

3826
	memset(buffer, 0, PG_CONTROL_SIZE);
3827 3828
	memcpy(buffer, ControlFile, sizeof(ControlFileData));

3829 3830
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3831
					   S_IRUSR | S_IWUSR);
3832
	if (fd < 0)
3833 3834 3835
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not create control file \"%s\": %m",
3836
						XLOG_CONTROL_FILE)));
3837

3838
	errno = 0;
3839
	if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3840 3841 3842 3843
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
3844 3845
		ereport(PANIC,
				(errcode_for_file_access(),
3846
				 errmsg("could not write to control file: %m")));
3847
	}
3848

3849
	if (pg_fsync(fd) != 0)
3850 3851
		ereport(PANIC,
				(errcode_for_file_access(),
3852
				 errmsg("could not fsync control file: %m")));
3853

3854 3855 3856 3857
	if (close(fd))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close control file: %m")));
3858 3859 3860 3861 3862
}

static void
ReadControlFile(void)
{
3863
	pg_crc32	crc;
3864 3865 3866 3867 3868
	int			fd;

	/*
	 * Read data...
	 */
3869 3870 3871
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
3872
	if (fd < 0)
3873 3874 3875
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
3876
						XLOG_CONTROL_FILE)));
3877 3878

	if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3879 3880
		ereport(PANIC,
				(errcode_for_file_access(),
3881
				 errmsg("could not read from control file: %m")));
3882 3883 3884

	close(fd);

T
Tom Lane 已提交
3885
	/*
B
Bruce Momjian 已提交
3886 3887 3888 3889
	 * 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 已提交
3890 3891
	 */
	if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3892 3893 3894
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
B
Bruce Momjian 已提交
3895 3896
				  " but the server was compiled with PG_CONTROL_VERSION %d.",
						ControlFile->pg_control_version, PG_CONTROL_VERSION),
3897
				 errhint("It looks like you need to initdb.")));
T
Tom Lane 已提交
3898
	/* Now check the CRC. */
3899 3900 3901 3902 3903
	INIT_CRC32(crc);
	COMP_CRC32(crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(crc);
3904

3905
	if (!EQ_CRC32(crc, ControlFile->crc))
3906
		ereport(FATAL,
3907
				(errmsg("incorrect checksum in control file")));
3908

3909
	/*
B
Bruce Momjian 已提交
3910
	 * Do compatibility checking immediately.  We do this here for 2 reasons:
3911
	 *
3912 3913
	 * (1) if the database isn't compatible with the backend executable, we
	 * want to abort before we can possibly do any damage;
3914 3915
	 *
	 * (2) this code is executed in the postmaster, so the setlocale() will
B
Bruce Momjian 已提交
3916 3917
	 * propagate to forked backends, which aren't going to read this file for
	 * themselves.	(These locale settings are considered critical
3918 3919
	 * compatibility items because they can affect sort order of indexes.)
	 */
T
Tom Lane 已提交
3920
	if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3921 3922 3923
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
B
Bruce Momjian 已提交
3924 3925
				  " but the server was compiled with CATALOG_VERSION_NO %d.",
						ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3926
				 errhint("It looks like you need to initdb.")));
3927 3928 3929
	if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
3930 3931 3932 3933
		   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.")));
3934 3935 3936
	if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
P
Peter Eisentraut 已提交
3937
				 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3938
				 errhint("It looks like you need to initdb.")));
3939
	if (ControlFile->blcksz != BLCKSZ)
3940 3941
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
3942 3943 3944 3945
			 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.")));
3946
	if (ControlFile->relseg_size != RELSEG_SIZE)
3947 3948
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
3949 3950 3951 3952
		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.")));
3953 3954 3955
	if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
3956 3957 3958
		errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
				  " but the server was compiled with XLOG_BLCKSZ %d.",
				  ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3959
				 errhint("It looks like you need to recompile or initdb.")));
3960 3961 3962 3963
	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 已提交
3964
					   " but the server was compiled with XLOG_SEG_SIZE %d.",
3965
						   ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
B
Bruce Momjian 已提交
3966
				 errhint("It looks like you need to recompile or initdb.")));
3967
	if (ControlFile->nameDataLen != NAMEDATALEN)
3968 3969
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
3970 3971 3972 3973
		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.")));
3974
	if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3975 3976
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
3977
				 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
B
Bruce Momjian 已提交
3978
					  " but the server was compiled with INDEX_MAX_KEYS %d.",
3979
						   ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
B
Bruce Momjian 已提交
3980
				 errhint("It looks like you need to recompile or initdb.")));
3981 3982 3983 3984
	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 已提交
3985 3986
				" but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
			  ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
3987
				 errhint("It looks like you need to recompile or initdb.")));
3988 3989 3990

#ifdef HAVE_INT64_TIMESTAMP
	if (ControlFile->enableIntTimes != TRUE)
3991 3992 3993
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
3994 3995
				  " but the server was compiled with HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
3996 3997
#else
	if (ControlFile->enableIntTimes != FALSE)
3998 3999 4000
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
4001 4002
			   " but the server was compiled without HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
4003 4004 4005
#endif

	if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
4006 4007 4008
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
B
Bruce Momjian 已提交
4009
				  " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
4010
						   ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
B
Bruce Momjian 已提交
4011
				 errhint("It looks like you need to recompile or initdb.")));
4012
	if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
4013
		ereport(FATAL,
B
Bruce Momjian 已提交
4014 4015 4016 4017 4018
			(errmsg("database files are incompatible with operating system"),
			 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
					   " which is not recognized by setlocale().",
					   ControlFile->lc_collate),
			 errhint("It looks like you need to initdb or install locale support.")));
4019
	if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
4020
		ereport(FATAL,
B
Bruce Momjian 已提交
4021 4022 4023 4024 4025
			(errmsg("database files are incompatible with operating system"),
		errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
				  " which is not recognized by setlocale().",
				  ControlFile->lc_ctype),
			 errhint("It looks like you need to initdb or install locale support.")));
4026 4027 4028 4029 4030 4031

	/* Make the fixed locale settings visible as GUC variables, too */
	SetConfigOption("lc_collate", ControlFile->lc_collate,
					PGC_INTERNAL, PGC_S_OVERRIDE);
	SetConfigOption("lc_ctype", ControlFile->lc_ctype,
					PGC_INTERNAL, PGC_S_OVERRIDE);
4032 4033
}

4034
void
4035
UpdateControlFile(void)
4036
{
4037
	int			fd;
4038

4039 4040 4041 4042 4043
	INIT_CRC32(ControlFile->crc);
	COMP_CRC32(ControlFile->crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(ControlFile->crc);
4044

4045 4046 4047
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
4048
	if (fd < 0)
4049 4050 4051
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
4052
						XLOG_CONTROL_FILE)));
4053

4054
	errno = 0;
4055
	if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4056 4057 4058 4059
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
4060 4061
		ereport(PANIC,
				(errcode_for_file_access(),
4062
				 errmsg("could not write to control file: %m")));
4063
	}
4064

4065
	if (pg_fsync(fd) != 0)
4066 4067
		ereport(PANIC,
				(errcode_for_file_access(),
4068
				 errmsg("could not fsync control file: %m")));
4069

4070 4071 4072 4073
	if (close(fd))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close control file: %m")));
4074 4075
}

4076
/*
T
Tom Lane 已提交
4077
 * Initialization of shared memory for XLOG
4078
 */
4079
Size
4080
XLOGShmemSize(void)
4081
{
4082
	Size		size;
4083

4084 4085 4086 4087 4088 4089 4090
	/* 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 */
4091
	size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4092 4093

	/*
B
Bruce Momjian 已提交
4094 4095 4096
	 * 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.
4097 4098 4099
	 */

	return size;
4100 4101 4102 4103 4104
}

void
XLOGShmemInit(void)
{
4105 4106
	bool		foundCFile,
				foundXLog;
4107
	char	   *allocptr;
4108

4109
	ControlFile = (ControlFileData *)
4110
		ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4111 4112
	XLogCtl = (XLogCtlData *)
		ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4113

4114
	if (foundCFile || foundXLog)
4115 4116
	{
		/* both should be present or neither */
4117
		Assert(foundCFile && foundXLog);
4118 4119
		return;
	}
4120

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

T
Tom Lane 已提交
4123
	/*
B
Bruce Momjian 已提交
4124 4125 4126
	 * 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 已提交
4127
	 */
4128 4129
	allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
	XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
T
Tom Lane 已提交
4130
	memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4131
	allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
B
Bruce Momjian 已提交
4132

T
Tom Lane 已提交
4133
	/*
4134
	 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
T
Tom Lane 已提交
4135
	 */
4136 4137
	allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
	XLogCtl->pages = allocptr;
4138
	memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
T
Tom Lane 已提交
4139 4140

	/*
B
Bruce Momjian 已提交
4141 4142
	 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
	 * in additional info.)
T
Tom Lane 已提交
4143
	 */
B
Bruce Momjian 已提交
4144
	XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
B
Bruce Momjian 已提交
4145

T
Tom Lane 已提交
4146 4147
	XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
	XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4148
	SpinLockInit(&XLogCtl->info_lck);
T
Tom Lane 已提交
4149

4150
	/*
B
Bruce Momjian 已提交
4151 4152 4153
	 * 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).
4154 4155 4156
	 */
	if (!IsBootstrapProcessingMode())
		ReadControlFile();
4157 4158 4159
}

/*
T
Tom Lane 已提交
4160 4161
 * This func must be called ONCE on system install.  It creates pg_control
 * and the initial XLOG segment.
4162 4163
 */
void
T
Tom Lane 已提交
4164
BootStrapXLOG(void)
4165
{
4166
	CheckPoint	checkPoint;
T
Tom Lane 已提交
4167 4168
	char	   *buffer;
	XLogPageHeader page;
4169
	XLogLongPageHeader longpage;
4170
	XLogRecord *record;
B
Bruce Momjian 已提交
4171
	bool		use_existent;
4172 4173
	uint64		sysidentifier;
	struct timeval tv;
4174
	pg_crc32	crc;
4175

4176
	/*
B
Bruce Momjian 已提交
4177 4178 4179 4180 4181 4182 4183 4184 4185 4186
	 * 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.
4187 4188 4189 4190 4191
	 */
	gettimeofday(&tv, NULL);
	sysidentifier = ((uint64) tv.tv_sec) << 32;
	sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);

4192 4193 4194
	/* First timeline ID is always 1 */
	ThisTimeLineID = 1;

4195
	/* page buffer must be aligned suitably for O_DIRECT */
4196
	buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4197
	page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4198
	memset(page, 0, XLOG_BLCKSZ);
T
Tom Lane 已提交
4199

4200
	/* Set up information for the initial checkpoint record */
4201
	checkPoint.redo.xlogid = 0;
4202 4203
	checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
	checkPoint.ThisTimeLineID = ThisTimeLineID;
4204
	checkPoint.nextXidEpoch = 0;
4205
	checkPoint.nextXid = FirstNormalTransactionId;
4206
	checkPoint.nextOid = FirstBootstrapObjectId;
4207
	checkPoint.nextMulti = FirstMultiXactId;
4208
	checkPoint.nextMultiOffset = 0;
T
Tom Lane 已提交
4209
	checkPoint.time = time(NULL);
4210

4211 4212 4213
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
	ShmemVariableCache->oidCount = 0;
4214
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4215

4216
	/* Set up the XLOG page header */
4217
	page->xlp_magic = XLOG_PAGE_MAGIC;
4218 4219
	page->xlp_info = XLP_LONG_HEADER;
	page->xlp_tli = ThisTimeLineID;
4220 4221
	page->xlp_pageaddr.xlogid = 0;
	page->xlp_pageaddr.xrecoff = 0;
4222 4223 4224
	longpage = (XLogLongPageHeader) page;
	longpage->xlp_sysid = sysidentifier;
	longpage->xlp_seg_size = XLogSegSize;
4225
	longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4226 4227

	/* Insert the initial checkpoint record */
4228
	record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4229
	record->xl_prev.xlogid = 0;
4230
	record->xl_prev.xrecoff = 0;
4231
	record->xl_xid = InvalidTransactionId;
4232
	record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4233
	record->xl_len = sizeof(checkPoint);
T
Tom Lane 已提交
4234
	record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4235
	record->xl_rmid = RM_XLOG_ID;
T
Tom Lane 已提交
4236
	memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4237

4238 4239 4240 4241 4242
	INIT_CRC32(crc);
	COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
	COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
			   SizeOfXLogRecord - sizeof(pg_crc32));
	FIN_CRC32(crc);
4243 4244
	record->xl_crc = crc;

4245
	/* Create first XLOG segment file */
4246 4247
	use_existent = false;
	openLogFile = XLogFileInit(0, 0, &use_existent, false);
4248

4249
	/* Write the first page with the initial record */
4250
	errno = 0;
4251
	if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4252 4253 4254 4255
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
4256 4257
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4258
			  errmsg("could not write bootstrap transaction log file: %m")));
4259
	}
4260

T
Tom Lane 已提交
4261
	if (pg_fsync(openLogFile) != 0)
4262 4263
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4264
			  errmsg("could not fsync bootstrap transaction log file: %m")));
4265

4266 4267 4268
	if (close(openLogFile))
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4269
			  errmsg("could not close bootstrap transaction log file: %m")));
4270

T
Tom Lane 已提交
4271
	openLogFile = -1;
4272

4273 4274
	/* Now create pg_control */

4275
	memset(ControlFile, 0, sizeof(ControlFileData));
T
Tom Lane 已提交
4276
	/* Initialize pg_control status fields */
4277
	ControlFile->system_identifier = sysidentifier;
T
Tom Lane 已提交
4278 4279
	ControlFile->state = DB_SHUTDOWNED;
	ControlFile->time = checkPoint.time;
4280
	ControlFile->checkPoint = checkPoint.redo;
T
Tom Lane 已提交
4281
	ControlFile->checkPointCopy = checkPoint;
4282
	/* some additional ControlFile fields are set in WriteControlFile() */
4283

4284
	WriteControlFile();
4285 4286 4287

	/* Bootstrap the commit log, too */
	BootStrapCLOG();
4288
	BootStrapSUBTRANS();
4289
	BootStrapMultiXact();
4290

4291
	pfree(buffer);
4292 4293
}

4294
static char *
4295
str_time(pg_time_t tnow)
4296
{
4297
	static char buf[128];
4298

4299 4300 4301
	pg_strftime(buf, sizeof(buf),
				"%Y-%m-%d %H:%M:%S %Z",
				pg_localtime(&tnow, log_timezone));
4302

4303
	return buf;
4304 4305
}

4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316
/*
 * See if there is a recovery command file (recovery.conf), and if so
 * read in parameters for archive recovery.
 *
 * 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 已提交
4317 4318 4319 4320 4321 4322
	FILE	   *fd;
	char		cmdline[MAXPGPATH];
	TimeLineID	rtli = 0;
	bool		rtliGiven = false;
	bool		syntaxError = false;

4323
	fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4324 4325 4326 4327 4328
	if (fd == NULL)
	{
		if (errno == ENOENT)
			return;				/* not there, so no archive recovery */
		ereport(FATAL,
B
Bruce Momjian 已提交
4329
				(errcode_for_file_access(),
4330
				 errmsg("could not open recovery command file \"%s\": %m",
4331
						RECOVERY_COMMAND_FILE)));
4332 4333 4334
	}

	ereport(LOG,
B
Bruce Momjian 已提交
4335
			(errmsg("starting archive recovery")));
4336

B
Bruce Momjian 已提交
4337 4338 4339
	/*
	 * Parse the file...
	 */
4340
	while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4341 4342
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
4343 4344 4345
		char	   *ptr;
		char	   *tok1;
		char	   *tok2;
4346 4347 4348 4349 4350 4351 4352 4353 4354 4355

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

		/* identify the quoted parameter value */
B
Bruce Momjian 已提交
4356
		tok1 = strtok(ptr, "'");
4357 4358 4359 4360 4361
		if (!tok1)
		{
			syntaxError = true;
			break;
		}
B
Bruce Momjian 已提交
4362
		tok2 = strtok(NULL, "'");
4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375
		if (!tok2)
		{
			syntaxError = true;
			break;
		}
		/* reparse to get just the parameter name */
		tok1 = strtok(ptr, " \t=");
		if (!tok1)
		{
			syntaxError = true;
			break;
		}

B
Bruce Momjian 已提交
4376 4377
		if (strcmp(tok1, "restore_command") == 0)
		{
4378
			recoveryRestoreCommand = pstrdup(tok2);
4379
			ereport(LOG,
4380
					(errmsg("restore_command = '%s'",
4381 4382
							recoveryRestoreCommand)));
		}
B
Bruce Momjian 已提交
4383 4384
		else if (strcmp(tok1, "recovery_target_timeline") == 0)
		{
4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403
			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)
				ereport(LOG,
						(errmsg("recovery_target_timeline = %u", rtli)));
			else
				ereport(LOG,
						(errmsg("recovery_target_timeline = latest")));
		}
B
Bruce Momjian 已提交
4404 4405
		else if (strcmp(tok1, "recovery_target_xid") == 0)
		{
4406 4407 4408 4409
			errno = 0;
			recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
			if (errno == EINVAL || errno == ERANGE)
				ereport(FATAL,
B
Bruce Momjian 已提交
4410 4411
				 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
						 tok2)));
4412 4413 4414 4415 4416 4417
			ereport(LOG,
					(errmsg("recovery_target_xid = %u",
							recoveryTargetXid)));
			recoveryTarget = true;
			recoveryTargetExact = true;
		}
B
Bruce Momjian 已提交
4418 4419
		else if (strcmp(tok1, "recovery_target_time") == 0)
		{
4420 4421 4422 4423 4424 4425 4426 4427
			/*
			 * if recovery_target_xid specified, then this overrides
			 * recovery_target_time
			 */
			if (recoveryTargetExact)
				continue;
			recoveryTarget = true;
			recoveryTargetExact = false;
B
Bruce Momjian 已提交
4428

4429
			/*
4430
			 * Convert the time string given by the user to TimestampTz form.
4431
			 */
4432 4433
			recoveryTargetTime =
				DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
B
Bruce Momjian 已提交
4434
														CStringGetDatum(tok2),
4435 4436
												ObjectIdGetDatum(InvalidOid),
														Int32GetDatum(-1)));
4437
			ereport(LOG,
4438
					(errmsg("recovery_target_time = '%s'",
4439
							timestamptz_to_str(recoveryTargetTime))));
4440
		}
B
Bruce Momjian 已提交
4441 4442
		else if (strcmp(tok1, "recovery_target_inclusive") == 0)
		{
4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455
			/*
			 * does nothing if a recovery_target is not also set
			 */
			if (strcmp(tok2, "true") == 0)
				recoveryTargetInclusive = true;
			else
			{
				recoveryTargetInclusive = false;
				tok2 = "false";
			}
			ereport(LOG,
					(errmsg("recovery_target_inclusive = %s", tok2)));
		}
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470
		else if (strcmp(tok1, "log_restartpoints") == 0)
		{
			/*
			 * does nothing if a recovery_target is not also set
			 */
			if (strcmp(tok2, "true") == 0)
				recoveryLogRestartpoints = true;
			else
			{
				recoveryLogRestartpoints = false;
				tok2 = "false";
			}
			ereport(LOG,
					(errmsg("log_restartpoints = %s", tok2)));
		}
4471 4472 4473 4474 4475 4476 4477 4478
		else
			ereport(FATAL,
					(errmsg("unrecognized recovery parameter \"%s\"",
							tok1)));
	}

	FreeFile(fd);

B
Bruce Momjian 已提交
4479 4480
	if (syntaxError)
		ereport(FATAL,
4481 4482
				(errmsg("syntax error in recovery command file: %s",
						cmdline),
B
Bruce Momjian 已提交
4483
			  errhint("Lines should have the format parameter = 'value'.")));
4484 4485

	/* Check that required parameters were supplied */
4486
	if (recoveryRestoreCommand == NULL)
4487 4488
		ereport(FATAL,
				(errmsg("recovery command file \"%s\" did not specify restore_command",
4489
						RECOVERY_COMMAND_FILE)));
4490

4491 4492 4493
	/* Enable fetching from archive recovery area */
	InArchiveRecovery = true;

4494
	/*
B
Bruce Momjian 已提交
4495 4496 4497 4498
	 * 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.
4499
	 */
4500 4501 4502 4503 4504 4505 4506
	if (rtliGiven)
	{
		if (rtli)
		{
			/* Timeline 1 does not have a history file, all else should */
			if (rtli != 1 && !existsTimeLineHistory(rtli))
				ereport(FATAL,
4507
						(errmsg("recovery target timeline %u does not exist",
B
Bruce Momjian 已提交
4508
								rtli)));
4509 4510 4511 4512 4513 4514 4515 4516
			recoveryTargetTLI = rtli;
		}
		else
		{
			/* We start the "latest" search from pg_control's timeline */
			recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
		}
	}
4517 4518 4519 4520 4521 4522
}

/*
 * Exit archive-recovery state
 */
static void
4523
exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4524
{
B
Bruce Momjian 已提交
4525 4526
	char		recoveryPath[MAXPGPATH];
	char		xlogpath[MAXPGPATH];
4527 4528

	/*
4529
	 * We are no longer in archive recovery state.
4530 4531 4532 4533
	 */
	InArchiveRecovery = false;

	/*
B
Bruce Momjian 已提交
4534 4535 4536
	 * We should have the ending log segment currently open.  Verify, and then
	 * close it (to avoid problems on Windows with trying to rename or delete
	 * an open file).
4537 4538 4539 4540 4541 4542 4543 4544 4545
	 */
	Assert(readFile >= 0);
	Assert(readId == endLogId);
	Assert(readSeg == endLogSeg);

	close(readFile);
	readFile = -1;

	/*
B
Bruce Momjian 已提交
4546 4547 4548 4549 4550 4551 4552
	 * 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.
4553
	 *
4554 4555
	 * 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
4556 4557
	 * of overwriting any existing file.  (This is, in fact, always the case
	 * at present.)
4558
	 */
4559
	snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4560
	XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4561 4562 4563 4564 4565 4566 4567 4568 4569 4570

	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(),
4571
					 errmsg("could not rename file \"%s\" to \"%s\": %m",
4572 4573 4574 4575 4576 4577 4578 4579 4580 4581
							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 已提交
4582

4583
		/*
B
Bruce Momjian 已提交
4584 4585 4586
		 * 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.
4587 4588 4589 4590
		 */
		if (endTLI != ThisTimeLineID)
			XLogFileCopy(endLogId, endLogSeg,
						 endTLI, endLogId, endLogSeg);
4591 4592 4593
	}

	/*
B
Bruce Momjian 已提交
4594 4595
	 * Let's just make real sure there are not .ready or .done flags posted
	 * for the new segment.
4596
	 */
4597 4598
	XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
	XLogArchiveCleanup(xlogpath);
4599

4600
	/* Get rid of any remaining recovered timeline-history file, too */
4601
	snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
B
Bruce Momjian 已提交
4602
	unlink(recoveryPath);		/* ignore any error */
4603 4604

	/*
B
Bruce Momjian 已提交
4605 4606
	 * Rename the config file out of the way, so that we don't accidentally
	 * re-enter archive recovery mode in a subsequent crash.
4607
	 */
4608 4609
	unlink(RECOVERY_COMMAND_DONE);
	if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4610 4611
		ereport(FATAL,
				(errcode_for_file_access(),
4612
				 errmsg("could not rename file \"%s\" to \"%s\": %m",
4613
						RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624

	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.
4625 4626
 * Also, some information is saved in recoveryStopXid et al for use in
 * annotating the new timeline's history file.
4627 4628 4629 4630 4631
 */
static bool
recoveryStopsHere(XLogRecord *record, bool *includeThis)
{
	bool		stopsHere;
B
Bruce Momjian 已提交
4632
	uint8		record_info;
B
Bruce Momjian 已提交
4633
	TimestampTz recordXtime;
4634 4635 4636 4637 4638 4639 4640

	/* We only consider stopping at COMMIT or ABORT records */
	if (record->xl_rmid != RM_XACT_ID)
		return false;
	record_info = record->xl_info & ~XLR_INFO_MASK;
	if (record_info == XLOG_XACT_COMMIT)
	{
B
Bruce Momjian 已提交
4641
		xl_xact_commit *recordXactCommitData;
4642 4643

		recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4644
		recordXtime = recordXactCommitData->xact_time;
4645 4646 4647
	}
	else if (record_info == XLOG_XACT_ABORT)
	{
B
Bruce Momjian 已提交
4648
		xl_xact_abort *recordXactAbortData;
4649 4650

		recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4651
		recordXtime = recordXactAbortData->xact_time;
4652 4653 4654 4655
	}
	else
		return false;

4656 4657 4658 4659 4660 4661 4662
	/* Remember the most recent COMMIT/ABORT time for logging purposes */
	recoveryLastXTime = recordXtime;

	/* Do we have a PITR target at all? */
	if (!recoveryTarget)
		return false;

4663 4664 4665
	if (recoveryTargetExact)
	{
		/*
B
Bruce Momjian 已提交
4666 4667
		 * there can be only one transaction end record with this exact
		 * transactionid
4668
		 *
B
Bruce Momjian 已提交
4669
		 * when testing for an xid, we MUST test for equality only, since
B
Bruce Momjian 已提交
4670 4671 4672
		 * 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...
4673 4674 4675 4676 4677 4678 4679 4680
		 */
		stopsHere = (record->xl_xid == recoveryTargetXid);
		if (stopsHere)
			*includeThis = recoveryTargetInclusive;
	}
	else
	{
		/*
B
Bruce Momjian 已提交
4681 4682 4683
		 * 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
4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694
		 */
		if (recoveryTargetInclusive)
			stopsHere = (recordXtime > recoveryTargetTime);
		else
			stopsHere = (recordXtime >= recoveryTargetTime);
		if (stopsHere)
			*includeThis = false;
	}

	if (stopsHere)
	{
4695 4696 4697 4698
		recoveryStopXid = record->xl_xid;
		recoveryStopTime = recordXtime;
		recoveryStopAfter = *includeThis;

4699 4700
		if (record_info == XLOG_XACT_COMMIT)
		{
4701
			if (recoveryStopAfter)
4702 4703
				ereport(LOG,
						(errmsg("recovery stopping after commit of transaction %u, time %s",
4704 4705
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
4706 4707 4708
			else
				ereport(LOG,
						(errmsg("recovery stopping before commit of transaction %u, time %s",
4709 4710
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
4711 4712 4713
		}
		else
		{
4714
			if (recoveryStopAfter)
4715 4716
				ereport(LOG,
						(errmsg("recovery stopping after abort of transaction %u, time %s",
4717 4718
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
4719 4720 4721
			else
				ereport(LOG,
						(errmsg("recovery stopping before abort of transaction %u, time %s",
4722 4723
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
4724 4725 4726 4727 4728 4729
		}
	}

	return stopsHere;
}

4730
/*
T
Tom Lane 已提交
4731
 * This must be called ONCE during postmaster or standalone-backend startup
4732 4733
 */
void
T
Tom Lane 已提交
4734
StartupXLOG(void)
4735
{
4736 4737
	XLogCtlInsert *Insert;
	CheckPoint	checkPoint;
T
Tom Lane 已提交
4738
	bool		wasShutdown;
4739
	bool		reachedStopPoint = false;
4740
	bool		haveBackupLabel = false;
4741
	XLogRecPtr	RecPtr,
T
Tom Lane 已提交
4742 4743
				LastRec,
				checkPointLoc,
4744
				minRecoveryLoc,
T
Tom Lane 已提交
4745
				EndOfLog;
4746 4747
	uint32		endLogId;
	uint32		endLogSeg;
4748
	XLogRecord *record;
4749
	uint32		freespace;
4750
	TransactionId oldestActiveXID;
4751

4752
	/*
4753 4754
	 * Read control file and check XLOG status looks valid.
	 *
4755 4756
	 * 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.
4757
	 */
4758
	ReadControlFile();
4759

4760
	if (ControlFile->state < DB_SHUTDOWNED ||
4761
		ControlFile->state > DB_IN_PRODUCTION ||
4762
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4763 4764
		ereport(FATAL,
				(errmsg("control file contains invalid data")));
4765 4766

	if (ControlFile->state == DB_SHUTDOWNED)
4767 4768 4769
		ereport(LOG,
				(errmsg("database system was shut down at %s",
						str_time(ControlFile->time))));
4770
	else if (ControlFile->state == DB_SHUTDOWNING)
4771
		ereport(LOG,
4772
				(errmsg("database system shutdown was interrupted; last known up at %s",
4773
						str_time(ControlFile->time))));
4774
	else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4775
		ereport(LOG,
B
Bruce Momjian 已提交
4776 4777 4778 4779
		   (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.")));
4780 4781
	else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
		ereport(LOG,
B
Bruce Momjian 已提交
4782 4783
				(errmsg("database system was interrupted while in recovery at log time %s",
						str_time(ControlFile->checkPointCopy.time)),
4784
				 errhint("If this has occurred more than once some data might be corrupted"
B
Bruce Momjian 已提交
4785
			  " and you might need to choose an earlier recovery target.")));
4786
	else if (ControlFile->state == DB_IN_PRODUCTION)
4787
		ereport(LOG,
B
Bruce Momjian 已提交
4788 4789
			  (errmsg("database system was interrupted; last known up at %s",
					  str_time(ControlFile->time))));
4790

4791 4792
	/* This is just to allow attaching to startup process with a debugger */
#ifdef XLOG_REPLAY_DELAY
4793
	if (ControlFile->state != DB_SHUTDOWNED)
4794
		pg_usleep(60000000L);
4795 4796
#endif

4797
	/*
B
Bruce Momjian 已提交
4798 4799
	 * Initialize on the assumption we want to recover to the same timeline
	 * that's active according to pg_control.
4800 4801 4802
	 */
	recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;

4803
	/*
B
Bruce Momjian 已提交
4804 4805
	 * Check for recovery control file, and if so set up state for offline
	 * recovery
4806 4807 4808
	 */
	readRecoveryCommandFile();

4809 4810 4811
	/* Now we can determine the list of expected TLIs */
	expectedTLIs = readTimeLineHistory(recoveryTargetTLI);

4812 4813 4814 4815 4816 4817
	/*
	 * 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 已提交
4818
						 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4819 4820 4821 4822 4823
		ereport(FATAL,
				(errmsg("requested timeline %u is not a child of database system timeline %u",
						recoveryTargetTLI,
						ControlFile->checkPointCopy.ThisTimeLineID)));

4824
	if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
T
Tom Lane 已提交
4825
	{
4826
		/*
B
Bruce Momjian 已提交
4827 4828
		 * When a backup_label file is present, we want to roll forward from
		 * the checkpoint it identifies, rather than using pg_control.
4829
		 */
4830
		record = ReadCheckpointRecord(checkPointLoc, 0);
4831 4832
		if (record != NULL)
		{
4833
			ereport(DEBUG1,
4834
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
4835
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4836 4837 4838 4839 4840
			InRecovery = true;	/* force recovery even if SHUTDOWNED */
		}
		else
		{
			ereport(PANIC,
B
Bruce Momjian 已提交
4841 4842
					(errmsg("could not locate required checkpoint record"),
					 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4843
		}
4844 4845
		/* set flag to delete it later */
		haveBackupLabel = true;
T
Tom Lane 已提交
4846 4847 4848
	}
	else
	{
4849
		/*
B
Bruce Momjian 已提交
4850 4851
		 * Get the last valid checkpoint record.  If the latest one according
		 * to pg_control is broken, try the next-to-last one.
4852 4853
		 */
		checkPointLoc = ControlFile->checkPoint;
4854
		record = ReadCheckpointRecord(checkPointLoc, 1);
T
Tom Lane 已提交
4855 4856
		if (record != NULL)
		{
4857
			ereport(DEBUG1,
4858
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
4859
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
T
Tom Lane 已提交
4860 4861
		}
		else
4862 4863
		{
			checkPointLoc = ControlFile->prevCheckPoint;
4864
			record = ReadCheckpointRecord(checkPointLoc, 2);
4865 4866 4867
			if (record != NULL)
			{
				ereport(LOG,
B
Bruce Momjian 已提交
4868 4869 4870
						(errmsg("using previous checkpoint record at %X/%X",
							  checkPointLoc.xlogid, checkPointLoc.xrecoff)));
				InRecovery = true;		/* force recovery even if SHUTDOWNED */
4871 4872 4873
			}
			else
				ereport(PANIC,
B
Bruce Momjian 已提交
4874
					 (errmsg("could not locate a valid checkpoint record")));
4875
		}
T
Tom Lane 已提交
4876
	}
4877

T
Tom Lane 已提交
4878 4879 4880
	LastRec = RecPtr = checkPointLoc;
	memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
	wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4881

4882
	ereport(DEBUG1,
B
Bruce Momjian 已提交
4883 4884 4885
			(errmsg("redo record is at %X/%X; shutdown %s",
					checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
					wasShutdown ? "TRUE" : "FALSE")));
4886
	ereport(DEBUG1,
4887 4888 4889
			(errmsg("next transaction ID: %u/%u; next OID: %u",
					checkPoint.nextXidEpoch, checkPoint.nextXid,
					checkPoint.nextOid)));
4890
	ereport(DEBUG1,
4891 4892
			(errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
					checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4893
	if (!TransactionIdIsNormal(checkPoint.nextXid))
4894
		ereport(PANIC,
4895
				(errmsg("invalid next transaction ID")));
4896 4897 4898

	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
4899
	ShmemVariableCache->oidCount = 0;
4900
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4901

4902
	/*
B
Bruce Momjian 已提交
4903 4904 4905
	 * 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()).
4906
	 */
4907
	ThisTimeLineID = checkPoint.ThisTimeLineID;
4908

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

4911
	if (XLByteLT(RecPtr, checkPoint.redo))
4912 4913
		ereport(PANIC,
				(errmsg("invalid redo in checkpoint record")));
4914

4915
	/*
B
Bruce Momjian 已提交
4916
	 * Check whether we need to force recovery from WAL.  If it appears to
B
Bruce Momjian 已提交
4917 4918
	 * have been a clean shutdown and we did not have a recovery.conf file,
	 * then assume no recovery needed.
4919
	 */
4920
	if (XLByteLT(checkPoint.redo, RecPtr))
4921
	{
T
Tom Lane 已提交
4922
		if (wasShutdown)
4923
			ereport(PANIC,
B
Bruce Momjian 已提交
4924
					(errmsg("invalid redo record in shutdown checkpoint")));
V
WAL  
Vadim B. Mikheev 已提交
4925
		InRecovery = true;
4926 4927
	}
	else if (ControlFile->state != DB_SHUTDOWNED)
V
WAL  
Vadim B. Mikheev 已提交
4928
		InRecovery = true;
4929 4930 4931 4932 4933
	else if (InArchiveRecovery)
	{
		/* force recovery due to presence of recovery.conf */
		InRecovery = true;
	}
4934

V
WAL  
Vadim B. Mikheev 已提交
4935
	/* REDO */
4936
	if (InRecovery)
4937
	{
B
Bruce Momjian 已提交
4938
		int			rmid;
4939

4940
		/*
B
Bruce Momjian 已提交
4941 4942 4943 4944
		 * 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.
4945
		 */
4946
		if (InArchiveRecovery)
4947
		{
4948
			ereport(LOG,
4949
					(errmsg("automatic recovery in progress")));
4950 4951
			ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
		}
4952
		else
4953
		{
4954
			ereport(LOG,
4955 4956
					(errmsg("database system was not properly shut down; "
							"automatic recovery in progress")));
4957 4958 4959 4960 4961 4962 4963
			ControlFile->state = DB_IN_CRASH_RECOVERY;
		}
		ControlFile->prevCheckPoint = ControlFile->checkPoint;
		ControlFile->checkPoint = checkPointLoc;
		ControlFile->checkPointCopy = checkPoint;
		if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
			ControlFile->minRecoveryPoint = minRecoveryLoc;
4964 4965 4966
		ControlFile->time = time(NULL);
		UpdateControlFile();

4967
		/*
B
Bruce Momjian 已提交
4968 4969 4970 4971 4972 4973
		 * 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.
4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984
		 */
		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)));
		}

4985
		/* Start up the recovery environment */
V
WAL  
Vadim B. Mikheev 已提交
4986
		XLogInitRelationCache();
V
Vadim B. Mikheev 已提交
4987

4988 4989 4990 4991 4992 4993
		for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
		{
			if (RmgrTable[rmid].rm_startup != NULL)
				RmgrTable[rmid].rm_startup();
		}

4994
		/*
B
Bruce Momjian 已提交
4995 4996
		 * Find the first record that logically follows the checkpoint --- it
		 * might physically precede it, though.
4997
		 */
4998
		if (XLByteLT(checkPoint.redo, RecPtr))
4999 5000
		{
			/* back up to find the record */
5001
			record = ReadRecord(&(checkPoint.redo), PANIC);
5002
		}
B
Bruce Momjian 已提交
5003
		else
5004
		{
5005
			/* just have to read next record after CheckPoint */
5006
			record = ReadRecord(NULL, LOG);
5007
		}
5008

T
Tom Lane 已提交
5009
		if (record != NULL)
5010
		{
5011 5012
			bool		recoveryContinue = true;
			bool		recoveryApply = true;
B
Bruce Momjian 已提交
5013
			ErrorContextCallback errcontext;
5014

V
WAL  
Vadim B. Mikheev 已提交
5015
			InRedo = true;
5016 5017 5018
			ereport(LOG,
					(errmsg("redo starts at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5019 5020 5021 5022

			/*
			 * main redo apply loop
			 */
5023 5024
			do
			{
5025
#ifdef WAL_DEBUG
V
WAL  
Vadim B. Mikheev 已提交
5026 5027
				if (XLOG_DEBUG)
				{
B
Bruce Momjian 已提交
5028
					StringInfoData buf;
V
WAL  
Vadim B. Mikheev 已提交
5029

5030 5031
					initStringInfo(&buf);
					appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
B
Bruce Momjian 已提交
5032 5033
									 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
									 EndRecPtr.xlogid, EndRecPtr.xrecoff);
5034 5035 5036 5037
					xlog_outrec(&buf, record);
					appendStringInfo(&buf, " - ");
					RmgrTable[record->xl_rmid].rm_desc(&buf,
													   record->xl_info,
B
Bruce Momjian 已提交
5038
													 XLogRecGetData(record));
5039 5040
					elog(LOG, "%s", buf.data);
					pfree(buf.data);
V
WAL  
Vadim B. Mikheev 已提交
5041
				}
5042
#endif
V
WAL  
Vadim B. Mikheev 已提交
5043

5044 5045 5046 5047 5048
				/*
				 * Have we reached our recovery target?
				 */
				if (recoveryStopsHere(record, &recoveryApply))
				{
B
Bruce Momjian 已提交
5049
					reachedStopPoint = true;	/* see below */
5050 5051 5052 5053 5054
					recoveryContinue = false;
					if (!recoveryApply)
						break;
				}

5055 5056 5057 5058 5059 5060
				/* 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;

5061 5062
				/* nextXid must be beyond record's xid */
				if (TransactionIdFollowsOrEquals(record->xl_xid,
B
Bruce Momjian 已提交
5063
												 ShmemVariableCache->nextXid))
5064 5065 5066 5067 5068
				{
					ShmemVariableCache->nextXid = record->xl_xid;
					TransactionIdAdvance(ShmemVariableCache->nextXid);
				}

T
Tom Lane 已提交
5069
				if (record->xl_info & XLR_BKP_BLOCK_MASK)
5070 5071
					RestoreBkpBlocks(record, EndRecPtr);

5072
				RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
5073

5074 5075 5076
				/* Pop the error context stack */
				error_context_stack = errcontext.previous;

5077 5078
				LastRec = ReadRecPtr;

5079
				record = ReadRecord(NULL, LOG);
5080
			} while (record != NULL && recoveryContinue);
B
Bruce Momjian 已提交
5081

5082 5083 5084 5085
			/*
			 * end of main redo apply loop
			 */

5086 5087 5088
			ereport(LOG,
					(errmsg("redo done at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5089 5090
			if (recoveryLastXTime)
				ereport(LOG,
B
Bruce Momjian 已提交
5091 5092
					 (errmsg("last completed transaction was at log time %s",
							 timestamptz_to_str(recoveryLastXTime))));
V
WAL  
Vadim B. Mikheev 已提交
5093
			InRedo = false;
5094 5095
		}
		else
5096 5097
		{
			/* there are no WAL records following the checkpoint */
5098 5099
			ereport(LOG,
					(errmsg("redo is not required")));
5100
		}
V
WAL  
Vadim B. Mikheev 已提交
5101 5102
	}

T
Tom Lane 已提交
5103
	/*
B
Bruce Momjian 已提交
5104 5105
	 * 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 已提交
5106
	 */
5107
	record = ReadRecord(&LastRec, PANIC);
T
Tom Lane 已提交
5108
	EndOfLog = EndRecPtr;
5109 5110
	XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);

5111 5112 5113 5114
	/*
	 * Complain if we did not roll forward far enough to render the backup
	 * dump consistent.
	 */
5115
	if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
5116
	{
5117
		if (reachedStopPoint)	/* stopped because of stop request */
5118 5119
			ereport(FATAL,
					(errmsg("requested recovery stop point is before end time of backup dump")));
B
Bruce Momjian 已提交
5120
		else	/* ran off end of WAL */
5121 5122 5123 5124
			ereport(FATAL,
					(errmsg("WAL ends before end time of backup dump")));
	}

5125 5126 5127
	/*
	 * Consider whether we need to assign a new timeline ID.
	 *
B
Bruce Momjian 已提交
5128 5129
	 * 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
5130 5131
	 * 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 已提交
5132 5133
	 * current last segment is problematic because it may result in trying to
	 * overwrite an already-archived copy of that segment, and we encourage
5134 5135 5136 5137
	 * 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.
5138
	 */
5139
	if (InArchiveRecovery)
5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150
	{
		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;

5151
	/*
B
Bruce Momjian 已提交
5152 5153 5154 5155
	 * 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.)
5156 5157
	 */
	if (InArchiveRecovery)
5158
		exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5159 5160 5161 5162 5163 5164 5165 5166

	/*
	 * 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;
5167
	openLogFile = XLogFileOpen(openLogId, openLogSeg);
T
Tom Lane 已提交
5168
	openLogOff = 0;
V
WAL  
Vadim B. Mikheev 已提交
5169
	Insert = &XLogCtl->Insert;
5170
	Insert->PrevRecord = LastRec;
5171 5172
	XLogCtl->xlblocks[0].xlogid = openLogId;
	XLogCtl->xlblocks[0].xrecoff =
5173
		((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
B
Bruce Momjian 已提交
5174 5175

	/*
B
Bruce Momjian 已提交
5176 5177 5178
	 * 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 已提交
5179
	 */
5180 5181
	Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
	memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5182
	Insert->currpos = (char *) Insert->currpage +
5183
		(EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
V
WAL  
Vadim B. Mikheev 已提交
5184

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

T
Tom Lane 已提交
5187 5188 5189
	XLogCtl->Write.LogwrtResult = LogwrtResult;
	Insert->LogwrtResult = LogwrtResult;
	XLogCtl->LogwrtResult = LogwrtResult;
V
WAL  
Vadim B. Mikheev 已提交
5190

T
Tom Lane 已提交
5191 5192
	XLogCtl->LogwrtRqst.Write = EndOfLog;
	XLogCtl->LogwrtRqst.Flush = EndOfLog;
5193

5194 5195 5196 5197 5198 5199 5200 5201 5202 5203
	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 已提交
5204 5205
		 * Whenever Write.LogwrtResult points to exactly the end of a page,
		 * Write.curridx must point to the *next* page (see XLogWrite()).
5206
		 *
B
Bruce Momjian 已提交
5207
		 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
B
Bruce Momjian 已提交
5208
		 * this is sufficient.	The first actual attempt to insert a log
5209
		 * record will advance the insert state.
5210 5211 5212 5213
		 */
		XLogCtl->Write.curridx = NextBufIdx(0);
	}

5214 5215
	/* Pre-scan prepared transactions to find out the range of XIDs present */
	oldestActiveXID = PrescanPreparedTransactions();
5216

V
WAL  
Vadim B. Mikheev 已提交
5217
	if (InRecovery)
5218
	{
B
Bruce Momjian 已提交
5219
		int			rmid;
5220 5221 5222 5223 5224 5225 5226 5227 5228 5229

		/*
		 * 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();
		}

5230 5231 5232 5233 5234 5235
		/*
		 * Check to see if the XLOG sequence contained any unresolved
		 * references to uninitialized pages.
		 */
		XLogCheckInvalidPages();

5236 5237 5238 5239 5240
		/*
		 * Reset pgstat data, because it may be invalid after recovery.
		 */
		pgstat_reset_all();

T
Tom Lane 已提交
5241
		/*
5242
		 * Perform a checkpoint to update all our recovery activity to disk.
5243
		 *
5244 5245 5246 5247 5248
		 * 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 已提交
5249
		 */
5250
		CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5251 5252 5253 5254

		/*
		 * Close down recovery environment
		 */
V
WAL  
Vadim B. Mikheev 已提交
5255
		XLogCloseRelationCache();
5256
	}
5257

T
Tom Lane 已提交
5258 5259 5260
	/*
	 * Preallocate additional log files, if wanted.
	 */
5261
	PreallocXlogFiles(EndOfLog);
5262

5263 5264 5265
	/*
	 * Okay, we're officially UP.
	 */
V
WAL  
Vadim B. Mikheev 已提交
5266
	InRecovery = false;
5267 5268 5269 5270 5271

	ControlFile->state = DB_IN_PRODUCTION;
	ControlFile->time = time(NULL);
	UpdateControlFile();

5272 5273 5274
	/* start the archive_timeout timer running */
	XLogCtl->Write.lastSegSwitchTime = ControlFile->time;

5275 5276 5277 5278
	/* initialize shared-memory copy of latest checkpoint XID/epoch */
	XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
	XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;

5279 5280 5281 5282
	/* also initialize latestCompletedXid, to nextXid - 1 */
	ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
	TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);

5283
	/* Start up the commit log and related stuff, too */
5284
	StartupCLOG();
5285
	StartupSUBTRANS(oldestActiveXID);
5286
	StartupMultiXact();
5287

5288 5289 5290
	/* Reload shared-memory state for prepared transactions */
	RecoverPreparedTransactions();

T
Tom Lane 已提交
5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301
	/* Shut down readFile facility, free space */
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
	if (readBuf)
	{
		free(readBuf);
		readBuf = NULL;
	}
5302 5303 5304 5305 5306 5307
	if (readRecordBuf)
	{
		free(readRecordBuf);
		readRecordBuf = NULL;
		readRecordBufSize = 0;
	}
T
Tom Lane 已提交
5308 5309
}

5310 5311
/*
 * Subroutine to try to fetch and validate a prior checkpoint record.
5312 5313 5314
 *
 * whichChkpt identifies the checkpoint (merely for reporting purposes).
 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5315
 */
T
Tom Lane 已提交
5316
static XLogRecord *
5317
ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
T
Tom Lane 已提交
5318 5319 5320 5321 5322
{
	XLogRecord *record;

	if (!XRecOffIsValid(RecPtr.xrecoff))
	{
5323 5324 5325 5326
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
5327
				(errmsg("invalid primary checkpoint link in control file")));
5328 5329 5330 5331 5332 5333 5334
				break;
			case 2:
				ereport(LOG,
						(errmsg("invalid secondary checkpoint link in control file")));
				break;
			default:
				ereport(LOG,
B
Bruce Momjian 已提交
5335
				   (errmsg("invalid checkpoint link in backup_label file")));
5336 5337
				break;
		}
T
Tom Lane 已提交
5338 5339 5340
		return NULL;
	}

5341
	record = ReadRecord(&RecPtr, LOG);
T
Tom Lane 已提交
5342 5343 5344

	if (record == NULL)
	{
5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359
		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 已提交
5360 5361 5362 5363
		return NULL;
	}
	if (record->xl_rmid != RM_XLOG_ID)
	{
5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375
		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 已提交
5376
				(errmsg("invalid resource manager ID in checkpoint record")));
5377 5378
				break;
		}
T
Tom Lane 已提交
5379 5380 5381 5382 5383
		return NULL;
	}
	if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
		record->xl_info != XLOG_CHECKPOINT_ONLINE)
	{
5384 5385 5386 5387
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
5388
				   (errmsg("invalid xl_info in primary checkpoint record")));
5389 5390 5391
				break;
			case 2:
				ereport(LOG,
B
Bruce Momjian 已提交
5392
				 (errmsg("invalid xl_info in secondary checkpoint record")));
5393 5394 5395 5396 5397 5398
				break;
			default:
				ereport(LOG,
						(errmsg("invalid xl_info in checkpoint record")));
				break;
		}
T
Tom Lane 已提交
5399 5400
		return NULL;
	}
5401 5402
	if (record->xl_len != sizeof(CheckPoint) ||
		record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
T
Tom Lane 已提交
5403
	{
5404 5405 5406 5407
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
5408
					(errmsg("invalid length of primary checkpoint record")));
5409 5410 5411
				break;
			case 2:
				ereport(LOG,
B
Bruce Momjian 已提交
5412
				  (errmsg("invalid length of secondary checkpoint record")));
5413 5414 5415 5416 5417 5418
				break;
			default:
				ereport(LOG,
						(errmsg("invalid length of checkpoint record")));
				break;
		}
T
Tom Lane 已提交
5419 5420 5421
		return NULL;
	}
	return record;
5422 5423
}

V
WAL  
Vadim B. Mikheev 已提交
5424
/*
5425 5426
 * This must be called during startup of a backend process, except that
 * it need not be called in a standalone backend (which does StartupXLOG
5427
 * instead).  We need to initialize the local copies of ThisTimeLineID and
5428 5429
 * RedoRecPtr.
 *
5430
 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5431
 * process's copies of ThisTimeLineID and RedoRecPtr valid too.  This was
5432
 * unnecessary however, since the postmaster itself never touches XLOG anyway.
V
WAL  
Vadim B. Mikheev 已提交
5433 5434
 */
void
5435
InitXLOGAccess(void)
V
WAL  
Vadim B. Mikheev 已提交
5436
{
5437 5438
	/* ThisTimeLineID doesn't change so we need no lock to copy it */
	ThisTimeLineID = XLogCtl->ThisTimeLineID;
5439 5440
	/* Use GetRedoRecPtr to copy the RedoRecPtr safely */
	(void) GetRedoRecPtr();
5441 5442 5443 5444 5445 5446 5447 5448
}

/*
 * 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
5449 5450
GetRedoRecPtr(void)
{
5451 5452 5453
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

5454
	SpinLockAcquire(&xlogctl->info_lck);
5455 5456
	Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
	RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5457
	SpinLockRelease(&xlogctl->info_lck);
5458 5459

	return RedoRecPtr;
V
WAL  
Vadim B. Mikheev 已提交
5460 5461
}

5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475
/*
 * 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 已提交
5476
	XLogRecPtr	recptr;
5477 5478 5479 5480 5481 5482 5483 5484

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

	return recptr;
}

5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500
/*
 * Get the time of the last xlog segment switch
 */
time_t
GetLastSegSwitchTime(void)
{
	time_t		result;

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

	return result;
}

5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511
/*
 * 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 已提交
5512 5513 5514
	uint32		ckptXidEpoch;
	TransactionId ckptXid;
	TransactionId nextXid;
5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540

	/* 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;
}

5541
/*
T
Tom Lane 已提交
5542
 * This must be called ONCE during postmaster or standalone-backend shutdown
5543 5544
 */
void
5545
ShutdownXLOG(int code, Datum arg)
5546
{
5547 5548
	ereport(LOG,
			(errmsg("shutting down")));
5549

5550
	CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5551
	ShutdownCLOG();
5552
	ShutdownSUBTRANS();
5553
	ShutdownMultiXact();
5554

5555 5556
	ereport(LOG,
			(errmsg("database system is shut down")));
5557 5558
}

5559
/*
5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573
 * Log start of a checkpoint.
 */
static void
LogCheckpointStart(int flags)
{
	elog(LOG, "checkpoint starting:%s%s%s%s%s%s",
		 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
		 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
		 (flags & CHECKPOINT_FORCE) ? " force" : "",
		 (flags & CHECKPOINT_WAIT) ? " wait" : "",
		 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
		 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
}

5574
/*
5575 5576 5577 5578 5579
 * Log end of a checkpoint.
 */
static void
LogCheckpointEnd(void)
{
B
Bruce Momjian 已提交
5580 5581 5582 5583 5584 5585
	long		write_secs,
				sync_secs,
				total_secs;
	int			write_usecs,
				sync_usecs,
				total_usecs;
5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608

	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);

	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,
B
Bruce Momjian 已提交
5609 5610 5611
		 write_secs, write_usecs / 1000,
		 sync_secs, sync_usecs / 1000,
		 total_secs, total_usecs / 1000);
5612 5613
}

T
Tom Lane 已提交
5614 5615
/*
 * Perform a checkpoint --- either during shutdown, or on-the-fly
5616
 *
5617 5618 5619
 * flags is a bitwise OR of the following:
 *	CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
 *	CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
5620
 *		ignoring checkpoint_completion_target parameter.
5621 5622 5623
 *	CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
 *		since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
 *
5624
 * Note: flags contains other bits, of interest here only for logging purposes.
5625 5626
 * In particular note that this routine is synchronous and does not pay
 * attention to CHECKPOINT_WAIT.
T
Tom Lane 已提交
5627
 */
5628
void
5629
CreateCheckPoint(int flags)
5630
{
5631
	bool		shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
5632 5633 5634
	CheckPoint	checkPoint;
	XLogRecPtr	recptr;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
B
Bruce Momjian 已提交
5635
	XLogRecData rdata;
5636
	uint32		freespace;
V
Vadim B. Mikheev 已提交
5637 5638
	uint32		_logId;
	uint32		_logSeg;
5639 5640
	TransactionId *inCommitXids;
	int			nInCommit;
V
Vadim B. Mikheev 已提交
5641

5642
	/*
B
Bruce Momjian 已提交
5643 5644 5645 5646
	 * 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.)
5647
	 */
5648
	LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5649

5650 5651 5652 5653 5654 5655 5656 5657 5658 5659
	/*
	 * 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();

5660 5661 5662
	/*
	 * Use a critical section to force system panic if we have trouble.
	 */
5663 5664
	START_CRIT_SECTION();

5665 5666 5667 5668 5669 5670
	if (shutdown)
	{
		ControlFile->state = DB_SHUTDOWNING;
		ControlFile->time = time(NULL);
		UpdateControlFile();
	}
T
Tom Lane 已提交
5671

5672
	/*
B
Bruce Momjian 已提交
5673 5674 5675
	 * 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.
5676 5677 5678 5679
	 */
	smgrpreckpt();

	/* Begin filling in the checkpoint WAL record */
5680
	MemSet(&checkPoint, 0, sizeof(checkPoint));
5681
	checkPoint.ThisTimeLineID = ThisTimeLineID;
T
Tom Lane 已提交
5682
	checkPoint.time = time(NULL);
5683

5684
	/*
5685 5686
	 * We must hold WALInsertLock while examining insert state to determine
	 * the checkpoint REDO pointer.
5687
	 */
5688
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
T
Tom Lane 已提交
5689 5690

	/*
B
Bruce Momjian 已提交
5691 5692 5693 5694 5695 5696 5697 5698
	 * 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 已提交
5699
	 *
5700 5701 5702 5703
	 * 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 已提交
5704
	 */
5705
	if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
T
Tom Lane 已提交
5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717
	{
		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)
		{
5718 5719
			LWLockRelease(WALInsertLock);
			LWLockRelease(CheckpointLock);
T
Tom Lane 已提交
5720 5721 5722 5723 5724 5725 5726 5727
			END_CRIT_SECTION();
			return;
		}
	}

	/*
	 * Compute new REDO record ptr = location of next XLOG record.
	 *
B
Bruce Momjian 已提交
5728 5729 5730 5731
	 * 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 已提交
5732 5733
	 */
	freespace = INSERT_FREESPACE(Insert);
5734 5735
	if (freespace < SizeOfXLogRecord)
	{
5736
		(void) AdvanceXLInsertBuffer(false);
T
Tom Lane 已提交
5737
		/* OK to ignore update return flag, since we will do flush anyway */
5738
		freespace = INSERT_FREESPACE(Insert);
5739
	}
T
Tom Lane 已提交
5740
	INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
B
Bruce Momjian 已提交
5741

T
Tom Lane 已提交
5742
	/*
B
Bruce Momjian 已提交
5743 5744
	 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
	 * must be done while holding the insert lock AND the info_lck.
5745
	 *
B
Bruce Momjian 已提交
5746
	 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
B
Bruce Momjian 已提交
5747 5748 5749 5750 5751
	 * 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 已提交
5752
	 */
5753 5754 5755 5756
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

5757
		SpinLockAcquire(&xlogctl->info_lck);
5758
		RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5759
		SpinLockRelease(&xlogctl->info_lck);
5760
	}
B
Bruce Momjian 已提交
5761

T
Tom Lane 已提交
5762
	/*
5763 5764
	 * Now we can release WAL insert lock, allowing other xacts to proceed
	 * while we are flushing disk buffers.
T
Tom Lane 已提交
5765
	 */
5766
	LWLockRelease(WALInsertLock);
5767

5768
	/*
B
Bruce Momjian 已提交
5769 5770
	 * If enabled, log checkpoint start.  We postpone this until now so as not
	 * to log anything if we decided to skip the checkpoint.
5771 5772 5773
	 */
	if (log_checkpoints)
		LogCheckpointStart(flags);
5774

5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789
	/*
	 * 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 已提交
5790 5791
	 * protected by different locks, but again that seems best on grounds of
	 * minimizing lock contention.)
5792
	 *
B
Bruce Momjian 已提交
5793 5794
	 * 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
5795 5796 5797 5798 5799 5800 5801
	 * 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 已提交
5802 5803 5804
		do
		{
			pg_usleep(10000L);	/* wait for 10 msec */
5805 5806 5807 5808
		} while (HaveTransactionsInCommit(inCommitXids, nInCommit));
	}
	pfree(inCommitXids);

5809 5810 5811
	/*
	 * Get the other info we need for the checkpoint record.
	 */
5812
	LWLockAcquire(XidGenLock, LW_SHARED);
5813
	checkPoint.nextXid = ShmemVariableCache->nextXid;
5814
	LWLockRelease(XidGenLock);
T
Tom Lane 已提交
5815

5816 5817 5818 5819 5820
	/* Increase XID epoch if we've wrapped around since last checkpoint */
	checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
	if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
		checkPoint.nextXidEpoch++;

5821
	LWLockAcquire(OidGenLock, LW_SHARED);
5822
	checkPoint.nextOid = ShmemVariableCache->nextOid;
5823 5824
	if (!shutdown)
		checkPoint.nextOid += ShmemVariableCache->oidCount;
5825
	LWLockRelease(OidGenLock);
5826

5827 5828 5829
	MultiXactGetCheckptMulti(shutdown,
							 &checkPoint.nextMulti,
							 &checkPoint.nextMultiOffset);
5830

T
Tom Lane 已提交
5831
	/*
B
Bruce Momjian 已提交
5832 5833
	 * Having constructed the checkpoint record, ensure all shmem disk buffers
	 * and commit-log buffers are flushed to disk.
5834
	 *
5835 5836
	 * 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
5837
	 * panic. Accordingly, exit critical section while doing it.
T
Tom Lane 已提交
5838
	 */
5839 5840
	END_CRIT_SECTION();

5841
	CheckPointGuts(checkPoint.redo, flags);
5842

5843 5844
	START_CRIT_SECTION();

T
Tom Lane 已提交
5845 5846 5847
	/*
	 * Now insert the checkpoint record into XLOG.
	 */
B
Bruce Momjian 已提交
5848
	rdata.data = (char *) (&checkPoint);
5849
	rdata.len = sizeof(checkPoint);
5850
	rdata.buffer = InvalidBuffer;
5851 5852
	rdata.next = NULL;

T
Tom Lane 已提交
5853 5854 5855 5856 5857 5858
	recptr = XLogInsert(RM_XLOG_ID,
						shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
						XLOG_CHECKPOINT_ONLINE,
						&rdata);

	XLogFlush(recptr);
5859

T
Tom Lane 已提交
5860
	/*
B
Bruce Momjian 已提交
5861 5862
	 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
	 * = end of actual checkpoint record.
T
Tom Lane 已提交
5863 5864
	 */
	if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5865 5866
		ereport(PANIC,
				(errmsg("concurrent transaction log activity while database system is shutting down")));
5867

T
Tom Lane 已提交
5868
	/*
5869 5870
	 * Select point at which we can truncate the log, which we base on the
	 * prior checkpoint's earliest info.
T
Tom Lane 已提交
5871
	 */
5872
	XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5873

T
Tom Lane 已提交
5874 5875 5876
	/*
	 * Update the control file.
	 */
5877
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5878 5879
	if (shutdown)
		ControlFile->state = DB_SHUTDOWNED;
T
Tom Lane 已提交
5880 5881 5882
	ControlFile->prevCheckPoint = ControlFile->checkPoint;
	ControlFile->checkPoint = ProcLastRecPtr;
	ControlFile->checkPointCopy = checkPoint;
5883 5884
	ControlFile->time = time(NULL);
	UpdateControlFile();
5885
	LWLockRelease(ControlFileLock);
5886

5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897
	/* 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);
	}

5898
	/*
B
Bruce Momjian 已提交
5899
	 * We are now done with critical updates; no need for system panic if we
5900
	 * have trouble while fooling with old log segments.
5901 5902 5903
	 */
	END_CRIT_SECTION();

5904 5905 5906 5907 5908
	/*
	 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
	 */
	smgrpostckpt();

V
Vadim B. Mikheev 已提交
5909
	/*
5910
	 * Delete old log files (those no longer needed even for previous
T
Tom Lane 已提交
5911
	 * checkpoint).
V
Vadim B. Mikheev 已提交
5912 5913 5914
	 */
	if (_logId || _logSeg)
	{
T
Tom Lane 已提交
5915
		PrevLogSeg(_logId, _logSeg);
5916
		RemoveOldXlogFiles(_logId, _logSeg, recptr);
V
Vadim B. Mikheev 已提交
5917 5918
	}

T
Tom Lane 已提交
5919
	/*
5920 5921
	 * 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 已提交
5922 5923
	 */
	if (!shutdown)
5924
		PreallocXlogFiles(recptr);
T
Tom Lane 已提交
5925

5926
	/*
B
Bruce Momjian 已提交
5927 5928 5929 5930 5931
	 * 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.
5932
	 */
5933
	if (!InRecovery)
5934
		TruncateSUBTRANS(GetOldestXmin(true, false));
5935

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

5940
	LWLockRelease(CheckpointLock);
5941
}
V
WAL  
Vadim B. Mikheev 已提交
5942

5943 5944 5945 5946 5947 5948 5949
/*
 * Flush all data in shared memory to disk, and fsync
 *
 * This is the common code shared between regular checkpoints and
 * recovery restartpoints.
 */
static void
5950
CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
5951 5952 5953 5954
{
	CheckPointCLOG();
	CheckPointSUBTRANS();
	CheckPointMultiXact();
B
Bruce Momjian 已提交
5955
	CheckPointBuffers(flags);	/* performs all required fsyncs */
5956 5957 5958 5959 5960 5961 5962
	/* We deliberately delay 2PC checkpointing as long as possible */
	CheckPointTwoPhase(checkPointRedo);
}

/*
 * Set a recovery restart point if appropriate
 *
5963
 * This is similar to CreateCheckPoint, but is used during WAL recovery
5964 5965 5966 5967 5968 5969 5970 5971
 * to establish a point from which recovery can roll forward without
 * replaying the entire recovery log.  This function is called each time
 * a checkpoint record is read from XLOG; it must determine whether a
 * restartpoint is needed or not.
 */
static void
RecoveryRestartPoint(const CheckPoint *checkPoint)
{
B
Bruce Momjian 已提交
5972 5973
	int			elapsed_secs;
	int			rmid;
5974 5975

	/*
B
Bruce Momjian 已提交
5976 5977
	 * Do nothing if the elapsed time since the last restartpoint is less than
	 * half of checkpoint_timeout.	(We use a value less than
5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997
	 * checkpoint_timeout so that variations in the timing of checkpoints on
	 * the master, or speed of transmission of WAL segments to a slave, won't
	 * make the slave skip a restartpoint once it's synced with the master.)
	 * Checking true elapsed time keeps us from doing restartpoints too often
	 * while rapidly scanning large amounts of WAL.
	 */
	elapsed_secs = time(NULL) - ControlFile->time;
	if (elapsed_secs < CheckPointTimeout / 2)
		return;

	/*
	 * 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()))
5998 5999 6000 6001 6002
			{
				elog(DEBUG2, "RM %d not safe to record restart point at %X/%X",
					 rmid,
					 checkPoint->redo.xlogid,
					 checkPoint->redo.xrecoff);
6003
				return;
6004
			}
6005 6006 6007 6008 6009
	}

	/*
	 * OK, force data out to disk
	 */
6010
	CheckPointGuts(checkPoint->redo, CHECKPOINT_IMMEDIATE);
6011 6012

	/*
B
Bruce Momjian 已提交
6013 6014 6015
	 * Update pg_control so that any subsequent crash will restart from this
	 * checkpoint.	Note: ReadRecPtr gives the XLOG address of the checkpoint
	 * record itself.
6016 6017 6018 6019 6020 6021 6022
	 */
	ControlFile->prevCheckPoint = ControlFile->checkPoint;
	ControlFile->checkPoint = ReadRecPtr;
	ControlFile->checkPointCopy = *checkPoint;
	ControlFile->time = time(NULL);
	UpdateControlFile();

6023
	ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
6024 6025
			(errmsg("recovery restart point at %X/%X",
					checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
6026 6027 6028 6029
	if (recoveryLastXTime)
		ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
				(errmsg("last completed transaction was at log time %s",
						timestamptz_to_str(recoveryLastXTime))));
6030 6031
}

T
Tom Lane 已提交
6032 6033 6034
/*
 * Write a NEXTOID log record
 */
6035 6036 6037
void
XLogPutNextOid(Oid nextOid)
{
B
Bruce Momjian 已提交
6038
	XLogRecData rdata;
6039

B
Bruce Momjian 已提交
6040
	rdata.data = (char *) (&nextOid);
6041
	rdata.len = sizeof(Oid);
6042
	rdata.buffer = InvalidBuffer;
6043 6044
	rdata.next = NULL;
	(void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
B
Bruce Momjian 已提交
6045

6046 6047
	/*
	 * We need not flush the NEXTOID record immediately, because any of the
B
Bruce Momjian 已提交
6048 6049 6050 6051 6052
	 * 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.
6053 6054
	 *
	 * Note, however, that the above statement only covers state "within" the
B
Bruce Momjian 已提交
6055 6056
	 * 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
6057
	 * change may reach disk before the NEXTOID WAL record does.  The impact
B
Bruce Momjian 已提交
6058 6059 6060 6061 6062
	 * 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.
6063 6064 6065
	 */
}

6066 6067 6068 6069 6070 6071 6072 6073 6074 6075
/*
 * 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.
 */
6076
XLogRecPtr
6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092
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;
}

T
Tom Lane 已提交
6093 6094 6095
/*
 * XLOG resource manager's routines
 */
V
WAL  
Vadim B. Mikheev 已提交
6096 6097 6098
void
xlog_redo(XLogRecPtr lsn, XLogRecord *record)
{
B
Bruce Momjian 已提交
6099
	uint8		info = record->xl_info & ~XLR_INFO_MASK;
6100

6101
	if (info == XLOG_NEXTOID)
6102
	{
B
Bruce Momjian 已提交
6103
		Oid			nextOid;
6104 6105 6106

		memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
		if (ShmemVariableCache->nextOid < nextOid)
T
Tom Lane 已提交
6107
		{
6108
			ShmemVariableCache->nextOid = nextOid;
T
Tom Lane 已提交
6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120
			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;
6121 6122
		MultiXactSetNextMXact(checkPoint.nextMulti,
							  checkPoint.nextMultiOffset);
B
Bruce Momjian 已提交
6123

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

6128
		/*
B
Bruce Momjian 已提交
6129
		 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
6130 6131 6132 6133 6134 6135 6136 6137
		 */
		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",
B
Bruce Momjian 已提交
6138
								checkPoint.ThisTimeLineID, ThisTimeLineID)));
6139 6140 6141
			/* Following WAL records should be run with new TLI */
			ThisTimeLineID = checkPoint.ThisTimeLineID;
		}
6142 6143

		RecoveryRestartPoint(&checkPoint);
T
Tom Lane 已提交
6144 6145 6146 6147 6148 6149
	}
	else if (info == XLOG_CHECKPOINT_ONLINE)
	{
		CheckPoint	checkPoint;

		memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6150
		/* In an ONLINE checkpoint, treat the counters like NEXTOID */
6151 6152
		if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
								  checkPoint.nextXid))
T
Tom Lane 已提交
6153 6154 6155 6156 6157 6158
			ShmemVariableCache->nextXid = checkPoint.nextXid;
		if (ShmemVariableCache->nextOid < checkPoint.nextOid)
		{
			ShmemVariableCache->nextOid = checkPoint.nextOid;
			ShmemVariableCache->oidCount = 0;
		}
6159 6160
		MultiXactAdvanceNextMXact(checkPoint.nextMulti,
								  checkPoint.nextMultiOffset);
6161 6162 6163 6164 6165

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

6166 6167
		/* TLI should not change in an on-line checkpoint */
		if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6168
			ereport(PANIC,
6169 6170
					(errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
							checkPoint.ThisTimeLineID, ThisTimeLineID)));
6171 6172

		RecoveryRestartPoint(&checkPoint);
6173
	}
6174 6175 6176 6177
	else if (info == XLOG_NOOP)
	{
		/* nothing to do here */
	}
6178 6179 6180 6181
	else if (info == XLOG_SWITCH)
	{
		/* nothing to do here */
	}
V
WAL  
Vadim B. Mikheev 已提交
6182
}
B
Bruce Momjian 已提交
6183

V
WAL  
Vadim B. Mikheev 已提交
6184
void
6185
xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
V
WAL  
Vadim B. Mikheev 已提交
6186
{
B
Bruce Momjian 已提交
6187
	uint8		info = xl_info & ~XLR_INFO_MASK;
V
WAL  
Vadim B. Mikheev 已提交
6188

T
Tom Lane 已提交
6189 6190
	if (info == XLOG_CHECKPOINT_SHUTDOWN ||
		info == XLOG_CHECKPOINT_ONLINE)
V
WAL  
Vadim B. Mikheev 已提交
6191
	{
B
Bruce Momjian 已提交
6192 6193
		CheckPoint *checkpoint = (CheckPoint *) rec;

6194
		appendStringInfo(buf, "checkpoint: redo %X/%X; "
B
Bruce Momjian 已提交
6195 6196 6197 6198 6199 6200 6201 6202
						 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
						 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
						 checkpoint->ThisTimeLineID,
						 checkpoint->nextXidEpoch, checkpoint->nextXid,
						 checkpoint->nextOid,
						 checkpoint->nextMulti,
						 checkpoint->nextMultiOffset,
				 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
T
Tom Lane 已提交
6203
	}
6204 6205 6206 6207
	else if (info == XLOG_NOOP)
	{
		appendStringInfo(buf, "xlog no-op");
	}
6208 6209
	else if (info == XLOG_NEXTOID)
	{
B
Bruce Momjian 已提交
6210
		Oid			nextOid;
6211 6212

		memcpy(&nextOid, rec, sizeof(Oid));
6213
		appendStringInfo(buf, "nextOid: %u", nextOid);
6214
	}
6215 6216 6217 6218
	else if (info == XLOG_SWITCH)
	{
		appendStringInfo(buf, "xlog switch");
	}
V
WAL  
Vadim B. Mikheev 已提交
6219
	else
6220
		appendStringInfo(buf, "UNKNOWN");
V
WAL  
Vadim B. Mikheev 已提交
6221 6222
}

6223
#ifdef WAL_DEBUG
6224

V
WAL  
Vadim B. Mikheev 已提交
6225
static void
6226
xlog_outrec(StringInfo buf, XLogRecord *record)
V
WAL  
Vadim B. Mikheev 已提交
6227
{
B
Bruce Momjian 已提交
6228
	int			i;
6229

6230
	appendStringInfo(buf, "prev %X/%X; xid %u",
6231 6232
					 record->xl_prev.xlogid, record->xl_prev.xrecoff,
					 record->xl_xid);
6233

6234
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
6235
	{
6236
		if (record->xl_info & XLR_SET_BKP_BLOCK(i))
B
Bruce Momjian 已提交
6237
			appendStringInfo(buf, "; bkpb%d", i + 1);
6238 6239
	}

6240
	appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
V
WAL  
Vadim B. Mikheev 已提交
6241
}
B
Bruce Momjian 已提交
6242
#endif   /* WAL_DEBUG */
6243 6244 6245


/*
6246
 * GUC support
6247
 */
6248
const char *
6249
assign_xlog_sync_method(const char *method, bool doit, GucSource source)
6250
{
B
Bruce Momjian 已提交
6251 6252
	int			new_sync_method;
	int			new_sync_bit;
6253

6254
	if (pg_strcasecmp(method, "fsync") == 0)
6255 6256 6257 6258
	{
		new_sync_method = SYNC_METHOD_FSYNC;
		new_sync_bit = 0;
	}
6259 6260 6261 6262 6263 6264 6265
#ifdef HAVE_FSYNC_WRITETHROUGH
	else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
	{
		new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
		new_sync_bit = 0;
	}
#endif
6266
#ifdef HAVE_FDATASYNC
6267
	else if (pg_strcasecmp(method, "fdatasync") == 0)
6268 6269 6270 6271 6272 6273
	{
		new_sync_method = SYNC_METHOD_FDATASYNC;
		new_sync_bit = 0;
	}
#endif
#ifdef OPEN_SYNC_FLAG
6274
	else if (pg_strcasecmp(method, "open_sync") == 0)
6275 6276 6277 6278 6279 6280
	{
		new_sync_method = SYNC_METHOD_OPEN;
		new_sync_bit = OPEN_SYNC_FLAG;
	}
#endif
#ifdef OPEN_DATASYNC_FLAG
6281
	else if (pg_strcasecmp(method, "open_datasync") == 0)
6282 6283 6284 6285 6286 6287
	{
		new_sync_method = SYNC_METHOD_OPEN;
		new_sync_bit = OPEN_DATASYNC_FLAG;
	}
#endif
	else
6288
		return NULL;
6289

6290 6291 6292
	if (!doit)
		return method;

6293 6294 6295
	if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
	{
		/*
B
Bruce Momjian 已提交
6296 6297
		 * 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 已提交
6298 6299
		 * changing, close the log file so it will be reopened (with new flag
		 * bit) at next use.
6300 6301 6302 6303
		 */
		if (openLogFile >= 0)
		{
			if (pg_fsync(openLogFile) != 0)
6304 6305
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
6306 6307
						 errmsg("could not fsync log file %u, segment %u: %m",
								openLogId, openLogSeg)));
6308
			if (open_sync_bit != new_sync_bit)
6309
				XLogFileClose();
6310 6311 6312 6313
		}
		sync_method = new_sync_method;
		open_sync_bit = new_sync_bit;
	}
6314 6315

	return method;
6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326
}


/*
 * Issue appropriate kind of fsync (if any) on the current XLOG output file
 */
static void
issue_xlog_fsync(void)
{
	switch (sync_method)
	{
6327
		case SYNC_METHOD_FSYNC:
6328
			if (pg_fsync_no_writethrough(openLogFile) != 0)
6329 6330
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
6331 6332
						 errmsg("could not fsync log file %u, segment %u: %m",
								openLogId, openLogSeg)));
6333
			break;
6334 6335 6336 6337 6338
#ifdef HAVE_FSYNC_WRITETHROUGH
		case SYNC_METHOD_FSYNC_WRITETHROUGH:
			if (pg_fsync_writethrough(openLogFile) != 0)
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
6339 6340
						 errmsg("could not fsync write-through log file %u, segment %u: %m",
								openLogId, openLogSeg)));
6341 6342
			break;
#endif
6343 6344 6345
#ifdef HAVE_FDATASYNC
		case SYNC_METHOD_FDATASYNC:
			if (pg_fdatasync(openLogFile) != 0)
6346 6347
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
6348 6349
					errmsg("could not fdatasync log file %u, segment %u: %m",
						   openLogId, openLogSeg)));
6350 6351 6352 6353 6354 6355
			break;
#endif
		case SYNC_METHOD_OPEN:
			/* write synced it already */
			break;
		default:
6356
			elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6357 6358 6359
			break;
	}
}
6360 6361 6362 6363 6364 6365 6366 6367 6368


/*
 * 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
6369
 * starting WAL location for the dump.
6370 6371 6372 6373 6374 6375 6376
 */
Datum
pg_start_backup(PG_FUNCTION_ARGS)
{
	text	   *backupid = PG_GETARG_TEXT_P(0);
	text	   *result;
	char	   *backupidstr;
6377
	XLogRecPtr	checkpointloc;
6378
	XLogRecPtr	startpoint;
6379
	pg_time_t	stamp_time;
6380 6381 6382 6383 6384 6385 6386
	char		strfbuf[128];
	char		xlogfilename[MAXFNAMELEN];
	uint32		_logId;
	uint32		_logSeg;
	struct stat stat_buf;
	FILE	   *fp;

B
Bruce Momjian 已提交
6387
	if (!superuser())
6388 6389
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6390
				 errmsg("must be superuser to run a backup")));
6391 6392 6393 6394

	if (!XLogArchivingActive())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6395 6396 6397 6398 6399 6400 6401 6402 6403
				 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.")));
6404

6405
	backupidstr = DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
6406
												 PointerGetDatum(backupid)));
B
Bruce Momjian 已提交
6407

6408
	/*
6409 6410 6411
	 * 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 已提交
6412 6413 6414 6415 6416 6417 6418 6419 6420
	 * 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.)
6421
	 *
B
Bruce Momjian 已提交
6422 6423
	 * We must hold WALInsertLock to change the value of forcePageWrites, to
	 * ensure adequate interlocking against XLogInsert().
6424
	 */
6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435
	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 已提交
6436

6437 6438 6439 6440
	/* Use a TRY block to ensure we release forcePageWrites if fail below */
	PG_TRY();
	{
		/*
B
Bruce Momjian 已提交
6441
		 * Force a CHECKPOINT.	Aside from being necessary to prevent torn
6442 6443 6444
		 * 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.
6445 6446
		 *
		 * We don't use CHECKPOINT_IMMEDIATE, hence this can take awhile.
6447
		 */
6448
		RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT);
6449

6450 6451 6452 6453 6454 6455 6456 6457 6458
		/*
		 * 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.
		 */
		LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
		checkpointloc = ControlFile->checkPoint;
		startpoint = ControlFile->checkPointCopy.redo;
		LWLockRelease(ControlFileLock);
B
Bruce Momjian 已提交
6459

6460 6461
		XLByteToSeg(startpoint, _logId, _logSeg);
		XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
B
Bruce Momjian 已提交
6462

6463 6464 6465 6466 6467
		/* 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));
6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493

		/*
		 * 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)
6494 6495
			ereport(ERROR,
					(errcode_for_file_access(),
6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507
					 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",
6508
							BACKUP_LABEL_FILE)));
6509
	}
6510 6511 6512 6513 6514 6515
	PG_CATCH();
	{
		/* Turn off forcePageWrites on failure */
		LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
		XLogCtl->Insert.forcePageWrites = false;
		LWLockRelease(WALInsertLock);
B
Bruce Momjian 已提交
6516

6517 6518 6519
		PG_RE_THROW();
	}
	PG_END_TRY();
B
Bruce Momjian 已提交
6520

6521
	/*
6522
	 * We're done.  As a convenience, return the starting WAL location.
6523 6524 6525 6526
	 */
	snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
			 startpoint.xlogid, startpoint.xrecoff);
	result = DatumGetTextP(DirectFunctionCall1(textin,
B
Bruce Momjian 已提交
6527
											 CStringGetDatum(xlogfilename)));
6528 6529 6530 6531 6532 6533 6534 6535 6536
	PG_RETURN_TEXT_P(result);
}

/*
 * pg_stop_backup: finish taking an on-line backup dump
 *
 * We remove the backup label file created by pg_start_backup, and instead
 * create a backup history file in pg_xlog (whence it will immediately be
 * archived).  The backup history file contains the same info found in
6537
 * the label file, plus the backup-end time and WAL location.
6538 6539 6540 6541 6542 6543 6544
 */
Datum
pg_stop_backup(PG_FUNCTION_ARGS)
{
	text	   *result;
	XLogRecPtr	startpoint;
	XLogRecPtr	stoppoint;
6545
	pg_time_t	stamp_time;
6546
	char		strfbuf[128];
6547
	char		histfilepath[MAXPGPATH];
6548 6549 6550 6551 6552 6553 6554 6555 6556
	char		startxlogfilename[MAXFNAMELEN];
	char		stopxlogfilename[MAXFNAMELEN];
	uint32		_logId;
	uint32		_logSeg;
	FILE	   *lfp;
	FILE	   *fp;
	char		ch;
	int			ich;

B
Bruce Momjian 已提交
6557
	if (!superuser())
6558 6559 6560
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 (errmsg("must be superuser to run a backup"))));
B
Bruce Momjian 已提交
6561

6562
	/*
6563
	 * OK to clear forcePageWrites
6564 6565
	 */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6566
	XLogCtl->Insert.forcePageWrites = false;
6567 6568
	LWLockRelease(WALInsertLock);

6569
	/*
B
Bruce Momjian 已提交
6570 6571 6572
	 * 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. We'll report
	 * the end address of the XLOG SWITCH record as the backup stopping point.
6573 6574 6575
	 */
	stoppoint = RequestXLogSwitch();

6576 6577
	XLByteToSeg(stoppoint, _logId, _logSeg);
	XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
B
Bruce Momjian 已提交
6578

6579 6580 6581 6582 6583
	/* 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));
B
Bruce Momjian 已提交
6584

6585 6586 6587
	/*
	 * Open the existing label file
	 */
6588
	lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6589 6590 6591 6592 6593 6594
	if (!lfp)
	{
		if (errno != ENOENT)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
6595
							BACKUP_LABEL_FILE)));
6596 6597 6598 6599
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("a backup is not in progress")));
	}
B
Bruce Momjian 已提交
6600

6601
	/*
B
Bruce Momjian 已提交
6602 6603
	 * Read and parse the START WAL LOCATION line (this code is pretty crude,
	 * but we are not expecting any variability in the file format).
6604 6605 6606 6607 6608 6609
	 */
	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),
6610
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
6611

6612 6613 6614 6615
	/*
	 * Write the backup history file
	 */
	XLByteToSeg(startpoint, _logId, _logSeg);
6616
	BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6617
						  startpoint.xrecoff % XLogSegSize);
6618
	fp = AllocateFile(histfilepath, "w");
6619 6620 6621 6622
	if (!fp)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m",
6623
						histfilepath)));
6624 6625 6626 6627
	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);
6628
	/* transfer remaining lines from label to history file */
6629 6630 6631 6632 6633 6634 6635
	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",
6636
						histfilepath)));
B
Bruce Momjian 已提交
6637

6638 6639 6640 6641 6642 6643 6644
	/*
	 * 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",
6645 6646
						BACKUP_LABEL_FILE)));
	if (unlink(BACKUP_LABEL_FILE) != 0)
6647 6648 6649
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not remove file \"%s\": %m",
6650
						BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
6651

6652
	/*
B
Bruce Momjian 已提交
6653 6654 6655
	 * 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.
6656
	 */
6657
	CleanupBackupHistory();
B
Bruce Momjian 已提交
6658

6659
	/*
6660
	 * We're done.  As a convenience, return the ending WAL location.
6661 6662 6663 6664
	 */
	snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
			 stoppoint.xlogid, stoppoint.xrecoff);
	result = DatumGetTextP(DirectFunctionCall1(textin,
B
Bruce Momjian 已提交
6665
										 CStringGetDatum(stopxlogfilename)));
6666 6667
	PG_RETURN_TEXT_P(result);
}
6668

6669 6670 6671 6672 6673 6674 6675
/*
 * pg_switch_xlog: switch to next xlog file
 */
Datum
pg_switch_xlog(PG_FUNCTION_ARGS)
{
	text	   *result;
B
Bruce Momjian 已提交
6676
	XLogRecPtr	switchpoint;
6677 6678 6679 6680 6681
	char		location[MAXFNAMELEN];

	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
B
Bruce Momjian 已提交
6682
			 (errmsg("must be superuser to switch transaction log files"))));
6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696

	switchpoint = RequestXLogSwitch();

	/*
	 * As a convenience, return the WAL location of the switch record
	 */
	snprintf(location, sizeof(location), "%X/%X",
			 switchpoint.xlogid, switchpoint.xrecoff);
	result = DatumGetTextP(DirectFunctionCall1(textin,
											   CStringGetDatum(location)));
	PG_RETURN_TEXT_P(result);
}

/*
6697 6698 6699 6700 6701
 * 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.
6702 6703 6704
 */
Datum
pg_current_xlog_location(PG_FUNCTION_ARGS)
6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733
{
	text	   *result;
	char		location[MAXFNAMELEN];

	/* 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);

	result = DatumGetTextP(DirectFunctionCall1(textin,
											   CStringGetDatum(location)));
	PG_RETURN_TEXT_P(result);
}

/*
 * 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)
6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774
{
	text	   *result;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecPtr	current_recptr;
	char		location[MAXFNAMELEN];

	/*
	 * 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);

	result = DatumGetTextP(DirectFunctionCall1(textin,
											   CStringGetDatum(location)));
	PG_RETURN_TEXT_P(result);
}

/*
 * 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 已提交
6775 6776 6777 6778 6779
	Datum		values[2];
	bool		isnull[2];
	TupleDesc	resultTupleDesc;
	HeapTuple	resultHeapTuple;
	Datum		result;
6780

6781 6782 6783
	/*
	 * Read input and parse
	 */
6784
	locationstr = DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
6785
												 PointerGetDatum(location)));
6786 6787 6788 6789

	if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
P
Peter Eisentraut 已提交
6790
				 errmsg("could not parse transaction log location \"%s\"",
6791 6792 6793 6794 6795
						locationstr)));

	locationpoint.xlogid = uxlogid;
	locationpoint.xrecoff = uxrecoff;

6796
	/*
B
Bruce Momjian 已提交
6797 6798
	 * Construct a tuple descriptor for the result row.  This must match this
	 * function's pg_proc entry!
6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810
	 */
	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
	 */
6811 6812 6813
	XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
	XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);

6814 6815 6816 6817 6818 6819 6820
	values[0] = DirectFunctionCall1(textin,
									CStringGetDatum(xlogfilename));
	isnull[0] = false;

	/*
	 * offset
	 */
6821 6822
	xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;

6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833
	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);
6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853
}

/*
 * 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);
	text	   *result;
	char	   *locationstr;
	unsigned int uxlogid;
	unsigned int uxrecoff;
	uint32		xlogid;
	uint32		xlogseg;
	XLogRecPtr	locationpoint;
	char		xlogfilename[MAXFNAMELEN];

	locationstr = DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
6854
												 PointerGetDatum(location)));
6855 6856 6857 6858

	if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
P
Peter Eisentraut 已提交
6859
				 errmsg("could not parse transaction log location \"%s\"",
6860 6861 6862 6863 6864 6865 6866 6867 6868
						locationstr)));

	locationpoint.xlogid = uxlogid;
	locationpoint.xrecoff = uxrecoff;

	XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
	XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);

	result = DatumGetTextP(DirectFunctionCall1(textin,
B
Bruce Momjian 已提交
6869
											 CStringGetDatum(xlogfilename)));
6870 6871 6872
	PG_RETURN_TEXT_P(result);
}

6873 6874 6875 6876 6877
/*
 * 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 已提交
6878
 * identified by the label file, NOT what pg_control says.	This avoids the
6879 6880 6881 6882 6883
 * 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.
 *
 * We also attempt to retrieve the corresponding backup history file.
6884
 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6885 6886 6887 6888 6889 6890
 * points.
 *
 * Returns TRUE if a backup_label was found (and fills the checkpoint
 * location into *checkPointLoc); returns FALSE if not.
 */
static bool
6891
read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905
{
	XLogRecPtr	startpoint;
	XLogRecPtr	stoppoint;
	char		histfilename[MAXFNAMELEN];
	char		histfilepath[MAXPGPATH];
	char		startxlogfilename[MAXFNAMELEN];
	char		stopxlogfilename[MAXFNAMELEN];
	TimeLineID	tli;
	uint32		_logId;
	uint32		_logSeg;
	FILE	   *lfp;
	FILE	   *fp;
	char		ch;

6906 6907 6908 6909
	/* Default is to not constrain recovery stop point */
	minRecoveryLoc->xlogid = 0;
	minRecoveryLoc->xrecoff = 0;

6910 6911 6912
	/*
	 * See if label file is present
	 */
6913
	lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6914 6915 6916 6917 6918 6919
	if (!lfp)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
6920
							BACKUP_LABEL_FILE)));
6921 6922
		return false;			/* it's not there, all is fine */
	}
B
Bruce Momjian 已提交
6923

6924
	/*
B
Bruce Momjian 已提交
6925 6926 6927
	 * 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).
6928 6929 6930 6931 6932 6933
	 */
	if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
			   &startpoint.xlogid, &startpoint.xrecoff, &tli,
			   startxlogfilename, &ch) != 5 || ch != '\n')
		ereport(FATAL,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6934
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6935 6936 6937 6938 6939
	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),
6940
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6941 6942 6943 6944
	if (ferror(lfp) || FreeFile(lfp))
		ereport(FATAL,
				(errcode_for_file_access(),
				 errmsg("could not read file \"%s\": %m",
6945
						BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
6946

6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959
	/*
	 * Try to retrieve the backup history file (no error if we can't)
	 */
	XLByteToSeg(startpoint, _logId, _logSeg);
	BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
						  startpoint.xrecoff % XLogSegSize);

	if (InArchiveRecovery)
		RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
	else
		BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
							  startpoint.xrecoff % XLogSegSize);

B
Bruce Momjian 已提交
6960
	fp = AllocateFile(histfilepath, "r");
6961 6962 6963 6964 6965 6966
	if (fp)
	{
		/*
		 * Parse history file to identify stop point.
		 */
		if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
B
Bruce Momjian 已提交
6967
				   &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6968 6969 6970
				   &ch) != 4 || ch != '\n')
			ereport(FATAL,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
B
Bruce Momjian 已提交
6971
					 errmsg("invalid data in file \"%s\"", histfilename)));
6972
		if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
B
Bruce Momjian 已提交
6973
				   &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6974 6975 6976
				   &ch) != 4 || ch != '\n')
			ereport(FATAL,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
B
Bruce Momjian 已提交
6977
					 errmsg("invalid data in file \"%s\"", histfilename)));
6978
		*minRecoveryLoc = stoppoint;
6979 6980 6981 6982 6983 6984 6985 6986 6987 6988
		if (ferror(fp) || FreeFile(fp))
			ereport(FATAL,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
							histfilepath)));
	}

	return true;
}

6989 6990 6991 6992 6993 6994
/*
 * Error context callback for errors occurring during rm_redo().
 */
static void
rm_redo_error_callback(void *arg)
{
B
Bruce Momjian 已提交
6995 6996
	XLogRecord *record = (XLogRecord *) arg;
	StringInfoData buf;
6997 6998

	initStringInfo(&buf);
6999 7000
	RmgrTable[record->xl_rmid].rm_desc(&buf,
									   record->xl_info,
7001 7002 7003 7004 7005 7006 7007 7008
									   XLogRecGetData(record));

	/* don't bother emitting empty description */
	if (buf.len > 0)
		errcontext("xlog redo %s", buf.data);

	pfree(buf.data);
}