xlog.c 210.7 KB
Newer Older
1
/*-------------------------------------------------------------------------
2 3
 *
 * xlog.c
4
 *		PostgreSQL transaction log manager
5 6
 *
 *
7
 * Portions Copyright (c) 1996-2008, 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.314 2008/06/12 09:12:30 heikki Exp $
11 12 13
 *
 *-------------------------------------------------------------------------
 */
14

15 16
#include "postgres.h"

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

25
#include "access/clog.h"
26
#include "access/multixact.h"
27
#include "access/subtrans.h"
28
#include "access/transam.h"
29
#include "access/tuptoaster.h"
30
#include "access/twophase.h"
31
#include "access/xact.h"
32
#include "access/xlog_internal.h"
33
#include "access/xlogutils.h"
34
#include "catalog/catversion.h"
T
Tom Lane 已提交
35
#include "catalog/pg_control.h"
36 37
#include "catalog/pg_type.h"
#include "funcapi.h"
38
#include "miscadmin.h"
39
#include "pgstat.h"
40
#include "postmaster/bgwriter.h"
41
#include "storage/bufmgr.h"
42
#include "storage/fd.h"
43
#include "storage/ipc.h"
44
#include "storage/pmsignal.h"
45
#include "storage/procarray.h"
46
#include "storage/smgr.h"
47
#include "storage/spin.h"
48
#include "utils/builtins.h"
49
#include "utils/pg_locale.h"
50
#include "utils/ps_status.h"
51

52

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


T
Tom Lane 已提交
60 61
/* User-settable parameters */
int			CheckPointSegments = 3;
V
Vadim B. Mikheev 已提交
62
int			XLOGbuffers = 8;
63
int			XLogArchiveTimeout = 0;
64
bool		XLogArchiveMode = false;
65
char	   *XLogArchiveCommand = NULL;
66
bool		fullPageWrites = true;
67
bool		log_checkpoints = false;
68
int 		sync_method = DEFAULT_SYNC_METHOD;
T
Tom Lane 已提交
69

70 71 72 73
#ifdef WAL_DEBUG
bool		XLOG_DEBUG = false;
#endif

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

87 88 89 90
/*
 * GUC support
 */
const struct config_enum_entry sync_method_options[] = {
91
	{"fsync", SYNC_METHOD_FSYNC, false},
92
#ifdef HAVE_FSYNC_WRITETHROUGH
93
	{"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
94 95
#endif
#ifdef HAVE_FDATASYNC
96
	{"fdatasync", SYNC_METHOD_FDATASYNC, false},
97 98
#endif
#ifdef OPEN_SYNC_FLAG
99
	{"open_sync", SYNC_METHOD_OPEN, false},
100 101
#endif
#ifdef OPEN_DATASYNC_FLAG
102
	{"open_datasync", SYNC_METHOD_OPEN_DSYNC, false},
103
#endif
104
	{NULL, 0, false}
105
};
T
Tom Lane 已提交
106

107 108 109 110 111 112 113
/*
 * 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 已提交
114
/*
115 116
 * ThisTimeLineID will be same in all backends --- it identifies current
 * WAL timeline for the database system.
T
Tom Lane 已提交
117
 */
118
TimeLineID	ThisTimeLineID = 0;
V
WAL  
Vadim B. Mikheev 已提交
119

120
/* Are we doing recovery from XLOG? */
T
Tom Lane 已提交
121
bool		InRecovery = false;
B
Bruce Momjian 已提交
122

123
/* Are we recovering using offline XLOG archives? */
B
Bruce Momjian 已提交
124 125
static bool InArchiveRecovery = false;

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

129 130
/* options taken from recovery.conf */
static char *recoveryRestoreCommand = NULL;
131 132 133
static bool recoveryTarget = false;
static bool recoveryTargetExact = false;
static bool recoveryTargetInclusive = true;
134
static bool recoveryLogRestartpoints = false;
B
Bruce Momjian 已提交
135
static TransactionId recoveryTargetXid;
136
static TimestampTz recoveryTargetTime;
137
static TimestampTz recoveryLastXTime = 0;
138

139
/* if recoveryStopsHere returns true, it saves actual stop xid/time here */
B
Bruce Momjian 已提交
140
static TransactionId recoveryStopXid;
141
static TimestampTz recoveryStopTime;
B
Bruce Momjian 已提交
142
static bool recoveryStopAfter;
143 144 145 146 147 148 149 150 151 152 153 154 155

/*
 * 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 已提交
156
 * first list member).	Only these TLIs are expected to be seen in the WAL
157 158 159 160 161 162 163 164 165
 * 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 已提交
166 167 168
static TimeLineID recoveryTargetTLI;
static List *expectedTLIs;
static TimeLineID curFileTLI;
169

T
Tom Lane 已提交
170 171
/*
 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
172 173 174 175
 * 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 已提交
176 177
 */
static XLogRecPtr ProcLastRecPtr = {0, 0};
178

179
XLogRecPtr	XactLastRecEnd = {0, 0};
180

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

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

T
Tom Lane 已提交
250
typedef struct XLogwrtRqst
251
{
T
Tom Lane 已提交
252 253
	XLogRecPtr	Write;			/* last byte + 1 to write out */
	XLogRecPtr	Flush;			/* last byte + 1 to flush */
254
} XLogwrtRqst;
255

256 257 258 259 260 261
typedef struct XLogwrtResult
{
	XLogRecPtr	Write;			/* last byte + 1 written out */
	XLogRecPtr	Flush;			/* last byte + 1 flushed */
} XLogwrtResult;

T
Tom Lane 已提交
262 263 264
/*
 * Shared state data for XLogInsert.
 */
265 266
typedef struct XLogCtlInsert
{
B
Bruce Momjian 已提交
267 268
	XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
	XLogRecPtr	PrevRecord;		/* start of previously-inserted record */
269
	int			curridx;		/* current block index in cache */
B
Bruce Momjian 已提交
270 271 272
	XLogPageHeader currpage;	/* points to header of block in cache */
	char	   *currpos;		/* current insertion point in cache */
	XLogRecPtr	RedoRecPtr;		/* current redo point for insertions */
273
	bool		forcePageWrites;	/* forcing full-page writes for PITR? */
274 275
} XLogCtlInsert;

T
Tom Lane 已提交
276 277 278
/*
 * Shared state data for XLogWrite/XLogFlush.
 */
279 280
typedef struct XLogCtlWrite
{
B
Bruce Momjian 已提交
281 282
	XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
	int			curridx;		/* cache index of next block to write */
283
	pg_time_t	lastSegSwitchTime;		/* time of last xlog segment switch */
284 285
} XLogCtlWrite;

T
Tom Lane 已提交
286 287 288
/*
 * Total shared-memory state for XLOG.
 */
289 290
typedef struct XLogCtlData
{
291
	/* Protected by WALInsertLock: */
B
Bruce Momjian 已提交
292
	XLogCtlInsert Insert;
293

T
Tom Lane 已提交
294
	/* Protected by info_lck: */
B
Bruce Momjian 已提交
295 296
	XLogwrtRqst LogwrtRqst;
	XLogwrtResult LogwrtResult;
297 298
	uint32		ckptXidEpoch;	/* nextXID & epoch of latest checkpoint */
	TransactionId ckptXid;
B
Bruce Momjian 已提交
299
	XLogRecPtr	asyncCommitLSN; /* LSN of newest async commit */
300

301
	/* Protected by WALWriteLock: */
B
Bruce Momjian 已提交
302 303
	XLogCtlWrite Write;

T
Tom Lane 已提交
304
	/*
B
Bruce Momjian 已提交
305 306 307
	 * 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 已提交
308
	 */
B
Bruce Momjian 已提交
309
	char	   *pages;			/* buffers for unwritten XLOG pages */
310
	XLogRecPtr *xlblocks;		/* 1st byte ptr-s + XLOG_BLCKSZ */
311
	int			XLogCacheBlck;	/* highest allocated xlog buffer index */
312
	TimeLineID	ThisTimeLineID;
T
Tom Lane 已提交
313

314
	slock_t		info_lck;		/* locks shared variables shown above */
315 316
} XLogCtlData;

317
static XLogCtlData *XLogCtl = NULL;
318

319
/*
T
Tom Lane 已提交
320
 * We maintain an image of pg_control in shared memory.
321
 */
322
static ControlFileData *ControlFile = NULL;
323

T
Tom Lane 已提交
324 325 326 327 328
/*
 * 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.
 */
329

T
Tom Lane 已提交
330 331
/* Free space remaining in the current xlog page buffer */
#define INSERT_FREESPACE(Insert)  \
332
	(XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
T
Tom Lane 已提交
333 334 335 336 337 338

/* Construct XLogRecPtr value for current insertion point */
#define INSERT_RECPTR(recptr,Insert,curridx)  \
	( \
	  (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
	  (recptr).xrecoff = \
B
Bruce Momjian 已提交
339
		XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
T
Tom Lane 已提交
340 341 342 343 344 345 346
	)

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

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

T
Tom Lane 已提交
348 349 350 351
/*
 * Private, possibly out-of-date copy of shared LogwrtResult.
 * See discussion above.
 */
352
static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
353

T
Tom Lane 已提交
354 355 356 357 358 359 360 361 362 363
/*
 * 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;
364

T
Tom Lane 已提交
365 366 367 368 369 370
/*
 * 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.
 */
371 372 373 374
static int	readFile = -1;
static uint32 readId = 0;
static uint32 readSeg = 0;
static uint32 readOff = 0;
B
Bruce Momjian 已提交
375

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

379 380 381 382
/* Buffer for current ReadRecord result (expandable) */
static char *readRecordBuf = NULL;
static uint32 readRecordBufSize = 0;

T
Tom Lane 已提交
383
/* State information for XLOG reading */
B
Bruce Momjian 已提交
384 385
static XLogRecPtr ReadRecPtr;	/* start of last record read */
static XLogRecPtr EndRecPtr;	/* end+1 of last record read */
386
static XLogRecord *nextRecord = NULL;
387
static TimeLineID lastPageTLI = 0;
388

V
WAL  
Vadim B. Mikheev 已提交
389 390
static bool InRedo = false;

391

392 393
static void XLogArchiveNotify(const char *xlog);
static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
394
static bool XLogArchiveCheckDone(const char *xlog, bool create_if_missing);
395 396
static void XLogArchiveCleanup(const char *xlog);
static void readRecoveryCommandFile(void);
397
static void exitArchiveRecovery(TimeLineID endTLI,
B
Bruce Momjian 已提交
398
					uint32 endLogId, uint32 endLogSeg);
399
static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
400
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
T
Tom Lane 已提交
401

402
static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
B
Bruce Momjian 已提交
403
				XLogRecPtr *lsn, BkpBlock *bkpb);
404 405
static bool AdvanceXLInsertBuffer(bool new_segment);
static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
B
Bruce Momjian 已提交
406 407
static int XLogFileInit(uint32 log, uint32 seg,
			 bool *use_existent, bool use_lock);
408 409
static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
410
					   bool use_lock);
411 412
static int	XLogFileOpen(uint32 log, uint32 seg);
static int	XLogFileRead(uint32 log, uint32 seg, int emode);
B
Bruce Momjian 已提交
413
static void XLogFileClose(void);
414
static bool RestoreArchivedFile(char *path, const char *xlogfname,
B
Bruce Momjian 已提交
415
					const char *recovername, off_t expectedSize);
416 417
static void PreallocXlogFiles(XLogRecPtr endptr);
static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
418
static void CleanupBackupHistory(void);
419
static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
420
static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
421
static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
422 423 424 425
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 已提交
426 427
					 TimeLineID endTLI,
					 uint32 endLogId, uint32 endLogSeg);
T
Tom Lane 已提交
428 429
static void WriteControlFile(void);
static void ReadControlFile(void);
430
static char *str_time(pg_time_t tnow);
431
#ifdef WAL_DEBUG
432
static void xlog_outrec(StringInfo buf, XLogRecord *record);
433
#endif
434 435
static void issue_xlog_fsync(void);
static void pg_start_backup_callback(int code, Datum arg);
436
static bool read_backup_label(XLogRecPtr *checkPointLoc,
B
Bruce Momjian 已提交
437
				  XLogRecPtr *minRecoveryLoc);
438
static void rm_redo_error_callback(void *arg);
439
static int get_sync_bit(int method);
T
Tom Lane 已提交
440 441 442 443 444


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

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

T
Tom Lane 已提交
487
	/*
B
Bruce Momjian 已提交
488 489
	 * In bootstrap mode, we don't actually log anything but XLOG resources;
	 * return a phony record pointer.
T
Tom Lane 已提交
490
	 */
V
Vadim B. Mikheev 已提交
491
	if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
V
WAL  
Vadim B. Mikheev 已提交
492 493
	{
		RecPtr.xlogid = 0;
B
Bruce Momjian 已提交
494
		RecPtr.xrecoff = SizeOfXLogLongPHD;		/* start of 1st chkpt record */
495
		return RecPtr;
V
WAL  
Vadim B. Mikheev 已提交
496 497
	}

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

524 525 526 527 528 529 530 531
	/*
	 * 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;

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

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
	/*
	 * 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 已提交
620
	/*
621 622
	 * 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 已提交
623 624 625
	 * 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 已提交
626
	 */
627
	if (len == 0 && !isLogSwitch)
628
		elog(PANIC, "invalid xlog record length %u", len);
629

630
	START_CRIT_SECTION();
631

632 633 634
	/* Now wait to get insert lock */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);

T
Tom Lane 已提交
635
	/*
B
Bruce Momjian 已提交
636 637 638
	 * 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.
639 640
	 *
	 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
B
Bruce Momjian 已提交
641 642
	 * affect the contents of the XLOG record, so we'll update our local copy
	 * but not force a recomputation.
T
Tom Lane 已提交
643 644
	 */
	if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
645
	{
T
Tom Lane 已提交
646 647 648
		Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
		RedoRecPtr = Insert->RedoRecPtr;

649
		if (doPageWrites)
650
		{
651
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
T
Tom Lane 已提交
652
			{
653 654 655 656 657 658 659 660 661 662 663 664 665
				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 已提交
666
			}
667 668 669
		}
	}

670
	/*
B
Bruce Momjian 已提交
671 672 673 674
	 * 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.)
675 676 677 678 679 680 681 682 683
	 */
	if (Insert->forcePageWrites && !doPageWrites)
	{
		/* Oops, must redo it with full-page data */
		LWLockRelease(WALInsertLock);
		END_CRIT_SECTION();
		goto begin;
	}

T
Tom Lane 已提交
684
	/*
B
Bruce Momjian 已提交
685 686 687 688
	 * 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 已提交
689
	 *
690 691 692
	 * 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 已提交
693 694 695
	 */
	write_len = len;
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
696
	{
697 698 699
		BkpBlock   *bkpb;
		char	   *page;

700
		if (!dtbuf_bkp[i])
701 702
			continue;

T
Tom Lane 已提交
703
		info |= XLR_SET_BKP_BLOCK(i);
704

705 706 707 708 709
		bkpb = &(dtbuf_xlg[i]);
		page = (char *) BufferGetBlock(dtbuf[i]);

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

711 712
		rdt->data = (char *) bkpb;
		rdt->len = sizeof(BkpBlock);
T
Tom Lane 已提交
713
		write_len += sizeof(BkpBlock);
714

715 716
		rdt->next = &(dtbuf_rdt2[i]);
		rdt = rdt->next;
717

718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
		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;
		}
740 741
	}

742 743 744 745 746 747 748
	/*
	 * 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 已提交
749 750
	 * defining it like this leaves the info bit free for some potential other
	 * use in records without any backup blocks.
751 752 753 754
	 */
	if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
		info |= XLR_BKP_REMOVABLE;

755
	/*
756
	 * If there isn't enough space on the current XLOG page for a record
B
Bruce Momjian 已提交
757
	 * header, advance to the next page (leaving the unused space as zeroes).
758
	 */
T
Tom Lane 已提交
759 760
	updrqst = false;
	freespace = INSERT_FREESPACE(Insert);
761 762
	if (freespace < SizeOfXLogRecord)
	{
763
		updrqst = AdvanceXLInsertBuffer(false);
764 765 766
		freespace = INSERT_FREESPACE(Insert);
	}

767
	/* Compute record's XLOG location */
T
Tom Lane 已提交
768
	curridx = Insert->curridx;
769 770 771
	INSERT_RECPTR(RecPtr, Insert, curridx);

	/*
B
Bruce Momjian 已提交
772 773 774 775 776
	 * 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.
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
	 */
	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 已提交
808

809 810
	/* Insert record header */

811
	record = (XLogRecord *) Insert->currpos;
812
	record->xl_prev = Insert->PrevRecord;
813
	record->xl_xid = GetCurrentTransactionIdIfAny();
814
	record->xl_tot_len = SizeOfXLogRecord + write_len;
T
Tom Lane 已提交
815
	record->xl_len = len;		/* doesn't include backup blocks */
816
	record->xl_info = info;
817
	record->xl_rmid = rmid;
818

819 820 821 822
	/* 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);
823 824
	record->xl_crc = rdata_crc;

825
#ifdef WAL_DEBUG
V
WAL  
Vadim B. Mikheev 已提交
826 827
	if (XLOG_DEBUG)
	{
B
Bruce Momjian 已提交
828
		StringInfoData buf;
V
WAL  
Vadim B. Mikheev 已提交
829

830
		initStringInfo(&buf);
831 832
		appendStringInfo(&buf, "INSERT @ %X/%X: ",
						 RecPtr.xlogid, RecPtr.xrecoff);
833
		xlog_outrec(&buf, record);
834
		if (rdata->data != NULL)
V
WAL  
Vadim B. Mikheev 已提交
835
		{
836 837
			appendStringInfo(&buf, " - ");
			RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
V
WAL  
Vadim B. Mikheev 已提交
838
		}
839 840
		elog(LOG, "%s", buf.data);
		pfree(buf.data);
V
WAL  
Vadim B. Mikheev 已提交
841
	}
842
#endif
V
WAL  
Vadim B. Mikheev 已提交
843

T
Tom Lane 已提交
844 845 846 847
	/* Record begin of record in appropriate places */
	ProcLastRecPtr = RecPtr;
	Insert->PrevRecord = RecPtr;

848
	Insert->currpos += SizeOfXLogRecord;
T
Tom Lane 已提交
849
	freespace -= SizeOfXLogRecord;
850

T
Tom Lane 已提交
851 852 853 854
	/*
	 * Append the data, including backup blocks if any
	 */
	while (write_len)
855
	{
856 857 858 859
		while (rdata->data == NULL)
			rdata = rdata->next;

		if (freespace > 0)
860
		{
861 862 863 864 865
			if (rdata->len > freespace)
			{
				memcpy(Insert->currpos, rdata->data, freespace);
				rdata->data += freespace;
				rdata->len -= freespace;
T
Tom Lane 已提交
866
				write_len -= freespace;
867 868 869 870 871
			}
			else
			{
				memcpy(Insert->currpos, rdata->data, rdata->len);
				freespace -= rdata->len;
T
Tom Lane 已提交
872
				write_len -= rdata->len;
873 874 875 876
				Insert->currpos += rdata->len;
				rdata = rdata->next;
				continue;
			}
877 878
		}

879
		/* Use next buffer */
880
		updrqst = AdvanceXLInsertBuffer(false);
T
Tom Lane 已提交
881 882 883 884 885 886
		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;
887
		freespace = INSERT_FREESPACE(Insert);
888
	}
889

T
Tom Lane 已提交
890 891
	/* Ensure next record will be properly aligned */
	Insert->currpos = (char *) Insert->currpage +
B
Bruce Momjian 已提交
892
		MAXALIGN(Insert->currpos - (char *) Insert->currpage);
T
Tom Lane 已提交
893
	freespace = INSERT_FREESPACE(Insert);
894

V
Vadim B. Mikheev 已提交
895
	/*
B
Bruce Momjian 已提交
896 897
	 * 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 已提交
898
	 */
T
Tom Lane 已提交
899
	INSERT_RECPTR(RecPtr, Insert, curridx);
V
Vadim B. Mikheev 已提交
900

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
	/*
	 * 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 已提交
918 919
		 * Flush through the end of the page containing XLOG_SWITCH, and
		 * perform end-of-segment actions (eg, notifying archiver).
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 961 962 963 964 965 966 967 968 969
		 */
		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 */
	}
970
	else
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
	{
		/* 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];
	}
987

988
	LWLockRelease(WALInsertLock);
989 990 991

	if (updrqst)
	{
992 993 994
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

995
		SpinLockAcquire(&xlogctl->info_lck);
T
Tom Lane 已提交
996
		/* advance global request to include new block(s) */
997 998
		if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
			xlogctl->LogwrtRqst.Write = WriteRqst;
T
Tom Lane 已提交
999
		/* update local result copy while I have the chance */
1000
		LogwrtResult = xlogctl->LogwrtResult;
1001
		SpinLockRelease(&xlogctl->info_lck);
1002 1003
	}

1004
	XactLastRecEnd = RecPtr;
1005

1006
	END_CRIT_SECTION();
1007

1008
	return RecPtr;
1009
}
1010

1011
/*
1012 1013 1014
 * 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.
1015
 */
1016
static bool
1017
XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1018
				XLogRecPtr *lsn, BkpBlock *bkpb)
1019 1020
{
	PageHeader	page;
1021 1022 1023 1024

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

	/*
B
Bruce Momjian 已提交
1025 1026 1027
	 * 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.
1028 1029 1030
	 */
	*lsn = page->pd_lsn;

1031
	if (doPageWrites &&
1032
		XLByteLE(page->pd_lsn, RedoRecPtr))
1033
	{
1034 1035 1036 1037 1038
		/*
		 * The page needs to be backed up, so set up *bkpb
		 */
		bkpb->node = BufferGetFileNode(rdata->buffer);
		bkpb->block = BufferGetBlockNumber(rdata->buffer);
1039

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
		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;
		}
1066

1067
		return true;			/* buffer requires backup */
1068
	}
1069 1070

	return false;				/* buffer does not need to be backed up */
1071 1072
}

1073 1074 1075 1076 1077 1078
/*
 * XLogArchiveNotify
 *
 * Create an archive notification file
 *
 * The name of the notification file is the message that will be picked up
1079
 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1080
 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1081
 * then when complete, rename it to 0000000100000001000000C6.done
1082 1083 1084 1085 1086
 */
static void
XLogArchiveNotify(const char *xlog)
{
	char		archiveStatusPath[MAXPGPATH];
B
Bruce Momjian 已提交
1087
	FILE	   *fd;
1088 1089 1090 1091

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

1122
	XLogFileName(xlog, ThisTimeLineID, log, seg);
1123 1124 1125 1126
	XLogArchiveNotify(xlog);
}

/*
1127
 * XLogArchiveCheckDone
1128
 *
1129 1130 1131 1132
 * 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.
1133 1134
 *
 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1135 1136 1137 1138
 * 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.
1139 1140
 */
static bool
1141
XLogArchiveCheckDone(const char *xlog, bool create_if_missing)
1142 1143 1144 1145
{
	char		archiveStatusPath[MAXPGPATH];
	struct stat stat_buf;

1146 1147 1148 1149 1150
	/* Always deletable if archiving is off */
	if (!XLogArchivingActive())
		return true;

	/* First check for .done --- this means archiver is done with it */
1151 1152 1153 1154 1155 1156 1157
	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 已提交
1158
		return false;
1159 1160 1161 1162 1163 1164 1165

	/* 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 */
1166 1167 1168
	if (create_if_missing)
		XLogArchiveNotify(xlog);

1169 1170 1171 1172 1173 1174
	return false;
}

/*
 * XLogArchiveCleanup
 *
1175
 * Cleanup archive notification file(s) for a particular xlog segment
1176 1177 1178 1179
 */
static void
XLogArchiveCleanup(const char *xlog)
{
B
Bruce Momjian 已提交
1180
	char		archiveStatusPath[MAXPGPATH];
1181

1182
	/* Remove the .done file */
1183 1184 1185
	StatusFilePath(archiveStatusPath, xlog, ".done");
	unlink(archiveStatusPath);
	/* should we complain about failure? */
1186 1187 1188 1189 1190

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

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

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

T
Tom Lane 已提交
1224
	/*
B
Bruce Momjian 已提交
1225 1226 1227
	 * 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 已提交
1228 1229 1230 1231 1232 1233
	 */
	OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
	if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
	{
		/* nope, got work to do... */
		XLogRecPtr	FinishedPageRqstPtr;
1234

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

1237
		/* Before waiting, get info_lck and update LogwrtResult */
1238 1239 1240 1241
		{
			/* use volatile pointer to prevent code rearrangement */
			volatile XLogCtlData *xlogctl = XLogCtl;

1242
			SpinLockAcquire(&xlogctl->info_lck);
1243 1244 1245
			if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
				xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
			LogwrtResult = xlogctl->LogwrtResult;
1246
			SpinLockRelease(&xlogctl->info_lck);
1247
		}
1248 1249 1250 1251 1252 1253 1254 1255 1256

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

		if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
		{
			/* OK, someone wrote it already */
			Insert->LogwrtResult = LogwrtResult;
		}
		else
1257
		{
1258 1259 1260 1261
			/* Must acquire write lock */
			LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
			LogwrtResult = Write->LogwrtResult;
			if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1262
			{
1263 1264 1265
				/* OK, someone wrote it already */
				LWLockRelease(WALWriteLock);
				Insert->LogwrtResult = LogwrtResult;
T
Tom Lane 已提交
1266
			}
1267
			else
T
Tom Lane 已提交
1268 1269
			{
				/*
B
Bruce Momjian 已提交
1270 1271
				 * Have to write buffers while holding insert lock. This is
				 * not good, so only write as much as we absolutely must.
T
Tom Lane 已提交
1272 1273 1274 1275
				 */
				WriteRqst.Write = OldPageRqstPtr;
				WriteRqst.Flush.xlogid = 0;
				WriteRqst.Flush.xrecoff = 0;
1276
				XLogWrite(WriteRqst, false, false);
1277
				LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
1278
				Insert->LogwrtResult = LogwrtResult;
1279 1280 1281 1282
			}
		}
	}

T
Tom Lane 已提交
1283
	/*
B
Bruce Momjian 已提交
1284 1285
	 * Now the next buffer slot is free and we can set it up to be the next
	 * output page.
T
Tom Lane 已提交
1286
	 */
1287
	NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1288 1289 1290 1291 1292 1293 1294 1295

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

1296
	if (NewPageEndPtr.xrecoff >= XLogFileSize)
1297
	{
T
Tom Lane 已提交
1298
		/* crossing a logid boundary */
1299
		NewPageEndPtr.xlogid += 1;
1300
		NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1301
	}
T
Tom Lane 已提交
1302
	else
1303
		NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1304
	XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1305
	NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
B
Bruce Momjian 已提交
1306

T
Tom Lane 已提交
1307
	Insert->curridx = nextidx;
1308
	Insert->currpage = NewPage;
B
Bruce Momjian 已提交
1309 1310

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

T
Tom Lane 已提交
1312
	/*
B
Bruce Momjian 已提交
1313 1314
	 * 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 已提交
1315
	 */
1316
	MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1317

1318 1319 1320
	/*
	 * Fill the new page's header
	 */
B
Bruce Momjian 已提交
1321 1322
	NewPage   ->xlp_magic = XLOG_PAGE_MAGIC;

1323
	/* NewPage->xlp_info = 0; */	/* done by memset */
B
Bruce Momjian 已提交
1324 1325
	NewPage   ->xlp_tli = ThisTimeLineID;
	NewPage   ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1326
	NewPage   ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
T
Tom Lane 已提交
1327

1328
	/*
1329
	 * If first page of an XLOG segment file, make it a long header.
1330 1331 1332
	 */
	if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
	{
1333
		XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1334

1335 1336
		NewLongPage->xlp_sysid = ControlFile->system_identifier;
		NewLongPage->xlp_seg_size = XLogSegSize;
1337
		NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
B
Bruce Momjian 已提交
1338 1339 1340
		NewPage   ->xlp_info |= XLP_LONG_HEADER;

		Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1341 1342
	}

T
Tom Lane 已提交
1343
	return update_needed;
1344 1345
}

1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
/*
 * 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)
{
	/*
1359 1360
	 * 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 已提交
1361 1362
	 * highest-order bits separately, and force a checkpoint immediately when
	 * they change.
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
	 */
	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 已提交
1375
		new_segno >= old_segno + (uint32) (CheckPointSegments - 1))
1376 1377 1378 1379
		return true;
	return false;
}

T
Tom Lane 已提交
1380 1381 1382
/*
 * Write and/or fsync the log at least as far as WriteRqst indicates.
 *
1383 1384 1385 1386 1387
 * 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.
 *
1388 1389 1390 1391 1392 1393
 * 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.)
 *
1394
 * Must be called with WALWriteLock held.
T
Tom Lane 已提交
1395
 */
1396
static void
1397
XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1398
{
1399
	XLogCtlWrite *Write = &XLogCtl->Write;
T
Tom Lane 已提交
1400
	bool		ispartialpage;
1401
	bool		last_iteration;
1402
	bool		finishing_seg;
1403
	bool		use_existent;
1404 1405 1406 1407
	int			curridx;
	int			npages;
	int			startidx;
	uint32		startoffset;
1408

1409 1410 1411
	/* We should always be inside a critical section here */
	Assert(CritSectionCount > 0);

B
Bruce Momjian 已提交
1412
	/*
B
Bruce Momjian 已提交
1413
	 * Update local LogwrtResult (caller probably did this already, but...)
B
Bruce Momjian 已提交
1414
	 */
T
Tom Lane 已提交
1415 1416
	LogwrtResult = Write->LogwrtResult;

1417 1418 1419
	/*
	 * Since successive pages in the xlog cache are consecutively allocated,
	 * we can usually gather multiple pages together and issue just one
B
Bruce Momjian 已提交
1420 1421 1422 1423 1424
	 * 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.
1425 1426 1427 1428 1429 1430 1431 1432 1433
	 */
	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 已提交
1434 1435
	 * going to PANIC if any error occurs anyway; but someday it may come in
	 * useful.)
1436 1437
	 */
	curridx = Write->curridx;
B
 
Bruce Momjian 已提交
1438

T
Tom Lane 已提交
1439
	while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1440
	{
1441
		/*
B
Bruce Momjian 已提交
1442 1443 1444
		 * 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.
1445
		 */
1446
		if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1447
			elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1448
				 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1449 1450
				 XLogCtl->xlblocks[curridx].xlogid,
				 XLogCtl->xlblocks[curridx].xrecoff);
1451

T
Tom Lane 已提交
1452
		/* Advance LogwrtResult.Write to end of current buffer page */
1453
		LogwrtResult.Write = XLogCtl->xlblocks[curridx];
T
Tom Lane 已提交
1454 1455 1456
		ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);

		if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1457
		{
T
Tom Lane 已提交
1458
			/*
1459 1460
			 * Switch to new logfile segment.  We cannot have any pending
			 * pages here (since we dump what we have at segment end).
T
Tom Lane 已提交
1461
			 */
1462
			Assert(npages == 0);
T
Tom Lane 已提交
1463
			if (openLogFile >= 0)
1464
				XLogFileClose();
T
Tom Lane 已提交
1465 1466
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);

1467 1468 1469 1470
			/* create/use new log file */
			use_existent = true;
			openLogFile = XLogFileInit(openLogId, openLogSeg,
									   &use_existent, true);
T
Tom Lane 已提交
1471
			openLogOff = 0;
1472 1473
		}

1474
		/* Make sure we have the current logfile open */
T
Tom Lane 已提交
1475
		if (openLogFile < 0)
1476
		{
T
Tom Lane 已提交
1477
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1478
			openLogFile = XLogFileOpen(openLogId, openLogSeg);
T
Tom Lane 已提交
1479
			openLogOff = 0;
1480 1481
		}

1482 1483 1484 1485 1486
		/* Add current page to the set of pending pages-to-dump */
		if (npages == 0)
		{
			/* first of group */
			startidx = curridx;
1487
			startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1488 1489
		}
		npages++;
1490

T
Tom Lane 已提交
1491
		/*
B
Bruce Momjian 已提交
1492 1493 1494 1495
		 * 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 已提交
1496
		 */
1497 1498
		last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);

1499
		finishing_seg = !ispartialpage &&
1500
			(startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1501

1502
		if (last_iteration ||
1503 1504
			curridx == XLogCtl->XLogCacheBlck ||
			finishing_seg)
T
Tom Lane 已提交
1505
		{
1506 1507
			char	   *from;
			Size		nbytes;
1508

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

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

1567
				Write->lastSegSwitchTime = (pg_time_t) time(NULL);
1568 1569

				/*
1570
				 * Signal bgwriter to start a checkpoint if we've consumed too
1571
				 * much xlog since the last one.  For speed, we first check
B
Bruce Momjian 已提交
1572 1573 1574
				 * 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.
1575
				 */
1576 1577
				if (IsUnderPostmaster &&
					XLogCheckpointNeeded())
1578
				{
1579 1580
					(void) GetRedoRecPtr();
					if (XLogCheckpointNeeded())
1581
						RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1582
				}
1583
			}
T
Tom Lane 已提交
1584
		}
1585

T
Tom Lane 已提交
1586 1587 1588 1589 1590 1591
		if (ispartialpage)
		{
			/* Only asked to write a partial page */
			LogwrtResult.Write = WriteRqst.Write;
			break;
		}
1592 1593 1594 1595 1596
		curridx = NextBufIdx(curridx);

		/* If flexible, break out of loop as soon as we wrote something */
		if (flexible && npages == 0)
			break;
1597
	}
1598 1599 1600

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

T
Tom Lane 已提交
1602 1603 1604 1605 1606
	/*
	 * If asked to flush, do so
	 */
	if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
		XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1607
	{
T
Tom Lane 已提交
1608
		/*
B
Bruce Momjian 已提交
1609 1610 1611
		 * 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 已提交
1612
		 */
1613 1614
		if (sync_method != SYNC_METHOD_OPEN &&
			sync_method != SYNC_METHOD_OPEN_DSYNC)
T
Tom Lane 已提交
1615
		{
1616
			if (openLogFile >= 0 &&
B
Bruce Momjian 已提交
1617
				!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1618
				XLogFileClose();
1619 1620 1621
			if (openLogFile < 0)
			{
				XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1622
				openLogFile = XLogFileOpen(openLogId, openLogSeg);
1623 1624 1625
				openLogOff = 0;
			}
			issue_xlog_fsync();
T
Tom Lane 已提交
1626 1627
		}
		LogwrtResult.Flush = LogwrtResult.Write;
1628 1629
	}

T
Tom Lane 已提交
1630 1631 1632
	/*
	 * Update shared-memory status
	 *
B
Bruce Momjian 已提交
1633
	 * We make sure that the shared 'request' values do not fall behind the
B
Bruce Momjian 已提交
1634 1635
	 * 'result' values.  This is not absolutely essential, but it saves some
	 * code in a couple of places.
T
Tom Lane 已提交
1636
	 */
1637 1638 1639 1640
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

1641
		SpinLockAcquire(&xlogctl->info_lck);
1642 1643 1644 1645 1646
		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;
1647
		SpinLockRelease(&xlogctl->info_lck);
1648
	}
1649

T
Tom Lane 已提交
1650 1651 1652
	Write->LogwrtResult = LogwrtResult;
}

1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
/*
 * 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 已提交
1669 1670 1671
/*
 * Ensure that all XLOG data through the given position is flushed to disk.
 *
1672
 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
T
Tom Lane 已提交
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
 * 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;

1689
#ifdef WAL_DEBUG
1690
	if (XLOG_DEBUG)
1691
		elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1692 1693 1694
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1695
#endif
1696

T
Tom Lane 已提交
1697 1698 1699 1700
	START_CRIT_SECTION();

	/*
	 * Since fsync is usually a horribly expensive operation, we try to
B
Bruce Momjian 已提交
1701 1702 1703 1704
	 * 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 已提交
1705 1706 1707 1708 1709
	 */

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

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

1715
		SpinLockAcquire(&xlogctl->info_lck);
1716 1717 1718
		if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
			WriteRqstPtr = xlogctl->LogwrtRqst.Write;
		LogwrtResult = xlogctl->LogwrtResult;
1719
		SpinLockRelease(&xlogctl->info_lck);
1720
	}
1721 1722 1723

	/* done already? */
	if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
1724
	{
1725 1726 1727 1728
		/* now wait for the write lock */
		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
		LogwrtResult = XLogCtl->Write.LogwrtResult;
		if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
1729
		{
1730 1731 1732 1733 1734 1735
			/* 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 已提交
1736
				if (freespace < SizeOfXLogRecord)		/* buffer is full */
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
					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;
			}
1752
			XLogWrite(WriteRqst, false, false);
T
Tom Lane 已提交
1753
		}
1754
		LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
1755 1756 1757
	}

	END_CRIT_SECTION();
1758 1759 1760

	/*
	 * If we still haven't flushed to the request point then we have a
B
Bruce Momjian 已提交
1761 1762
	 * 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.
1763
	 *
1764 1765 1766 1767 1768 1769 1770 1771 1772
	 * 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.)
1773
	 *
1774 1775 1776 1777
	 * 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 已提交
1778 1779
	 * 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.
1780 1781
	 */
	if (XLByteLT(LogwrtResult.Flush, record))
B
Bruce Momjian 已提交
1782
		elog(InRecovery ? WARNING : ERROR,
B
Bruce Momjian 已提交
1783
		"xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1784 1785
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1786 1787
}

1788 1789 1790 1791 1792 1793
/*
 * 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 已提交
1794
 * are not being used, we will flush complete blocks only.	We can guarantee
1795
 * that async commits reach disk after at most three cycles; normally only
B
Bruce Momjian 已提交
1796
 * one or two.	(We allow XLogWrite to write "flexibly", meaning it can stop
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
 * 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;

1829
		SpinLockAcquire(&xlogctl->info_lck);
1830
		WriteRqstPtr = xlogctl->asyncCommitLSN;
1831
		SpinLockRelease(&xlogctl->info_lck);
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
		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();
}

1865 1866
/*
 * Flush any previous asynchronously-committed transactions' commit records.
1867 1868 1869 1870
 *
 * 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.
1871 1872 1873 1874 1875
 */
void
XLogAsyncCommitFlush(void)
{
	XLogRecPtr	WriteRqstPtr;
B
Bruce Momjian 已提交
1876

1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

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

	XLogFlush(WriteRqstPtr);
}

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

1950
	XLogFilePath(path, ThisTimeLineID, log, seg);
V
Vadim B. Mikheev 已提交
1951 1952

	/*
B
Bruce Momjian 已提交
1953
	 * Try to use existent file (checkpoint maker may have created it already)
V
Vadim B. Mikheev 已提交
1954
	 */
1955
	if (*use_existent)
V
Vadim B. Mikheev 已提交
1956
	{
1957
		fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
1958
						   S_IRUSR | S_IWUSR);
V
Vadim B. Mikheev 已提交
1959 1960 1961
		if (fd < 0)
		{
			if (errno != ENOENT)
1962
				ereport(ERROR,
1963
						(errcode_for_file_access(),
1964
						 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1965
								path, log, seg)));
V
Vadim B. Mikheev 已提交
1966 1967
		}
		else
1968
			return fd;
V
Vadim B. Mikheev 已提交
1969 1970
	}

1971
	/*
B
Bruce Momjian 已提交
1972 1973 1974 1975
	 * 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.
1976
	 */
1977 1978
	elog(DEBUG2, "creating and filling new WAL file");

1979
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1980 1981

	unlink(tmppath);
1982

1983
	/* do not use get_sync_bit() here --- want to fsync only at end of fill */
1984
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
T
Tom Lane 已提交
1985
					   S_IRUSR | S_IWUSR);
1986
	if (fd < 0)
1987
		ereport(ERROR,
1988
				(errcode_for_file_access(),
1989
				 errmsg("could not create file \"%s\": %m", tmppath)));
1990

1991
	/*
B
Bruce Momjian 已提交
1992 1993 1994 1995 1996 1997 1998
	 * 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.
1999 2000 2001 2002
	 *
	 * 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.
2003
	 */
2004 2005
	zbuffer = (char *) palloc0(XLOG_BLCKSZ);
	for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
2006
	{
2007
		errno = 0;
2008
		if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
T
Tom Lane 已提交
2009
		{
B
Bruce Momjian 已提交
2010
			int			save_errno = errno;
T
Tom Lane 已提交
2011

B
Bruce Momjian 已提交
2012
			/*
B
Bruce Momjian 已提交
2013
			 * If we fail to make the file, delete it to release disk space
B
Bruce Momjian 已提交
2014
			 */
2015
			unlink(tmppath);
2016 2017
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;
T
Tom Lane 已提交
2018

2019
			ereport(ERROR,
2020
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2021
					 errmsg("could not write to file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2022
		}
2023
	}
2024
	pfree(zbuffer);
2025

2026
	if (pg_fsync(fd) != 0)
2027
		ereport(ERROR,
2028
				(errcode_for_file_access(),
2029
				 errmsg("could not fsync file \"%s\": %m", tmppath)));
2030

2031
	if (close(fd))
2032
		ereport(ERROR,
2033 2034
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2035

2036
	/*
2037 2038
	 * Now move the segment into place with its final name.
	 *
2039
	 * If caller didn't want to use a pre-existing file, get rid of any
B
Bruce Momjian 已提交
2040 2041 2042
	 * 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.
2043
	 */
2044 2045 2046 2047 2048
	installed_log = log;
	installed_seg = seg;
	max_advance = XLOGfileslop;
	if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
								*use_existent, &max_advance,
2049 2050 2051 2052 2053 2054
								use_lock))
	{
		/* No need for any more future segments... */
		unlink(tmppath);
	}

2055 2056
	elog(DEBUG2, "done creating and filling new WAL file");

2057 2058 2059 2060
	/* 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) */
2061
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2062 2063
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
2064
		ereport(ERROR,
2065
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2066 2067
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2068

2069
	return fd;
2070 2071
}

2072 2073 2074 2075 2076 2077 2078 2079 2080
/*
 * 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 已提交
2081
 * considerations.	But we should be just as tense as XLogFileInit to avoid
2082 2083 2084 2085 2086 2087 2088 2089
 * emplacing a bogus file.
 */
static void
XLogFileCopy(uint32 log, uint32 seg,
			 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
{
	char		path[MAXPGPATH];
	char		tmppath[MAXPGPATH];
2090
	char		buffer[XLOG_BLCKSZ];
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
	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)
2101
		ereport(ERROR,
2102 2103 2104 2105 2106 2107
				(errcode_for_file_access(),
				 errmsg("could not open file \"%s\": %m", path)));

	/*
	 * Copy into a temp file name.
	 */
2108
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2109 2110 2111

	unlink(tmppath);

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

			/*
B
Bruce Momjian 已提交
2142
			 * If we fail to make the file, delete it to release disk space
2143 2144 2145 2146 2147
			 */
			unlink(tmppath);
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;

2148
			ereport(ERROR,
2149
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2150
					 errmsg("could not write to file \"%s\": %m", tmppath)));
2151 2152 2153 2154
		}
	}

	if (pg_fsync(fd) != 0)
2155
		ereport(ERROR,
2156 2157 2158 2159
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
2160
		ereport(ERROR,
2161 2162 2163 2164 2165 2166 2167 2168
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));

	close(srcfd);

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

2173 2174 2175 2176 2177 2178
/*
 * 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.
 *
2179 2180 2181
 * *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.
2182 2183 2184 2185 2186 2187 2188
 *
 * 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.
 *
2189 2190 2191 2192
 * *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.)
2193
 *
2194
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2195
 * place.  This should be TRUE except during bootstrap log creation.  The
2196
 * caller must *not* hold the lock at call.
2197 2198
 *
 * Returns TRUE if file installed, FALSE if not installed because of
2199 2200 2201
 * 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().)
2202 2203
 */
static bool
2204 2205
InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
2206 2207 2208
					   bool use_lock)
{
	char		path[MAXPGPATH];
2209
	struct stat stat_buf;
2210

2211
	XLogFilePath(path, ThisTimeLineID, *log, *seg);
2212 2213 2214 2215 2216

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

2219 2220 2221 2222 2223
	if (!find_free)
	{
		/* Force installation: get rid of any pre-existing segment file */
		unlink(path);
	}
2224 2225
	else
	{
2226
		/* Find a free slot to put it in */
2227
		while (stat(path, &stat_buf) == 0)
2228
		{
2229
			if (*max_advance <= 0)
2230 2231 2232
			{
				/* Failed to find a free slot within specified range */
				if (use_lock)
2233
					LWLockRelease(ControlFileLock);
2234 2235
				return false;
			}
2236 2237 2238
			NextLogSeg(*log, *seg);
			(*max_advance)--;
			XLogFilePath(path, ThisTimeLineID, *log, *seg);
2239 2240 2241 2242 2243 2244 2245
		}
	}

	/*
	 * 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.
2246
	 */
2247
#if HAVE_WORKING_LINK
2248
	if (link(tmppath, path) < 0)
2249
		ereport(ERROR,
2250
				(errcode_for_file_access(),
2251
				 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2252
						tmppath, path, *log, *seg)));
2253
	unlink(tmppath);
2254
#else
2255
	if (rename(tmppath, path) < 0)
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
	{
#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 已提交
2268
#endif   /* WIN32 */
2269

2270
		ereport(ERROR,
2271
				(errcode_for_file_access(),
2272
				 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2273
						tmppath, path, *log, *seg)));
2274
	}
2275
#endif
V
Vadim B. Mikheev 已提交
2276

2277
	if (use_lock)
2278
		LWLockRelease(ControlFileLock);
2279

2280
	return true;
2281 2282
}

T
Tom Lane 已提交
2283
/*
2284
 * Open a pre-existing logfile segment for writing.
T
Tom Lane 已提交
2285
 */
2286
static int
2287
XLogFileOpen(uint32 log, uint32 seg)
2288
{
2289 2290
	char		path[MAXPGPATH];
	int			fd;
2291

2292
	XLogFilePath(path, ThisTimeLineID, log, seg);
2293

2294
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2295
					   S_IRUSR | S_IWUSR);
2296
	if (fd < 0)
2297 2298
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2299 2300
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312

	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];
2313
	char		activitymsg[MAXFNAMELEN + 16];
2314 2315
	ListCell   *cell;
	int			fd;
2316

2317
	/*
B
Bruce Momjian 已提交
2318 2319
	 * Loop looking for a suitable timeline ID: we might need to read any of
	 * the timelines listed in expectedTLIs.
2320
	 *
B
Bruce Momjian 已提交
2321
	 * We expect curFileTLI on entry to be the TLI of the preceding file in
B
Bruce Momjian 已提交
2322 2323 2324 2325
	 * 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.
2326
	 */
2327 2328 2329
	foreach(cell, expectedTLIs)
	{
		TimeLineID	tli = (TimeLineID) lfirst_int(cell);
2330

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

2334 2335
		XLogFileName(xlogfname, tli, log, seg);

2336 2337
		if (InArchiveRecovery)
		{
2338 2339 2340 2341 2342
			/* Report recovery progress in PS display */
			snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
					 xlogfname);
			set_ps_display(activitymsg, false);

2343
			restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2344 2345
													  "RECOVERYXLOG",
													  XLogSegSize);
2346 2347 2348 2349 2350 2351 2352 2353 2354
		}
		else
			XLogFilePath(path, tli, log, seg);

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

			/* Report recovery progress in PS display */
2357 2358
			snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
					 xlogfname);
2359 2360
			set_ps_display(activitymsg, false);

2361 2362 2363 2364 2365
			return fd;
		}
		if (errno != ENOENT)	/* unexpected failure? */
			ereport(PANIC,
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2366 2367
			errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				   path, log, seg)));
2368 2369 2370 2371 2372 2373 2374
	}

	/* 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 已提交
2375 2376
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2377
	return -1;
2378 2379
}

2380 2381 2382 2383 2384 2385 2386 2387
/*
 * Close the current logfile segment for writing.
 */
static void
XLogFileClose(void)
{
	Assert(openLogFile >= 0);

2388
	/*
B
Bruce Momjian 已提交
2389 2390 2391 2392 2393 2394
	 * 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.
2395 2396 2397
	 */
#ifdef NOT_USED

2398
	/*
2399
	 * WAL segment files will not be re-read in normal operation, so we advise
B
Bruce Momjian 已提交
2400
	 * OS to release any cached pages.	But do not do so if WAL archiving is
2401 2402 2403
	 * active, because archiver process could use the cache to read the WAL
	 * segment.
	 *
B
Bruce Momjian 已提交
2404 2405
	 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
	 * O_SYNC, and some platforms only have posix_fadvise().
2406
	 */
2407
#if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2408 2409 2410
	if (!XLogArchivingActive())
		posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
#endif
B
Bruce Momjian 已提交
2411
#endif   /* NOT_USED */
2412

2413 2414
	if (close(openLogFile))
		ereport(PANIC,
B
Bruce Momjian 已提交
2415 2416 2417
				(errcode_for_file_access(),
				 errmsg("could not close log file %u, segment %u: %m",
						openLogId, openLogSeg)));
2418 2419 2420
	openLogFile = -1;
}

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

	/*
B
Bruce Momjian 已提交
2452 2453 2454 2455
	 * 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.
2456
	 *
B
Bruce Momjian 已提交
2457
	 * We could try to optimize this slightly by checking the local copy
B
Bruce Momjian 已提交
2458 2459 2460 2461
	 * 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.
2462
	 *
2463 2464 2465
	 * 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.
2466
	 *
2467 2468 2469 2470
	 * 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 已提交
2471 2472
	 * copy-from-archive filename is always the same, ensuring that we don't
	 * run out of disk space on long recoveries.
2473
	 */
2474
	snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2475 2476

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

2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
	/*
	 * Calculate the archive file cutoff point for use during log shipping
	 * replication. All files earlier than this point can be deleted
	 * from the archive, though there is no requirement to do so.
	 *
	 * We initialise this with the filename of an InvalidXLogRecPtr, which
	 * will prevent the deletion of any WAL files from the archive
	 * because of the alphabetic sorting property of WAL filenames. 
	 *
	 * Once we have successfully located the redo pointer of the checkpoint
	 * from which we start recovery we never request a file prior to the redo
	 * pointer of the last restartpoint. When redo begins we know that we
	 * have successfully located it, so there is no need for additional
	 * status flags to signify the point when we can begin deleting WAL files
	 * from the archive. 
	 */
	if (InRedo)
	{
		XLByteToSeg(ControlFile->checkPointCopy.redo,
					restartLog, restartSeg);
		XLogFileName(lastRestartPointFname,
					 ControlFile->checkPointCopy.ThisTimeLineID,
					 restartLog, restartSeg);
		/* we shouldn't need anything earlier than last restart point */
2520
		Assert(strcmp(lastRestartPointFname, xlogfname) <= 0);
2521 2522 2523 2524
	}
	else
		XLogFileName(lastRestartPointFname, 0, 0, 0);

2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
	/*
	 * 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':
2539
					/* %p: relative path of target file */
2540
					sp++;
B
Bruce Momjian 已提交
2541
					StrNCpy(dp, xlogpath, endp - dp);
2542
					make_native_path(dp);
2543 2544 2545 2546 2547
					dp += strlen(dp);
					break;
				case 'f':
					/* %f: filename of desired file */
					sp++;
B
Bruce Momjian 已提交
2548
					StrNCpy(dp, xlogfname, endp - dp);
2549 2550
					dp += strlen(dp);
					break;
2551 2552 2553 2554 2555 2556
				case 'r':
					/* %r: filename of last restartpoint */
					sp++;
					StrNCpy(dp, lastRestartPointFname, endp - dp);
					dp += strlen(dp);
					break;
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
				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 已提交
2579
			(errmsg_internal("executing restore command \"%s\"",
2580 2581 2582
							 xlogRestoreCmd)));

	/*
2583
	 * Copy xlog from archival storage to XLOGDIR
2584 2585 2586 2587
	 */
	rc = system(xlogRestoreCmd);
	if (rc == 0)
	{
2588 2589 2590 2591
		/*
		 * command apparently succeeded, but let's make sure the file is
		 * really there now and has the correct size.
		 *
2592 2593 2594 2595 2596
		 * 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 ...
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
		 */
		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 已提交
2621
						 errmsg("could not stat file \"%s\": %m",
2622
								xlogpath)));
2623 2624 2625 2626
		}
	}

	/*
2627
	 * Remember, we rollforward UNTIL the restore fails so failure here is
B
Bruce Momjian 已提交
2628
	 * just part of the process... that makes it difficult to determine
B
Bruce Momjian 已提交
2629 2630 2631
	 * 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.
2632 2633
	 *
	 * However, if the failure was due to any sort of signal, it's best to
B
Bruce Momjian 已提交
2634 2635 2636
	 * 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
2637 2638 2639 2640
	 * 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 已提交
2641 2642 2643 2644
	 * 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.
2645
	 */
2646 2647 2648
	signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;

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

	/*
B
Bruce Momjian 已提交
2653 2654
	 * 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.
2655
	 *
B
Bruce Momjian 已提交
2656 2657
	 * In many recovery scenarios we expect this to fail also, but if so that
	 * just means we've reached the end of WAL.
2658
	 */
2659
	snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2660
	return false;
2661 2662
}

V
Vadim B. Mikheev 已提交
2663
/*
2664 2665 2666 2667 2668 2669 2670 2671
 * 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 已提交
2672
 */
2673
static void
T
Tom Lane 已提交
2674 2675 2676 2677 2678
PreallocXlogFiles(XLogRecPtr endptr)
{
	uint32		_logId;
	uint32		_logSeg;
	int			lf;
2679
	bool		use_existent;
T
Tom Lane 已提交
2680 2681

	XLByteToPrevSeg(endptr, _logId, _logSeg);
B
Bruce Momjian 已提交
2682
	if ((endptr.xrecoff - 1) % XLogSegSize >=
B
Bruce Momjian 已提交
2683
		(uint32) (0.75 * XLogSegSize))
T
Tom Lane 已提交
2684 2685
	{
		NextLogSeg(_logId, _logSeg);
2686 2687
		use_existent = true;
		lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
T
Tom Lane 已提交
2688
		close(lf);
2689
		if (!use_existent)
2690
			CheckpointStats.ckpt_segs_added++;
T
Tom Lane 已提交
2691 2692 2693 2694
	}
}

/*
2695
 * Recycle or remove all log files older or equal to passed log/seg#
2696 2697 2698
 *
 * 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 已提交
2699 2700
 */
static void
2701
RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
V
Vadim B. Mikheev 已提交
2702
{
2703 2704
	uint32		endlogId;
	uint32		endlogSeg;
2705
	int			max_advance;
B
Bruce Momjian 已提交
2706 2707
	DIR		   *xldir;
	struct dirent *xlde;
2708
	char		lastoff[MAXFNAMELEN];
B
Bruce Momjian 已提交
2709
	char		path[MAXPGPATH];
V
Vadim B. Mikheev 已提交
2710

2711 2712 2713 2714
	/*
	 * Initialize info about where to try to recycle to.  We allow recycling
	 * segments up to XLOGfileslop segments beyond the current XLOG location.
	 */
2715
	XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2716
	max_advance = XLOGfileslop;
V
Vadim B. Mikheev 已提交
2717

2718
	xldir = AllocateDir(XLOGDIR);
V
Vadim B. Mikheev 已提交
2719
	if (xldir == NULL)
2720
		ereport(ERROR,
2721
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2722 2723
				 errmsg("could not open transaction log directory \"%s\": %m",
						XLOGDIR)));
V
Vadim B. Mikheev 已提交
2724

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

2727
	while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
V
Vadim B. Mikheev 已提交
2728
	{
2729
		/*
2730
		 * We ignore the timeline part of the XLOG segment identifiers in
B
Bruce Momjian 已提交
2731 2732 2733 2734 2735
		 * 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.
2736
		 *
B
Bruce Momjian 已提交
2737 2738
		 * We use the alphanumeric sorting property of the filenames to decide
		 * which ones are earlier than the lastoff segment.
2739
		 */
2740 2741 2742
		if (strlen(xlde->d_name) == 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
V
Vadim B. Mikheev 已提交
2743
		{
2744
			if (XLogArchiveCheckDone(xlde->d_name, true))
2745
			{
2746
				snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2747

2748
				/*
B
Bruce Momjian 已提交
2749 2750
				 * Before deleting the file, see if it can be recycled as a
				 * future log segment.
2751
				 */
2752 2753
				if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
										   true, &max_advance,
2754 2755
										   true))
				{
2756
					ereport(DEBUG2,
B
Bruce Momjian 已提交
2757 2758
							(errmsg("recycled transaction log file \"%s\"",
									xlde->d_name)));
2759
					CheckpointStats.ckpt_segs_recycled++;
2760 2761 2762 2763 2764 2765
					/* Needn't recheck that slot on future iterations */
					if (max_advance > 0)
					{
						NextLogSeg(endlogId, endlogSeg);
						max_advance--;
					}
2766 2767 2768 2769
				}
				else
				{
					/* No need for any more future segments... */
2770
					ereport(DEBUG2,
B
Bruce Momjian 已提交
2771 2772
							(errmsg("removing transaction log file \"%s\"",
									xlde->d_name)));
2773
					unlink(path);
2774
					CheckpointStats.ckpt_segs_removed++;
2775
				}
2776 2777

				XLogArchiveCleanup(xlde->d_name);
2778
			}
V
Vadim B. Mikheev 已提交
2779 2780
		}
	}
B
Bruce Momjian 已提交
2781

2782
	FreeDir(xldir);
V
Vadim B. Mikheev 已提交
2783 2784
}

2785
/*
2786 2787 2788
 * Remove previous backup history files.  This also retries creation of
 * .ready files for any backup history files for which XLogArchiveNotify
 * failed earlier.
2789 2790
 */
static void
2791
CleanupBackupHistory(void)
2792 2793 2794 2795 2796
{
	DIR		   *xldir;
	struct dirent *xlde;
	char		path[MAXPGPATH];

2797
	xldir = AllocateDir(XLOGDIR);
2798 2799 2800
	if (xldir == NULL)
		ereport(ERROR,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2801 2802
				 errmsg("could not open transaction log directory \"%s\": %m",
						XLOGDIR)));
2803

2804
	while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2805 2806 2807 2808 2809 2810
	{
		if (strlen(xlde->d_name) > 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
				   ".backup") == 0)
		{
2811
			if (XLogArchiveCheckDone(xlde->d_name, true))
2812 2813
			{
				ereport(DEBUG2,
B
Bruce Momjian 已提交
2814 2815
				(errmsg("removing transaction log backup history file \"%s\"",
						xlde->d_name)));
2816
				snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2817 2818 2819 2820 2821 2822 2823 2824 2825
				unlink(path);
				XLogArchiveCleanup(xlde->d_name);
			}
		}
	}

	FreeDir(xldir);
}

T
Tom Lane 已提交
2826 2827 2828 2829
/*
 * Restore the backup blocks present in an XLOG record, if any.
 *
 * We assume all of the record has been read into memory at *record.
2830 2831 2832 2833 2834 2835 2836 2837 2838
 *
 * 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 已提交
2839
 */
2840 2841 2842 2843 2844 2845 2846 2847 2848
static void
RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
{
	Buffer		buffer;
	Page		page;
	BkpBlock	bkpb;
	char	   *blk;
	int			i;

B
Bruce Momjian 已提交
2849
	blk = (char *) XLogRecGetData(record) + record->xl_len;
T
Tom Lane 已提交
2850
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2851
	{
T
Tom Lane 已提交
2852
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2853 2854
			continue;

2855
		memcpy(&bkpb, blk, sizeof(BkpBlock));
2856 2857
		blk += sizeof(BkpBlock);

2858
		buffer = XLogReadBuffer(bkpb.node, bkpb.block, true);
2859 2860
		Assert(BufferIsValid(buffer));
		page = (Page) BufferGetPage(buffer);
2861

2862
		if (bkpb.hole_length == 0)
2863
		{
2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
			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));
2874 2875
		}

2876 2877
		PageSetLSN(page, lsn);
		PageSetTLI(page, ThisTimeLineID);
2878 2879
		MarkBufferDirty(buffer);
		UnlockReleaseBuffer(buffer);
2880

2881
		blk += BLCKSZ - bkpb.hole_length;
2882 2883 2884
	}
}

T
Tom Lane 已提交
2885 2886 2887 2888 2889 2890 2891
/*
 * 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.
 */
2892 2893 2894
static bool
RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
{
2895
	pg_crc32	crc;
2896 2897
	int			i;
	uint32		len = record->xl_len;
2898
	BkpBlock	bkpb;
2899 2900
	char	   *blk;

2901 2902 2903
	/* First the rmgr data */
	INIT_CRC32(crc);
	COMP_CRC32(crc, XLogRecGetData(record), len);
2904

2905
	/* Add in the backup blocks, if any */
B
Bruce Momjian 已提交
2906
	blk = (char *) XLogRecGetData(record) + len;
T
Tom Lane 已提交
2907
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2908
	{
B
Bruce Momjian 已提交
2909
		uint32		blen;
2910

T
Tom Lane 已提交
2911
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2912 2913
			continue;

2914 2915
		memcpy(&bkpb, blk, sizeof(BkpBlock));
		if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2916
		{
2917
			ereport(emode,
2918 2919 2920
					(errmsg("incorrect hole size in record at %X/%X",
							recptr.xlogid, recptr.xrecoff)));
			return false;
2921
		}
2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
		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 已提交
2944 2945
		(errmsg("incorrect resource manager data checksum in record at %X/%X",
				recptr.xlogid, recptr.xrecoff)));
2946
		return false;
2947 2948
	}

2949
	return true;
2950 2951
}

T
Tom Lane 已提交
2952 2953 2954 2955 2956 2957
/*
 * 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.
 *
2958 2959
 * If no valid record is available, returns NULL, or fails if emode is PANIC.
 * (emode must be either PANIC or LOG.)
T
Tom Lane 已提交
2960
 *
2961 2962
 * The record is copied into readRecordBuf, so that on successful return,
 * the returned record pointer always points there.
T
Tom Lane 已提交
2963
 */
2964
static XLogRecord *
2965
ReadRecord(XLogRecPtr *RecPtr, int emode)
2966
{
2967
	XLogRecord *record;
2968
	char	   *buffer;
2969
	XLogRecPtr	tmpRecPtr = EndRecPtr;
2970
	bool		randAccess = false;
T
Tom Lane 已提交
2971 2972 2973
	uint32		len,
				total_len;
	uint32		targetPageOff;
2974 2975
	uint32		targetRecOff;
	uint32		pageHeaderSize;
T
Tom Lane 已提交
2976 2977 2978 2979

	if (readBuf == NULL)
	{
		/*
B
Bruce Momjian 已提交
2980 2981 2982 2983 2984
		 * 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 已提交
2985
		 */
2986
		readBuf = (char *) malloc(XLOG_BLCKSZ);
T
Tom Lane 已提交
2987 2988
		Assert(readBuf != NULL);
	}
2989

T
Tom Lane 已提交
2990
	if (RecPtr == NULL)
2991
	{
2992
		RecPtr = &tmpRecPtr;
T
Tom Lane 已提交
2993
		/* fast case if next record is on same page */
2994 2995 2996 2997 2998
		if (nextRecord != NULL)
		{
			record = nextRecord;
			goto got_record;
		}
T
Tom Lane 已提交
2999
		/* align old recptr to next page */
3000 3001
		if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
			tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
3002 3003 3004 3005 3006
		if (tmpRecPtr.xrecoff >= XLogFileSize)
		{
			(tmpRecPtr.xlogid)++;
			tmpRecPtr.xrecoff = 0;
		}
3007 3008 3009 3010 3011 3012 3013 3014
		/* 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 已提交
3015

3016
		/*
B
Bruce Momjian 已提交
3017 3018 3019 3020 3021
		 * 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).
3022 3023 3024
		 */
		lastPageTLI = 0;		/* see comment in ValidXLOGHeader */
		randAccess = true;		/* allow curFileTLI to go backwards too */
3025 3026
	}

T
Tom Lane 已提交
3027
	if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
3028
	{
3029 3030
		close(readFile);
		readFile = -1;
3031
	}
T
Tom Lane 已提交
3032
	XLByteToSeg(*RecPtr, readId, readSeg);
3033
	if (readFile < 0)
3034
	{
3035 3036 3037 3038 3039
		/* Now it's okay to reset curFileTLI if random fetch */
		if (randAccess)
			curFileTLI = 0;

		readFile = XLogFileRead(readId, readSeg, emode);
3040 3041
		if (readFile < 0)
			goto next_record_is_invalid;
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060

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

3063
	targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
T
Tom Lane 已提交
3064
	if (readOff != targetPageOff)
3065
	{
T
Tom Lane 已提交
3066 3067 3068
		readOff = targetPageOff;
		if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
		{
3069 3070
			ereport(emode,
					(errcode_for_file_access(),
3071
					 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
3072
							readId, readSeg, readOff)));
T
Tom Lane 已提交
3073 3074
			goto next_record_is_invalid;
		}
3075
		if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
T
Tom Lane 已提交
3076
		{
3077 3078
			ereport(emode,
					(errcode_for_file_access(),
3079
					 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3080
							readId, readSeg, readOff)));
T
Tom Lane 已提交
3081 3082
			goto next_record_is_invalid;
		}
3083
		if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3084 3085
			goto next_record_is_invalid;
	}
3086
	pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3087
	targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
3088 3089 3090
	if (targetRecOff == 0)
	{
		/*
B
Bruce Momjian 已提交
3091 3092 3093
		 * 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.
3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
		 */
		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 已提交
3105
	if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3106
		targetRecOff == pageHeaderSize)
3107
	{
3108 3109 3110
		ereport(emode,
				(errmsg("contrecord is requested by %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
3111 3112
		goto next_record_is_invalid;
	}
3113
	record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3114 3115

got_record:;
B
Bruce Momjian 已提交
3116

T
Tom Lane 已提交
3117
	/*
B
Bruce Momjian 已提交
3118 3119
	 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
	 * required.
T
Tom Lane 已提交
3120
	 */
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131
	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)
3132
	{
3133 3134 3135
		ereport(emode,
				(errmsg("record with zero length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
3136 3137
		goto next_record_is_invalid;
	}
3138 3139 3140 3141 3142 3143 3144 3145 3146
	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;
	}
3147 3148 3149 3150
	if (record->xl_rmid > RM_MAX_ID)
	{
		ereport(emode,
				(errmsg("invalid resource manager ID %u at %X/%X",
B
Bruce Momjian 已提交
3151
						record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3152 3153
		goto next_record_is_invalid;
	}
3154 3155 3156
	if (randAccess)
	{
		/*
B
Bruce Momjian 已提交
3157 3158
		 * We can't exactly verify the prev-link, but surely it should be less
		 * than the record's own address.
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
		 */
		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 已提交
3172 3173 3174
		 * 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.
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184
		 */
		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 已提交
3185

T
Tom Lane 已提交
3186
	/*
B
Bruce Momjian 已提交
3187
	 * Allocate or enlarge readRecordBuf as needed.  To avoid useless small
3188 3189 3190 3191
	 * 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 已提交
3192
	 */
3193
	total_len = record->xl_tot_len;
3194
	if (total_len > readRecordBufSize)
3195
	{
3196 3197
		uint32		newSize = total_len;

3198 3199
		newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
		newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
		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;
3213
	}
3214 3215

	buffer = readRecordBuf;
3216
	nextRecord = NULL;
3217
	len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
T
Tom Lane 已提交
3218
	if (total_len > len)
3219
	{
T
Tom Lane 已提交
3220 3221
		/* Need to reassemble record */
		XLogContRecord *contrecord;
B
Bruce Momjian 已提交
3222
		uint32		gotlen = len;
3223

T
Tom Lane 已提交
3224
		memcpy(buffer, record, len);
3225
		record = (XLogRecord *) buffer;
T
Tom Lane 已提交
3226
		buffer += len;
3227
		for (;;)
3228
		{
3229
			readOff += XLOG_BLCKSZ;
T
Tom Lane 已提交
3230
			if (readOff >= XLogSegSize)
3231 3232
			{
				close(readFile);
T
Tom Lane 已提交
3233 3234
				readFile = -1;
				NextLogSeg(readId, readSeg);
3235
				readFile = XLogFileRead(readId, readSeg, emode);
3236 3237
				if (readFile < 0)
					goto next_record_is_invalid;
T
Tom Lane 已提交
3238
				readOff = 0;
3239
			}
3240
			if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
T
Tom Lane 已提交
3241
			{
3242 3243
				ereport(emode,
						(errcode_for_file_access(),
T
Tom Lane 已提交
3244
						 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3245
								readId, readSeg, readOff)));
T
Tom Lane 已提交
3246 3247
				goto next_record_is_invalid;
			}
3248
			if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3249
				goto next_record_is_invalid;
T
Tom Lane 已提交
3250
			if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3251
			{
3252 3253 3254
				ereport(emode,
						(errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
								readId, readSeg, readOff)));
3255 3256
				goto next_record_is_invalid;
			}
3257 3258
			pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
			contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
B
Bruce Momjian 已提交
3259
			if (contrecord->xl_rem_len == 0 ||
T
Tom Lane 已提交
3260
				total_len != (contrecord->xl_rem_len + gotlen))
3261
			{
3262 3263 3264 3265
				ereport(emode,
						(errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
								contrecord->xl_rem_len,
								readId, readSeg, readOff)));
3266 3267
				goto next_record_is_invalid;
			}
3268
			len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
T
Tom Lane 已提交
3269
			if (contrecord->xl_rem_len > len)
3270
			{
B
Bruce Momjian 已提交
3271
				memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
T
Tom Lane 已提交
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
				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;
3282
		pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3283
		if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3284
			MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
T
Tom Lane 已提交
3285
		{
B
Bruce Momjian 已提交
3286
			nextRecord = (XLogRecord *) ((char *) contrecord +
B
Bruce Momjian 已提交
3287
					MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
T
Tom Lane 已提交
3288 3289 3290
		}
		EndRecPtr.xlogid = readId;
		EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3291 3292
			pageHeaderSize +
			MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
T
Tom Lane 已提交
3293
		ReadRecPtr = *RecPtr;
3294
		/* needn't worry about XLOG SWITCH, it can't cross page boundaries */
T
Tom Lane 已提交
3295
		return record;
3296 3297
	}

T
Tom Lane 已提交
3298 3299 3300
	/* Record does not cross a page boundary */
	if (!RecordIsValid(record, *RecPtr, emode))
		goto next_record_is_invalid;
3301
	if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
T
Tom Lane 已提交
3302 3303 3304 3305 3306 3307
		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 已提交
3308

3309 3310 3311 3312 3313 3314 3315 3316 3317
	/*
	 * 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 已提交
3318

3319
		/*
B
Bruce Momjian 已提交
3320 3321 3322
		 * 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.
3323 3324 3325
		 */
		readOff = XLogSegSize - XLOG_BLCKSZ;
	}
T
Tom Lane 已提交
3326
	return (XLogRecord *) buffer;
3327

T
Tom Lane 已提交
3328
next_record_is_invalid:;
3329 3330 3331 3332 3333
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
T
Tom Lane 已提交
3334 3335
	nextRecord = NULL;
	return NULL;
3336 3337
}

3338 3339 3340 3341
/*
 * 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 已提交
3342
 * ReadRecord.	It's not intended for use from anywhere else.
3343 3344
 */
static bool
3345
ValidXLOGHeader(XLogPageHeader hdr, int emode)
3346
{
3347 3348
	XLogRecPtr	recaddr;

3349 3350
	if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
	{
3351 3352 3353
		ereport(emode,
				(errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
						hdr->xlp_magic, readId, readSeg, readOff)));
3354 3355 3356 3357
		return false;
	}
	if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
	{
3358 3359 3360
		ereport(emode,
				(errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
						hdr->xlp_info, readId, readSeg, readOff)));
3361 3362
		return false;
	}
3363
	if (hdr->xlp_info & XLP_LONG_HEADER)
3364
	{
3365
		XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
B
Bruce Momjian 已提交
3366

3367
		if (longhdr->xlp_sysid != ControlFile->system_identifier)
3368
		{
3369 3370
			char		fhdrident_str[32];
			char		sysident_str[32];
3371

3372
			/*
B
Bruce Momjian 已提交
3373 3374
			 * Format sysids separately to keep platform-dependent format code
			 * out of the translatable message string.
3375 3376 3377 3378 3379 3380 3381
			 */
			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 已提交
3382 3383
					 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
							   fhdrident_str, sysident_str)));
3384 3385 3386 3387 3388 3389
			return false;
		}
		if (longhdr->xlp_seg_size != XLogSegSize)
		{
			ereport(emode,
					(errmsg("WAL file is from different system"),
B
Bruce Momjian 已提交
3390
					 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3391 3392
			return false;
		}
3393 3394 3395 3396 3397 3398 3399
		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;
		}
3400
	}
3401 3402 3403 3404 3405 3406 3407 3408 3409
	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;
	}

3410 3411 3412 3413 3414 3415
	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 已提交
3416
						hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
						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 已提交
3438 3439 3440
	 * 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.
3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457
	 */
	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 已提交
3458
 * its ancestor TLIs).	If we can't find the history file, assume that the
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
 * 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 已提交
3469
	FILE	   *fd;
3470 3471 3472 3473

	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, targetTLI);
3474
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3475 3476 3477 3478
	}
	else
		TLHistoryFilePath(path, targetTLI);

B
Bruce Momjian 已提交
3479
	fd = AllocateFile(path, "r");
3480 3481 3482 3483 3484
	if (fd == NULL)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
3485
					 errmsg("could not open file \"%s\": %m", path)));
3486 3487 3488 3489 3490 3491
		/* Not there, so assume no parents */
		return list_make1_int((int) targetTLI);
	}

	result = NIL;

B
Bruce Momjian 已提交
3492 3493 3494
	/*
	 * Parse the file...
	 */
3495
	while (fgets(fline, sizeof(fline), fd) != NULL)
3496 3497
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
3498 3499 3500
		char	   *ptr;
		char	   *endptr;
		TimeLineID	tli;
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520

		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 已提交
3521
				   errhint("Timeline IDs must be in increasing sequence.")));
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534

		/* 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 已提交
3535
			errhint("Timeline IDs must be less than child timeline's ID.")));
3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553

	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 已提交
3554
	FILE	   *fd;
3555 3556 3557 3558

	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, probeTLI);
3559
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
	}
	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 已提交
3575
					 errmsg("could not open file \"%s\": %m", path)));
3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
		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 已提交
3594 3595
	 * The algorithm is just to probe for the existence of timeline history
	 * files.  XXX is it useful to allow gaps in the sequence?
3596 3597 3598
	 */
	newestTLI = startTLI;

B
Bruce Momjian 已提交
3599
	for (probeTLI = startTLI + 1;; probeTLI++)
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
	{
		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 已提交
3623
 * considerations.	But we should be just as tense as XLogFileInit to avoid
3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638
 * 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 已提交
3639
	Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3640 3641 3642 3643

	/*
	 * Write into a temp file name.
	 */
3644
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3645 3646 3647

	unlink(tmppath);

3648
	/* do not use get_sync_bit() here --- want to fsync only at end of fill */
3649 3650 3651
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
3652
		ereport(ERROR,
3653 3654 3655 3656 3657 3658 3659 3660 3661
				(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);
3662
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3663 3664 3665 3666 3667 3668 3669 3670
	}
	else
		TLHistoryFilePath(path, parentTLI);

	srcfd = BasicOpenFile(path, O_RDONLY, 0);
	if (srcfd < 0)
	{
		if (errno != ENOENT)
3671
			ereport(ERROR,
3672
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
3673
					 errmsg("could not open file \"%s\": %m", path)));
3674 3675 3676 3677 3678 3679 3680 3681 3682
		/* Not there, so assume parent has no parents */
	}
	else
	{
		for (;;)
		{
			errno = 0;
			nbytes = (int) read(srcfd, buffer, sizeof(buffer));
			if (nbytes < 0 || errno != 0)
3683
				ereport(ERROR,
3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697
						(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 已提交
3698 3699

				/*
B
Bruce Momjian 已提交
3700
				 * if write didn't set errno, assume problem is no disk space
B
Bruce Momjian 已提交
3701
				 */
3702 3703
				errno = save_errno ? save_errno : ENOSPC;

3704
				ereport(ERROR,
3705
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
3706
					 errmsg("could not write to file \"%s\": %m", tmppath)));
3707 3708 3709 3710 3711 3712 3713 3714
			}
		}
		close(srcfd);
	}

	/*
	 * Append one line with the details of this timeline split.
	 *
B
Bruce Momjian 已提交
3715 3716
	 * If we did have a parent file, insert an extra newline just in case the
	 * parent file failed to end with one.
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726
	 */
	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,
3727
			 timestamptz_to_str(recoveryStopTime));
3728 3729 3730 3731 3732 3733 3734 3735

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

		/*
B
Bruce Momjian 已提交
3736
		 * If we fail to make the file, delete it to release disk space
3737 3738 3739 3740 3741
		 */
		unlink(tmppath);
		/* if write didn't set errno, assume problem is no disk space */
		errno = save_errno ? save_errno : ENOSPC;

3742
		ereport(ERROR,
3743 3744 3745 3746 3747
				(errcode_for_file_access(),
				 errmsg("could not write to file \"%s\": %m", tmppath)));
	}

	if (pg_fsync(fd) != 0)
3748
		ereport(ERROR,
3749 3750 3751 3752
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
3753
		ereport(ERROR,
3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769
				(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)
3770
		ereport(ERROR,
3771 3772 3773 3774 3775 3776
				(errcode_for_file_access(),
				 errmsg("could not link file \"%s\" to \"%s\": %m",
						tmppath, path)));
	unlink(tmppath);
#else
	if (rename(tmppath, path) < 0)
3777
		ereport(ERROR,
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
				(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
3790 3791
 *
 * *ControlFile is a buffer in shared memory that holds an image of the
B
Bruce Momjian 已提交
3792
 * contents of pg_control.	WriteControlFile() initializes pg_control
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805
 * 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 已提交
3806
	char		buffer[PG_CONTROL_SIZE];		/* need not be aligned */
3807 3808 3809
	char	   *localeptr;

	/*
T
Tom Lane 已提交
3810
	 * Initialize version and compatibility-check fields
3811
	 */
T
Tom Lane 已提交
3812 3813
	ControlFile->pg_control_version = PG_CONTROL_VERSION;
	ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3814 3815 3816 3817

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

3818 3819
	ControlFile->blcksz = BLCKSZ;
	ControlFile->relseg_size = RELSEG_SIZE;
3820
	ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3821
	ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3822 3823

	ControlFile->nameDataLen = NAMEDATALEN;
3824
	ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3825

3826 3827
	ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;

3828
#ifdef HAVE_INT64_TIMESTAMP
3829
	ControlFile->enableIntTimes = true;
3830
#else
3831
	ControlFile->enableIntTimes = false;
3832
#endif
3833 3834
	ControlFile->float4ByVal = FLOAT4PASSBYVAL;
	ControlFile->float8ByVal = FLOAT8PASSBYVAL;
3835 3836

	ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3837 3838
	localeptr = setlocale(LC_COLLATE, NULL);
	if (!localeptr)
3839 3840
		ereport(PANIC,
				(errmsg("invalid LC_COLLATE setting")));
3841 3842 3843
	StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
	localeptr = setlocale(LC_CTYPE, NULL);
	if (!localeptr)
3844 3845
		ereport(PANIC,
				(errmsg("invalid LC_CTYPE setting")));
3846
	StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
B
Bruce Momjian 已提交
3847

T
Tom Lane 已提交
3848
	/* Contents are protected with a CRC */
3849 3850 3851 3852 3853
	INIT_CRC32(ControlFile->crc);
	COMP_CRC32(ControlFile->crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(ControlFile->crc);
T
Tom Lane 已提交
3854

3855
	/*
3856 3857 3858 3859 3860
	 * 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".
3861
	 */
3862 3863
	if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
		elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3864

3865
	memset(buffer, 0, PG_CONTROL_SIZE);
3866 3867
	memcpy(buffer, ControlFile, sizeof(ControlFileData));

3868 3869
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3870
					   S_IRUSR | S_IWUSR);
3871
	if (fd < 0)
3872 3873 3874
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not create control file \"%s\": %m",
3875
						XLOG_CONTROL_FILE)));
3876

3877
	errno = 0;
3878
	if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3879 3880 3881 3882
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
3883 3884
		ereport(PANIC,
				(errcode_for_file_access(),
3885
				 errmsg("could not write to control file: %m")));
3886
	}
3887

3888
	if (pg_fsync(fd) != 0)
3889 3890
		ereport(PANIC,
				(errcode_for_file_access(),
3891
				 errmsg("could not fsync control file: %m")));
3892

3893 3894 3895 3896
	if (close(fd))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close control file: %m")));
3897 3898 3899 3900 3901
}

static void
ReadControlFile(void)
{
3902
	pg_crc32	crc;
3903 3904 3905 3906 3907
	int			fd;

	/*
	 * Read data...
	 */
3908 3909 3910
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
3911
	if (fd < 0)
3912 3913 3914
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
3915
						XLOG_CONTROL_FILE)));
3916 3917

	if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3918 3919
		ereport(PANIC,
				(errcode_for_file_access(),
3920
				 errmsg("could not read from control file: %m")));
3921 3922 3923

	close(fd);

T
Tom Lane 已提交
3924
	/*
B
Bruce Momjian 已提交
3925 3926 3927 3928
	 * 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 已提交
3929
	 */
3930 3931 3932 3933 3934 3935 3936 3937 3938 3939

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

T
Tom Lane 已提交
3940
	if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3941 3942 3943
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
B
Bruce Momjian 已提交
3944 3945
				  " but the server was compiled with PG_CONTROL_VERSION %d.",
						ControlFile->pg_control_version, PG_CONTROL_VERSION),
3946
				 errhint("It looks like you need to initdb.")));
3947

T
Tom Lane 已提交
3948
	/* Now check the CRC. */
3949 3950 3951 3952 3953
	INIT_CRC32(crc);
	COMP_CRC32(crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(crc);
3954

3955
	if (!EQ_CRC32(crc, ControlFile->crc))
3956
		ereport(FATAL,
3957
				(errmsg("incorrect checksum in control file")));
3958

3959
	/*
B
Bruce Momjian 已提交
3960
	 * Do compatibility checking immediately.  We do this here for 2 reasons:
3961
	 *
3962 3963
	 * (1) if the database isn't compatible with the backend executable, we
	 * want to abort before we can possibly do any damage;
3964 3965
	 *
	 * (2) this code is executed in the postmaster, so the setlocale() will
B
Bruce Momjian 已提交
3966 3967
	 * propagate to forked backends, which aren't going to read this file for
	 * themselves.	(These locale settings are considered critical
3968 3969
	 * compatibility items because they can affect sort order of indexes.)
	 */
T
Tom Lane 已提交
3970
	if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3971 3972 3973
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
B
Bruce Momjian 已提交
3974 3975
				  " but the server was compiled with CATALOG_VERSION_NO %d.",
						ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3976
				 errhint("It looks like you need to initdb.")));
3977 3978 3979
	if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
3980 3981 3982 3983
		   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.")));
3984 3985 3986
	if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
P
Peter Eisentraut 已提交
3987
				 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3988
				 errhint("It looks like you need to initdb.")));
3989
	if (ControlFile->blcksz != BLCKSZ)
3990 3991
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
3992 3993 3994 3995
			 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.")));
3996
	if (ControlFile->relseg_size != RELSEG_SIZE)
3997 3998
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
3999 4000 4001 4002
		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.")));
4003 4004 4005
	if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
4006 4007 4008
		errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
				  " but the server was compiled with XLOG_BLCKSZ %d.",
				  ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4009
				 errhint("It looks like you need to recompile or initdb.")));
4010 4011 4012 4013
	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 已提交
4014
					   " but the server was compiled with XLOG_SEG_SIZE %d.",
4015
						   ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
B
Bruce Momjian 已提交
4016
				 errhint("It looks like you need to recompile or initdb.")));
4017
	if (ControlFile->nameDataLen != NAMEDATALEN)
4018 4019
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
4020 4021 4022 4023
		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.")));
4024
	if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4025 4026
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
4027
				 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
B
Bruce Momjian 已提交
4028
					  " but the server was compiled with INDEX_MAX_KEYS %d.",
4029
						   ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
B
Bruce Momjian 已提交
4030
				 errhint("It looks like you need to recompile or initdb.")));
4031 4032 4033 4034
	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 已提交
4035 4036
				" but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
			  ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4037
				 errhint("It looks like you need to recompile or initdb.")));
4038 4039

#ifdef HAVE_INT64_TIMESTAMP
4040
	if (ControlFile->enableIntTimes != true)
4041 4042 4043
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
4044 4045
				  " but the server was compiled with HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
4046
#else
4047
	if (ControlFile->enableIntTimes != false)
4048 4049 4050
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
4051 4052
			   " but the server was compiled without HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
4053 4054
#endif

4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086
#ifdef USE_FLOAT4_BYVAL
	if (ControlFile->float4ByVal != true)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without USE_FLOAT4_BYVAL"
						   " but the server was compiled with USE_FLOAT4_BYVAL."),
				 errhint("It looks like you need to recompile or initdb.")));
#else
	if (ControlFile->float4ByVal != false)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
						   " but the server was compiled without USE_FLOAT4_BYVAL."),
				 errhint("It looks like you need to recompile or initdb.")));
#endif

#ifdef USE_FLOAT8_BYVAL
	if (ControlFile->float8ByVal != true)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
						   " but the server was compiled with USE_FLOAT8_BYVAL."),
				 errhint("It looks like you need to recompile or initdb.")));
#else
	if (ControlFile->float8ByVal != false)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
						   " but the server was compiled without USE_FLOAT8_BYVAL."),
				 errhint("It looks like you need to recompile or initdb.")));
#endif

4087
	if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
4088 4089 4090
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
B
Bruce Momjian 已提交
4091
				  " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
4092
						   ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
B
Bruce Momjian 已提交
4093
				 errhint("It looks like you need to recompile or initdb.")));
4094
	if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
4095
		ereport(FATAL,
B
Bruce Momjian 已提交
4096 4097 4098 4099 4100
			(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.")));
4101
	if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
4102
		ereport(FATAL,
B
Bruce Momjian 已提交
4103 4104 4105 4106 4107
			(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.")));
4108 4109 4110 4111 4112 4113

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

4116
void
4117
UpdateControlFile(void)
4118
{
4119
	int			fd;
4120

4121 4122 4123 4124 4125
	INIT_CRC32(ControlFile->crc);
	COMP_CRC32(ControlFile->crc,
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(ControlFile->crc);
4126

4127 4128 4129
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
4130
	if (fd < 0)
4131 4132 4133
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
4134
						XLOG_CONTROL_FILE)));
4135

4136
	errno = 0;
4137
	if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4138 4139 4140 4141
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
4142 4143
		ereport(PANIC,
				(errcode_for_file_access(),
4144
				 errmsg("could not write to control file: %m")));
4145
	}
4146

4147
	if (pg_fsync(fd) != 0)
4148 4149
		ereport(PANIC,
				(errcode_for_file_access(),
4150
				 errmsg("could not fsync control file: %m")));
4151

4152 4153 4154 4155
	if (close(fd))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close control file: %m")));
4156 4157
}

4158
/*
T
Tom Lane 已提交
4159
 * Initialization of shared memory for XLOG
4160
 */
4161
Size
4162
XLOGShmemSize(void)
4163
{
4164
	Size		size;
4165

4166 4167 4168 4169 4170 4171 4172
	/* 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 */
4173
	size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4174 4175

	/*
B
Bruce Momjian 已提交
4176 4177 4178
	 * 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.
4179 4180 4181
	 */

	return size;
4182 4183 4184 4185 4186
}

void
XLOGShmemInit(void)
{
4187 4188
	bool		foundCFile,
				foundXLog;
4189
	char	   *allocptr;
4190

4191
	ControlFile = (ControlFileData *)
4192
		ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4193 4194
	XLogCtl = (XLogCtlData *)
		ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4195

4196
	if (foundCFile || foundXLog)
4197 4198
	{
		/* both should be present or neither */
4199
		Assert(foundCFile && foundXLog);
4200 4201
		return;
	}
4202

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

T
Tom Lane 已提交
4205
	/*
B
Bruce Momjian 已提交
4206 4207 4208
	 * 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 已提交
4209
	 */
4210 4211
	allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
	XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
T
Tom Lane 已提交
4212
	memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4213
	allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
B
Bruce Momjian 已提交
4214

T
Tom Lane 已提交
4215
	/*
4216
	 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
T
Tom Lane 已提交
4217
	 */
4218 4219
	allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
	XLogCtl->pages = allocptr;
4220
	memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
T
Tom Lane 已提交
4221 4222

	/*
B
Bruce Momjian 已提交
4223 4224
	 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
	 * in additional info.)
T
Tom Lane 已提交
4225 4226 4227
	 */
	XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
	XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4228
	SpinLockInit(&XLogCtl->info_lck);
T
Tom Lane 已提交
4229

4230
	/*
B
Bruce Momjian 已提交
4231 4232 4233
	 * 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).
4234 4235 4236
	 */
	if (!IsBootstrapProcessingMode())
		ReadControlFile();
4237 4238 4239
}

/*
T
Tom Lane 已提交
4240 4241
 * This func must be called ONCE on system install.  It creates pg_control
 * and the initial XLOG segment.
4242 4243
 */
void
T
Tom Lane 已提交
4244
BootStrapXLOG(void)
4245
{
4246
	CheckPoint	checkPoint;
T
Tom Lane 已提交
4247 4248
	char	   *buffer;
	XLogPageHeader page;
4249
	XLogLongPageHeader longpage;
4250
	XLogRecord *record;
B
Bruce Momjian 已提交
4251
	bool		use_existent;
4252 4253
	uint64		sysidentifier;
	struct timeval tv;
4254
	pg_crc32	crc;
4255

4256
	/*
B
Bruce Momjian 已提交
4257 4258 4259 4260 4261 4262 4263 4264 4265 4266
	 * 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.
4267 4268 4269 4270 4271
	 */
	gettimeofday(&tv, NULL);
	sysidentifier = ((uint64) tv.tv_sec) << 32;
	sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);

4272 4273 4274
	/* First timeline ID is always 1 */
	ThisTimeLineID = 1;

4275
	/* page buffer must be aligned suitably for O_DIRECT */
4276
	buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4277
	page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4278
	memset(page, 0, XLOG_BLCKSZ);
T
Tom Lane 已提交
4279

4280
	/* Set up information for the initial checkpoint record */
4281
	checkPoint.redo.xlogid = 0;
4282 4283
	checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
	checkPoint.ThisTimeLineID = ThisTimeLineID;
4284
	checkPoint.nextXidEpoch = 0;
4285
	checkPoint.nextXid = FirstNormalTransactionId;
4286
	checkPoint.nextOid = FirstBootstrapObjectId;
4287
	checkPoint.nextMulti = FirstMultiXactId;
4288
	checkPoint.nextMultiOffset = 0;
4289
	checkPoint.time = (pg_time_t) time(NULL);
4290

4291 4292 4293
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
	ShmemVariableCache->oidCount = 0;
4294
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4295

4296
	/* Set up the XLOG page header */
4297
	page->xlp_magic = XLOG_PAGE_MAGIC;
4298 4299
	page->xlp_info = XLP_LONG_HEADER;
	page->xlp_tli = ThisTimeLineID;
4300 4301
	page->xlp_pageaddr.xlogid = 0;
	page->xlp_pageaddr.xrecoff = 0;
4302 4303 4304
	longpage = (XLogLongPageHeader) page;
	longpage->xlp_sysid = sysidentifier;
	longpage->xlp_seg_size = XLogSegSize;
4305
	longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4306 4307

	/* Insert the initial checkpoint record */
4308
	record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4309
	record->xl_prev.xlogid = 0;
4310
	record->xl_prev.xrecoff = 0;
4311
	record->xl_xid = InvalidTransactionId;
4312
	record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4313
	record->xl_len = sizeof(checkPoint);
T
Tom Lane 已提交
4314
	record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4315
	record->xl_rmid = RM_XLOG_ID;
T
Tom Lane 已提交
4316
	memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4317

4318 4319 4320 4321 4322
	INIT_CRC32(crc);
	COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
	COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
			   SizeOfXLogRecord - sizeof(pg_crc32));
	FIN_CRC32(crc);
4323 4324
	record->xl_crc = crc;

4325
	/* Create first XLOG segment file */
4326 4327
	use_existent = false;
	openLogFile = XLogFileInit(0, 0, &use_existent, false);
4328

4329
	/* Write the first page with the initial record */
4330
	errno = 0;
4331
	if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4332 4333 4334 4335
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
4336 4337
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4338
			  errmsg("could not write bootstrap transaction log file: %m")));
4339
	}
4340

T
Tom Lane 已提交
4341
	if (pg_fsync(openLogFile) != 0)
4342 4343
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4344
			  errmsg("could not fsync bootstrap transaction log file: %m")));
4345

4346 4347 4348
	if (close(openLogFile))
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
4349
			  errmsg("could not close bootstrap transaction log file: %m")));
4350

T
Tom Lane 已提交
4351
	openLogFile = -1;
4352

4353 4354
	/* Now create pg_control */

4355
	memset(ControlFile, 0, sizeof(ControlFileData));
T
Tom Lane 已提交
4356
	/* Initialize pg_control status fields */
4357
	ControlFile->system_identifier = sysidentifier;
T
Tom Lane 已提交
4358 4359
	ControlFile->state = DB_SHUTDOWNED;
	ControlFile->time = checkPoint.time;
4360
	ControlFile->checkPoint = checkPoint.redo;
T
Tom Lane 已提交
4361
	ControlFile->checkPointCopy = checkPoint;
4362
	/* some additional ControlFile fields are set in WriteControlFile() */
4363

4364
	WriteControlFile();
4365 4366 4367

	/* Bootstrap the commit log, too */
	BootStrapCLOG();
4368
	BootStrapSUBTRANS();
4369
	BootStrapMultiXact();
4370

4371
	pfree(buffer);
4372 4373
}

4374
static char *
4375
str_time(pg_time_t tnow)
4376
{
4377
	static char buf[128];
4378

4379 4380 4381
	pg_strftime(buf, sizeof(buf),
				"%Y-%m-%d %H:%M:%S %Z",
				pg_localtime(&tnow, log_timezone));
4382

4383
	return buf;
4384 4385
}

4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396
/*
 * 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 已提交
4397 4398 4399 4400 4401 4402
	FILE	   *fd;
	char		cmdline[MAXPGPATH];
	TimeLineID	rtli = 0;
	bool		rtliGiven = false;
	bool		syntaxError = false;

4403
	fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4404 4405 4406 4407 4408
	if (fd == NULL)
	{
		if (errno == ENOENT)
			return;				/* not there, so no archive recovery */
		ereport(FATAL,
B
Bruce Momjian 已提交
4409
				(errcode_for_file_access(),
4410
				 errmsg("could not open recovery command file \"%s\": %m",
4411
						RECOVERY_COMMAND_FILE)));
4412 4413 4414
	}

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

B
Bruce Momjian 已提交
4417 4418 4419
	/*
	 * Parse the file...
	 */
4420
	while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4421 4422
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
4423 4424 4425
		char	   *ptr;
		char	   *tok1;
		char	   *tok2;
4426 4427 4428 4429 4430 4431 4432 4433 4434 4435

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

		/* identify the quoted parameter value */
B
Bruce Momjian 已提交
4436
		tok1 = strtok(ptr, "'");
4437 4438 4439 4440 4441
		if (!tok1)
		{
			syntaxError = true;
			break;
		}
B
Bruce Momjian 已提交
4442
		tok2 = strtok(NULL, "'");
4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455
		if (!tok2)
		{
			syntaxError = true;
			break;
		}
		/* reparse to get just the parameter name */
		tok1 = strtok(ptr, " \t=");
		if (!tok1)
		{
			syntaxError = true;
			break;
		}

B
Bruce Momjian 已提交
4456 4457
		if (strcmp(tok1, "restore_command") == 0)
		{
4458
			recoveryRestoreCommand = pstrdup(tok2);
4459
			ereport(LOG,
4460
					(errmsg("restore_command = '%s'",
4461 4462
							recoveryRestoreCommand)));
		}
B
Bruce Momjian 已提交
4463 4464
		else if (strcmp(tok1, "recovery_target_timeline") == 0)
		{
4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483
			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 已提交
4484 4485
		else if (strcmp(tok1, "recovery_target_xid") == 0)
		{
4486 4487 4488 4489
			errno = 0;
			recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
			if (errno == EINVAL || errno == ERANGE)
				ereport(FATAL,
B
Bruce Momjian 已提交
4490 4491
				 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
						 tok2)));
4492 4493 4494 4495 4496 4497
			ereport(LOG,
					(errmsg("recovery_target_xid = %u",
							recoveryTargetXid)));
			recoveryTarget = true;
			recoveryTargetExact = true;
		}
B
Bruce Momjian 已提交
4498 4499
		else if (strcmp(tok1, "recovery_target_time") == 0)
		{
4500 4501 4502 4503 4504 4505 4506 4507
			/*
			 * if recovery_target_xid specified, then this overrides
			 * recovery_target_time
			 */
			if (recoveryTargetExact)
				continue;
			recoveryTarget = true;
			recoveryTargetExact = false;
B
Bruce Momjian 已提交
4508

4509
			/*
4510
			 * Convert the time string given by the user to TimestampTz form.
4511
			 */
4512 4513
			recoveryTargetTime =
				DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
B
Bruce Momjian 已提交
4514
														CStringGetDatum(tok2),
4515 4516
												ObjectIdGetDatum(InvalidOid),
														Int32GetDatum(-1)));
4517
			ereport(LOG,
4518
					(errmsg("recovery_target_time = '%s'",
4519
							timestamptz_to_str(recoveryTargetTime))));
4520
		}
B
Bruce Momjian 已提交
4521 4522
		else if (strcmp(tok1, "recovery_target_inclusive") == 0)
		{
4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535
			/*
			 * 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)));
		}
4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550
		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)));
		}
4551 4552 4553 4554 4555 4556 4557 4558
		else
			ereport(FATAL,
					(errmsg("unrecognized recovery parameter \"%s\"",
							tok1)));
	}

	FreeFile(fd);

B
Bruce Momjian 已提交
4559 4560
	if (syntaxError)
		ereport(FATAL,
4561 4562
				(errmsg("syntax error in recovery command file: %s",
						cmdline),
B
Bruce Momjian 已提交
4563
			  errhint("Lines should have the format parameter = 'value'.")));
4564 4565

	/* Check that required parameters were supplied */
4566
	if (recoveryRestoreCommand == NULL)
4567 4568
		ereport(FATAL,
				(errmsg("recovery command file \"%s\" did not specify restore_command",
4569
						RECOVERY_COMMAND_FILE)));
4570

4571 4572 4573
	/* Enable fetching from archive recovery area */
	InArchiveRecovery = true;

4574
	/*
B
Bruce Momjian 已提交
4575 4576 4577 4578
	 * 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.
4579
	 */
4580 4581 4582 4583 4584 4585 4586
	if (rtliGiven)
	{
		if (rtli)
		{
			/* Timeline 1 does not have a history file, all else should */
			if (rtli != 1 && !existsTimeLineHistory(rtli))
				ereport(FATAL,
4587
						(errmsg("recovery target timeline %u does not exist",
B
Bruce Momjian 已提交
4588
								rtli)));
4589 4590 4591 4592 4593 4594 4595 4596
			recoveryTargetTLI = rtli;
		}
		else
		{
			/* We start the "latest" search from pg_control's timeline */
			recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
		}
	}
4597 4598 4599 4600 4601 4602
}

/*
 * Exit archive-recovery state
 */
static void
4603
exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4604
{
B
Bruce Momjian 已提交
4605 4606
	char		recoveryPath[MAXPGPATH];
	char		xlogpath[MAXPGPATH];
4607 4608

	/*
4609
	 * We are no longer in archive recovery state.
4610 4611 4612 4613
	 */
	InArchiveRecovery = false;

	/*
B
Bruce Momjian 已提交
4614 4615 4616
	 * 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).
4617 4618 4619 4620 4621 4622 4623 4624 4625
	 */
	Assert(readFile >= 0);
	Assert(readId == endLogId);
	Assert(readSeg == endLogSeg);

	close(readFile);
	readFile = -1;

	/*
B
Bruce Momjian 已提交
4626 4627 4628 4629 4630 4631 4632
	 * 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.
4633
	 *
4634 4635
	 * 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
4636 4637
	 * of overwriting any existing file.  (This is, in fact, always the case
	 * at present.)
4638
	 */
4639
	snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4640
	XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4641 4642 4643 4644 4645 4646 4647 4648 4649 4650

	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(),
4651
					 errmsg("could not rename file \"%s\" to \"%s\": %m",
4652 4653 4654 4655 4656 4657 4658 4659 4660 4661
							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 已提交
4662

4663
		/*
B
Bruce Momjian 已提交
4664 4665 4666
		 * 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.
4667 4668 4669 4670
		 */
		if (endTLI != ThisTimeLineID)
			XLogFileCopy(endLogId, endLogSeg,
						 endTLI, endLogId, endLogSeg);
4671 4672 4673
	}

	/*
B
Bruce Momjian 已提交
4674 4675
	 * Let's just make real sure there are not .ready or .done flags posted
	 * for the new segment.
4676
	 */
4677 4678
	XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
	XLogArchiveCleanup(xlogpath);
4679

4680
	/* Get rid of any remaining recovered timeline-history file, too */
4681
	snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
B
Bruce Momjian 已提交
4682
	unlink(recoveryPath);		/* ignore any error */
4683 4684

	/*
B
Bruce Momjian 已提交
4685 4686
	 * Rename the config file out of the way, so that we don't accidentally
	 * re-enter archive recovery mode in a subsequent crash.
4687
	 */
4688 4689
	unlink(RECOVERY_COMMAND_DONE);
	if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4690 4691
		ereport(FATAL,
				(errcode_for_file_access(),
4692
				 errmsg("could not rename file \"%s\" to \"%s\": %m",
4693
						RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704

	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.
4705 4706
 * Also, some information is saved in recoveryStopXid et al for use in
 * annotating the new timeline's history file.
4707 4708 4709 4710 4711
 */
static bool
recoveryStopsHere(XLogRecord *record, bool *includeThis)
{
	bool		stopsHere;
B
Bruce Momjian 已提交
4712
	uint8		record_info;
B
Bruce Momjian 已提交
4713
	TimestampTz recordXtime;
4714 4715 4716 4717 4718 4719 4720

	/* 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 已提交
4721
		xl_xact_commit *recordXactCommitData;
4722 4723

		recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4724
		recordXtime = recordXactCommitData->xact_time;
4725 4726 4727
	}
	else if (record_info == XLOG_XACT_ABORT)
	{
B
Bruce Momjian 已提交
4728
		xl_xact_abort *recordXactAbortData;
4729 4730

		recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4731
		recordXtime = recordXactAbortData->xact_time;
4732 4733 4734 4735
	}
	else
		return false;

4736 4737 4738 4739 4740 4741 4742
	/* Remember the most recent COMMIT/ABORT time for logging purposes */
	recoveryLastXTime = recordXtime;

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

4743 4744 4745
	if (recoveryTargetExact)
	{
		/*
B
Bruce Momjian 已提交
4746 4747
		 * there can be only one transaction end record with this exact
		 * transactionid
4748
		 *
B
Bruce Momjian 已提交
4749
		 * when testing for an xid, we MUST test for equality only, since
B
Bruce Momjian 已提交
4750 4751 4752
		 * 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...
4753 4754 4755 4756 4757 4758 4759 4760
		 */
		stopsHere = (record->xl_xid == recoveryTargetXid);
		if (stopsHere)
			*includeThis = recoveryTargetInclusive;
	}
	else
	{
		/*
B
Bruce Momjian 已提交
4761 4762 4763
		 * 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
4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774
		 */
		if (recoveryTargetInclusive)
			stopsHere = (recordXtime > recoveryTargetTime);
		else
			stopsHere = (recordXtime >= recoveryTargetTime);
		if (stopsHere)
			*includeThis = false;
	}

	if (stopsHere)
	{
4775 4776 4777 4778
		recoveryStopXid = record->xl_xid;
		recoveryStopTime = recordXtime;
		recoveryStopAfter = *includeThis;

4779 4780
		if (record_info == XLOG_XACT_COMMIT)
		{
4781
			if (recoveryStopAfter)
4782 4783
				ereport(LOG,
						(errmsg("recovery stopping after commit of transaction %u, time %s",
4784 4785
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
4786 4787 4788
			else
				ereport(LOG,
						(errmsg("recovery stopping before commit of transaction %u, time %s",
4789 4790
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
4791 4792 4793
		}
		else
		{
4794
			if (recoveryStopAfter)
4795 4796
				ereport(LOG,
						(errmsg("recovery stopping after abort of transaction %u, time %s",
4797 4798
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
4799 4800 4801
			else
				ereport(LOG,
						(errmsg("recovery stopping before abort of transaction %u, time %s",
4802 4803
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
4804 4805 4806 4807 4808 4809
		}
	}

	return stopsHere;
}

4810
/*
T
Tom Lane 已提交
4811
 * This must be called ONCE during postmaster or standalone-backend startup
4812 4813
 */
void
T
Tom Lane 已提交
4814
StartupXLOG(void)
4815
{
4816 4817
	XLogCtlInsert *Insert;
	CheckPoint	checkPoint;
T
Tom Lane 已提交
4818
	bool		wasShutdown;
4819
	bool		reachedStopPoint = false;
4820
	bool		haveBackupLabel = false;
4821
	XLogRecPtr	RecPtr,
T
Tom Lane 已提交
4822 4823
				LastRec,
				checkPointLoc,
4824
				minRecoveryLoc,
T
Tom Lane 已提交
4825
				EndOfLog;
4826 4827
	uint32		endLogId;
	uint32		endLogSeg;
4828
	XLogRecord *record;
4829
	uint32		freespace;
4830
	TransactionId oldestActiveXID;
4831

4832
	/*
4833 4834
	 * Read control file and check XLOG status looks valid.
	 *
4835 4836
	 * 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.
4837
	 */
4838
	ReadControlFile();
4839

4840
	if (ControlFile->state < DB_SHUTDOWNED ||
4841
		ControlFile->state > DB_IN_PRODUCTION ||
4842
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4843 4844
		ereport(FATAL,
				(errmsg("control file contains invalid data")));
4845 4846

	if (ControlFile->state == DB_SHUTDOWNED)
4847 4848 4849
		ereport(LOG,
				(errmsg("database system was shut down at %s",
						str_time(ControlFile->time))));
4850
	else if (ControlFile->state == DB_SHUTDOWNING)
4851
		ereport(LOG,
4852
				(errmsg("database system shutdown was interrupted; last known up at %s",
4853
						str_time(ControlFile->time))));
4854
	else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4855
		ereport(LOG,
B
Bruce Momjian 已提交
4856 4857 4858 4859
		   (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.")));
4860 4861
	else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
		ereport(LOG,
B
Bruce Momjian 已提交
4862 4863
				(errmsg("database system was interrupted while in recovery at log time %s",
						str_time(ControlFile->checkPointCopy.time)),
4864
				 errhint("If this has occurred more than once some data might be corrupted"
B
Bruce Momjian 已提交
4865
			  " and you might need to choose an earlier recovery target.")));
4866
	else if (ControlFile->state == DB_IN_PRODUCTION)
4867
		ereport(LOG,
B
Bruce Momjian 已提交
4868 4869
			  (errmsg("database system was interrupted; last known up at %s",
					  str_time(ControlFile->time))));
4870

4871 4872
	/* This is just to allow attaching to startup process with a debugger */
#ifdef XLOG_REPLAY_DELAY
4873
	if (ControlFile->state != DB_SHUTDOWNED)
4874
		pg_usleep(60000000L);
4875 4876
#endif

4877
	/*
B
Bruce Momjian 已提交
4878 4879
	 * Initialize on the assumption we want to recover to the same timeline
	 * that's active according to pg_control.
4880 4881 4882
	 */
	recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;

4883
	/*
B
Bruce Momjian 已提交
4884 4885
	 * Check for recovery control file, and if so set up state for offline
	 * recovery
4886 4887 4888
	 */
	readRecoveryCommandFile();

4889 4890 4891
	/* Now we can determine the list of expected TLIs */
	expectedTLIs = readTimeLineHistory(recoveryTargetTLI);

4892 4893 4894 4895 4896 4897
	/*
	 * 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 已提交
4898
						 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4899 4900 4901 4902 4903
		ereport(FATAL,
				(errmsg("requested timeline %u is not a child of database system timeline %u",
						recoveryTargetTLI,
						ControlFile->checkPointCopy.ThisTimeLineID)));

4904
	if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
T
Tom Lane 已提交
4905
	{
4906
		/*
B
Bruce Momjian 已提交
4907 4908
		 * When a backup_label file is present, we want to roll forward from
		 * the checkpoint it identifies, rather than using pg_control.
4909
		 */
4910
		record = ReadCheckpointRecord(checkPointLoc, 0);
4911 4912
		if (record != NULL)
		{
4913
			ereport(DEBUG1,
4914
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
4915
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4916 4917 4918 4919 4920
			InRecovery = true;	/* force recovery even if SHUTDOWNED */
		}
		else
		{
			ereport(PANIC,
B
Bruce Momjian 已提交
4921 4922
					(errmsg("could not locate required checkpoint record"),
					 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4923
		}
4924 4925
		/* set flag to delete it later */
		haveBackupLabel = true;
T
Tom Lane 已提交
4926 4927 4928
	}
	else
	{
4929
		/*
B
Bruce Momjian 已提交
4930 4931
		 * Get the last valid checkpoint record.  If the latest one according
		 * to pg_control is broken, try the next-to-last one.
4932 4933
		 */
		checkPointLoc = ControlFile->checkPoint;
4934
		record = ReadCheckpointRecord(checkPointLoc, 1);
T
Tom Lane 已提交
4935 4936
		if (record != NULL)
		{
4937
			ereport(DEBUG1,
4938
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
4939
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
T
Tom Lane 已提交
4940 4941
		}
		else
4942 4943
		{
			checkPointLoc = ControlFile->prevCheckPoint;
4944
			record = ReadCheckpointRecord(checkPointLoc, 2);
4945 4946 4947
			if (record != NULL)
			{
				ereport(LOG,
B
Bruce Momjian 已提交
4948 4949 4950
						(errmsg("using previous checkpoint record at %X/%X",
							  checkPointLoc.xlogid, checkPointLoc.xrecoff)));
				InRecovery = true;		/* force recovery even if SHUTDOWNED */
4951 4952 4953
			}
			else
				ereport(PANIC,
B
Bruce Momjian 已提交
4954
					 (errmsg("could not locate a valid checkpoint record")));
4955
		}
T
Tom Lane 已提交
4956
	}
4957

T
Tom Lane 已提交
4958 4959 4960
	LastRec = RecPtr = checkPointLoc;
	memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
	wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4961

4962
	ereport(DEBUG1,
B
Bruce Momjian 已提交
4963 4964 4965
			(errmsg("redo record is at %X/%X; shutdown %s",
					checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
					wasShutdown ? "TRUE" : "FALSE")));
4966
	ereport(DEBUG1,
4967 4968 4969
			(errmsg("next transaction ID: %u/%u; next OID: %u",
					checkPoint.nextXidEpoch, checkPoint.nextXid,
					checkPoint.nextOid)));
4970
	ereport(DEBUG1,
4971 4972
			(errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
					checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4973
	if (!TransactionIdIsNormal(checkPoint.nextXid))
4974
		ereport(PANIC,
4975
				(errmsg("invalid next transaction ID")));
4976 4977 4978

	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
4979
	ShmemVariableCache->oidCount = 0;
4980
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4981

4982
	/*
B
Bruce Momjian 已提交
4983 4984 4985
	 * 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()).
4986
	 */
4987
	ThisTimeLineID = checkPoint.ThisTimeLineID;
4988

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

4991
	if (XLByteLT(RecPtr, checkPoint.redo))
4992 4993
		ereport(PANIC,
				(errmsg("invalid redo in checkpoint record")));
4994

4995
	/*
B
Bruce Momjian 已提交
4996
	 * Check whether we need to force recovery from WAL.  If it appears to
B
Bruce Momjian 已提交
4997 4998
	 * have been a clean shutdown and we did not have a recovery.conf file,
	 * then assume no recovery needed.
4999
	 */
5000
	if (XLByteLT(checkPoint.redo, RecPtr))
5001
	{
T
Tom Lane 已提交
5002
		if (wasShutdown)
5003
			ereport(PANIC,
B
Bruce Momjian 已提交
5004
					(errmsg("invalid redo record in shutdown checkpoint")));
V
WAL  
Vadim B. Mikheev 已提交
5005
		InRecovery = true;
5006 5007
	}
	else if (ControlFile->state != DB_SHUTDOWNED)
V
WAL  
Vadim B. Mikheev 已提交
5008
		InRecovery = true;
5009 5010 5011 5012 5013
	else if (InArchiveRecovery)
	{
		/* force recovery due to presence of recovery.conf */
		InRecovery = true;
	}
5014

V
WAL  
Vadim B. Mikheev 已提交
5015
	/* REDO */
5016
	if (InRecovery)
5017
	{
B
Bruce Momjian 已提交
5018
		int			rmid;
5019

5020
		/*
B
Bruce Momjian 已提交
5021 5022 5023 5024
		 * 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.
5025
		 */
5026
		if (InArchiveRecovery)
5027
		{
5028
			ereport(LOG,
5029
					(errmsg("automatic recovery in progress")));
5030 5031
			ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
		}
5032
		else
5033
		{
5034
			ereport(LOG,
5035 5036
					(errmsg("database system was not properly shut down; "
							"automatic recovery in progress")));
5037 5038 5039 5040 5041 5042 5043
			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;
5044
		ControlFile->time = (pg_time_t) time(NULL);
5045 5046
		UpdateControlFile();

5047
		/*
B
Bruce Momjian 已提交
5048 5049 5050 5051 5052 5053
		 * 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.
5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064
		 */
		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)));
		}

5065
		/* Initialize resource managers */
5066 5067 5068 5069 5070 5071
		for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
		{
			if (RmgrTable[rmid].rm_startup != NULL)
				RmgrTable[rmid].rm_startup();
		}

5072
		/*
B
Bruce Momjian 已提交
5073 5074
		 * Find the first record that logically follows the checkpoint --- it
		 * might physically precede it, though.
5075
		 */
5076
		if (XLByteLT(checkPoint.redo, RecPtr))
5077 5078
		{
			/* back up to find the record */
5079
			record = ReadRecord(&(checkPoint.redo), PANIC);
5080
		}
B
Bruce Momjian 已提交
5081
		else
5082
		{
5083
			/* just have to read next record after CheckPoint */
5084
			record = ReadRecord(NULL, LOG);
5085
		}
5086

T
Tom Lane 已提交
5087
		if (record != NULL)
5088
		{
5089 5090
			bool		recoveryContinue = true;
			bool		recoveryApply = true;
B
Bruce Momjian 已提交
5091
			ErrorContextCallback errcontext;
5092

V
WAL  
Vadim B. Mikheev 已提交
5093
			InRedo = true;
5094 5095 5096
			ereport(LOG,
					(errmsg("redo starts at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5097 5098 5099 5100

			/*
			 * main redo apply loop
			 */
5101 5102
			do
			{
5103
#ifdef WAL_DEBUG
V
WAL  
Vadim B. Mikheev 已提交
5104 5105
				if (XLOG_DEBUG)
				{
B
Bruce Momjian 已提交
5106
					StringInfoData buf;
V
WAL  
Vadim B. Mikheev 已提交
5107

5108 5109
					initStringInfo(&buf);
					appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
B
Bruce Momjian 已提交
5110 5111
									 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
									 EndRecPtr.xlogid, EndRecPtr.xrecoff);
5112 5113 5114 5115
					xlog_outrec(&buf, record);
					appendStringInfo(&buf, " - ");
					RmgrTable[record->xl_rmid].rm_desc(&buf,
													   record->xl_info,
B
Bruce Momjian 已提交
5116
													 XLogRecGetData(record));
5117 5118
					elog(LOG, "%s", buf.data);
					pfree(buf.data);
V
WAL  
Vadim B. Mikheev 已提交
5119
				}
5120
#endif
V
WAL  
Vadim B. Mikheev 已提交
5121

5122 5123 5124 5125 5126
				/*
				 * Have we reached our recovery target?
				 */
				if (recoveryStopsHere(record, &recoveryApply))
				{
B
Bruce Momjian 已提交
5127
					reachedStopPoint = true;	/* see below */
5128 5129 5130 5131 5132
					recoveryContinue = false;
					if (!recoveryApply)
						break;
				}

5133 5134 5135 5136 5137 5138
				/* 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;

5139 5140
				/* nextXid must be beyond record's xid */
				if (TransactionIdFollowsOrEquals(record->xl_xid,
B
Bruce Momjian 已提交
5141
												 ShmemVariableCache->nextXid))
5142 5143 5144 5145 5146
				{
					ShmemVariableCache->nextXid = record->xl_xid;
					TransactionIdAdvance(ShmemVariableCache->nextXid);
				}

T
Tom Lane 已提交
5147
				if (record->xl_info & XLR_BKP_BLOCK_MASK)
5148 5149
					RestoreBkpBlocks(record, EndRecPtr);

5150
				RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
5151

5152 5153 5154
				/* Pop the error context stack */
				error_context_stack = errcontext.previous;

5155 5156
				LastRec = ReadRecPtr;

5157
				record = ReadRecord(NULL, LOG);
5158
			} while (record != NULL && recoveryContinue);
B
Bruce Momjian 已提交
5159

5160 5161 5162 5163
			/*
			 * end of main redo apply loop
			 */

5164 5165 5166
			ereport(LOG,
					(errmsg("redo done at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5167 5168
			if (recoveryLastXTime)
				ereport(LOG,
B
Bruce Momjian 已提交
5169 5170
					 (errmsg("last completed transaction was at log time %s",
							 timestamptz_to_str(recoveryLastXTime))));
V
WAL  
Vadim B. Mikheev 已提交
5171
			InRedo = false;
5172 5173
		}
		else
5174 5175
		{
			/* there are no WAL records following the checkpoint */
5176 5177
			ereport(LOG,
					(errmsg("redo is not required")));
5178
		}
V
WAL  
Vadim B. Mikheev 已提交
5179 5180
	}

T
Tom Lane 已提交
5181
	/*
B
Bruce Momjian 已提交
5182 5183
	 * 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 已提交
5184
	 */
5185
	record = ReadRecord(&LastRec, PANIC);
T
Tom Lane 已提交
5186
	EndOfLog = EndRecPtr;
5187 5188
	XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);

5189 5190 5191 5192
	/*
	 * Complain if we did not roll forward far enough to render the backup
	 * dump consistent.
	 */
5193
	if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
5194
	{
5195
		if (reachedStopPoint)	/* stopped because of stop request */
5196 5197
			ereport(FATAL,
					(errmsg("requested recovery stop point is before end time of backup dump")));
B
Bruce Momjian 已提交
5198
		else	/* ran off end of WAL */
5199 5200 5201 5202
			ereport(FATAL,
					(errmsg("WAL ends before end time of backup dump")));
	}

5203 5204 5205
	/*
	 * Consider whether we need to assign a new timeline ID.
	 *
B
Bruce Momjian 已提交
5206 5207
	 * 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
5208 5209
	 * 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 已提交
5210 5211
	 * current last segment is problematic because it may result in trying to
	 * overwrite an already-archived copy of that segment, and we encourage
5212 5213 5214 5215
	 * 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.
5216
	 */
5217
	if (InArchiveRecovery)
5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228
	{
		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;

5229
	/*
B
Bruce Momjian 已提交
5230 5231 5232 5233
	 * 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.)
5234 5235
	 */
	if (InArchiveRecovery)
5236
		exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5237 5238 5239 5240 5241 5242 5243 5244

	/*
	 * 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;
5245
	openLogFile = XLogFileOpen(openLogId, openLogSeg);
T
Tom Lane 已提交
5246
	openLogOff = 0;
V
WAL  
Vadim B. Mikheev 已提交
5247
	Insert = &XLogCtl->Insert;
5248
	Insert->PrevRecord = LastRec;
5249 5250
	XLogCtl->xlblocks[0].xlogid = openLogId;
	XLogCtl->xlblocks[0].xrecoff =
5251
		((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
B
Bruce Momjian 已提交
5252 5253

	/*
B
Bruce Momjian 已提交
5254 5255 5256
	 * 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 已提交
5257
	 */
5258 5259
	Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
	memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5260
	Insert->currpos = (char *) Insert->currpage +
5261
		(EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
V
WAL  
Vadim B. Mikheev 已提交
5262

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

T
Tom Lane 已提交
5265 5266 5267
	XLogCtl->Write.LogwrtResult = LogwrtResult;
	Insert->LogwrtResult = LogwrtResult;
	XLogCtl->LogwrtResult = LogwrtResult;
V
WAL  
Vadim B. Mikheev 已提交
5268

T
Tom Lane 已提交
5269 5270
	XLogCtl->LogwrtRqst.Write = EndOfLog;
	XLogCtl->LogwrtRqst.Flush = EndOfLog;
5271

5272 5273 5274 5275 5276 5277 5278 5279 5280 5281
	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 已提交
5282 5283
		 * Whenever Write.LogwrtResult points to exactly the end of a page,
		 * Write.curridx must point to the *next* page (see XLogWrite()).
5284
		 *
B
Bruce Momjian 已提交
5285
		 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
B
Bruce Momjian 已提交
5286
		 * this is sufficient.	The first actual attempt to insert a log
5287
		 * record will advance the insert state.
5288 5289 5290 5291
		 */
		XLogCtl->Write.curridx = NextBufIdx(0);
	}

5292 5293
	/* Pre-scan prepared transactions to find out the range of XIDs present */
	oldestActiveXID = PrescanPreparedTransactions();
5294

V
WAL  
Vadim B. Mikheev 已提交
5295
	if (InRecovery)
5296
	{
B
Bruce Momjian 已提交
5297
		int			rmid;
5298 5299 5300 5301 5302 5303 5304 5305 5306 5307

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

5308 5309 5310 5311 5312 5313
		/*
		 * Check to see if the XLOG sequence contained any unresolved
		 * references to uninitialized pages.
		 */
		XLogCheckInvalidPages();

5314 5315 5316 5317 5318
		/*
		 * Reset pgstat data, because it may be invalid after recovery.
		 */
		pgstat_reset_all();

T
Tom Lane 已提交
5319
		/*
5320
		 * Perform a checkpoint to update all our recovery activity to disk.
5321
		 *
5322 5323 5324 5325 5326
		 * 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 已提交
5327
		 */
5328
		CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5329
	}
5330

T
Tom Lane 已提交
5331 5332 5333
	/*
	 * Preallocate additional log files, if wanted.
	 */
5334
	PreallocXlogFiles(EndOfLog);
5335

5336 5337 5338
	/*
	 * Okay, we're officially UP.
	 */
V
WAL  
Vadim B. Mikheev 已提交
5339
	InRecovery = false;
5340 5341

	ControlFile->state = DB_IN_PRODUCTION;
5342
	ControlFile->time = (pg_time_t) time(NULL);
5343 5344
	UpdateControlFile();

5345 5346 5347
	/* start the archive_timeout timer running */
	XLogCtl->Write.lastSegSwitchTime = ControlFile->time;

5348 5349 5350 5351
	/* initialize shared-memory copy of latest checkpoint XID/epoch */
	XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
	XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;

5352 5353 5354 5355
	/* also initialize latestCompletedXid, to nextXid - 1 */
	ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
	TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);

5356
	/* Start up the commit log and related stuff, too */
5357
	StartupCLOG();
5358
	StartupSUBTRANS(oldestActiveXID);
5359
	StartupMultiXact();
5360

5361 5362 5363
	/* Reload shared-memory state for prepared transactions */
	RecoverPreparedTransactions();

T
Tom Lane 已提交
5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374
	/* Shut down readFile facility, free space */
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
	if (readBuf)
	{
		free(readBuf);
		readBuf = NULL;
	}
5375 5376 5377 5378 5379 5380
	if (readRecordBuf)
	{
		free(readRecordBuf);
		readRecordBuf = NULL;
		readRecordBufSize = 0;
	}
T
Tom Lane 已提交
5381 5382
}

5383 5384
/*
 * Subroutine to try to fetch and validate a prior checkpoint record.
5385 5386 5387
 *
 * whichChkpt identifies the checkpoint (merely for reporting purposes).
 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5388
 */
T
Tom Lane 已提交
5389
static XLogRecord *
5390
ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
T
Tom Lane 已提交
5391 5392 5393 5394 5395
{
	XLogRecord *record;

	if (!XRecOffIsValid(RecPtr.xrecoff))
	{
5396 5397 5398 5399
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
5400
				(errmsg("invalid primary checkpoint link in control file")));
5401 5402 5403 5404 5405 5406 5407
				break;
			case 2:
				ereport(LOG,
						(errmsg("invalid secondary checkpoint link in control file")));
				break;
			default:
				ereport(LOG,
B
Bruce Momjian 已提交
5408
				   (errmsg("invalid checkpoint link in backup_label file")));
5409 5410
				break;
		}
T
Tom Lane 已提交
5411 5412 5413
		return NULL;
	}

5414
	record = ReadRecord(&RecPtr, LOG);
T
Tom Lane 已提交
5415 5416 5417

	if (record == NULL)
	{
5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432
		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 已提交
5433 5434 5435 5436
		return NULL;
	}
	if (record->xl_rmid != RM_XLOG_ID)
	{
5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448
		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 已提交
5449
				(errmsg("invalid resource manager ID in checkpoint record")));
5450 5451
				break;
		}
T
Tom Lane 已提交
5452 5453 5454 5455 5456
		return NULL;
	}
	if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
		record->xl_info != XLOG_CHECKPOINT_ONLINE)
	{
5457 5458 5459 5460
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
5461
				   (errmsg("invalid xl_info in primary checkpoint record")));
5462 5463 5464
				break;
			case 2:
				ereport(LOG,
B
Bruce Momjian 已提交
5465
				 (errmsg("invalid xl_info in secondary checkpoint record")));
5466 5467 5468 5469 5470 5471
				break;
			default:
				ereport(LOG,
						(errmsg("invalid xl_info in checkpoint record")));
				break;
		}
T
Tom Lane 已提交
5472 5473
		return NULL;
	}
5474 5475
	if (record->xl_len != sizeof(CheckPoint) ||
		record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
T
Tom Lane 已提交
5476
	{
5477 5478 5479 5480
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
B
Bruce Momjian 已提交
5481
					(errmsg("invalid length of primary checkpoint record")));
5482 5483 5484
				break;
			case 2:
				ereport(LOG,
B
Bruce Momjian 已提交
5485
				  (errmsg("invalid length of secondary checkpoint record")));
5486 5487 5488 5489 5490 5491
				break;
			default:
				ereport(LOG,
						(errmsg("invalid length of checkpoint record")));
				break;
		}
T
Tom Lane 已提交
5492 5493 5494
		return NULL;
	}
	return record;
5495 5496
}

V
WAL  
Vadim B. Mikheev 已提交
5497
/*
5498 5499
 * This must be called during startup of a backend process, except that
 * it need not be called in a standalone backend (which does StartupXLOG
5500
 * instead).  We need to initialize the local copies of ThisTimeLineID and
5501 5502
 * RedoRecPtr.
 *
5503
 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5504
 * process's copies of ThisTimeLineID and RedoRecPtr valid too.  This was
5505
 * unnecessary however, since the postmaster itself never touches XLOG anyway.
V
WAL  
Vadim B. Mikheev 已提交
5506 5507
 */
void
5508
InitXLOGAccess(void)
V
WAL  
Vadim B. Mikheev 已提交
5509
{
5510 5511
	/* ThisTimeLineID doesn't change so we need no lock to copy it */
	ThisTimeLineID = XLogCtl->ThisTimeLineID;
5512 5513
	/* Use GetRedoRecPtr to copy the RedoRecPtr safely */
	(void) GetRedoRecPtr();
5514 5515 5516 5517 5518 5519 5520 5521
}

/*
 * 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
5522 5523
GetRedoRecPtr(void)
{
5524 5525 5526
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

5527
	SpinLockAcquire(&xlogctl->info_lck);
5528 5529
	Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
	RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5530
	SpinLockRelease(&xlogctl->info_lck);
5531 5532

	return RedoRecPtr;
V
WAL  
Vadim B. Mikheev 已提交
5533 5534
}

5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548
/*
 * 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 已提交
5549
	XLogRecPtr	recptr;
5550 5551 5552 5553 5554 5555 5556 5557

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

	return recptr;
}

5558 5559 5560
/*
 * Get the time of the last xlog segment switch
 */
5561
pg_time_t
5562 5563
GetLastSegSwitchTime(void)
{
5564
	pg_time_t	result;
5565 5566 5567 5568 5569 5570 5571 5572 5573

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

	return result;
}

5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584
/*
 * 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 已提交
5585 5586 5587
	uint32		ckptXidEpoch;
	TransactionId ckptXid;
	TransactionId nextXid;
5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613

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

5614
/*
T
Tom Lane 已提交
5615
 * This must be called ONCE during postmaster or standalone-backend shutdown
5616 5617
 */
void
5618
ShutdownXLOG(int code, Datum arg)
5619
{
5620 5621
	ereport(LOG,
			(errmsg("shutting down")));
5622

5623
	CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5624
	ShutdownCLOG();
5625
	ShutdownSUBTRANS();
5626
	ShutdownMultiXact();
5627

5628 5629
	ereport(LOG,
			(errmsg("database system is shut down")));
5630 5631
}

5632
/*
5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646
 * 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" : "");
}

5647
/*
5648 5649 5650 5651 5652
 * Log end of a checkpoint.
 */
static void
LogCheckpointEnd(void)
{
B
Bruce Momjian 已提交
5653 5654 5655 5656 5657 5658
	long		write_secs,
				sync_secs,
				total_secs;
	int			write_usecs,
				sync_usecs,
				total_usecs;
5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681

	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 已提交
5682 5683 5684
		 write_secs, write_usecs / 1000,
		 sync_secs, sync_usecs / 1000,
		 total_secs, total_usecs / 1000);
5685 5686
}

T
Tom Lane 已提交
5687 5688
/*
 * Perform a checkpoint --- either during shutdown, or on-the-fly
5689
 *
5690 5691 5692
 * flags is a bitwise OR of the following:
 *	CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
 *	CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
5693
 *		ignoring checkpoint_completion_target parameter.
5694 5695 5696
 *	CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
 *		since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
 *
5697
 * Note: flags contains other bits, of interest here only for logging purposes.
5698 5699
 * In particular note that this routine is synchronous and does not pay
 * attention to CHECKPOINT_WAIT.
T
Tom Lane 已提交
5700
 */
5701
void
5702
CreateCheckPoint(int flags)
5703
{
5704
	bool		shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
5705 5706 5707
	CheckPoint	checkPoint;
	XLogRecPtr	recptr;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
B
Bruce Momjian 已提交
5708
	XLogRecData rdata;
5709
	uint32		freespace;
V
Vadim B. Mikheev 已提交
5710 5711
	uint32		_logId;
	uint32		_logSeg;
5712 5713
	TransactionId *inCommitXids;
	int			nInCommit;
V
Vadim B. Mikheev 已提交
5714

5715
	/*
B
Bruce Momjian 已提交
5716 5717 5718 5719
	 * 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.)
5720
	 */
5721
	LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5722

5723 5724 5725 5726 5727 5728 5729 5730 5731 5732
	/*
	 * 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();

5733 5734 5735
	/*
	 * Use a critical section to force system panic if we have trouble.
	 */
5736 5737
	START_CRIT_SECTION();

5738 5739 5740
	if (shutdown)
	{
		ControlFile->state = DB_SHUTDOWNING;
5741
		ControlFile->time = (pg_time_t) time(NULL);
5742 5743
		UpdateControlFile();
	}
T
Tom Lane 已提交
5744

5745
	/*
B
Bruce Momjian 已提交
5746 5747 5748
	 * 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.
5749 5750 5751 5752
	 */
	smgrpreckpt();

	/* Begin filling in the checkpoint WAL record */
5753
	MemSet(&checkPoint, 0, sizeof(checkPoint));
5754
	checkPoint.ThisTimeLineID = ThisTimeLineID;
5755
	checkPoint.time = (pg_time_t) time(NULL);
5756

5757
	/*
5758 5759
	 * We must hold WALInsertLock while examining insert state to determine
	 * the checkpoint REDO pointer.
5760
	 */
5761
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
T
Tom Lane 已提交
5762 5763

	/*
B
Bruce Momjian 已提交
5764 5765 5766 5767 5768 5769 5770 5771
	 * 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 已提交
5772
	 *
5773 5774 5775 5776
	 * 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 已提交
5777
	 */
5778
	if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
T
Tom Lane 已提交
5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790
	{
		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)
		{
5791 5792
			LWLockRelease(WALInsertLock);
			LWLockRelease(CheckpointLock);
T
Tom Lane 已提交
5793 5794 5795 5796 5797 5798 5799 5800
			END_CRIT_SECTION();
			return;
		}
	}

	/*
	 * Compute new REDO record ptr = location of next XLOG record.
	 *
B
Bruce Momjian 已提交
5801 5802 5803 5804
	 * 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 已提交
5805 5806
	 */
	freespace = INSERT_FREESPACE(Insert);
5807 5808
	if (freespace < SizeOfXLogRecord)
	{
5809
		(void) AdvanceXLInsertBuffer(false);
T
Tom Lane 已提交
5810
		/* OK to ignore update return flag, since we will do flush anyway */
5811
		freespace = INSERT_FREESPACE(Insert);
5812
	}
T
Tom Lane 已提交
5813
	INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
B
Bruce Momjian 已提交
5814

T
Tom Lane 已提交
5815
	/*
B
Bruce Momjian 已提交
5816 5817
	 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
	 * must be done while holding the insert lock AND the info_lck.
5818
	 *
B
Bruce Momjian 已提交
5819
	 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
B
Bruce Momjian 已提交
5820 5821 5822 5823 5824
	 * 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 已提交
5825
	 */
5826 5827 5828 5829
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

5830
		SpinLockAcquire(&xlogctl->info_lck);
5831
		RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5832
		SpinLockRelease(&xlogctl->info_lck);
5833
	}
B
Bruce Momjian 已提交
5834

T
Tom Lane 已提交
5835
	/*
5836 5837
	 * Now we can release WAL insert lock, allowing other xacts to proceed
	 * while we are flushing disk buffers.
T
Tom Lane 已提交
5838
	 */
5839
	LWLockRelease(WALInsertLock);
5840

5841
	/*
B
Bruce Momjian 已提交
5842 5843
	 * If enabled, log checkpoint start.  We postpone this until now so as not
	 * to log anything if we decided to skip the checkpoint.
5844 5845 5846
	 */
	if (log_checkpoints)
		LogCheckpointStart(flags);
5847

5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862
	/*
	 * 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 已提交
5863 5864
	 * protected by different locks, but again that seems best on grounds of
	 * minimizing lock contention.)
5865
	 *
B
Bruce Momjian 已提交
5866 5867
	 * 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
5868 5869 5870 5871 5872 5873 5874
	 * 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 已提交
5875 5876 5877
		do
		{
			pg_usleep(10000L);	/* wait for 10 msec */
5878 5879 5880 5881
		} while (HaveTransactionsInCommit(inCommitXids, nInCommit));
	}
	pfree(inCommitXids);

5882 5883 5884
	/*
	 * Get the other info we need for the checkpoint record.
	 */
5885
	LWLockAcquire(XidGenLock, LW_SHARED);
5886
	checkPoint.nextXid = ShmemVariableCache->nextXid;
5887
	LWLockRelease(XidGenLock);
T
Tom Lane 已提交
5888

5889 5890 5891 5892 5893
	/* Increase XID epoch if we've wrapped around since last checkpoint */
	checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
	if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
		checkPoint.nextXidEpoch++;

5894
	LWLockAcquire(OidGenLock, LW_SHARED);
5895
	checkPoint.nextOid = ShmemVariableCache->nextOid;
5896 5897
	if (!shutdown)
		checkPoint.nextOid += ShmemVariableCache->oidCount;
5898
	LWLockRelease(OidGenLock);
5899

5900 5901 5902
	MultiXactGetCheckptMulti(shutdown,
							 &checkPoint.nextMulti,
							 &checkPoint.nextMultiOffset);
5903

T
Tom Lane 已提交
5904
	/*
B
Bruce Momjian 已提交
5905 5906
	 * Having constructed the checkpoint record, ensure all shmem disk buffers
	 * and commit-log buffers are flushed to disk.
5907
	 *
5908 5909
	 * 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
5910
	 * panic. Accordingly, exit critical section while doing it.
T
Tom Lane 已提交
5911
	 */
5912 5913
	END_CRIT_SECTION();

5914
	CheckPointGuts(checkPoint.redo, flags);
5915

5916 5917
	START_CRIT_SECTION();

T
Tom Lane 已提交
5918 5919 5920
	/*
	 * Now insert the checkpoint record into XLOG.
	 */
B
Bruce Momjian 已提交
5921
	rdata.data = (char *) (&checkPoint);
5922
	rdata.len = sizeof(checkPoint);
5923
	rdata.buffer = InvalidBuffer;
5924 5925
	rdata.next = NULL;

T
Tom Lane 已提交
5926 5927 5928 5929 5930 5931
	recptr = XLogInsert(RM_XLOG_ID,
						shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
						XLOG_CHECKPOINT_ONLINE,
						&rdata);

	XLogFlush(recptr);
5932

T
Tom Lane 已提交
5933
	/*
B
Bruce Momjian 已提交
5934 5935
	 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
	 * = end of actual checkpoint record.
T
Tom Lane 已提交
5936 5937
	 */
	if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5938 5939
		ereport(PANIC,
				(errmsg("concurrent transaction log activity while database system is shutting down")));
5940

T
Tom Lane 已提交
5941
	/*
5942 5943
	 * Select point at which we can truncate the log, which we base on the
	 * prior checkpoint's earliest info.
T
Tom Lane 已提交
5944
	 */
5945
	XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5946

T
Tom Lane 已提交
5947 5948 5949
	/*
	 * Update the control file.
	 */
5950
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5951 5952
	if (shutdown)
		ControlFile->state = DB_SHUTDOWNED;
T
Tom Lane 已提交
5953 5954 5955
	ControlFile->prevCheckPoint = ControlFile->checkPoint;
	ControlFile->checkPoint = ProcLastRecPtr;
	ControlFile->checkPointCopy = checkPoint;
5956
	ControlFile->time = (pg_time_t) time(NULL);
5957
	UpdateControlFile();
5958
	LWLockRelease(ControlFileLock);
5959

5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970
	/* 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);
	}

5971
	/*
B
Bruce Momjian 已提交
5972
	 * We are now done with critical updates; no need for system panic if we
5973
	 * have trouble while fooling with old log segments.
5974 5975 5976
	 */
	END_CRIT_SECTION();

5977 5978 5979 5980 5981
	/*
	 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
	 */
	smgrpostckpt();

V
Vadim B. Mikheev 已提交
5982
	/*
5983
	 * Delete old log files (those no longer needed even for previous
T
Tom Lane 已提交
5984
	 * checkpoint).
V
Vadim B. Mikheev 已提交
5985 5986 5987
	 */
	if (_logId || _logSeg)
	{
T
Tom Lane 已提交
5988
		PrevLogSeg(_logId, _logSeg);
5989
		RemoveOldXlogFiles(_logId, _logSeg, recptr);
V
Vadim B. Mikheev 已提交
5990 5991
	}

T
Tom Lane 已提交
5992
	/*
5993 5994
	 * 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 已提交
5995 5996
	 */
	if (!shutdown)
5997
		PreallocXlogFiles(recptr);
T
Tom Lane 已提交
5998

5999
	/*
B
Bruce Momjian 已提交
6000 6001 6002 6003 6004
	 * 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.
6005
	 */
6006
	if (!InRecovery)
6007
		TruncateSUBTRANS(GetOldestXmin(true, false));
6008

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

6013
	LWLockRelease(CheckpointLock);
6014
}
V
WAL  
Vadim B. Mikheev 已提交
6015

6016 6017 6018 6019 6020 6021 6022
/*
 * Flush all data in shared memory to disk, and fsync
 *
 * This is the common code shared between regular checkpoints and
 * recovery restartpoints.
 */
static void
6023
CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
6024 6025 6026 6027
{
	CheckPointCLOG();
	CheckPointSUBTRANS();
	CheckPointMultiXact();
B
Bruce Momjian 已提交
6028
	CheckPointBuffers(flags);	/* performs all required fsyncs */
6029 6030 6031 6032 6033 6034 6035
	/* We deliberately delay 2PC checkpointing as long as possible */
	CheckPointTwoPhase(checkPointRedo);
}

/*
 * Set a recovery restart point if appropriate
 *
6036
 * This is similar to CreateCheckPoint, but is used during WAL recovery
6037 6038 6039 6040 6041 6042 6043 6044
 * 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 已提交
6045 6046
	int			elapsed_secs;
	int			rmid;
6047 6048

	/*
B
Bruce Momjian 已提交
6049 6050
	 * Do nothing if the elapsed time since the last restartpoint is less than
	 * half of checkpoint_timeout.	(We use a value less than
6051 6052 6053 6054 6055 6056
	 * 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.
	 */
6057
	elapsed_secs = (pg_time_t) time(NULL) - ControlFile->time;
6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070
	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()))
6071 6072 6073 6074 6075
			{
				elog(DEBUG2, "RM %d not safe to record restart point at %X/%X",
					 rmid,
					 checkPoint->redo.xlogid,
					 checkPoint->redo.xrecoff);
6076
				return;
6077
			}
6078 6079 6080 6081 6082
	}

	/*
	 * OK, force data out to disk
	 */
6083
	CheckPointGuts(checkPoint->redo, CHECKPOINT_IMMEDIATE);
6084 6085

	/*
B
Bruce Momjian 已提交
6086 6087 6088
	 * Update pg_control so that any subsequent crash will restart from this
	 * checkpoint.	Note: ReadRecPtr gives the XLOG address of the checkpoint
	 * record itself.
6089 6090 6091 6092
	 */
	ControlFile->prevCheckPoint = ControlFile->checkPoint;
	ControlFile->checkPoint = ReadRecPtr;
	ControlFile->checkPointCopy = *checkPoint;
6093
	ControlFile->time = (pg_time_t) time(NULL);
6094 6095
	UpdateControlFile();

6096
	ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
6097 6098
			(errmsg("recovery restart point at %X/%X",
					checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
6099 6100 6101 6102
	if (recoveryLastXTime)
		ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
				(errmsg("last completed transaction was at log time %s",
						timestamptz_to_str(recoveryLastXTime))));
6103 6104
}

T
Tom Lane 已提交
6105 6106 6107
/*
 * Write a NEXTOID log record
 */
6108 6109 6110
void
XLogPutNextOid(Oid nextOid)
{
B
Bruce Momjian 已提交
6111
	XLogRecData rdata;
6112

B
Bruce Momjian 已提交
6113
	rdata.data = (char *) (&nextOid);
6114
	rdata.len = sizeof(Oid);
6115
	rdata.buffer = InvalidBuffer;
6116 6117
	rdata.next = NULL;
	(void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
B
Bruce Momjian 已提交
6118

6119 6120
	/*
	 * We need not flush the NEXTOID record immediately, because any of the
B
Bruce Momjian 已提交
6121 6122 6123 6124 6125
	 * 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.
6126 6127
	 *
	 * Note, however, that the above statement only covers state "within" the
B
Bruce Momjian 已提交
6128 6129
	 * 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
6130
	 * change may reach disk before the NEXTOID WAL record does.  The impact
B
Bruce Momjian 已提交
6131 6132 6133 6134 6135
	 * 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.
6136 6137 6138
	 */
}

6139 6140 6141 6142 6143 6144 6145 6146 6147 6148
/*
 * 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.
 */
6149
XLogRecPtr
6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165
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 已提交
6166 6167 6168
/*
 * XLOG resource manager's routines
 */
V
WAL  
Vadim B. Mikheev 已提交
6169 6170 6171
void
xlog_redo(XLogRecPtr lsn, XLogRecord *record)
{
B
Bruce Momjian 已提交
6172
	uint8		info = record->xl_info & ~XLR_INFO_MASK;
6173

6174
	if (info == XLOG_NEXTOID)
6175
	{
B
Bruce Momjian 已提交
6176
		Oid			nextOid;
6177 6178 6179

		memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
		if (ShmemVariableCache->nextOid < nextOid)
T
Tom Lane 已提交
6180
		{
6181
			ShmemVariableCache->nextOid = nextOid;
T
Tom Lane 已提交
6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193
			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;
6194 6195
		MultiXactSetNextMXact(checkPoint.nextMulti,
							  checkPoint.nextMultiOffset);
B
Bruce Momjian 已提交
6196

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

6201
		/*
B
Bruce Momjian 已提交
6202
		 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
6203 6204 6205 6206 6207 6208 6209 6210
		 */
		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 已提交
6211
								checkPoint.ThisTimeLineID, ThisTimeLineID)));
6212 6213 6214
			/* Following WAL records should be run with new TLI */
			ThisTimeLineID = checkPoint.ThisTimeLineID;
		}
6215 6216

		RecoveryRestartPoint(&checkPoint);
T
Tom Lane 已提交
6217 6218 6219 6220 6221 6222
	}
	else if (info == XLOG_CHECKPOINT_ONLINE)
	{
		CheckPoint	checkPoint;

		memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6223
		/* In an ONLINE checkpoint, treat the counters like NEXTOID */
6224 6225
		if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
								  checkPoint.nextXid))
T
Tom Lane 已提交
6226 6227 6228 6229 6230 6231
			ShmemVariableCache->nextXid = checkPoint.nextXid;
		if (ShmemVariableCache->nextOid < checkPoint.nextOid)
		{
			ShmemVariableCache->nextOid = checkPoint.nextOid;
			ShmemVariableCache->oidCount = 0;
		}
6232 6233
		MultiXactAdvanceNextMXact(checkPoint.nextMulti,
								  checkPoint.nextMultiOffset);
6234 6235 6236 6237 6238

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

6239 6240
		/* TLI should not change in an on-line checkpoint */
		if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6241
			ereport(PANIC,
6242 6243
					(errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
							checkPoint.ThisTimeLineID, ThisTimeLineID)));
6244 6245

		RecoveryRestartPoint(&checkPoint);
6246
	}
6247 6248 6249 6250
	else if (info == XLOG_NOOP)
	{
		/* nothing to do here */
	}
6251 6252 6253 6254
	else if (info == XLOG_SWITCH)
	{
		/* nothing to do here */
	}
V
WAL  
Vadim B. Mikheev 已提交
6255
}
B
Bruce Momjian 已提交
6256

V
WAL  
Vadim B. Mikheev 已提交
6257
void
6258
xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
V
WAL  
Vadim B. Mikheev 已提交
6259
{
B
Bruce Momjian 已提交
6260
	uint8		info = xl_info & ~XLR_INFO_MASK;
V
WAL  
Vadim B. Mikheev 已提交
6261

T
Tom Lane 已提交
6262 6263
	if (info == XLOG_CHECKPOINT_SHUTDOWN ||
		info == XLOG_CHECKPOINT_ONLINE)
V
WAL  
Vadim B. Mikheev 已提交
6264
	{
B
Bruce Momjian 已提交
6265 6266
		CheckPoint *checkpoint = (CheckPoint *) rec;

6267
		appendStringInfo(buf, "checkpoint: redo %X/%X; "
B
Bruce Momjian 已提交
6268 6269 6270 6271 6272 6273 6274 6275
						 "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 已提交
6276
	}
6277 6278 6279 6280
	else if (info == XLOG_NOOP)
	{
		appendStringInfo(buf, "xlog no-op");
	}
6281 6282
	else if (info == XLOG_NEXTOID)
	{
B
Bruce Momjian 已提交
6283
		Oid			nextOid;
6284 6285

		memcpy(&nextOid, rec, sizeof(Oid));
6286
		appendStringInfo(buf, "nextOid: %u", nextOid);
6287
	}
6288 6289 6290 6291
	else if (info == XLOG_SWITCH)
	{
		appendStringInfo(buf, "xlog switch");
	}
V
WAL  
Vadim B. Mikheev 已提交
6292
	else
6293
		appendStringInfo(buf, "UNKNOWN");
V
WAL  
Vadim B. Mikheev 已提交
6294 6295
}

6296
#ifdef WAL_DEBUG
6297

V
WAL  
Vadim B. Mikheev 已提交
6298
static void
6299
xlog_outrec(StringInfo buf, XLogRecord *record)
V
WAL  
Vadim B. Mikheev 已提交
6300
{
B
Bruce Momjian 已提交
6301
	int			i;
6302

6303
	appendStringInfo(buf, "prev %X/%X; xid %u",
6304 6305
					 record->xl_prev.xlogid, record->xl_prev.xrecoff,
					 record->xl_xid);
6306

6307
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
6308
	{
6309
		if (record->xl_info & XLR_SET_BKP_BLOCK(i))
B
Bruce Momjian 已提交
6310
			appendStringInfo(buf, "; bkpb%d", i + 1);
6311 6312
	}

6313
	appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
V
WAL  
Vadim B. Mikheev 已提交
6314
}
B
Bruce Momjian 已提交
6315
#endif   /* WAL_DEBUG */
6316 6317 6318


/*
6319 6320
 * Return the (possible) sync flag used for opening a file, depending on the
 * value of the GUC wal_sync_method.
6321
 */
6322 6323
static int
get_sync_bit(int method)
6324
{
6325 6326 6327
	/* If fsync is disabled, never open in sync mode */
	if (!enableFsync)
		return 0;
6328

6329
	switch (method)
6330
	{
6331
		/*
6332 6333 6334 6335
		 * enum values for all sync options are defined even if they are not
		 * supported on the current platform.  But if not, they are not
		 * included in the enum option array, and therefore will never be seen
		 * here.
6336 6337 6338 6339
		 */
		case SYNC_METHOD_FSYNC:
		case SYNC_METHOD_FSYNC_WRITETHROUGH:
		case SYNC_METHOD_FDATASYNC:
6340
			return 0;
6341
#ifdef OPEN_SYNC_FLAG
6342
		case SYNC_METHOD_OPEN:
6343
			return OPEN_SYNC_FLAG;
6344 6345
#endif
#ifdef OPEN_DATASYNC_FLAG
6346
		case SYNC_METHOD_OPEN_DSYNC:
6347
			return OPEN_DATASYNC_FLAG;
6348
#endif
6349
		default:
6350 6351
			/* can't happen (unless we are out of sync with option array) */
			elog(ERROR, "unrecognized wal_sync_method: %d", method);
6352
			return 0; /* silence warning */
6353
	}
6354
}
6355

6356 6357 6358 6359 6360 6361
/*
 * GUC support
 */
bool
assign_xlog_sync_method(int new_sync_method, bool doit, GucSource source)
{
6362
	if (!doit)
6363
		return true;
6364

6365
	if (sync_method != new_sync_method)
6366 6367
	{
		/*
B
Bruce Momjian 已提交
6368 6369
		 * 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 已提交
6370 6371
		 * changing, close the log file so it will be reopened (with new flag
		 * bit) at next use.
6372 6373 6374 6375
		 */
		if (openLogFile >= 0)
		{
			if (pg_fsync(openLogFile) != 0)
6376 6377
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
6378 6379
						 errmsg("could not fsync log file %u, segment %u: %m",
								openLogId, openLogSeg)));
6380
			if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
6381
				XLogFileClose();
6382 6383
		}
	}
6384

6385
	return true;
6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396
}


/*
 * Issue appropriate kind of fsync (if any) on the current XLOG output file
 */
static void
issue_xlog_fsync(void)
{
	switch (sync_method)
	{
6397
		case SYNC_METHOD_FSYNC:
6398
			if (pg_fsync_no_writethrough(openLogFile) != 0)
6399 6400
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
6401 6402
						 errmsg("could not fsync log file %u, segment %u: %m",
								openLogId, openLogSeg)));
6403
			break;
6404 6405 6406 6407 6408
#ifdef HAVE_FSYNC_WRITETHROUGH
		case SYNC_METHOD_FSYNC_WRITETHROUGH:
			if (pg_fsync_writethrough(openLogFile) != 0)
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
6409 6410
						 errmsg("could not fsync write-through log file %u, segment %u: %m",
								openLogId, openLogSeg)));
6411 6412
			break;
#endif
6413 6414 6415
#ifdef HAVE_FDATASYNC
		case SYNC_METHOD_FDATASYNC:
			if (pg_fdatasync(openLogFile) != 0)
6416 6417
				ereport(PANIC,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
6418 6419
					errmsg("could not fdatasync log file %u, segment %u: %m",
						   openLogId, openLogSeg)));
6420 6421 6422
			break;
#endif
		case SYNC_METHOD_OPEN:
6423
		case SYNC_METHOD_OPEN_DSYNC:
6424 6425 6426
			/* write synced it already */
			break;
		default:
6427
			elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6428 6429 6430
			break;
	}
}
6431 6432 6433 6434 6435 6436 6437 6438 6439


/*
 * 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
6440
 * starting WAL location for the dump.
6441 6442 6443 6444 6445 6446
 */
Datum
pg_start_backup(PG_FUNCTION_ARGS)
{
	text	   *backupid = PG_GETARG_TEXT_P(0);
	char	   *backupidstr;
6447
	XLogRecPtr	checkpointloc;
6448
	XLogRecPtr	startpoint;
6449
	pg_time_t	stamp_time;
6450 6451 6452 6453 6454 6455 6456
	char		strfbuf[128];
	char		xlogfilename[MAXFNAMELEN];
	uint32		_logId;
	uint32		_logSeg;
	struct stat stat_buf;
	FILE	   *fp;

B
Bruce Momjian 已提交
6457
	if (!superuser())
6458 6459
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6460
				 errmsg("must be superuser to run a backup")));
6461 6462 6463 6464

	if (!XLogArchivingActive())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6465 6466 6467 6468 6469 6470 6471 6472 6473
				 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.")));
6474

6475
	backupidstr = text_to_cstring(backupid);
B
Bruce Momjian 已提交
6476

6477
	/*
6478 6479 6480
	 * 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 已提交
6481 6482 6483 6484 6485 6486 6487 6488 6489
	 * 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.)
6490
	 *
B
Bruce Momjian 已提交
6491 6492
	 * We must hold WALInsertLock to change the value of forcePageWrites, to
	 * ensure adequate interlocking against XLogInsert().
6493
	 */
6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504
	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 已提交
6505

6506 6507
	/* Ensure we release forcePageWrites if fail below */
	PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
6508 6509
	{
		/*
B
Bruce Momjian 已提交
6510
		 * Force a CHECKPOINT.	Aside from being necessary to prevent torn
6511 6512 6513
		 * 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.
6514 6515
		 *
		 * We don't use CHECKPOINT_IMMEDIATE, hence this can take awhile.
6516
		 */
6517
		RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT);
6518

6519 6520 6521 6522 6523 6524 6525 6526 6527
		/*
		 * 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 已提交
6528

6529 6530
		XLByteToSeg(startpoint, _logId, _logSeg);
		XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
B
Bruce Momjian 已提交
6531

6532 6533 6534 6535 6536
		/* 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));
6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562

		/*
		 * 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)
6563 6564
			ereport(ERROR,
					(errcode_for_file_access(),
6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576
					 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",
6577
							BACKUP_LABEL_FILE)));
6578
	}
6579
	PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
B
Bruce Momjian 已提交
6580

6581
	/*
6582
	 * We're done.  As a convenience, return the starting WAL location.
6583 6584 6585
	 */
	snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
			 startpoint.xlogid, startpoint.xrecoff);
6586
	PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
6587 6588
}

6589 6590 6591 6592 6593 6594 6595 6596 6597 6598
/* Error cleanup callback for pg_start_backup */
static void
pg_start_backup_callback(int code, Datum arg)
{
	/* Turn off forcePageWrites on failure */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
	XLogCtl->Insert.forcePageWrites = false;
	LWLockRelease(WALInsertLock);
}

6599 6600 6601 6602 6603 6604
/*
 * 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
6605
 * the label file, plus the backup-end time and WAL location.
6606
 * Note: different from CancelBackup which just cancels online backup mode.
6607 6608 6609 6610 6611 6612
 */
Datum
pg_stop_backup(PG_FUNCTION_ARGS)
{
	XLogRecPtr	startpoint;
	XLogRecPtr	stoppoint;
6613
	pg_time_t	stamp_time;
6614
	char		strfbuf[128];
6615
	char		histfilepath[MAXPGPATH];
6616 6617 6618 6619 6620 6621 6622 6623
	char		startxlogfilename[MAXFNAMELEN];
	char		stopxlogfilename[MAXFNAMELEN];
	uint32		_logId;
	uint32		_logSeg;
	FILE	   *lfp;
	FILE	   *fp;
	char		ch;
	int			ich;
6624 6625
	int			seconds_before_warning;
	int			waits = 0;
6626

B
Bruce Momjian 已提交
6627
	if (!superuser())
6628 6629 6630
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 (errmsg("must be superuser to run a backup"))));
B
Bruce Momjian 已提交
6631

6632
	/*
6633
	 * OK to clear forcePageWrites
6634 6635
	 */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6636
	XLogCtl->Insert.forcePageWrites = false;
6637 6638
	LWLockRelease(WALInsertLock);

6639
	/*
B
Bruce Momjian 已提交
6640 6641 6642
	 * 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.
6643 6644 6645
	 */
	stoppoint = RequestXLogSwitch();

6646 6647
	XLByteToSeg(stoppoint, _logId, _logSeg);
	XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
B
Bruce Momjian 已提交
6648

6649 6650 6651 6652 6653
	/* 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 已提交
6654

6655 6656 6657
	/*
	 * Open the existing label file
	 */
6658
	lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6659 6660 6661 6662 6663 6664
	if (!lfp)
	{
		if (errno != ENOENT)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
6665
							BACKUP_LABEL_FILE)));
6666 6667 6668 6669
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("a backup is not in progress")));
	}
B
Bruce Momjian 已提交
6670

6671
	/*
B
Bruce Momjian 已提交
6672 6673
	 * Read and parse the START WAL LOCATION line (this code is pretty crude,
	 * but we are not expecting any variability in the file format).
6674 6675 6676 6677 6678 6679
	 */
	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),
6680
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
6681

6682 6683 6684 6685
	/*
	 * Write the backup history file
	 */
	XLByteToSeg(startpoint, _logId, _logSeg);
6686
	BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6687
						  startpoint.xrecoff % XLogSegSize);
6688
	fp = AllocateFile(histfilepath, "w");
6689 6690 6691 6692
	if (!fp)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m",
6693
						histfilepath)));
6694 6695 6696 6697
	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);
6698
	/* transfer remaining lines from label to history file */
6699 6700 6701 6702 6703 6704 6705
	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",
6706
						histfilepath)));
B
Bruce Momjian 已提交
6707

6708 6709 6710 6711 6712 6713 6714
	/*
	 * 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",
6715 6716
						BACKUP_LABEL_FILE)));
	if (unlink(BACKUP_LABEL_FILE) != 0)
6717 6718 6719
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not remove file \"%s\": %m",
6720
						BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
6721

6722
	/*
B
Bruce Momjian 已提交
6723 6724 6725
	 * 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.
6726
	 */
6727
	CleanupBackupHistory();
B
Bruce Momjian 已提交
6728

6729 6730 6731 6732 6733 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
	/*
	 * Wait until the history file has been archived. We assume that the 
	 * alphabetic sorting property of the WAL files ensures the last WAL
	 * file is guaranteed archived by the time the history file is archived.
	 *
	 * We wait forever, since archive_command is supposed to work and
	 * we assume the admin wanted his backup to work completely. If you 
	 * don't wish to wait, you can SET statement_timeout = xx;
	 *
	 * If the status file is missing, we assume that is because it was
	 * set to .ready before we slept, then while asleep it has been set
	 * to .done and then removed by a concurrent checkpoint.
	 */
	BackupHistoryFileName(histfilepath, ThisTimeLineID, _logId, _logSeg,
						  startpoint.xrecoff % XLogSegSize);

	seconds_before_warning = 60;
	waits = 0;

	while (!XLogArchiveCheckDone(histfilepath, false))
	{
		CHECK_FOR_INTERRUPTS();

		pg_usleep(1000000L);

		if (++waits >= seconds_before_warning)
		{
			seconds_before_warning *= 2;     /* This wraps in >10 years... */
			elog(WARNING, "pg_stop_backup() waiting for archive to complete " 
							"(%d seconds delay)", waits);
		}
	}

6762
	/*
6763
	 * We're done.  As a convenience, return the ending WAL location.
6764 6765 6766
	 */
	snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
			 stoppoint.xlogid, stoppoint.xrecoff);
6767
	PG_RETURN_TEXT_P(cstring_to_text(stopxlogfilename));
6768
}
6769

6770 6771 6772 6773 6774 6775
/*
 * pg_switch_xlog: switch to next xlog file
 */
Datum
pg_switch_xlog(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
6776
	XLogRecPtr	switchpoint;
6777 6778 6779 6780 6781
	char		location[MAXFNAMELEN];

	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
B
Bruce Momjian 已提交
6782
			 (errmsg("must be superuser to switch transaction log files"))));
6783 6784 6785 6786 6787 6788 6789 6790

	switchpoint = RequestXLogSwitch();

	/*
	 * As a convenience, return the WAL location of the switch record
	 */
	snprintf(location, sizeof(location), "%X/%X",
			 switchpoint.xlogid, switchpoint.xrecoff);
6791
	PG_RETURN_TEXT_P(cstring_to_text(location));
6792 6793 6794
}

/*
6795 6796 6797 6798 6799
 * 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.
6800 6801 6802
 */
Datum
pg_current_xlog_location(PG_FUNCTION_ARGS)
6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817
{
	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);
6818
	PG_RETURN_TEXT_P(cstring_to_text(location));
6819 6820 6821 6822 6823 6824 6825 6826 6827
}

/*
 * 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)
6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841
{
	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);
6842
	PG_RETURN_TEXT_P(cstring_to_text(location));
6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864
}

/*
 * 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 已提交
6865 6866 6867 6868 6869
	Datum		values[2];
	bool		isnull[2];
	TupleDesc	resultTupleDesc;
	HeapTuple	resultHeapTuple;
	Datum		result;
6870

6871 6872 6873
	/*
	 * Read input and parse
	 */
6874
	locationstr = text_to_cstring(location);
6875 6876 6877 6878

	if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
P
Peter Eisentraut 已提交
6879
				 errmsg("could not parse transaction log location \"%s\"",
6880 6881 6882 6883 6884
						locationstr)));

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

6885
	/*
B
Bruce Momjian 已提交
6886 6887
	 * Construct a tuple descriptor for the result row.  This must match this
	 * function's pg_proc entry!
6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899
	 */
	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
	 */
6900 6901 6902
	XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
	XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);

6903
	values[0] = CStringGetTextDatum(xlogfilename);
6904 6905 6906 6907 6908
	isnull[0] = false;

	/*
	 * offset
	 */
6909 6910
	xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;

6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921
	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);
6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939
}

/*
 * Compute an xlog file name given a WAL location,
 * such as is returned by pg_stop_backup() or pg_xlog_switch().
 */
Datum
pg_xlogfile_name(PG_FUNCTION_ARGS)
{
	text	   *location = PG_GETARG_TEXT_P(0);
	char	   *locationstr;
	unsigned int uxlogid;
	unsigned int uxrecoff;
	uint32		xlogid;
	uint32		xlogseg;
	XLogRecPtr	locationpoint;
	char		xlogfilename[MAXFNAMELEN];

6940
	locationstr = text_to_cstring(location);
6941 6942 6943 6944

	if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
P
Peter Eisentraut 已提交
6945
				 errmsg("could not parse transaction log location \"%s\"",
6946 6947 6948 6949 6950 6951 6952 6953
						locationstr)));

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

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

6954
	PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
6955 6956
}

6957 6958 6959 6960 6961
/*
 * 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 已提交
6962
 * identified by the label file, NOT what pg_control says.	This avoids the
6963 6964 6965 6966 6967
 * 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.
6968
 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6969 6970 6971 6972 6973 6974
 * points.
 *
 * Returns TRUE if a backup_label was found (and fills the checkpoint
 * location into *checkPointLoc); returns FALSE if not.
 */
static bool
6975
read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989
{
	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;

6990 6991 6992 6993
	/* Default is to not constrain recovery stop point */
	minRecoveryLoc->xlogid = 0;
	minRecoveryLoc->xrecoff = 0;

6994 6995 6996
	/*
	 * See if label file is present
	 */
6997
	lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6998 6999 7000 7001 7002 7003
	if (!lfp)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
7004
							BACKUP_LABEL_FILE)));
7005 7006
		return false;			/* it's not there, all is fine */
	}
B
Bruce Momjian 已提交
7007

7008
	/*
B
Bruce Momjian 已提交
7009 7010 7011
	 * 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).
7012 7013 7014 7015 7016 7017
	 */
	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),
7018
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7019 7020 7021 7022 7023
	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),
7024
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7025 7026 7027 7028
	if (ferror(lfp) || FreeFile(lfp))
		ereport(FATAL,
				(errcode_for_file_access(),
				 errmsg("could not read file \"%s\": %m",
7029
						BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
7030

7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043
	/*
	 * 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 已提交
7044
	fp = AllocateFile(histfilepath, "r");
7045 7046 7047 7048 7049 7050
	if (fp)
	{
		/*
		 * Parse history file to identify stop point.
		 */
		if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
B
Bruce Momjian 已提交
7051
				   &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
7052 7053 7054
				   &ch) != 4 || ch != '\n')
			ereport(FATAL,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
B
Bruce Momjian 已提交
7055
					 errmsg("invalid data in file \"%s\"", histfilename)));
7056
		if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
B
Bruce Momjian 已提交
7057
				   &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
7058 7059 7060
				   &ch) != 4 || ch != '\n')
			ereport(FATAL,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
B
Bruce Momjian 已提交
7061
					 errmsg("invalid data in file \"%s\"", histfilename)));
7062
		*minRecoveryLoc = stoppoint;
7063 7064 7065 7066 7067 7068 7069 7070 7071 7072
		if (ferror(fp) || FreeFile(fp))
			ereport(FATAL,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
							histfilepath)));
	}

	return true;
}

7073 7074 7075 7076 7077 7078
/*
 * Error context callback for errors occurring during rm_redo().
 */
static void
rm_redo_error_callback(void *arg)
{
B
Bruce Momjian 已提交
7079 7080
	XLogRecord *record = (XLogRecord *) arg;
	StringInfoData buf;
7081 7082

	initStringInfo(&buf);
7083 7084
	RmgrTable[record->xl_rmid].rm_desc(&buf,
									   record->xl_info,
7085 7086 7087 7088 7089 7090 7091 7092
									   XLogRecGetData(record));

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

	pfree(buf.data);
}
7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129

/*
 * BackupInProgress: check if online backup mode is active
 *
 * This is done by checking for existence of the "backup_label" file.
 */
bool
BackupInProgress(void)
{
	struct stat stat_buf;

	return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
}

/*
 * CancelBackup: rename the "backup_label" file to cancel backup mode
 *
 * If the "backup_label" file exists, it will be renamed to "backup_label.old".
 * Note that this will render an online backup in progress useless.
 * To correctly finish an online backup, pg_stop_backup must be called.
 */
void
CancelBackup(void)
{
	struct stat stat_buf;

	/* if the file is not there, return */
	if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
		return;

	/* remove leftover file from previously cancelled backup if it exists */
	unlink(BACKUP_LABEL_OLD);

	if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) == 0)
	{
		ereport(LOG,
				(errmsg("online backup mode cancelled"),
7130
				 errdetail("\"%s\" was renamed to \"%s\".",
7131 7132 7133 7134 7135 7136
						BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
	}
	else
	{
		ereport(WARNING,
				(errcode_for_file_access(),
7137 7138
				 errmsg("online backup mode was not cancelled"),
				 errdetail("Could not rename \"%s\" to \"%s\": %m.",
7139 7140 7141 7142
						BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
	}
}