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

15 16
#include "postgres.h"

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

26
#include "access/clog.h"
27
#include "access/multixact.h"
28
#include "access/distributedlog.h"
29
#include "access/subtrans.h"
30
#include "access/transam.h"
31
#include "access/tuptoaster.h"
32
#include "access/twophase.h"
33
#include "access/xact.h"
34
#include "access/xlog_internal.h"
35
#include "access/xlogdefs.h"
36
#include "access/xlogutils.h"
37
#include "catalog/catalog.h"
38
#include "catalog/catversion.h"
H
Heikki Linnakangas 已提交
39
#include "catalog/pg_authid.h"
T
Tom Lane 已提交
40
#include "catalog/pg_control.h"
41
#include "catalog/pg_database.h"
42
#include "catalog/pg_type.h"
43 44 45
#include "catalog/pg_database.h"
#include "catalog/pg_tablespace.h"
#include "executor/spi.h"
46
#include "funcapi.h"
47
#include "libpq/pqsignal.h"
48
#include "miscadmin.h"
49
#include "pgstat.h"
50
#include "postmaster/bgwriter.h"
51
#include "postmaster/postmaster.h"
52 53
#include "replication/walreceiver.h"
#include "replication/walsender.h"
54
#include "storage/bufmgr.h"
55
#include "storage/bufpage.h"
56
#include "storage/fd.h"
57
#include "storage/ipc.h"
58
#include "storage/latch.h"
59
#include "storage/pmsignal.h"
60
#include "storage/predicate.h"
61
#include "storage/proc.h"
62
#include "storage/procarray.h"
R
Robert Haas 已提交
63
#include "storage/reinit.h"
64
#include "storage/smgr.h"
65
#include "storage/spin.h"
66
#include "utils/builtins.h"
67
#include "utils/nabstime.h"
68 69 70
#include "utils/faultinjector.h"
#include "utils/guc.h"
#include "utils/ps_status.h"
71
#include "utils/relmapper.h"
72 73 74 75 76
#include "pg_trace.h"
#include "utils/catcache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/pg_crc.h"
77
#include "utils/ps_status.h"
78 79 80 81 82 83 84
#include "replication/walreceiver.h"
#include "replication/walsender.h"
#include "storage/backendid.h"
#include "storage/sinvaladt.h"

#include "cdb/cdbtm.h"
#include "cdb/cdbvars.h"
85
#include "utils/resscheduler.h"
86
#include "utils/snapmgr.h"
87

88
extern uint32 bootstrap_data_checksum_version;
89

T
Tom Lane 已提交
90 91
/* User-settable parameters */
int			CheckPointSegments = 3;
92
int			wal_keep_segments = 0;
93
int			XLOGbuffers = -1;
94
int			XLogArchiveTimeout = 0;
95
bool		XLogArchiveMode = false;
96
char	   *XLogArchiveCommand = NULL;
97
bool		EnableHotStandby = false;
98
bool		fullPageWrites = true;
99 100
char   *wal_consistency_checking_string = NULL;
bool   *wal_consistency_checking = NULL;
101
bool		log_checkpoints = false;
102
int			sync_method = DEFAULT_SYNC_METHOD;
103
int			wal_level = WAL_LEVEL_MINIMAL;
T
Tom Lane 已提交
104

105 106 107 108
#ifdef WAL_DEBUG
bool		XLOG_DEBUG = false;
#endif

109
/*
110 111 112 113 114
 * 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 已提交
115
 * 2*CheckPointSegments+1.	Under normal conditions, a checkpoint will free
116 117 118
 * 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.
119 120 121
 */
#define XLOGfileslop	(2*CheckPointSegments + 1)

122
bool am_startup = false;
123

124
/*
125
 * GUC support
126
 */
127 128 129 130 131 132 133
const struct config_enum_entry wal_level_options[] = {
	{"minimal", WAL_LEVEL_MINIMAL, false},
	{"archive", WAL_LEVEL_ARCHIVE, false},
	{"hot_standby", WAL_LEVEL_HOT_STANDBY, false},
	{NULL, 0, false}
};

134
const struct config_enum_entry sync_method_options[] = {
135
	{"fsync", SYNC_METHOD_FSYNC, false},
136
#ifdef HAVE_FSYNC_WRITETHROUGH
137
	{"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
138 139
#endif
#ifdef HAVE_FDATASYNC
140
	{"fdatasync", SYNC_METHOD_FDATASYNC, false},
141 142
#endif
#ifdef OPEN_SYNC_FLAG
143
	{"open_sync", SYNC_METHOD_OPEN, false},
144 145
#endif
#ifdef OPEN_DATASYNC_FLAG
146
	{"open_datasync", SYNC_METHOD_OPEN_DSYNC, false},
147
#endif
148
	{NULL, 0, false}
149
};
T
Tom Lane 已提交
150

151 152 153 154 155 156 157
/*
 * 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 已提交
158
/*
159 160
 * ThisTimeLineID will be same in all backends --- it identifies current
 * WAL timeline for the database system.
T
Tom Lane 已提交
161
 */
162
TimeLineID	ThisTimeLineID = 0;
V
WAL  
Vadim B. Mikheev 已提交
163

164
/*
165
 * Are we doing recovery from XLOG?
166
 *
167 168 169 170 171
 * This is only ever true in the startup process; it should be read as meaning
 * "this process is replaying WAL records", rather than "the system is in
 * recovery mode".  It should be examined primarily by functions that need
 * to act differently when called from a WAL redo function (e.g., to skip WAL
 * logging).  To check whether the system is in recovery regardless of which
172 173
 * process you're running in, use RecoveryInProgress() but only after shared
 * memory startup and lock initialization.
174
 */
T
Tom Lane 已提交
175
bool		InRecovery = false;
B
Bruce Momjian 已提交
176

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

B
Bruce Momjian 已提交
180
static XLogRecPtr LastRec;
181

182 183 184 185 186
/*
 * Local copy of SharedRecoveryInProgress variable. True actually means "not
 * known, need to check the shared state".
 */
static bool LocalRecoveryInProgress = true;
B
Bruce Momjian 已提交
187

188 189 190 191 192
/*
 * Local copy of SharedHotStandbyActive variable. False actually means "not
 * known, need to check the shared state".
 */
static bool LocalHotStandbyActive = false;
193

194 195 196 197 198 199
/*
 * Local state for XLogInsertAllowed():
 *		1: unconditionally allowed to insert XLOG
 *		0: unconditionally not allowed to insert XLOG
 *		-1: must check RecoveryInProgress(); disallow until it is false
 * Most processes start with -1 and transition to 1 after seeing that recovery
B
Bruce Momjian 已提交
200
 * is not in progress.	But we can also force the value for special cases.
201 202 203 204 205 206 207 208
 * The coding in XLogInsertAllowed() depends on the first two of these states
 * being numerically the same as bool true and false.
 */
static int	LocalXLogInsertAllowed = -1;

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

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

212
/* options taken from recovery.conf for archive recovery */
213
static char *recoveryRestoreCommand = NULL;
214
static char *recoveryEndCommand = NULL;
215
static char *archiveCleanupCommand = NULL;
216
static RecoveryTargetType recoveryTarget = RECOVERY_TARGET_UNSET;
217
static bool recoveryTargetInclusive = true;
218
static bool recoveryPauseAtTarget = true;
B
Bruce Momjian 已提交
219
static TransactionId recoveryTargetXid;
220
static TimestampTz recoveryTargetTime;
221
static char *recoveryTargetName;
222

223 224 225
/* options taken from recovery.conf for XLOG streaming */
static bool StandbyModeRequested = false;
static char *PrimaryConnInfo = NULL;
226
static char *TriggerFile = NULL;
227 228 229 230

/* are we currently in standby mode? */
bool StandbyMode = false;

231
/* if recoveryStopsHere returns true, it saves actual stop xid/time/name here */
B
Bruce Momjian 已提交
232
static TransactionId recoveryStopXid;
233
static TimestampTz recoveryStopTime;
234
static char recoveryStopName[MAXFNAMELEN];
B
Bruce Momjian 已提交
235
static bool recoveryStopAfter;
236

237 238 239
static char *replay_image_masked = NULL;
static char *master_image_masked = NULL;

240 241 242 243 244 245 246 247 248 249
/*
 * 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.
 *
250 251
 * recoveryTargetIsLatest: was the requested target timeline 'latest'?
 *
252 253
 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
 * its known parents, newest first (so recoveryTargetTLI is always the
B
Bruce Momjian 已提交
254
 * first list member).	Only these TLIs are expected to be seen in the WAL
255 256 257 258 259 260 261 262 263
 * 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 已提交
264
static TimeLineID recoveryTargetTLI;
265
List *expectedTLIs;
A
Asim R P 已提交
266
#if 0
267
static bool recoveryTargetIsLatest = false;
A
Asim R P 已提交
268
#endif
B
Bruce Momjian 已提交
269
static TimeLineID curFileTLI;
270

T
Tom Lane 已提交
271 272
/*
 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
273 274 275 276
 * 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 已提交
277 278
 */
static XLogRecPtr ProcLastRecPtr = {0, 0};
279

280
XLogRecPtr	XactLastRecEnd = {0, 0};
281

282 283 284 285
static uint32 ProcLastRecTotalLen = 0;

static uint32 ProcLastRecDataLen = 0;

286 287
static XLogRecPtr InvalidXLogRecPtr = {0, 0};

T
Tom Lane 已提交
288 289 290
/*
 * 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 已提交
291
 * CHECKPOINT record).	We update this from the shared-memory copy,
T
Tom Lane 已提交
292
 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
B
Bruce Momjian 已提交
293
 * hold the Insert lock).  See XLogInsert for details.	We are also allowed
294
 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
295 296
 * see GetRedoRecPtr.  A freshly spawned backend obtains the value during
 * InitXLOGAccess.
T
Tom Lane 已提交
297
 */
298
static XLogRecPtr RedoRecPtr;
299

300 301 302 303 304 305 306 307 308 309 310 311
/*
 * RedoStartLSN points to the checkpoint's REDO location which is specified
 * in a backup label file, backup history file or control file. In standby
 * mode, XLOG streaming usually starts from the position where an invalid
 * record was found. But if we fail to read even the initial checkpoint
 * record, we use the REDO location instead of the checkpoint location as
 * the start position of XLOG streaming. Otherwise we would have to jump
 * backwards to the REDO location after reading the checkpoint record,
 * because the REDO record can precede the checkpoint record.
 */
static XLogRecPtr RedoStartLSN = {0, 0};

T
Tom Lane 已提交
312 313 314 315 316 317 318 319 320
/*----------
 * 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.
 *
321
 * We do a lot of pushups to minimize the amount of access to lockable
T
Tom Lane 已提交
322 323 324
 * 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
325 326 327 328
 *		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 已提交
329 330 331
 *
 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
 * right", since both are updated by a write or flush operation before
332 333
 * 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 已提交
334 335 336
 * without needing to grab info_lck as well.
 *
 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
B
Bruce Momjian 已提交
337
 * but is updated when convenient.	Again, it exists for the convenience of
338
 * code that is already holding WALInsertLock but not the other locks.
T
Tom Lane 已提交
339 340 341 342 343 344 345 346 347 348
 *
 * 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".
349 350 351 352 353 354 355 356 357 358 359 360 361
 *
 * 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.
 *
362
 * CheckpointLock: must be held to do a checkpoint or restartpoint (ensures
363 364
 * only one checkpointer at a time; currently, with all checkpoints done by
 * the bgwriter, this is just pro forma).
365
 *
T
Tom Lane 已提交
366 367
 *----------
 */
368

T
Tom Lane 已提交
369
typedef struct XLogwrtRqst
370
{
T
Tom Lane 已提交
371 372
	XLogRecPtr	Write;			/* last byte + 1 to write out */
	XLogRecPtr	Flush;			/* last byte + 1 to flush */
373
} XLogwrtRqst;
374

375 376 377 378 379 380
typedef struct XLogwrtResult
{
	XLogRecPtr	Write;			/* last byte + 1 written out */
	XLogRecPtr	Flush;			/* last byte + 1 flushed */
} XLogwrtResult;

T
Tom Lane 已提交
381 382 383
/*
 * Shared state data for XLogInsert.
 */
384 385
typedef struct XLogCtlInsert
{
B
Bruce Momjian 已提交
386 387
	XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
	XLogRecPtr	PrevRecord;		/* start of previously-inserted record */
388
	int			curridx;		/* current block index in cache */
B
Bruce Momjian 已提交
389 390 391
	XLogPageHeader currpage;	/* points to header of block in cache */
	char	   *currpos;		/* current insertion point in cache */
	XLogRecPtr	RedoRecPtr;		/* current redo point for insertions */
392
	bool		forcePageWrites;	/* forcing full-page writes for PITR? */
393 394 395 396 397 398 399 400 401 402 403

	/*
	 * exclusiveBackup is true if a backup started with pg_start_backup() is
	 * in progress, and nonExclusiveBackups is a counter indicating the number
	 * of streaming base backups currently in progress. forcePageWrites is set
	 * to true when either of these is non-zero. lastBackupStart is the latest
	 * checkpoint redo location used as a starting point for an online backup.
	 */
	bool		exclusiveBackup;
	int			nonExclusiveBackups;
	XLogRecPtr	lastBackupStart;
404 405
} XLogCtlInsert;

T
Tom Lane 已提交
406 407 408
/*
 * Shared state data for XLogWrite/XLogFlush.
 */
409 410
typedef struct XLogCtlWrite
{
B
Bruce Momjian 已提交
411 412
	XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
	int			curridx;		/* cache index of next block to write */
413
	pg_time_t	lastSegSwitchTime;		/* time of last xlog segment switch */
414 415
} XLogCtlWrite;

T
Tom Lane 已提交
416 417 418
/*
 * Total shared-memory state for XLOG.
 */
419 420
typedef struct XLogCtlData
{
421
	/* Protected by WALInsertLock: */
B
Bruce Momjian 已提交
422
	XLogCtlInsert Insert;
423

T
Tom Lane 已提交
424
	/* Protected by info_lck: */
B
Bruce Momjian 已提交
425 426
	XLogwrtRqst LogwrtRqst;
	XLogwrtResult LogwrtResult;
427 428
	uint32		ckptXidEpoch;	/* nextXID & epoch of latest checkpoint */
	TransactionId ckptXid;
429
	XLogRecPtr	asyncXactLSN;	/* LSN of newest async commit/abort */
430 431
	uint32		lastRemovedLog; /* latest removed/recycled XLOG segment */
	uint32		lastRemovedSeg;
432

433
	/* Protected by WALWriteLock: */
B
Bruce Momjian 已提交
434 435
	XLogCtlWrite Write;

T
Tom Lane 已提交
436
	/*
B
Bruce Momjian 已提交
437 438 439
	 * 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 已提交
440
	 */
B
Bruce Momjian 已提交
441
	char	   *pages;			/* buffers for unwritten XLOG pages */
442
	XLogRecPtr *xlblocks;		/* 1st byte ptr-s + XLOG_BLCKSZ */
443
	int			XLogCacheBlck;	/* highest allocated xlog buffer index */
444
	TimeLineID	ThisTimeLineID;
T
Tom Lane 已提交
445

446
	/*
447
	 * archiveCleanupCommand is read from recovery.conf but needs to be in
448 449
	 * shared memory so that the bgwriter process can access it.
	 */
450
	char		archiveCleanupCommand[MAXPGPATH];
T
Tom Lane 已提交
451

452
	/*
453
	 * SharedRecoveryInProgress indicates if we're still in crash or archive
454
	 * recovery.  Protected by info_lck.
455 456 457
	 */
	bool		SharedRecoveryInProgress;

458 459 460 461 462 463
	/*
	 * SharedHotStandbyActive indicates if we're still in crash or archive
	 * recovery.  Protected by info_lck.
	 */
	bool		SharedHotStandbyActive;

464 465 466 467 468 469 470
	/*
	 * recoveryWakeupLatch is used to wake up the startup process to continue
	 * WAL replay, if it is waiting for WAL to arrive or failover trigger file
	 * to appear.
	 */
	Latch		recoveryWakeupLatch;

471
	/*
472 473
	 * During recovery, we keep a copy of the latest checkpoint record here.
	 * Used by the background writer when it wants to create a restartpoint.
474 475 476 477 478 479
	 *
	 * Protected by info_lck.
	 */
	XLogRecPtr	lastCheckPointRecPtr;
	CheckPoint	lastCheckPoint;

480 481 482 483 484 485 486 487 488 489 490
	/*
	 * Save the location of the last checkpoint record to enable supressing
	 * unnecessary checkpoint records -- when no new xlog has been written
	 * since the last one.
	 */
	bool 		haveLastCheckpointLoc;
	XLogRecPtr	lastCheckpointLoc;
	XLogRecPtr	lastCheckpointEndLoc;

	/*
	 * lastReplayedEndRecPtr points to end+1 of the last record successfully
491 492 493
	 * replayed. When we're currently replaying a record, ie. in a redo
	 * function, replayEndRecPtr points to the end+1 of the record being
	 * replayed, otherwise it's equal to lastReplayedEndRecPtr.
494 495
	 */
	XLogRecPtr	lastReplayedEndRecPtr;
496
	XLogRecPtr	replayEndRecPtr;
497 498
	/* end+1 of the last record replayed */
	XLogRecPtr	recoveryLastRecPtr;
499 500
	/* timestamp of last COMMIT/ABORT record replayed (or being replayed) */
	TimestampTz recoveryLastXTime;
501 502
	/* current effective recovery target timeline */
	TimeLineID	RecoveryTargetTLI;
503 504
	/* Are we requested to pause recovery? */
	bool		recoveryPause;
505 506

	slock_t		info_lck;		/* locks shared variables shown above */
507 508 509 510 511 512 513


	/*
	 * timestamp of when we started replaying the current chunk of WAL data,
	 * only relevant for replication or archive recovery
	 */
	TimestampTz currentChunkStartTime;
514 515
} XLogCtlData;

516
static XLogCtlData *XLogCtl = NULL;
517

518
/*
T
Tom Lane 已提交
519
 * We maintain an image of pg_control in shared memory.
520
 */
521
static ControlFileData *ControlFile = NULL;
522

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
typedef struct ControlFileWatch
{
	bool		watcherInitialized;
	XLogRecPtr	current_checkPointLoc;		/* current last check point record ptr */
	XLogRecPtr	current_prevCheckPointLoc;  /* current previous check point record ptr */
	XLogRecPtr	current_checkPointCopy_redo;
								/* current checkpointCopy value for
								 * next RecPtr available when we began to
								 * create CheckPoint (i.e. REDO start point) */

} ControlFileWatch;


/*
 * We keep the watcher in shared memory.
 */
static ControlFileWatch *ControlFileWatcher = NULL;

T
Tom Lane 已提交
541 542 543 544 545
/*
 * 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.
 */
546

T
Tom Lane 已提交
547 548
/* Free space remaining in the current xlog page buffer */
#define INSERT_FREESPACE(Insert)  \
549
	(XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
T
Tom Lane 已提交
550 551 552 553 554 555

/* Construct XLogRecPtr value for current insertion point */
#define INSERT_RECPTR(recptr,Insert,curridx)  \
	( \
	  (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
	  (recptr).xrecoff = \
B
Bruce Momjian 已提交
556
		XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
T
Tom Lane 已提交
557 558 559 560 561 562 563
	)

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

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

T
Tom Lane 已提交
565 566 567 568
/*
 * Private, possibly out-of-date copy of shared LogwrtResult.
 * See discussion above.
 */
569
static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
570

571 572 573 574 575 576 577 578 579
/*
 * Codes indicating where we got a WAL file from during recovery, or where
 * to attempt to get one.  These are chosen so that they can be OR'd together
 * in a bitmask state variable.
 */
#define XLOG_FROM_ARCHIVE		(1<<0)	/* Restored using restore_command */
#define XLOG_FROM_PG_XLOG		(1<<1)	/* Existing file in pg_xlog */
#define XLOG_FROM_STREAM		(1<<2)	/* Streamed from master */

T
Tom Lane 已提交
580 581 582 583 584 585
/*
 * 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.
 */
586
static int	openLogFile = -1;
T
Tom Lane 已提交
587 588 589
static uint32 openLogId = 0;
static uint32 openLogSeg = 0;
static uint32 openLogOff = 0;
590

T
Tom Lane 已提交
591 592 593 594
/*
 * 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
595 596 597
 * will be just past that page.readLen indicates how much of the current
 * page has been read into readBuf, and readSource indicates where we got
 * the currently open file from.
T
Tom Lane 已提交
598
 */
599 600 601 602
static int	readFile = -1;
static uint32 readId = 0;
static uint32 readSeg = 0;
static uint32 readOff = 0;
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
static uint32 readLen = 0;
static int	readSource = 0;		/* XLOG_FROM_* code */

/*
 * Keeps track of which sources we've tried to read the current WAL
 * record from and failed.
 */
static int	failedSources = 0;	/* OR of XLOG_FROM_* codes */

/*
 * These variables track when we last obtained some WAL data to process,
 * and where we got it from.  (XLogReceiptSource is initially the same as
 * readSource, but readSource gets reset to zero when we don't have data
 * to process right now.)
 */
static TimestampTz XLogReceiptTime = 0;
static int	XLogReceiptSource = 0;		/* XLOG_FROM_* code */
B
Bruce Momjian 已提交
620

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

624 625 626 627
/* Buffer for current ReadRecord result (expandable) */
static char *readRecordBuf = NULL;
static uint32 readRecordBufSize = 0;

T
Tom Lane 已提交
628
/* State information for XLOG reading */
B
Bruce Momjian 已提交
629 630
static XLogRecPtr ReadRecPtr;	/* start of last record read */
static XLogRecPtr EndRecPtr;	/* end+1 of last record read */
631
static TimeLineID lastPageTLI = 0;
632
static TimeLineID lastSegmentTLI = 0;
633

634 635 636
static XLogRecPtr minRecoveryPoint;		/* local copy of
										 * ControlFile->minRecoveryPoint */
static bool updateMinRecoveryPoint = true;
637
static bool reachedMinRecoveryPoint = false;
638

V
WAL  
Vadim B. Mikheev 已提交
639 640
static bool InRedo = false;

641 642 643
/* Have we launched bgwriter during recovery? */
static bool bgwriterLaunched = false;

644 645 646 647 648 649 650 651 652 653 654 655
/*
 * Information logged when we detect a change in one of the parameters
 * important for Hot Standby.
 */
typedef struct xl_parameter_change
{
	int			MaxConnections;
	int			max_prepared_xacts;
	int			max_locks_per_xact;
	int			wal_level;
} xl_parameter_change;

656 657 658
/* logs restore point */
typedef struct xl_restore_point
{
659
	TimestampTz rp_time;
660 661 662
	char		rp_name[MAXFNAMELEN];
} xl_restore_point;

663
/*
664
 * Flags set by interrupt handlers for later service in the redo loop.
665 666 667
 */
static volatile sig_atomic_t got_SIGHUP = false;
static volatile sig_atomic_t shutdown_requested = false;
R
Robert Haas 已提交
668
static volatile sig_atomic_t promote_triggered = false;
669 670 671 672 673 674

/*
 * Flag set when executing a restore command, to tell SIGTERM signal handler
 * that it's safe to just proc_exit.
 */
static volatile sig_atomic_t in_restore_command = false;
675 676


677 678
static void XLogArchiveNotify(const char *xlog);
static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
679 680
static bool XLogArchiveCheckDone(const char *xlog);
static bool XLogArchiveIsBusy(const char *xlog);
681
static void XLogArchiveCleanup(const char *xlog);
682
static void exitArchiveRecovery(TimeLineID endTLI,
B
Bruce Momjian 已提交
683
					uint32 endLogId, uint32 endLogSeg);
684
static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
685 686 687
static void recoveryPausesHere(void);
static bool RecoveryIsPaused(void);
static void SetRecoveryPause(bool recoveryPause);
688 689
static void SetLatestXTime(TimestampTz xtime);
static TimestampTz GetLatestXTime(void);
690 691
static void CheckRequiredParameterValues(void);
static void XLogReportParameters(void);
692
static void LocalSetXLogInsertAllowed(void);
693
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
T
Tom Lane 已提交
694

695
static bool XLogCheckBuffer(XLogRecData *rdata, bool holdsExclusiveLock,
696 697 698
							bool wal_check_consistency_enabled,
							XLogRecPtr *lsn, BkpBlock *bkpb);
static void RestoreBackupBlockContents(XLogRecPtr lsn, BkpBlock bkpb,
699
				char *blk, bool get_cleanup_lock, bool keep_buffer);
700

701
static bool AdvanceXLInsertBuffer(bool new_segment);
702
static bool XLogCheckpointNeeded(uint32 logid, uint32 logseg);
703
static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
704 705
static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
706
					   bool use_lock);
B
Bruce Momjian 已提交
707
static int XLogFileRead(uint32 log, uint32 seg, int emode, TimeLineID tli,
708
			 int source, bool notexistOk);
B
Bruce Momjian 已提交
709
static int XLogFileReadAnyTLI(uint32 log, uint32 seg, int emode,
710
				   int sources);
711 712
static bool XLogPageRead(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt,
			 bool randAccess);
B
Bruce Momjian 已提交
713
static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
B
Bruce Momjian 已提交
714
static void XLogFileClose(void);
715

716
#ifdef NOT_USED
717
static bool RestoreArchivedFile(char *path, const char *xlogfname,
B
Bruce Momjian 已提交
718
					const char *recovername, off_t expectedSize);
719 720
static void ExecuteRecoveryCommand(char *command, char *commandName,
					   bool failOnerror);
721
#endif
722
static void PreallocXlogFiles(XLogRecPtr endptr);
723
static void UpdateLastRemovedPtr(char *filename);
724
static void ValidateXLOGDirectoryStructure(void);
725
static void CleanupBackupHistory(void);
726
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
727
#ifdef NOT_USED
728
static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt);
729
#endif
730
static void CheckRecoveryConsistency(void);
731
static bool ValidXLOGHeader(XLogPageHeader hdr, int emode, bool segmentonly);
732
static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
733

734 735 736 737 738 739 740 741 742
typedef struct CheckpointExtendedRecord
{
	TMGXACT_CHECKPOINT	*dtxCheckpoint;
	uint32				dtxCheckpointLen;
	prepared_transaction_agg_state  *ptas;
} CheckpointExtendedRecord;

static void UnpackCheckPointRecord(XLogRecord *record,
								   CheckpointExtendedRecord *ckptExtended);
743
static bool existsTimeLineHistory(TimeLineID probeTLI);
A
Asim R P 已提交
744
#if 0
745
static bool rescanLatestTimeLine(void);
A
Asim R P 已提交
746
#endif
747 748
static TimeLineID findNewestTimeLine(TimeLineID startTLI);
static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
B
Bruce Momjian 已提交
749 750
					 TimeLineID endTLI,
					 uint32 endLogId, uint32 endLogSeg);
751 752 753 754
static void ControlFileWatcherSaveInitial(void);
static void ControlFileWatcherCheckForChange(void);
static bool XLogGetWriteAndFlushedLoc(XLogRecPtr *writeLoc, XLogRecPtr *flushedLoc);
static XLogRecPtr XLogInsert_Internal(RmgrId rmid, uint8 info, XLogRecData *rdata, TransactionId headerXid);
T
Tom Lane 已提交
755 756
static void WriteControlFile(void);
static void ReadControlFile(void);
757

758
static char *str_time(pg_time_t tnow);
759
static bool CheckForStandbyTrigger(void);
760

761
static void xlog_outrec(StringInfo buf, XLogRecord *record);
762 763
static void pg_start_backup_callback(int code, Datum arg);
static bool read_backup_label(XLogRecPtr *checkPointLoc, bool *backupEndRequired);
764
static void rm_redo_error_callback(void *arg);
765
static int	get_sync_bit(int method);
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

/* New functions added for WAL replication */
static void SetCurrentChunkStartTime(TimestampTz xtime);
static int XLogFileReadAnyTLI(uint32 log, uint32 seg, int emode, int sources);
static void XLogProcessCheckpointRecord(XLogRecord *rec, XLogRecPtr loc);

typedef struct RedoErrorCallBack
{
	XLogRecPtr	location;

	XLogRecord 	*record;
} RedoErrorCallBack;

void HandleStartupProcInterrupts(void);

781
static void GetXLogCleanUpTo(XLogRecPtr recptr, uint32 *_logId, uint32 *_logSeg);
782
static void checkXLogConsistency(XLogRecord *record, XLogRecPtr EndRecPtr);
783

784 785 786 787 788 789 790 791 792 793
static char *XLogContiguousCopy(
	XLogRecord 		*record,

	XLogRecData 	*rdata)
{
	XLogRecData *rdt;
	int32 len;
	char *buffer;

	rdt = rdata;
794
	len = SizeOfXLogRecord;
795 796 797 798 799 800 801 802 803 804 805
	while (rdt != NULL)
	{
		if (rdt->data != NULL)
		{
			len += rdt->len;
		}
		rdt = rdt->next;
	}

	buffer = (char*)palloc(len);

806
	memcpy(buffer, record, SizeOfXLogRecord);
807
	rdt = rdata;
808
	len = SizeOfXLogRecord;
809 810 811 812 813 814 815 816 817 818 819 820
	while (rdt != NULL)
	{
		if (rdt->data != NULL)
		{
			memcpy(&buffer[len], rdt->data, rdt->len);
			len += rdt->len;
		}
		rdt = rdt->next;
	}

	return buffer;
}
T
Tom Lane 已提交
821 822 823 824

/*
 * Insert an XLOG record having the specified RMID and info bytes,
 * with the body of the record being the data chunk(s) described by
825
 * the rdata chain (see xlog.h for notes about rdata).
T
Tom Lane 已提交
826 827 828 829 830 831 832 833 834 835 836
 *
 * 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.
 */
837
XLogRecPtr
838
XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
839
{
840 841 842 843 844 845 846 847 848 849 850 851 852 853
	return XLogInsert_Internal(rmid, info, rdata, GetCurrentTransactionIdIfAny());
}

XLogRecPtr
XLogInsert_OverrideXid(RmgrId rmid, uint8 info, XLogRecData *rdata, TransactionId overrideXid)
{
	return XLogInsert_Internal(rmid, info, rdata, overrideXid);
}


static XLogRecPtr
XLogInsert_Internal(RmgrId rmid, uint8 info, XLogRecData *rdata, TransactionId headerXid)
{

B
Bruce Momjian 已提交
854 855
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecord *record;
T
Tom Lane 已提交
856
	XLogContRecord *contrecord;
B
Bruce Momjian 已提交
857 858 859
	XLogRecPtr	RecPtr;
	XLogRecPtr	WriteRqst;
	uint32		freespace;
860
	int			curridx;
B
Bruce Momjian 已提交
861 862 863 864 865
	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];
866 867 868 869
	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 已提交
870 871 872 873
	uint32		len,
				write_len;
	unsigned	i;
	bool		updrqst;
874
	bool		doPageWrites;
875
	bool		isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
876
	uint8       extended_info = 0;
877

878
	/* cross-check on whether we should be here or not */
879 880
	if (!XLogInsertAllowed())
		elog(ERROR, "cannot make new WAL entries during recovery");
881

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

886 887
	TRACE_POSTGRESQL_XLOG_INSERT(rmid, info);

T
Tom Lane 已提交
888
	/*
B
Bruce Momjian 已提交
889 890
	 * In bootstrap mode, we don't actually log anything but XLOG resources;
	 * return a phony record pointer.
T
Tom Lane 已提交
891
	 */
V
Vadim B. Mikheev 已提交
892
	if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
V
WAL  
Vadim B. Mikheev 已提交
893 894
	{
		RecPtr.xlogid = 0;
B
Bruce Momjian 已提交
895
		RecPtr.xrecoff = SizeOfXLogLongPHD;		/* start of 1st chkpt record */
896
		return RecPtr;
V
WAL  
Vadim B. Mikheev 已提交
897 898
	}

899 900 901 902 903 904 905 906 907
	/*
	 * Enforce consistency checks for this record if user is looking for
	 * it. Do this before at the beginning of this routine to give the
	 * possibility for callers of XLogInsert() to pass XLR_CHECK_CONSISTENCY
	 * directly for a record.
	 */
	if (wal_consistency_checking[rmid])
		extended_info |= XLR_CHECK_CONSISTENCY;

T
Tom Lane 已提交
908
	/*
909
	 * Here we scan the rdata chain, determine which buffers must be backed
T
Tom Lane 已提交
910
	 * up, and compute the CRC values for the data.  Note that the record
B
Bruce Momjian 已提交
911 912 913 914
	 * 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 已提交
915
	 *
916 917 918 919 920
	 * 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 已提交
921 922 923 924 925
	 * 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 已提交
926
	 */
927
begin:;
T
Tom Lane 已提交
928 929 930 931 932 933
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
	{
		dtbuf[i] = InvalidBuffer;
		dtbuf_bkp[i] = false;
	}

934 935 936 937 938 939 940 941
	/*
	 * 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;

942
	INIT_CRC32C(rdata_crc);
T
Tom Lane 已提交
943
	len = 0;
B
Bruce Momjian 已提交
944
	for (rdt = rdata;;)
945 946 947
	{
		if (rdt->buffer == InvalidBuffer)
		{
T
Tom Lane 已提交
948
			/* Simple data, just include it */
949
			len += rdt->len;
950
			COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
951
		}
T
Tom Lane 已提交
952
		else
953
		{
T
Tom Lane 已提交
954 955
			/* Find info for buffer */
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
956
			{
T
Tom Lane 已提交
957
				if (rdt->buffer == dtbuf[i])
958
				{
959 960 961 962 963 964 965
					/*
					 * Buffer already referenced by earlier chain item and
					 * will be applied then only ignore it. Block can exist
					 * for consistency check purpose and hence should include
					 * original data along if its only for that purpose.
					 */
					if (dtbuf_bkp[i] && (dtbuf_xlg[i].block_info & BLOCK_APPLY))
T
Tom Lane 已提交
966 967 968 969
						rdt->data = NULL;
					else if (rdt->data)
					{
						len += rdt->len;
970
						COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
T
Tom Lane 已提交
971 972
					}
					break;
973
				}
T
Tom Lane 已提交
974
				if (dtbuf[i] == InvalidBuffer)
975
				{
T
Tom Lane 已提交
976 977
					/* OK, put it in this slot */
					dtbuf[i] = rdt->buffer;
978

979
					if (doPageWrites && XLogCheckBuffer(rdt, true,
980
										(extended_info & XLR_CHECK_CONSISTENCY) != 0,
981
										&(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
T
Tom Lane 已提交
982 983
					{
						dtbuf_bkp[i] = true;
984 985 986 987 988 989 990 991 992 993 994

						if (dtbuf_xlg[i].block_info & BLOCK_APPLY)
							rdt->data = NULL;
						else
						{
							if (rdt->data)
							{
								len += rdt->len;
								COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
							}
						}
T
Tom Lane 已提交
995 996 997 998
					}
					else if (rdt->data)
					{
						len += rdt->len;
999
						COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
T
Tom Lane 已提交
1000 1001
					}
					break;
1002 1003
				}
			}
T
Tom Lane 已提交
1004
			if (i >= XLR_MAX_BKP_BLOCKS)
1005
				elog(PANIC, "can backup at most %d blocks per xlog record",
T
Tom Lane 已提交
1006
					 XLR_MAX_BKP_BLOCKS);
1007
		}
1008
		/* Break out of loop when rdt points to last chain item */
1009 1010 1011 1012 1013
		if (rdt->next == NULL)
			break;
		rdt = rdt->next;
	}

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	/*
	 * 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;

1024
			COMP_CRC32C(rdata_crc,
1025 1026 1027 1028 1029
					   (char *) bkpb,
					   sizeof(BkpBlock));
			page = (char *) BufferGetBlock(dtbuf[i]);
			if (bkpb->hole_length == 0)
			{
1030
				COMP_CRC32C(rdata_crc, page, BLCKSZ);
1031 1032 1033 1034
			}
			else
			{
				/* must skip the hole */
1035 1036
				COMP_CRC32C(rdata_crc, page, bkpb->hole_offset);
				COMP_CRC32C(rdata_crc,
1037 1038 1039 1040 1041 1042
						   page + (bkpb->hole_offset + bkpb->hole_length),
						   BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
			}
		}
	}

T
Tom Lane 已提交
1043
	/*
1044 1045
	 * 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 已提交
1046 1047 1048
	 * 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 已提交
1049
	 */
1050
	if (len == 0 && !isLogSwitch)
1051
		elog(PANIC, "invalid xlog record length %u", len);
1052

1053
	START_CRIT_SECTION();
1054

1055 1056 1057
	/* Now wait to get insert lock */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);

T
Tom Lane 已提交
1058
	/*
B
Bruce Momjian 已提交
1059 1060 1061
	 * 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.
1062 1063
	 *
	 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
B
Bruce Momjian 已提交
1064 1065
	 * affect the contents of the XLOG record, so we'll update our local copy
	 * but not force a recomputation.
T
Tom Lane 已提交
1066 1067
	 */
	if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
1068
	{
T
Tom Lane 已提交
1069 1070 1071
		Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
		RedoRecPtr = Insert->RedoRecPtr;

1072
		if (doPageWrites)
1073
		{
1074
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
T
Tom Lane 已提交
1075
			{
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
				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);
1086

1087 1088 1089
					END_CRIT_SECTION();
					goto begin;
				}
T
Tom Lane 已提交
1090
			}
1091 1092 1093
		}
	}

1094
	/*
B
Bruce Momjian 已提交
1095 1096 1097 1098
	 * 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.)
1099 1100 1101 1102 1103 1104 1105 1106 1107
	 */
	if (Insert->forcePageWrites && !doPageWrites)
	{
		/* Oops, must redo it with full-page data */
		LWLockRelease(WALInsertLock);
		END_CRIT_SECTION();
		goto begin;
	}

T
Tom Lane 已提交
1108
	/*
B
Bruce Momjian 已提交
1109 1110 1111 1112
	 * 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 已提交
1113
	 *
1114 1115 1116
	 * 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 已提交
1117 1118 1119
	 */
	write_len = len;
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
1120
	{
1121 1122 1123
		BkpBlock   *bkpb;
		char	   *page;

1124
		if (!dtbuf_bkp[i])
1125 1126
			continue;

T
Tom Lane 已提交
1127
		info |= XLR_SET_BKP_BLOCK(i);
1128

1129 1130 1131 1132 1133
		bkpb = &(dtbuf_xlg[i]);
		page = (char *) BufferGetBlock(dtbuf[i]);

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

1135 1136
		rdt->data = (char *) bkpb;
		rdt->len = sizeof(BkpBlock);
T
Tom Lane 已提交
1137
		write_len += sizeof(BkpBlock);
1138

1139 1140
		rdt->next = &(dtbuf_rdt2[i]);
		rdt = rdt->next;
1141

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
		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;
		}
1164 1165
	}

1166 1167 1168 1169 1170 1171 1172
	/*
	 * 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 已提交
1173 1174
	 * defining it like this leaves the info bit free for some potential other
	 * use in records without any backup blocks.
1175 1176 1177 1178
	 */
	if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
		info |= XLR_BKP_REMOVABLE;

1179
	/*
1180
	 * If there isn't enough space on the current XLOG page for a record
B
Bruce Momjian 已提交
1181
	 * header, advance to the next page (leaving the unused space as zeroes).
1182
	 */
T
Tom Lane 已提交
1183 1184
	updrqst = false;
	freespace = INSERT_FREESPACE(Insert);
1185 1186
	if (freespace < SizeOfXLogRecord)
	{
1187
		updrqst = AdvanceXLInsertBuffer(false);
1188 1189 1190
		freespace = INSERT_FREESPACE(Insert);
	}

1191
	/* Compute record's XLOG location */
T
Tom Lane 已提交
1192
	curridx = Insert->curridx;
1193 1194 1195
	INSERT_RECPTR(RecPtr, Insert, curridx);

	/*
B
Bruce Momjian 已提交
1196 1197 1198 1199 1200
	 * 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.
1201 1202 1203 1204
	 */
	if (isLogSwitch &&
		(RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
	{
1205
		/* We can release insert lock immediately */
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
		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 已提交
1232

1233 1234
	/* Insert record header */

1235
	record = (XLogRecord *) Insert->currpos;
1236
	record->xl_prev = Insert->PrevRecord;
1237
	record->xl_xid = headerXid;
1238
	record->xl_tot_len = SizeOfXLogRecord + write_len;
T
Tom Lane 已提交
1239
	record->xl_len = len;		/* doesn't include backup blocks */
1240
	record->xl_info = info;
1241
	record->xl_rmid = rmid;
1242
	record->xl_extended_info = extended_info;
1243

1244
	/* Now we can finish computing the record's CRC */
1245
	COMP_CRC32C(rdata_crc, (char *) record + sizeof(pg_crc32),
1246
			   SizeOfXLogRecord - sizeof(pg_crc32));
1247
	FIN_CRC32C(rdata_crc);
1248 1249
	record->xl_crc = rdata_crc;

T
Tom Lane 已提交
1250 1251 1252 1253
	/* Record begin of record in appropriate places */
	ProcLastRecPtr = RecPtr;
	Insert->PrevRecord = RecPtr;

1254 1255 1256
	ProcLastRecTotalLen = record->xl_tot_len;
	ProcLastRecDataLen = write_len;

1257
	Insert->currpos += SizeOfXLogRecord;
T
Tom Lane 已提交
1258
	freespace -= SizeOfXLogRecord;
1259

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
	if (Debug_xlog_insert_print)
	{
		StringInfoData buf;
		char *contiguousCopy;

		initStringInfo(&buf);
		appendStringInfo(&buf, "XLOG INSERT @ %s, total length %u, data length %u: ",
						 XLogLocationToString(&RecPtr),
						 ProcLastRecTotalLen,
						 ProcLastRecDataLen);
1270
		xlog_outrec(&buf, record);
1271 1272 1273

		contiguousCopy = XLogContiguousCopy(record, rdata);
		appendStringInfo(&buf, " - ");
1274
		RmgrTable[record->xl_rmid].rm_desc(&buf, (XLogRecord*)contiguousCopy);
1275 1276 1277 1278 1279 1280
		pfree(contiguousCopy);

		elog(LOG, "%s", buf.data);
		pfree(buf.data);
	}

T
Tom Lane 已提交
1281 1282 1283 1284
	/*
	 * Append the data, including backup blocks if any
	 */
	while (write_len)
1285
	{
1286 1287 1288 1289
		while (rdata->data == NULL)
			rdata = rdata->next;

		if (freespace > 0)
1290
		{
1291 1292 1293 1294 1295
			if (rdata->len > freespace)
			{
				memcpy(Insert->currpos, rdata->data, freespace);
				rdata->data += freespace;
				rdata->len -= freespace;
T
Tom Lane 已提交
1296
				write_len -= freespace;
1297 1298 1299
			}
			else
			{
1300
				/* enough room to write whole data. do it. */
1301 1302
				memcpy(Insert->currpos, rdata->data, rdata->len);
				freespace -= rdata->len;
T
Tom Lane 已提交
1303
				write_len -= rdata->len;
1304 1305 1306 1307
				Insert->currpos += rdata->len;
				rdata = rdata->next;
				continue;
			}
1308 1309
		}

1310
		/* Use next buffer */
1311
		updrqst = AdvanceXLInsertBuffer(false);
T
Tom Lane 已提交
1312 1313 1314 1315 1316 1317
		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;
1318
		freespace = INSERT_FREESPACE(Insert);
1319
	}
1320

T
Tom Lane 已提交
1321 1322
	/* Ensure next record will be properly aligned */
	Insert->currpos = (char *) Insert->currpage +
B
Bruce Momjian 已提交
1323
		MAXALIGN(Insert->currpos - (char *) Insert->currpage);
T
Tom Lane 已提交
1324
	freespace = INSERT_FREESPACE(Insert);
1325

V
Vadim B. Mikheev 已提交
1326
	/*
B
Bruce Momjian 已提交
1327 1328
	 * 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 已提交
1329
	 */
T
Tom Lane 已提交
1330
	INSERT_RECPTR(RecPtr, Insert, curridx);
V
Vadim B. Mikheev 已提交
1331

1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
	/*
	 * 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;

1346 1347
		TRACE_POSTGRESQL_XLOG_SWITCH();

1348 1349 1350
		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);

		/*
B
Bruce Momjian 已提交
1351 1352
		 * Flush through the end of the page containing XLOG_SWITCH, and
		 * perform end-of-segment actions (eg, notifying archiver).
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
		 */
		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 */
	}
1403
	else
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
	{
		/* 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];
	}
1420

1421
	LWLockRelease(WALInsertLock);
1422 1423 1424

	if (updrqst)
	{
1425 1426 1427
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

1428
		SpinLockAcquire(&xlogctl->info_lck);
T
Tom Lane 已提交
1429
		/* advance global request to include new block(s) */
1430 1431
		if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
			xlogctl->LogwrtRqst.Write = WriteRqst;
T
Tom Lane 已提交
1432
		/* update local result copy while I have the chance */
1433
		LogwrtResult = xlogctl->LogwrtResult;
1434
		SpinLockRelease(&xlogctl->info_lck);
1435 1436
	}

1437
	XactLastRecEnd = RecPtr;
1438

1439
	END_CRIT_SECTION();
1440

1441
	return RecPtr;
1442
}
1443

1444 1445 1446 1447 1448 1449
XLogRecPtr
XLogLastInsertBeginLoc(void)
{
	return ProcLastRecPtr;
}

1450
/*
1451 1452 1453
 * 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.
1454
 */
1455
static bool
1456
XLogCheckBuffer(XLogRecData *rdata, bool holdsExclusiveLock,
1457
				bool wal_check_consistency_enabled,
1458
				XLogRecPtr *lsn, BkpBlock *bkpb)
1459
{
1460
	Page		page;
1461
	bool needs_backup;
1462

1463
	page = BufferGetPage(rdata->buffer);
1464 1465

	/*
1466 1467 1468 1469
	 * We assume page LSN is first data on *every* page that can be passed
	 * to XLogInsert, whether it has the standard page layout or not. We
	 * don't need to take the buffer header lock for PageGetLSN if we hold
	 * an exclusive lock on the page and/or the relation.
1470
	 */
1471
	if (holdsExclusiveLock)
1472
		*lsn = PageGetLSN(page);
1473 1474
	else
		*lsn = BufferGetLSNAtomic(rdata->buffer);
1475

1476
	needs_backup = XLByteLE(((PageHeader) page)->pd_lsn, RedoRecPtr);
1477 1478

	if (needs_backup || wal_check_consistency_enabled)
1479
	{
1480 1481 1482
		/*
		 * The page needs to be backed up, so set up *bkpb
		 */
1483
		BufferGetTag(rdata->buffer, &bkpb->node, &bkpb->fork, &bkpb->block);
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
		bkpb->block_info = 0;

		/*
		 * If WAL consistency checking is enabled for the
		 * resource manager of this WAL record, a full-page
		 * image is included in the record for the block
		 * modified. During redo, the full-page is replayed
		 * only if block_apply is set.
		 */
		if (needs_backup)
			bkpb->block_info |= BLOCK_APPLY;
1495

1496 1497 1498
		if (rdata->buffer_std)
		{
			/* Assume we can omit data between pd_lower and pd_upper */
1499 1500
			uint16		lower = ((PageHeader) page)->pd_lower;
			uint16		upper = ((PageHeader) page)->pd_upper;
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

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

1523
		return true;			/* buffer requires backup */
1524
	}
1525 1526

	return false;				/* buffer does not need to be backed up */
1527 1528
}

1529 1530 1531 1532 1533 1534
/*
 * XLogArchiveNotify
 *
 * Create an archive notification file
 *
 * The name of the notification file is the message that will be picked up
1535
 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1536
 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1537
 * then when complete, rename it to 0000000100000001000000C6.done
1538 1539 1540 1541 1542
 */
static void
XLogArchiveNotify(const char *xlog)
{
	char		archiveStatusPath[MAXPGPATH];
B
Bruce Momjian 已提交
1543
	FILE	   *fd;
1544 1545 1546 1547

	/* insert an otherwise empty file called <XLOG>.ready */
	StatusFilePath(archiveStatusPath, xlog, ".ready");
	fd = AllocateFile(archiveStatusPath, "w");
B
Bruce Momjian 已提交
1548 1549
	if (fd == NULL)
	{
1550 1551 1552 1553 1554 1555
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not create archive status file \"%s\": %m",
						archiveStatusPath)));
		return;
	}
B
Bruce Momjian 已提交
1556 1557
	if (FreeFile(fd))
	{
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
		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];

1578
	XLogFileName(xlog, ThisTimeLineID, log, seg);
1579 1580 1581 1582
	XLogArchiveNotify(xlog);
}

/*
1583
 * XLogArchiveCheckDone
1584
 *
1585 1586 1587 1588
 * 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.
1589 1590
 *
 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1591 1592 1593 1594
 * 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.
1595 1596
 */
static bool
1597
XLogArchiveCheckDone(const char *xlog)
1598 1599 1600 1601
{
	char		archiveStatusPath[MAXPGPATH];
	struct stat stat_buf;

1602 1603 1604 1605 1606
	/* Always deletable if archiving is off */
	if (!XLogArchivingActive())
		return true;

	/* First check for .done --- this means archiver is done with it */
1607 1608 1609 1610 1611 1612 1613
	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 已提交
1614
		return false;
1615 1616 1617 1618 1619 1620 1621

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

1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
/*
 * XLogArchiveIsBusy
 *
 * Check to see if an XLOG segment file is still unarchived.
 * This is almost but not quite the inverse of XLogArchiveCheckDone: in
 * the first place we aren't chartered to recreate the .ready file, and
 * in the second place we should consider that if the file is already gone
 * then it's not busy.  (This check is needed to handle the race condition
 * that a checkpoint already deleted the no-longer-needed file.)
 */
static bool
XLogArchiveIsBusy(const char *xlog)
{
	char		archiveStatusPath[MAXPGPATH];
	struct stat stat_buf;

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

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

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

	/*
1658 1659 1660
	 * Check to see if the WAL file has been removed by checkpoint, which
	 * implies it has already been archived, and explains why we can't see a
	 * status file for it.
1661 1662 1663 1664 1665 1666 1667 1668 1669
	 */
	snprintf(archiveStatusPath, MAXPGPATH, XLOGDIR "/%s", xlog);
	if (stat(archiveStatusPath, &stat_buf) != 0 &&
		errno == ENOENT)
		return false;

	return true;
}

1670 1671 1672
/*
 * XLogArchiveCleanup
 *
1673
 * Cleanup archive notification file(s) for a particular xlog segment
1674 1675 1676 1677
 */
static void
XLogArchiveCleanup(const char *xlog)
{
B
Bruce Momjian 已提交
1678
	char		archiveStatusPath[MAXPGPATH];
1679

1680
	/* Remove the .done file */
1681 1682 1683
	StatusFilePath(archiveStatusPath, xlog, ".done");
	unlink(archiveStatusPath);
	/* should we complain about failure? */
1684 1685 1686 1687 1688

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

T
Tom Lane 已提交
1691 1692 1693 1694
/*
 * Advance the Insert state to the next buffer page, writing out the next
 * buffer if it still contains unwritten data.
 *
1695 1696 1697 1698
 * 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 已提交
1699
 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1700
 * just-filled page.  If we can do this for free (without an extra lock),
T
Tom Lane 已提交
1701 1702 1703
 * 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.
 *
1704
 * Must be called with WALInsertLock held.
T
Tom Lane 已提交
1705 1706
 */
static bool
1707
AdvanceXLInsertBuffer(bool new_segment)
1708
{
T
Tom Lane 已提交
1709 1710
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogCtlWrite *Write = &XLogCtl->Write;
1711
	int			nextidx = NextBufIdx(Insert->curridx);
T
Tom Lane 已提交
1712 1713 1714
	bool		update_needed = true;
	XLogRecPtr	OldPageRqstPtr;
	XLogwrtRqst WriteRqst;
1715 1716
	XLogRecPtr	NewPageEndPtr;
	XLogPageHeader NewPage;
1717

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

T
Tom Lane 已提交
1722
	/*
B
Bruce Momjian 已提交
1723 1724 1725
	 * 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 已提交
1726 1727 1728 1729 1730 1731
	 */
	OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
	if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
	{
		/* nope, got work to do... */
		XLogRecPtr	FinishedPageRqstPtr;
1732

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

1735
		/* Before waiting, get info_lck and update LogwrtResult */
1736 1737 1738 1739
		{
			/* use volatile pointer to prevent code rearrangement */
			volatile XLogCtlData *xlogctl = XLogCtl;

1740
			SpinLockAcquire(&xlogctl->info_lck);
1741 1742 1743
			if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
				xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
			LogwrtResult = xlogctl->LogwrtResult;
1744
			SpinLockRelease(&xlogctl->info_lck);
1745
		}
1746 1747 1748 1749 1750 1751 1752 1753 1754

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

		if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
		{
			/* OK, someone wrote it already */
			Insert->LogwrtResult = LogwrtResult;
		}
		else
1755
		{
1756 1757 1758 1759
			/* Must acquire write lock */
			LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
			LogwrtResult = Write->LogwrtResult;
			if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1760
			{
1761 1762 1763
				/* OK, someone wrote it already */
				LWLockRelease(WALWriteLock);
				Insert->LogwrtResult = LogwrtResult;
T
Tom Lane 已提交
1764
			}
1765
			else
T
Tom Lane 已提交
1766 1767
			{
				/*
B
Bruce Momjian 已提交
1768 1769
				 * Have to write buffers while holding insert lock. This is
				 * not good, so only write as much as we absolutely must.
T
Tom Lane 已提交
1770
				 */
1771
				TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
T
Tom Lane 已提交
1772 1773 1774
				WriteRqst.Write = OldPageRqstPtr;
				WriteRqst.Flush.xlogid = 0;
				WriteRqst.Flush.xrecoff = 0;
1775
				XLogWrite(WriteRqst, false, false);
1776
				LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
1777
				Insert->LogwrtResult = LogwrtResult;
1778
				TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
1779 1780 1781 1782
			}
		}
	}

T
Tom Lane 已提交
1783
	/*
B
Bruce Momjian 已提交
1784 1785
	 * Now the next buffer slot is free and we can set it up to be the next
	 * output page.
T
Tom Lane 已提交
1786
	 */
1787
	NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1788 1789 1790 1791 1792 1793 1794 1795

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

1796
	if (NewPageEndPtr.xrecoff >= XLogFileSize)
1797
	{
T
Tom Lane 已提交
1798
		/* crossing a logid boundary */
1799
		NewPageEndPtr.xlogid += 1;
1800
		NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1801
	}
T
Tom Lane 已提交
1802
	else
1803
		NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1804
	XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1805
	NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
B
Bruce Momjian 已提交
1806

T
Tom Lane 已提交
1807
	Insert->curridx = nextidx;
1808
	Insert->currpage = NewPage;
B
Bruce Momjian 已提交
1809 1810

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

T
Tom Lane 已提交
1812
	/*
B
Bruce Momjian 已提交
1813 1814
	 * 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 已提交
1815
	 */
1816
	MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1817

1818 1819 1820
	/*
	 * Fill the new page's header
	 */
B
Bruce Momjian 已提交
1821 1822
	NewPage   ->xlp_magic = XLOG_PAGE_MAGIC;

1823
	/* NewPage->xlp_info = 0; */	/* done by memset */
B
Bruce Momjian 已提交
1824 1825
	NewPage   ->xlp_tli = ThisTimeLineID;
	NewPage   ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1826
	NewPage   ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
T
Tom Lane 已提交
1827

1828
	/*
1829
	 * If first page of an XLOG segment file, make it a long header.
1830 1831 1832
	 */
	if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
	{
1833
		XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1834

1835 1836
		NewLongPage->xlp_sysid = ControlFile->system_identifier;
		NewLongPage->xlp_seg_size = XLogSegSize;
1837
		NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
B
Bruce Momjian 已提交
1838 1839 1840
		NewPage   ->xlp_info |= XLP_LONG_HEADER;

		Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1841 1842
	}

T
Tom Lane 已提交
1843
	return update_needed;
1844 1845
}

1846 1847 1848
/*
 * Check whether we've consumed enough xlog space that a checkpoint is needed.
 *
1849 1850 1851
 * logid/logseg indicate a log file that has just been filled up (or read
 * during recovery). We measure the distance from RedoRecPtr to logid/logseg
 * and see if that exceeds CheckPointSegments.
1852 1853 1854 1855
 *
 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
 */
static bool
1856
XLogCheckpointNeeded(uint32 logid, uint32 logseg)
1857 1858
{
	/*
1859 1860
	 * 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 已提交
1861 1862
	 * highest-order bits separately, and force a checkpoint immediately when
	 * they change.
1863 1864 1865 1866 1867 1868 1869 1870 1871
	 */
	uint32		old_segno,
				new_segno;
	uint32		old_highbits,
				new_highbits;

	old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
		(RedoRecPtr.xrecoff / XLogSegSize);
	old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1872 1873
	new_segno = (logid % XLogSegSize) * XLogSegsPerFile + logseg;
	new_highbits = logid / XLogSegSize;
1874
	if (new_highbits != old_highbits ||
B
Bruce Momjian 已提交
1875
		new_segno >= old_segno + (uint32) (CheckPointSegments - 1))
1876 1877 1878 1879
		return true;
	return false;
}

T
Tom Lane 已提交
1880 1881 1882
/*
 * Write and/or fsync the log at least as far as WriteRqst indicates.
 *
1883 1884 1885 1886 1887
 * 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.
 *
1888 1889 1890 1891 1892 1893
 * 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.)
 *
1894
 * Must be called with WALWriteLock held.
T
Tom Lane 已提交
1895
 */
1896
static void
1897
XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1898
{
1899
	XLogCtlWrite *Write = &XLogCtl->Write;
T
Tom Lane 已提交
1900
	bool		ispartialpage;
1901
	bool		last_iteration;
1902
	bool		finishing_seg;
1903
	bool		use_existent;
1904 1905 1906 1907
	int			curridx;
	int			npages;
	int			startidx;
	uint32		startoffset;
1908

1909 1910 1911
	/* We should always be inside a critical section here */
	Assert(CritSectionCount > 0);

B
Bruce Momjian 已提交
1912
	/*
B
Bruce Momjian 已提交
1913
	 * Update local LogwrtResult (caller probably did this already, but...)
B
Bruce Momjian 已提交
1914
	 */
T
Tom Lane 已提交
1915 1916
	LogwrtResult = Write->LogwrtResult;

1917 1918 1919
	/*
	 * Since successive pages in the xlog cache are consecutively allocated,
	 * we can usually gather multiple pages together and issue just one
B
Bruce Momjian 已提交
1920 1921 1922 1923 1924
	 * 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.
1925 1926 1927 1928 1929 1930 1931 1932 1933
	 */
	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 已提交
1934 1935
	 * going to PANIC if any error occurs anyway; but someday it may come in
	 * useful.)
1936 1937
	 */
	curridx = Write->curridx;
B
 
Bruce Momjian 已提交
1938

T
Tom Lane 已提交
1939
	while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1940
	{
1941
		/*
B
Bruce Momjian 已提交
1942 1943 1944
		 * 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.
1945
		 */
1946
		if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1947
			elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1948
				 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1949 1950
				 XLogCtl->xlblocks[curridx].xlogid,
				 XLogCtl->xlblocks[curridx].xrecoff);
1951

T
Tom Lane 已提交
1952
		/* Advance LogwrtResult.Write to end of current buffer page */
1953
		LogwrtResult.Write = XLogCtl->xlblocks[curridx];
T
Tom Lane 已提交
1954 1955 1956
		ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);

		if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1957
		{
T
Tom Lane 已提交
1958
			/*
1959 1960
			 * Switch to new logfile segment.  We cannot have any pending
			 * pages here (since we dump what we have at segment end).
T
Tom Lane 已提交
1961
			 */
1962
			Assert(npages == 0);
1963
			if (openLogFile >= 0)
1964
				XLogFileClose();
T
Tom Lane 已提交
1965 1966
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);

1967 1968
			/* create/use new log file */
			use_existent = true;
1969 1970
			openLogFile = XLogFileInit(openLogId, openLogSeg,
									   &use_existent, true);
T
Tom Lane 已提交
1971
			openLogOff = 0;
1972 1973
		}

1974
		/* Make sure we have the current logfile open */
1975
		if (openLogFile < 0)
1976
		{
T
Tom Lane 已提交
1977
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1978
			openLogFile = XLogFileOpen(openLogId, openLogSeg);
T
Tom Lane 已提交
1979
			openLogOff = 0;
1980 1981
		}

1982 1983 1984 1985 1986
		/* Add current page to the set of pending pages-to-dump */
		if (npages == 0)
		{
			/* first of group */
			startidx = curridx;
1987
			startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1988 1989
		}
		npages++;
1990

T
Tom Lane 已提交
1991
		/*
B
Bruce Momjian 已提交
1992 1993 1994 1995
		 * 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 已提交
1996
		 */
1997 1998
		last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);

1999
		finishing_seg = !ispartialpage &&
2000
			(startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
2001

2002
		if (last_iteration ||
2003 2004
			curridx == XLogCtl->XLogCacheBlck ||
			finishing_seg)
T
Tom Lane 已提交
2005
		{
2006 2007
			char	   *from;
			Size		nbytes;
2008

2009 2010 2011
			/* Need to seek in the file? */
			if (openLogOff != startoffset)
			{
2012 2013 2014 2015 2016 2017
				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)));
2018 2019 2020 2021
				openLogOff = startoffset;
			}

			/* OK to write the page(s) */
2022 2023
			from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
			nbytes = npages * (Size) XLOG_BLCKSZ;
2024 2025
			errno = 0;
			if (write(openLogFile, from, nbytes) != nbytes)
2026
			{
2027 2028 2029
				/* if write didn't set errno, assume no disk space */
				if (errno == 0)
					errno = ENOSPC;
2030 2031 2032
				ereport(PANIC,
						(errcode_for_file_access(),
						 errmsg("could not write to log file %u, segment %u "
P
Peter Eisentraut 已提交
2033
								"at offset %u, length %lu: %m",
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
								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.
			 *
2050 2051 2052
			 * We also do this if this is the last page written for an xlog
			 * switch.
			 *
2053
			 * This is also the right place to notify the Archiver that the
B
Bruce Momjian 已提交
2054
			 * segment is ready to copy to archival storage, and to update the
2055 2056 2057
			 * timer for archive_timeout, and to signal for a checkpoint if
			 * too many logfile segments have been used since the last
			 * checkpoint.
2058
			 */
2059
			if (finishing_seg || (xlog_switch && last_iteration))
2060
			{
2061
				issue_xlog_fsync(openLogFile, openLogId, openLogSeg);
B
Bruce Momjian 已提交
2062
				LogwrtResult.Flush = LogwrtResult.Write;		/* end of page */
2063 2064 2065

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

2067
				Write->lastSegSwitchTime = (pg_time_t) time(NULL);
2068 2069

				/*
2070
				 * Signal bgwriter to start a checkpoint if we've consumed too
2071
				 * much xlog since the last one.  For speed, we first check
B
Bruce Momjian 已提交
2072 2073 2074
				 * 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.
2075
				 */
2076
				if (IsUnderPostmaster &&
2077
					XLogCheckpointNeeded(openLogId, openLogSeg))
2078
				{
2079
					(void) GetRedoRecPtr();
2080
					if (XLogCheckpointNeeded(openLogId, openLogSeg))
2081
						RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
2082
				}
2083
			}
T
Tom Lane 已提交
2084
		}
2085

T
Tom Lane 已提交
2086 2087 2088 2089 2090 2091
		if (ispartialpage)
		{
			/* Only asked to write a partial page */
			LogwrtResult.Write = WriteRqst.Write;
			break;
		}
2092 2093 2094 2095 2096
		curridx = NextBufIdx(curridx);

		/* If flexible, break out of loop as soon as we wrote something */
		if (flexible && npages == 0)
			break;
2097
	}
2098 2099 2100

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

T
Tom Lane 已提交
2102 2103 2104 2105 2106
	/*
	 * If asked to flush, do so
	 */
	if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
		XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
2107
	{
T
Tom Lane 已提交
2108
		/*
B
Bruce Momjian 已提交
2109 2110 2111
		 * 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 已提交
2112
		 */
2113 2114
		if (sync_method != SYNC_METHOD_OPEN &&
			sync_method != SYNC_METHOD_OPEN_DSYNC)
T
Tom Lane 已提交
2115
		{
2116
			if (openLogFile >= 0 &&
B
Bruce Momjian 已提交
2117
				!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
2118
				XLogFileClose();
2119
			if (openLogFile < 0)
2120 2121
			{
				XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
2122
				openLogFile = XLogFileOpen(openLogId, openLogSeg);
2123 2124
				openLogOff = 0;
			}
2125
			issue_xlog_fsync(openLogFile, openLogId, openLogSeg);
T
Tom Lane 已提交
2126 2127
		}
		LogwrtResult.Flush = LogwrtResult.Write;
2128 2129
	}

T
Tom Lane 已提交
2130 2131 2132
	/*
	 * Update shared-memory status
	 *
B
Bruce Momjian 已提交
2133
	 * We make sure that the shared 'request' values do not fall behind the
B
Bruce Momjian 已提交
2134 2135
	 * 'result' values.  This is not absolutely essential, but it saves some
	 * code in a couple of places.
T
Tom Lane 已提交
2136
	 */
2137 2138 2139 2140
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

2141
		SpinLockAcquire(&xlogctl->info_lck);
2142 2143 2144 2145 2146
		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;
2147
		SpinLockRelease(&xlogctl->info_lck);
2148
	}
2149

T
Tom Lane 已提交
2150 2151 2152
	Write->LogwrtResult = LogwrtResult;
}

2153
/*
2154 2155
 * Record the LSN for an asynchronous transaction commit/abort.
 * (This should not be called for for synchronous commits.)
2156 2157
 */
void
2158
XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
2159 2160 2161 2162 2163
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

	SpinLockAcquire(&xlogctl->info_lck);
2164 2165
	if (XLByteLT(xlogctl->asyncXactLSN, asyncXactLSN))
		xlogctl->asyncXactLSN = asyncXactLSN;
2166 2167 2168
	SpinLockRelease(&xlogctl->info_lck);
}

2169 2170 2171 2172
/*
 * Advance minRecoveryPoint in control file.
 *
 * If we crash during recovery, we must reach this point again before the
2173 2174
 * database is consistent.
 *
2175
 * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
2176
 * is only updated if it's not already greater than or equal to 'lsn'.
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
 */
static void
UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
{
	/* Quick check using our local copy of the variable */
	if (!updateMinRecoveryPoint || (!force && XLByteLE(lsn, minRecoveryPoint)))
		return;

	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);

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

	/*
	 * An invalid minRecoveryPoint means that we need to recover all the WAL,
2192 2193
	 * i.e., we're doing crash recovery.  We never modify the control file's
	 * value in that case, so we can short-circuit future checks here too.
2194 2195 2196 2197 2198 2199 2200
	 */
	if (minRecoveryPoint.xlogid == 0 && minRecoveryPoint.xrecoff == 0)
		updateMinRecoveryPoint = false;
	else if (force || XLByteLT(minRecoveryPoint, lsn))
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;
2201
		XLogRecPtr	newMinRecoveryPoint;
2202 2203 2204 2205

		/*
		 * To avoid having to update the control file too often, we update it
		 * all the way to the last record being replayed, even though 'lsn'
2206 2207 2208 2209
		 * would suffice for correctness.  This also allows the 'force' case
		 * to not need a valid 'lsn' value.
		 *
		 * Another important reason for doing it this way is that the passed
B
Bruce Momjian 已提交
2210 2211 2212 2213
		 * 'lsn' value could be bogus, i.e., past the end of available WAL, if
		 * the caller got it from a corrupted heap page.  Accepting such a
		 * value as the min recovery point would prevent us from coming up at
		 * all.  Instead, we just log a warning and continue with recovery.
2214
		 * (See also the comments about corrupt LSNs in XLogFlush.)
2215 2216 2217 2218 2219
		 */
		SpinLockAcquire(&xlogctl->info_lck);
		newMinRecoveryPoint = xlogctl->replayEndRecPtr;
		SpinLockRelease(&xlogctl->info_lck);

2220 2221
		if (!force && XLByteLT(newMinRecoveryPoint, lsn))
			elog(WARNING,
B
Bruce Momjian 已提交
2222
			   "xlog min recovery request %X/%X is past current point %X/%X",
2223 2224 2225
				 lsn.xlogid, lsn.xrecoff,
				 newMinRecoveryPoint.xlogid, newMinRecoveryPoint.xrecoff);

2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
		/* update control file */
		if (XLByteLT(ControlFile->minRecoveryPoint, newMinRecoveryPoint))
		{
			ControlFile->minRecoveryPoint = newMinRecoveryPoint;
			UpdateControlFile();
			minRecoveryPoint = newMinRecoveryPoint;

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

T
Tom Lane 已提交
2241 2242 2243
/*
 * Ensure that all XLOG data through the given position is flushed to disk.
 *
2244
 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
T
Tom Lane 已提交
2245 2246 2247 2248 2249 2250 2251 2252
 * already held, and we try to avoid acquiring it if possible.
 */
void
XLogFlush(XLogRecPtr record)
{
	XLogRecPtr	WriteRqstPtr;
	XLogwrtRqst WriteRqst;

2253
	/*
2254
	 * During REDO, we are reading not writing WAL.  Therefore, instead of
B
Bruce Momjian 已提交
2255 2256 2257 2258
	 * trying to flush the WAL, we should update minRecoveryPoint instead. We
	 * test XLogInsertAllowed(), not InRecovery, because we need the bgwriter
	 * to act this way too, and because when the bgwriter tries to write the
	 * end-of-recovery checkpoint, it should indeed flush.
2259
	 */
2260
	if (!XLogInsertAllowed())
2261 2262
	{
		UpdateMinRecoveryPoint(record, false);
T
Tom Lane 已提交
2263
		return;
2264
	}
T
Tom Lane 已提交
2265 2266 2267 2268 2269

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

2270
#ifdef WAL_DEBUG
2271
	if (XLOG_DEBUG)
2272
		elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
2273 2274 2275
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
2276
#endif
2277

T
Tom Lane 已提交
2278 2279 2280 2281
	START_CRIT_SECTION();

	/*
	 * Since fsync is usually a horribly expensive operation, we try to
B
Bruce Momjian 已提交
2282 2283 2284 2285
	 * 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 已提交
2286 2287 2288 2289 2290
	 */

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

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

2296
		SpinLockAcquire(&xlogctl->info_lck);
2297 2298 2299
		if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
			WriteRqstPtr = xlogctl->LogwrtRqst.Write;
		LogwrtResult = xlogctl->LogwrtResult;
2300
		SpinLockRelease(&xlogctl->info_lck);
2301
	}
2302 2303 2304

	/* done already? */
	if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
2305
	{
2306 2307 2308 2309
		/* now wait for the write lock */
		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
		LogwrtResult = XLogCtl->Write.LogwrtResult;
		if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
2310
		{
2311 2312 2313 2314 2315 2316
			/* 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 已提交
2317
				if (freespace < SizeOfXLogRecord)		/* buffer is full */
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
					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;
			}
2333
			XLogWrite(WriteRqst, false, false);
T
Tom Lane 已提交
2334
		}
2335
		LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
2336 2337 2338
	}

	END_CRIT_SECTION();
2339 2340 2341

	/*
	 * If we still haven't flushed to the request point then we have a
B
Bruce Momjian 已提交
2342 2343
	 * 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.
2344
	 *
2345 2346 2347 2348
	 * 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
2349
	 * unable to restart the database at all!  (This scenario actually
B
Bruce Momjian 已提交
2350 2351 2352 2353 2354
	 * happened in the field several times with 7.1 releases.)	As of 8.4, bad
	 * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
	 * the only time we can reach here during recovery is while flushing the
	 * end-of-recovery checkpoint record, and we don't expect that to have a
	 * bad LSN.
2355
	 *
B
Bruce Momjian 已提交
2356 2357 2358 2359
	 * Note that for calls from xact.c, the ERROR will be promoted to PANIC
	 * since xact.c calls this routine inside a critical section.  However,
	 * calls from bufmgr.c are not within critical sections and so we will not
	 * force a restart for a bad LSN on a data page.
2360 2361
	 */
	if (XLByteLT(LogwrtResult.Flush, record))
2362
		elog(ERROR,
B
Bruce Momjian 已提交
2363
		"xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
2364 2365
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
2366 2367
}

2368 2369 2370 2371 2372 2373
/*
 * 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 已提交
2374
 * are not being used, we will flush complete blocks only.	We can guarantee
2375
 * that async commits reach disk after at most three cycles; normally only
B
Bruce Momjian 已提交
2376
 * one or two.	(We allow XLogWrite to write "flexibly", meaning it can stop
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
 * 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;

2389 2390 2391 2392
	/* XLOG doesn't need flushing during recovery */
	if (RecoveryInProgress())
		return;

2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
	/* 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;

2413
		SpinLockAcquire(&xlogctl->info_lck);
2414
		WriteRqstPtr = xlogctl->asyncXactLSN;
2415
		SpinLockRelease(&xlogctl->info_lck);
2416 2417 2418
		flexible = false;		/* ensure it all gets written */
	}

2419
	/*
B
Bruce Momjian 已提交
2420 2421 2422
	 * If already known flushed, we're done. Just need to check if we are
	 * holding an open file handle to a logfile that's no longer in use,
	 * preventing the file from being deleted.
2423
	 */
2424
	if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
2425
	{
2426
		if (openLogFile >= 0)
2427
		{
2428 2429 2430 2431 2432
			if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
			{
				XLogFileClose();
			}
		}
2433
		return;
2434
	}
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461

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

2462 2463 2464 2465 2466 2467 2468 2469 2470
/*
 * 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)
{
2471 2472 2473 2474 2475
	/*
	 * During recovery, we don't flush WAL but update minRecoveryPoint
	 * instead. So "needs flush" is taken to mean whether minRecoveryPoint
	 * would need to be updated.
	 */
2476
	if (RecoveryInProgress())
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
	{
		/* Quick exit if already known updated */
		if (XLByteLE(record, minRecoveryPoint) || !updateMinRecoveryPoint)
			return false;

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

		/*
B
Bruce Momjian 已提交
2492 2493 2494 2495
		 * An invalid minRecoveryPoint means that we need to recover all the
		 * WAL, i.e., we're doing crash recovery.  We never modify the control
		 * file's value in that case, so we can short-circuit future checks
		 * here too.
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
		 */
		if (minRecoveryPoint.xlogid == 0 && minRecoveryPoint.xrecoff == 0)
			updateMinRecoveryPoint = false;

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

2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
	/* 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 已提交
2528 2529 2530
/*
 * Create a new XLOG file segment, or open a pre-existing one.
 *
2531 2532 2533
 * log, seg: identify segment to be created/opened.
 *
 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
B
Bruce Momjian 已提交
2534
 * pre-existing file will be deleted).	On return, TRUE if a pre-existing
2535 2536
 * file was used.
 *
2537
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2538
 * place.  This should be TRUE except during bootstrap log creation.  The
2539
 * caller must *not* hold the lock at call.
2540
 *
T
Tom Lane 已提交
2541
 * Returns FD of opened file.
2542 2543 2544 2545 2546
 *
 * 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 已提交
2547
 */
2548 2549 2550
int
XLogFileInit(uint32 log, uint32 seg,
			 bool *use_existent, bool use_lock)
2551
{
2552
	char		path[MAXPGPATH];
2553
	char		tmppath[MAXPGPATH];
2554
	char	   *zbuffer;
2555 2556 2557
	uint32		installed_log;
	uint32		installed_seg;
	int			max_advance;
2558
	int			fd;
2559
	int			nbytes;
2560

2561
	XLogFilePath(path, ThisTimeLineID, log, seg);
V
Vadim B. Mikheev 已提交
2562 2563

	/*
B
Bruce Momjian 已提交
2564
	 * Try to use existent file (checkpoint maker may have created it already)
V
Vadim B. Mikheev 已提交
2565
	 */
2566
	if (*use_existent)
V
Vadim B. Mikheev 已提交
2567
	{
2568 2569 2570
		fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
						   S_IRUSR | S_IWUSR);
		if (fd < 0)
V
Vadim B. Mikheev 已提交
2571 2572
		{
			if (errno != ENOENT)
2573
				ereport(ERROR,
2574
						(errcode_for_file_access(),
2575
						 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2576
								path, log, seg)));
V
Vadim B. Mikheev 已提交
2577 2578
		}
		else
2579
			return fd;
V
Vadim B. Mikheev 已提交
2580 2581
	}

2582
	/*
B
Bruce Momjian 已提交
2583 2584 2585 2586
	 * 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.
2587
	 */
2588 2589
	elog(DEBUG2, "creating and filling new WAL file");

2590
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2591

2592
	unlink(tmppath);
2593

2594
	/* do not use get_sync_bit here --- want to fsync only at end of fill */
2595 2596 2597 2598 2599 2600
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m", tmppath)));
2601

2602
	/*
B
Bruce Momjian 已提交
2603 2604 2605 2606 2607 2608 2609
	 * 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.
2610 2611 2612 2613
	 *
	 * 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.
2614
	 */
2615 2616
	zbuffer = (char *) palloc0(XLOG_BLCKSZ);
	for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
2617
	{
2618
		errno = 0;
2619
		if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
T
Tom Lane 已提交
2620
		{
B
Bruce Momjian 已提交
2621
			int			save_errno = errno;
T
Tom Lane 已提交
2622

B
Bruce Momjian 已提交
2623
			/*
B
Bruce Momjian 已提交
2624
			 * If we fail to make the file, delete it to release disk space
B
Bruce Momjian 已提交
2625
			 */
2626
			unlink(tmppath);
2627 2628
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;
T
Tom Lane 已提交
2629

2630
			ereport(ERROR,
2631
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2632
					 errmsg("could not write to file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2633
		}
2634
	}
2635
	pfree(zbuffer);
2636

2637 2638 2639 2640
	if (pg_fsync(fd) != 0)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));
2641

2642 2643 2644 2645
	if (close(fd))
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2646

2647
	/*
2648 2649
	 * Now move the segment into place with its final name.
	 *
2650
	 * If caller didn't want to use a pre-existing file, get rid of any
B
Bruce Momjian 已提交
2651 2652 2653
	 * 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.
2654
	 */
2655 2656 2657 2658 2659
	installed_log = log;
	installed_seg = seg;
	max_advance = XLOGfileslop;
	if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
								*use_existent, &max_advance,
2660
								use_lock))
2661
	{
2662 2663 2664 2665 2666
		/*
		 * No need for any more future segments, or InstallXLogFileSegment()
		 * failed to rename the file into place. If the rename failed, opening
		 * the file below will fail.
		 */
2667
		unlink(tmppath);
2668 2669 2670 2671 2672 2673
	}

	/* 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) */
2674 2675 2676 2677 2678 2679 2680
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
		ereport(ERROR,
				(errcode_for_file_access(),
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2681

2682
	elog(DEBUG2, "done creating and filling new WAL file");
2683 2684

	return fd;
2685 2686
}

2687 2688 2689 2690 2691 2692 2693 2694 2695
/*
 * 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 已提交
2696
 * considerations.	But we should be just as tense as XLogFileInit to avoid
2697 2698 2699 2700 2701 2702 2703 2704
 * emplacing a bogus file.
 */
static void
XLogFileCopy(uint32 log, uint32 seg,
			 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
{
	char		path[MAXPGPATH];
	char		tmppath[MAXPGPATH];
2705
	char		buffer[XLOG_BLCKSZ];
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
	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)
2716
		ereport(ERROR,
2717 2718 2719 2720 2721 2722
				(errcode_for_file_access(),
				 errmsg("could not open file \"%s\": %m", path)));

	/*
	 * Copy into a temp file name.
	 */
2723
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2724 2725
	unlink(tmppath);

2726
	/* do not use get_sync_bit() here --- want to fsync only at end of fill */
2727 2728 2729
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
2730
		ereport(ERROR,
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
				(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)
2743
				ereport(ERROR,
2744 2745 2746
						(errcode_for_file_access(),
						 errmsg("could not read file \"%s\": %m", path)));
			else
2747
				ereport(ERROR,
B
Bruce Momjian 已提交
2748
						(errmsg("not enough data in file \"%s\"", path)));
2749 2750 2751 2752 2753 2754 2755
		}
		errno = 0;
		if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
		{
			int			save_errno = errno;

			/*
B
Bruce Momjian 已提交
2756
			 * If we fail to make the file, delete it to release disk space
2757 2758 2759 2760 2761
			 */
			unlink(tmppath);
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;

2762
			ereport(ERROR,
2763
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2764
					 errmsg("could not write to file \"%s\": %m", tmppath)));
2765 2766 2767 2768
		}
	}

	if (pg_fsync(fd) != 0)
2769
		ereport(ERROR,
2770 2771 2772 2773
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
2774
		ereport(ERROR,
2775 2776 2777 2778 2779 2780 2781 2782
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));

	close(srcfd);

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

2787 2788 2789 2790 2791 2792
/*
 * 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.
 *
2793 2794 2795
 * *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.
2796 2797 2798 2799 2800 2801 2802
 *
 * 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.
 *
2803 2804 2805 2806
 * *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.)
2807
 *
2808
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2809
 * place.  This should be TRUE except during bootstrap log creation.  The
2810
 * caller must *not* hold the lock at call.
2811
 *
2812 2813 2814
 * Returns TRUE if the file was installed successfully.  FALSE indicates that
 * max_advance limit was exceeded, or an error occurred while renaming the
 * file into place.
2815 2816
 */
static bool
2817 2818
InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
2819
					   bool use_lock)
2820 2821
{
	char		path[MAXPGPATH];
2822
	struct stat stat_buf;
2823

2824
	XLogFilePath(path, ThisTimeLineID, *log, *seg);
2825 2826 2827 2828 2829

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

2832 2833 2834
	if (!find_free)
	{
		/* Force installation: get rid of any pre-existing segment file */
2835
		unlink(path);
2836
	}
2837 2838
	else
	{
2839
		/* Find a free slot to put it in */
2840
		while (stat(path, &stat_buf) == 0)
2841
		{
2842
			if (*max_advance <= 0)
2843 2844 2845
			{
				/* Failed to find a free slot within specified range */
				if (use_lock)
2846
					LWLockRelease(ControlFileLock);
2847 2848
				return false;
			}
2849 2850 2851
			NextLogSeg(*log, *seg);
			(*max_advance)--;
			XLogFilePath(path, ThisTimeLineID, *log, *seg);
2852 2853 2854 2855 2856 2857 2858
		}
	}

	/*
	 * 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.
2859
	 */
2860
#if HAVE_WORKING_LINK
2861
	if (link(tmppath, path) < 0)
2862 2863 2864 2865
	{
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
2866
				(errcode_for_file_access(),
2867
				 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2868
						tmppath, path, *log, *seg)));
2869 2870
		return false;
	}
2871
	unlink(tmppath);
2872
#else
2873
	if (rename(tmppath, path) < 0)
2874
	{
2875 2876 2877
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
2878
				(errcode_for_file_access(),
2879
				 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2880
						tmppath, path, *log, *seg)));
2881
		return false;
2882
	}
2883
#endif
V
Vadim B. Mikheev 已提交
2884

2885
	if (use_lock)
2886
		LWLockRelease(ControlFileLock);
2887

2888
	return true;
2889 2890
}

T
Tom Lane 已提交
2891
/*
2892
 * Open a pre-existing logfile segment for writing.
T
Tom Lane 已提交
2893
 */
2894 2895
int
XLogFileOpen(uint32 log, uint32 seg)
2896
{
2897 2898
	char		path[MAXPGPATH];
	int			fd;
2899

2900
	XLogFilePath(path, ThisTimeLineID, log, seg);
2901

2902 2903 2904
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
2905 2906
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2907 2908
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2909 2910

	return fd;
2911 2912
}

2913 2914
/*
 * Open a logfile segment for reading (during recovery).
2915
 *
2916
 * If source = XLOG_FROM_ARCHIVE, the segment is retrieved from archive.
2917
 * Otherwise, it's assumed to be already available in pg_xlog.
2918 2919
 */
static int
2920
XLogFileRead(uint32 log, uint32 seg, int emode, TimeLineID tli,
2921
			 int source, bool notfoundOk)
2922 2923
{
	char		xlogfname[MAXFNAMELEN];
2924
	char		activitymsg[MAXFNAMELEN + 16];
2925
	char		path[MAXPGPATH];
2926
	int			fd;
2927

B
Bruce Momjian 已提交
2928
	XLogFileName(xlogfname, tli, log, seg);
2929

2930
	switch (source)
B
Bruce Momjian 已提交
2931
	{
2932 2933
/* Archive recovery not supported in GPDB */
#if 0
2934 2935 2936 2937 2938
		case XLOG_FROM_ARCHIVE:
			/* Report recovery progress in PS display */
			snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
					 xlogfname);
			set_ps_display(activitymsg, false);
2939

2940 2941 2942 2943 2944 2945
			restoredFromArchive = RestoreArchivedFile(path, xlogfname,
													  "RECOVERYXLOG",
													  XLogSegSize);
			if (!restoredFromArchive)
				return -1;
			break;
2946
#endif
2947 2948

		case XLOG_FROM_PG_XLOG:
2949
		case XLOG_FROM_STREAM:
2950 2951 2952 2953 2954 2955
			XLogFilePath(path, tli, log, seg);
			restoredFromArchive = false;
			break;

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

B
Bruce Momjian 已提交
2958 2959 2960 2961 2962
	fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
	if (fd >= 0)
	{
		/* Success! */
		curFileTLI = tli;
2963

B
Bruce Momjian 已提交
2964 2965 2966 2967 2968
		/* Report recovery progress in PS display */
		snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
				 xlogfname);
		set_ps_display(activitymsg, false);

2969
		/* Track source of data in assorted state variables */
2970
		readSource = source;
2971 2972 2973 2974 2975
		XLogReceiptSource = source;
		/* In FROM_STREAM case, caller tracks receipt time, not me */
		if (source != XLOG_FROM_STREAM)
			XLogReceiptTime = GetCurrentTimestamp();

B
Bruce Momjian 已提交
2976 2977 2978 2979 2980 2981 2982 2983
		return fd;
	}
	if (errno != ENOENT || !notfoundOk) /* unexpected failure? */
		ereport(PANIC,
				(errcode_for_file_access(),
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
	return -1;
2984 2985 2986 2987 2988 2989 2990 2991
}

/*
 * Open a logfile segment for reading (during recovery).
 *
 * This version searches for the segment with any TLI listed in expectedTLIs.
 */
static int
2992
XLogFileReadAnyTLI(uint32 log, uint32 seg, int emode, int sources)
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
{
	char		path[MAXPGPATH];
	ListCell   *cell;
	int			fd;

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

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

3015 3016 3017 3018 3019 3020 3021 3022 3023
		if (sources & XLOG_FROM_ARCHIVE)
		{
			fd = XLogFileRead(log, seg, emode, tli, XLOG_FROM_ARCHIVE, true);
			if (fd != -1)
			{
				elog(DEBUG1, "got WAL segment from archive");
				return fd;
			}
		}
3024

3025
		if (sources & XLOG_FROM_PG_XLOG)
3026
		{
3027
			fd = XLogFileRead(log, seg, emode, tli, XLOG_FROM_PG_XLOG, true);
3028 3029 3030
			if (fd != -1)
				return fd;
		}
3031 3032 3033 3034 3035 3036 3037
	}

	/* 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 已提交
3038 3039
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
3040
	return -1;
3041 3042
}

3043 3044 3045
/*
 * Close the current logfile segment for writing.
 */
3046
static void
3047 3048
XLogFileClose(void)
{
3049
	Assert(openLogFile >= 0);
3050 3051

	/*
3052
	 * WAL segment files will not be re-read in normal operation, so we advise
3053
	 * the OS to release any cached pages.	But do not do so if WAL archiving
B
Bruce Momjian 已提交
3054 3055
	 * or streaming is active, because archiver and walsender process could
	 * use the cache to read the WAL segment.
3056
	 */
3057
#if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
A
Abhijit Subramanya 已提交
3058
	if (!XLogIsNeeded())
3059
		(void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3060
#endif
3061 3062 3063 3064 3065 3066 3067

	if (close(openLogFile))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close log file %u, segment %u: %m",
						openLogId, openLogSeg)));
	openLogFile = -1;
3068 3069 3070
}

/*
3071
 * Attempt to retrieve the specified file from off-line archival storage.
3072
 * If successful, fill "path" with its complete path (note that this will be
3073 3074
 * a temp file name that doesn't follow the normal naming convention), and
 * return TRUE.
3075
 *
3076 3077 3078
 * 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.
3079 3080 3081 3082
 *
 * 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.
3083
 */
3084 3085
static bool
RestoreArchivedFile(char *path, const char *xlogfname,
3086
					const char *recovername, off_t expectedSize)
3087
{
B
Bruce Momjian 已提交
3088 3089
	char		xlogpath[MAXPGPATH];
	char		xlogRestoreCmd[MAXPGPATH];
3090
	char		lastRestartPointFname[MAXPGPATH];
B
Bruce Momjian 已提交
3091 3092
	char	   *dp;
	char	   *endp;
3093
	const char *sp;
B
Bruce Momjian 已提交
3094
	int			rc;
3095
	bool		signaled;
3096
	struct stat stat_buf;
B
Bruce Momjian 已提交
3097 3098
	uint32		restartLog;
	uint32		restartSeg;
3099

3100
	/* In standby mode, restore_command might not be supplied */
3101
	if (recoveryRestoreCommand == NULL)
3102 3103
		goto not_available;

3104
	/*
B
Bruce Momjian 已提交
3105 3106 3107 3108
	 * 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.
3109
	 *
B
Bruce Momjian 已提交
3110
	 * We could try to optimize this slightly by checking the local copy
B
Bruce Momjian 已提交
3111 3112 3113 3114
	 * 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.
3115
	 *
3116 3117 3118
	 * 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.
3119
	 *
3120 3121 3122 3123
	 * 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 已提交
3124 3125
	 * copy-from-archive filename is always the same, ensuring that we don't
	 * run out of disk space on long recoveries.
3126
	 */
3127
	snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
3128 3129

	/*
3130
	 * Make sure there is no existing file named recovername.
3131 3132 3133 3134 3135 3136
	 */
	if (stat(xlogpath, &stat_buf) != 0)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
3137
					 errmsg("could not stat file \"%s\": %m",
3138 3139 3140 3141 3142 3143 3144
							xlogpath)));
	}
	else
	{
		if (unlink(xlogpath) != 0)
			ereport(FATAL,
					(errcode_for_file_access(),
3145
					 errmsg("could not remove file \"%s\": %m",
3146 3147 3148
							xlogpath)));
	}

3149 3150
	/*
	 * Calculate the archive file cutoff point for use during log shipping
3151 3152
	 * replication. All files earlier than this point can be deleted from the
	 * archive, though there is no requirement to do so.
3153 3154
	 *
	 * We initialise this with the filename of an InvalidXLogRecPtr, which
3155 3156
	 * will prevent the deletion of any WAL files from the archive because of
	 * the alphabetic sorting property of WAL filenames.
3157 3158 3159
	 *
	 * 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
3160 3161 3162 3163
	 * 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.
3164 3165 3166 3167 3168 3169 3170 3171 3172
	 */
	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 */
3173
		Assert(strcmp(lastRestartPointFname, xlogfname) <= 0);
3174 3175 3176 3177
	}
	else
		XLogFileName(lastRestartPointFname, 0, 0, 0);

3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
	/*
	 * 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':
3192
					/* %p: relative path of target file */
3193
					sp++;
B
Bruce Momjian 已提交
3194
					StrNCpy(dp, xlogpath, endp - dp);
3195
					make_native_path(dp);
3196 3197 3198 3199 3200
					dp += strlen(dp);
					break;
				case 'f':
					/* %f: filename of desired file */
					sp++;
B
Bruce Momjian 已提交
3201
					StrNCpy(dp, xlogfname, endp - dp);
3202 3203
					dp += strlen(dp);
					break;
3204 3205 3206 3207 3208 3209
				case 'r':
					/* %r: filename of last restartpoint */
					sp++;
					StrNCpy(dp, lastRestartPointFname, endp - dp);
					dp += strlen(dp);
					break;
3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
				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 已提交
3232
			(errmsg_internal("executing restore command \"%s\"",
3233 3234
							 xlogRestoreCmd)));

3235 3236
	/*
	 * Set in_restore_command to tell the signal handler that we should exit
3237
	 * right away on SIGTERM. We know that we're at a safe point to do that.
3238 3239 3240 3241 3242
	 * Check if we had already received the signal, so that we don't miss a
	 * shutdown request received just before this.
	 */
	in_restore_command = true;
	if (shutdown_requested)
3243
		proc_exit(1);
3244

3245
	/*
3246
	 * Copy xlog from archival storage to XLOGDIR
3247 3248
	 */
	rc = system(xlogRestoreCmd);
3249 3250 3251

	in_restore_command = false;

3252 3253
	if (rc == 0)
	{
3254 3255 3256 3257 3258 3259 3260
		/*
		 * command apparently succeeded, but let's make sure the file is
		 * really there now and has the correct size.
		 */
		if (stat(xlogpath, &stat_buf) == 0)
		{
			if (expectedSize > 0 && stat_buf.st_size != expectedSize)
3261
			{
B
Bruce Momjian 已提交
3262
				int			elevel;
3263 3264 3265 3266 3267 3268 3269

				/*
				 * If we find a partial file in standby mode, we assume it's
				 * because it's just being copied to the archive, and keep
				 * trying.
				 *
				 * Otherwise treat a wrong-sized file as FATAL to ensure the
B
Bruce Momjian 已提交
3270
				 * DBA would notice it, but is that too strong? We could try
3271 3272
				 * to plow ahead with a local copy of the file ... but the
				 * problem is that there probably isn't one, and we'd
B
Bruce Momjian 已提交
3273 3274
				 * incorrectly conclude we've reached the end of WAL and we're
				 * done recovering ...
3275 3276 3277 3278 3279 3280
				 */
				if (StandbyMode && stat_buf.st_size < expectedSize)
					elevel = DEBUG1;
				else
					elevel = FATAL;
				ereport(elevel,
3281 3282 3283 3284
						(errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
								xlogfname,
								(unsigned long) stat_buf.st_size,
								(unsigned long) expectedSize)));
3285 3286
				return false;
			}
3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301
			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 已提交
3302
						 errmsg("could not stat file \"%s\": %m",
3303
								xlogpath)));
3304 3305 3306 3307
		}
	}

	/*
3308
	 * Remember, we rollforward UNTIL the restore fails so failure here is
B
Bruce Momjian 已提交
3309
	 * just part of the process... that makes it difficult to determine
B
Bruce Momjian 已提交
3310 3311 3312
	 * 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.
3313 3314
	 *
	 * However, if the failure was due to any sort of signal, it's best to
B
Bruce Momjian 已提交
3315 3316 3317
	 * 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
3318
	 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
3319 3320 3321 3322 3323
	 * those it's a good bet we should have gotten it too.
	 *
	 * On SIGTERM, assume we have received a fast shutdown request, and exit
	 * cleanly. It's pure chance whether we receive the SIGTERM first, or the
	 * child process. If we receive it first, the signal handler will call
3324 3325 3326
	 * proc_exit, otherwise we do it here. If we or the child process received
	 * SIGTERM for any other reason than a fast shutdown request, postmaster
	 * will perform an immediate shutdown when it sees us exiting
3327
	 * unexpectedly.
3328
	 *
B
Bruce Momjian 已提交
3329 3330 3331 3332
	 * 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.
3333
	 */
3334
	if (WIFSIGNALED(rc) && WTERMSIG(rc) == SIGTERM)
3335
		proc_exit(1);
3336

3337 3338 3339
	signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;

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

3343
not_available:
B
Bruce Momjian 已提交
3344

3345
	/*
B
Bruce Momjian 已提交
3346 3347
	 * 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.
3348
	 *
B
Bruce Momjian 已提交
3349 3350
	 * In many recovery scenarios we expect this to fail also, but if so that
	 * just means we've reached the end of WAL.
3351
	 */
3352
	snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
3353
	return false;
3354 3355
}

3356
#ifdef NOT_USED
3357
/*
3358 3359 3360 3361
 * Attempt to execute an external shell command during recovery.
 *
 * 'command' is the shell command to be executed, 'commandName' is a
 * human-readable name describing the command emitted in the logs. If
3362
 * 'failOnSignal' is true and the command is killed by a signal, a FATAL
3363 3364
 * error is thrown. Otherwise a WARNING is emitted.
 *
3365
 * This is currently used for recovery_end_command and archive_cleanup_command.
3366 3367
 */
static void
3368
ExecuteRecoveryCommand(char *command, char *commandName, bool failOnSignal)
3369
{
3370
	char		xlogRecoveryCmd[MAXPGPATH];
3371 3372 3373 3374 3375 3376 3377 3378 3379
	char		lastRestartPointFname[MAXPGPATH];
	char	   *dp;
	char	   *endp;
	const char *sp;
	int			rc;
	bool		signaled;
	uint32		restartLog;
	uint32		restartSeg;

3380
	Assert(command && commandName);
3381 3382 3383

	/*
	 * Calculate the archive file cutoff point for use during log shipping
3384 3385
	 * replication. All files earlier than this point can be deleted from the
	 * archive, though there is no requirement to do so.
3386
	 */
3387 3388 3389 3390 3391 3392 3393
	LWLockAcquire(ControlFileLock, LW_SHARED);
	XLByteToSeg(ControlFile->checkPointCopy.redo,
				restartLog, restartSeg);
	XLogFileName(lastRestartPointFname,
				 ControlFile->checkPointCopy.ThisTimeLineID,
				 restartLog, restartSeg);
	LWLockRelease(ControlFileLock);
3394 3395 3396 3397

	/*
	 * construct the command to be executed
	 */
3398 3399
	dp = xlogRecoveryCmd;
	endp = xlogRecoveryCmd + MAXPGPATH - 1;
3400 3401
	*endp = '\0';

3402
	for (sp = command; *sp; sp++)
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435
	{
		if (*sp == '%')
		{
			switch (sp[1])
			{
				case 'r':
					/* %r: filename of last restartpoint */
					sp++;
					StrNCpy(dp, lastRestartPointFname, endp - dp);
					dp += strlen(dp);
					break;
				case '%':
					/* convert %% to a single % */
					sp++;
					if (dp < endp)
						*dp++ = *sp;
					break;
				default:
					/* otherwise treat the % as not special */
					if (dp < endp)
						*dp++ = *sp;
					break;
			}
		}
		else
		{
			if (dp < endp)
				*dp++ = *sp;
		}
	}
	*dp = '\0';

	ereport(DEBUG3,
3436
			(errmsg_internal("executing %s \"%s\"", commandName, command)));
3437 3438

	/*
T
Tom Lane 已提交
3439
	 * execute the constructed command
3440
	 */
3441
	rc = system(xlogRecoveryCmd);
3442 3443 3444 3445
	if (rc != 0)
	{
		/*
		 * If the failure was due to any sort of signal, it's best to punt and
3446
		 * abort recovery. See also detailed comments on signals in
3447 3448 3449 3450
		 * RestoreArchivedFile().
		 */
		signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;

3451 3452 3453 3454 3455 3456 3457
		/*
		 * translator: First %s represents a recovery.conf parameter name like
		 * "recovery_end_command", and the 2nd is the value of that parameter.
		 */
		ereport((signaled && failOnSignal) ? FATAL : WARNING,
				(errmsg("%s \"%s\": return code %d", commandName,
						command, rc)));
3458 3459
	}
}
3460
#endif
3461

V
Vadim B. Mikheev 已提交
3462
/*
3463 3464 3465 3466 3467 3468 3469 3470
 * 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 已提交
3471
 */
3472
static void
T
Tom Lane 已提交
3473 3474 3475 3476
PreallocXlogFiles(XLogRecPtr endptr)
{
	uint32		_logId;
	uint32		_logSeg;
3477
	int			lf;
3478
	bool		use_existent;
T
Tom Lane 已提交
3479 3480

	XLByteToPrevSeg(endptr, _logId, _logSeg);
B
Bruce Momjian 已提交
3481
	if ((endptr.xrecoff - 1) % XLogSegSize >=
B
Bruce Momjian 已提交
3482
		(uint32) (0.75 * XLogSegSize))
T
Tom Lane 已提交
3483 3484
	{
		NextLogSeg(_logId, _logSeg);
3485
		use_existent = true;
3486 3487
		lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
		close(lf);
3488
		if (!use_existent)
3489
			CheckpointStats.ckpt_segs_added++;
T
Tom Lane 已提交
3490 3491 3492
	}
}

3493 3494
/*
 * Get the log/seg of the latest removed or recycled WAL segment.
3495
 * Returns 0/0 if no WAL segments have been removed since startup.
3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
 */
void
XLogGetLastRemoved(uint32 *log, uint32 *seg)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

	SpinLockAcquire(&xlogctl->info_lck);
	*log = xlogctl->lastRemovedLog;
	*seg = xlogctl->lastRemovedSeg;
	SpinLockRelease(&xlogctl->info_lck);
}

/*
 * Update the last removed log/seg pointer in shared memory, to reflect
 * that the given XLOG file has been removed.
 */
static void
UpdateLastRemovedPtr(char *filename)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	uint32		tli,
				log,
				seg;

	XLogFromFileName(filename, &tli, &log, &seg);

	SpinLockAcquire(&xlogctl->info_lck);
	if (log > xlogctl->lastRemovedLog ||
		(log == xlogctl->lastRemovedLog && seg > xlogctl->lastRemovedSeg))
	{
		xlogctl->lastRemovedLog = log;
		xlogctl->lastRemovedSeg = seg;
	}
	SpinLockRelease(&xlogctl->info_lck);
}

T
Tom Lane 已提交
3534
/*
3535
 * Recycle or remove all log files older or equal to passed log/seg#
3536 3537 3538
 *
 * 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 已提交
3539 3540
 */
static void
3541
RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
V
Vadim B. Mikheev 已提交
3542
{
3543 3544
	uint32		endlogId;
	uint32		endlogSeg;
3545
	int			max_advance;
B
Bruce Momjian 已提交
3546 3547
	DIR		   *xldir;
	struct dirent *xlde;
3548
	char		lastoff[MAXFNAMELEN];
B
Bruce Momjian 已提交
3549
	char		path[MAXPGPATH];
B
Bruce Momjian 已提交
3550

3551 3552 3553
#ifdef WIN32
	char		newpath[MAXPGPATH];
#endif
3554
	struct stat statbuf;
3555

3556 3557 3558 3559
	/*
	 * Initialize info about where to try to recycle to.  We allow recycling
	 * segments up to XLOGfileslop segments beyond the current XLOG location.
	 */
3560
	XLByteToPrevSeg(endptr, endlogId, endlogSeg);
3561
	max_advance = XLOGfileslop;
V
Vadim B. Mikheev 已提交
3562

3563
	xldir = AllocateDir(XLOGDIR);
V
Vadim B. Mikheev 已提交
3564
	if (xldir == NULL)
3565
		ereport(ERROR,
3566
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
3567
				 errmsg("could not open transaction log directory \"%s\": %m",
3568
						XLOGDIR)));
V
Vadim B. Mikheev 已提交
3569

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

3572 3573 3574
	elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
		 lastoff);

3575
	while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
V
Vadim B. Mikheev 已提交
3576
	{
3577
		/*
3578
		 * We ignore the timeline part of the XLOG segment identifiers in
B
Bruce Momjian 已提交
3579 3580 3581 3582 3583
		 * 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.
3584
		 *
B
Bruce Momjian 已提交
3585 3586
		 * We use the alphanumeric sorting property of the filenames to decide
		 * which ones are earlier than the lastoff segment.
3587
		 */
3588 3589 3590
		if (strlen(xlde->d_name) == 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
V
Vadim B. Mikheev 已提交
3591
		{
3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602
			/*
			 * Normally we don't delete old XLOG files during recovery to
			 * avoid accidentally deleting a file that looks stale due to a
			 * bug or hardware issue, but in fact contains important data.
			 * During streaming recovery, however, we will eventually fill the
			 * disk if we never clean up, so we have to. That's not an issue
			 * with file-based archive recovery because in that case we
			 * restore one XLOG file at a time, on-demand, and with a
			 * different filename that can't be confused with regular XLOG
			 * files.
			 */
3603
			if (WalRcvInProgress() || XLogArchiveCheckDone(xlde->d_name))
3604
			{
3605
				snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3606 3607 3608

				/* Update the last removed location in shared memory first */
				UpdateLastRemovedPtr(xlde->d_name);
3609

3610
				/*
B
Bruce Momjian 已提交
3611
				 * Before deleting the file, see if it can be recycled as a
3612 3613 3614
				 * future log segment. Only recycle normal files, pg_standby
				 * for example can create symbolic links pointing to a
				 * separate archive directory.
3615
				 */
3616 3617
				if (lstat(path, &statbuf) == 0 && S_ISREG(statbuf.st_mode) &&
					InstallXLogFileSegment(&endlogId, &endlogSeg, path,
3618
										   true, &max_advance, true))
3619
				{
3620
					ereport(DEBUG2,
B
Bruce Momjian 已提交
3621 3622
							(errmsg("recycled transaction log file \"%s\"",
									xlde->d_name)));
3623
					CheckpointStats.ckpt_segs_recycled++;
3624 3625 3626 3627 3628 3629
					/* Needn't recheck that slot on future iterations */
					if (max_advance > 0)
					{
						NextLogSeg(endlogId, endlogSeg);
						max_advance--;
					}
3630 3631 3632 3633
				}
				else
				{
					/* No need for any more future segments... */
B
Bruce Momjian 已提交
3634
					int			rc;
3635

3636
					ereport(DEBUG2,
B
Bruce Momjian 已提交
3637 3638
							(errmsg("removing transaction log file \"%s\"",
									xlde->d_name)));
3639

3640
#ifdef WIN32
B
Bruce Momjian 已提交
3641

3642 3643 3644 3645
					/*
					 * On Windows, if another process (e.g another backend)
					 * holds the file open in FILE_SHARE_DELETE mode, unlink
					 * will succeed, but the file will still show up in
B
Bruce Momjian 已提交
3646 3647 3648 3649
					 * directory listing until the last handle is closed. To
					 * avoid confusing the lingering deleted file for a live
					 * WAL file that needs to be archived, rename it before
					 * deleting it.
3650 3651 3652 3653 3654 3655
					 *
					 * If another process holds the file open without
					 * FILE_SHARE_DELETE flag, rename will fail. We'll try
					 * again at the next checkpoint.
					 */
					snprintf(newpath, MAXPGPATH, "%s.deleted", path);
3656 3657 3658 3659 3660 3661 3662 3663 3664
					if (rename(path, newpath) != 0)
					{
						ereport(LOG,
								(errcode_for_file_access(),
								 errmsg("could not rename old transaction log file \"%s\": %m",
										path)));
						continue;
					}
					rc = unlink(newpath);
3665
#else
3666
					rc = unlink(path);
3667 3668
#endif
					if (rc != 0)
3669 3670
					{
						ereport(LOG,
3671 3672 3673
								(errcode_for_file_access(),
								 errmsg("could not remove old transaction log file \"%s\": %m",
										path)));
3674 3675
						continue;
					}
3676
					CheckpointStats.ckpt_segs_removed++;
3677
				}
3678 3679

				XLogArchiveCleanup(xlde->d_name);
3680
			}
V
Vadim B. Mikheev 已提交
3681 3682
		}
	}
B
Bruce Momjian 已提交
3683

3684
	FreeDir(xldir);
V
Vadim B. Mikheev 已提交
3685 3686
}

3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703
/*
 * Verify whether pg_xlog and pg_xlog/archive_status exist.
 * If the latter does not exist, recreate it.
 *
 * It is not the goal of this function to verify the contents of these
 * directories, but to help in cases where someone has performed a cluster
 * copy for PITR purposes but omitted pg_xlog from the copy.
 *
 * We could also recreate pg_xlog if it doesn't exist, but a deliberate
 * policy decision was made not to.  It is fairly common for pg_xlog to be
 * a symlink, and if that was the DBA's intent then automatically making a
 * plain directory would result in degraded performance with no notice.
 */
static void
ValidateXLOGDirectoryStructure(void)
{
	char		path[MAXPGPATH];
3704
	struct stat stat_buf;
3705 3706 3707 3708

	/* Check for pg_xlog; if it doesn't exist, error out */
	if (stat(XLOGDIR, &stat_buf) != 0 ||
		!S_ISDIR(stat_buf.st_mode))
3709
		ereport(FATAL,
3710 3711 3712 3713 3714 3715 3716 3717 3718
				(errmsg("required WAL directory \"%s\" does not exist",
						XLOGDIR)));

	/* Check for archive_status */
	snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
	if (stat(path, &stat_buf) == 0)
	{
		/* Check for weird cases where it exists but isn't a directory */
		if (!S_ISDIR(stat_buf.st_mode))
3719
			ereport(FATAL,
3720 3721 3722 3723 3724 3725 3726
					(errmsg("required WAL directory \"%s\" does not exist",
							path)));
	}
	else
	{
		ereport(LOG,
				(errmsg("creating missing WAL directory \"%s\"", path)));
3727
		if (mkdir(path, S_IRWXU) < 0)
3728
			ereport(FATAL,
3729 3730 3731 3732 3733
					(errmsg("could not create missing directory \"%s\": %m",
							path)));
	}
}

3734
/*
3735 3736 3737
 * Remove previous backup history files.  This also retries creation of
 * .ready files for any backup history files for which XLogArchiveNotify
 * failed earlier.
3738 3739
 */
static void
3740
CleanupBackupHistory(void)
3741 3742 3743 3744 3745
{
	DIR		   *xldir;
	struct dirent *xlde;
	char		path[MAXPGPATH];

H
Heikki Linnakangas 已提交
3746
	xldir = AllocateDir(XLOGDIR);
3747 3748 3749
	if (xldir == NULL)
		ereport(ERROR,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
3750
				 errmsg("could not open transaction log directory \"%s\": %m",
H
Heikki Linnakangas 已提交
3751
						XLOGDIR)));
3752

H
Heikki Linnakangas 已提交
3753
	while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3754 3755 3756 3757 3758 3759
	{
		if (strlen(xlde->d_name) > 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
				   ".backup") == 0)
		{
3760
			if (XLogArchiveCheckDone(xlde->d_name))
3761 3762
			{
				ereport(DEBUG2,
B
Bruce Momjian 已提交
3763 3764
				(errmsg("removing transaction log backup history file \"%s\"",
						xlde->d_name)));
3765
				snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3766 3767 3768 3769 3770 3771 3772 3773 3774
				unlink(path);
				XLogArchiveCleanup(xlde->d_name);
			}
		}
	}

	FreeDir(xldir);
}

T
Tom Lane 已提交
3775 3776 3777 3778
/*
 * Restore the backup blocks present in an XLOG record, if any.
 *
 * We assume all of the record has been read into memory at *record.
3779 3780 3781 3782 3783 3784 3785 3786 3787
 *
 * 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.
3788 3789
 *
 * If 'cleanup' is true, a cleanup lock is used when restoring blocks.
3790 3791 3792 3793 3794
 * Otherwise, a normal exclusive lock is used.	During crash recovery, that's
 * just pro forma because there can't be any regular backends in the system,
 * but in hot standby mode the distinction is important. The 'cleanup'
 * argument applies to all backup blocks in the WAL record, that suffices for
 * now.
T
Tom Lane 已提交
3795
 */
3796 3797
void
RestoreBkpBlocks(XLogRecPtr lsn, XLogRecord *record, bool cleanup)
3798 3799 3800 3801 3802
{
	BkpBlock	bkpb;
	char	   *blk;
	int			i;

B
Bruce Momjian 已提交
3803
	blk = (char *) XLogRecGetData(record) + record->xl_len;
T
Tom Lane 已提交
3804
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3805
	{
T
Tom Lane 已提交
3806
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3807 3808
			continue;

3809
		memcpy(&bkpb, blk, sizeof(BkpBlock));
3810 3811
		blk += sizeof(BkpBlock);

3812 3813 3814
		/* get_cleanup_lock is ignored in GPDB */
		RestoreBackupBlockContents(lsn, bkpb, blk, false, false);

3815 3816 3817
		blk += BLCKSZ - bkpb.hole_length;
	}
}
3818

3819 3820 3821 3822 3823
/*
 * Workhorse for RestoreBackupBlock usable without an xlog record
 *
 * Restores a full-page image from BkpBlock and a data pointer.
 */
3824
static void
3825 3826 3827 3828 3829
RestoreBackupBlockContents(XLogRecPtr lsn, BkpBlock bkpb, char *blk,
						   bool get_cleanup_lock, bool keep_buffer)
{
	Buffer		buffer;
	Page		page;
3830

3831 3832 3833
	if (! (bkpb.block_info & BLOCK_APPLY))
		return;

3834
	buffer = XLogReadBuffer(bkpb.node, bkpb.block, true);
3835 3836 3837 3838 3839 3840 3841
	Assert(BufferIsValid(buffer));
#if 0 /* upstream merge */
	if (get_cleanup_lock)
		LockBufferForCleanup(buffer);
	else
		LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
#endif
3842

3843
	page = (Page) BufferGetPage(buffer);
3844

3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856
	if (bkpb.hole_length == 0)
	{
		memcpy((char *) page, blk, BLCKSZ);
	}
	else
	{
		memcpy((char *) page, blk, bkpb.hole_offset);
		/* must zero-fill the hole */
		MemSet((char *) page + bkpb.hole_offset, 0, bkpb.hole_length);
		memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
			   blk + bkpb.hole_offset,
			   BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
3857
	}
3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869

	/*
	 * The checksum value on this page is currently invalid. We don't
	 * need to reset it here since it will be set before being written.
	 */

	PageSetLSN(page, lsn);
	MarkBufferDirty(buffer);

	if (!keep_buffer)
		UnlockReleaseBuffer(buffer);

3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897
	return;
}

bool
IsBkpBlockApplied(XLogRecord *record, uint8 block_id)
{
	BkpBlock	bkpb;
	char	   *blk;
	int			i;

	Assert(block_id < XLR_MAX_BKP_BLOCKS);

	blk = (char *) XLogRecGetData(record) + record->xl_len;
	for (i = 0; i <= block_id; i++)
	{
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
			continue;

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

		if (i == block_id)
			return (bkpb.block_info & BLOCK_APPLY) != 0;

		blk += BLCKSZ - bkpb.hole_length;
	}

	return false;
3898 3899
}

T
Tom Lane 已提交
3900 3901 3902 3903 3904 3905 3906
/*
 * 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.
 */
3907 3908 3909
static bool
RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
{
3910
	pg_crc32	crc;
3911 3912
	int			i;
	uint32		len = record->xl_len;
3913
	BkpBlock	bkpb;
3914 3915
	char	   *blk;

3916 3917 3918 3919
	/*
	 * Calculate the crc using the new fast crc32c algorithm
	 */

3920
	/* First the rmgr data */
3921 3922
	INIT_CRC32C(crc);
	COMP_CRC32C(crc, XLogRecGetData(record), len);
3923

3924
	/* Add in the backup blocks, if any */
B
Bruce Momjian 已提交
3925
	blk = (char *) XLogRecGetData(record) + len;
T
Tom Lane 已提交
3926
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3927
	{
B
Bruce Momjian 已提交
3928
		uint32		blen;
3929

T
Tom Lane 已提交
3930
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3931 3932
			continue;

3933 3934
		memcpy(&bkpb, blk, sizeof(BkpBlock));
		if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
3935
		{
3936
			ereport(emode_for_corrupt_record(emode, recptr),
3937 3938 3939
					(errmsg("incorrect hole size in record at %X/%X",
							recptr.xlogid, recptr.xrecoff)));
			return false;
3940
		}
3941
		blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
3942
		COMP_CRC32C(crc, blk, blen);
3943 3944 3945 3946 3947 3948
		blk += blen;
	}

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

	/* Finally include the record header */
3956
	COMP_CRC32C(crc, (char *) record + sizeof(pg_crc32),
3957
			   SizeOfXLogRecord - sizeof(pg_crc32));
3958
	FIN_CRC32C(crc);
3959

3960
	if (!EQ_CRC32C(record->xl_crc, crc))
3961
	{
3962
		ereport(emode_for_corrupt_record(emode, recptr),
3963
		(errmsg("incorrect resource manager data checksum in record at %X/%X",
B
Bruce Momjian 已提交
3964
				recptr.xlogid, recptr.xrecoff)));
3965
		return false;
3966 3967
	}

3968
	return true;
3969 3970
}

T
Tom Lane 已提交
3971 3972
/*
 * Attempt to read an XLOG record.
3973
 *
T
Tom Lane 已提交
3974 3975
 * 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.
3976
 *
3977
 * If no valid record is available, returns NULL, or fails if emode is PANIC.
3978
 * (emode must be either PANIC, LOG)
3979
 *
3980 3981
 * The record is copied into readRecordBuf, so that on successful return,
 * the returned record pointer always points there.
3982
 */
A
Asim R P 已提交
3983 3984
XLogRecord *
XLogReadRecord(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt)
3985
{
3986
	XLogRecord *record;
3987
	char	   *buffer;
3988
	XLogRecPtr	tmpRecPtr = EndRecPtr;
3989
	bool		randAccess = false;
T
Tom Lane 已提交
3990 3991
	uint32		len,
				total_len;
3992
	uint32		targetRecOff;
3993
	uint32		pageHeaderSize;
3994

T
Tom Lane 已提交
3995
	if (readBuf == NULL)
3996
	{
T
Tom Lane 已提交
3997
		/*
B
Bruce Momjian 已提交
3998 3999 4000 4001 4002
		 * 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 已提交
4003
		 */
4004
		readBuf = (char *) malloc(XLOG_BLCKSZ);
A
Asim R P 已提交
4005 4006
		if(!readBuf)
			ereport(PANIC, (errmsg("Cannot allocate memory for read log record. Out of Memory")));
4007 4008
	}

T
Tom Lane 已提交
4009
	if (RecPtr == NULL)
4010
	{
4011
		RecPtr = &tmpRecPtr;
4012

4013
		/*
4014 4015 4016
		 * RecPtr is pointing to end+1 of the previous WAL record.  We must
		 * advance it if necessary to where the next record starts.  First,
		 * align to next page if no more records can fit on the current page.
4017
		 */
4018
		if (XLOG_BLCKSZ - (RecPtr->xrecoff % XLOG_BLCKSZ) < SizeOfXLogRecord)
4019
			NextLogPage(*RecPtr);
4020

A
Asim R P 已提交
4021
		/* Check for crossing of xlog logid boundary */
4022
		if (RecPtr->xrecoff >= XLogFileSize)
4023
		{
4024 4025
			(RecPtr->xlogid)++;
			RecPtr->xrecoff = 0;
4026
		}
4027

4028 4029 4030 4031 4032
		/*
		 * If at page start, we must skip over the page header.  But we can't
		 * do that until we've read in the page, since the header size is
		 * variable.
		 */
4033
	}
4034 4035
	else
	{
4036 4037 4038 4039
		/*
		 * In this case, the passed-in record pointer should already be
		 * pointing to a valid record starting position.
		 */
4040 4041 4042 4043
		if (!XRecOffIsValid(RecPtr->xrecoff))
			ereport(PANIC,
					(errmsg("invalid record offset at %X/%X",
							RecPtr->xlogid, RecPtr->xrecoff)));
4044

4045
		/*
B
Bruce Momjian 已提交
4046 4047 4048 4049 4050
		 * 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).
4051
		 */
A
Asim R P 已提交
4052
		lastPageTLI = lastSegmentTLI = 0;	/* see comment in ValidXLOGHeader */
4053
		randAccess = true;		/* allow curFileTLI to go backwards too */
4054
	}
4055

4056 4057
	/* This is the first try to read this page. */
	failedSources = 0;
4058
retry:
4059 4060
	/* Read the page containing the record */
	if (!XLogPageRead(RecPtr, emode, fetching_ckpt, randAccess))
4061
	{
A
Asim R P 已提交
4062 4063 4064 4065
		/*
		 * In standby mode, XLogPageRead returning false means that promotion
		 * has been triggered.
		 */
4066
		if (StandbyMode)
A
Asim R P 已提交
4067 4068 4069 4070
			return NULL;
		else
			goto next_record_is_invalid;
	}
4071 4072 4073 4074 4075

	/* *********Above this xlogpageread should called ***********/
	pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
	targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
	if (targetRecOff == 0)
4076 4077
	{
		/*
4078 4079 4080 4081
		 * At page start, so skip over page header.  The Assert checks that
		 * we're not scribbling on caller's record pointer; it's OK because we
		 * can only get here in the continuing-from-prev-record case, since
		 * XRecOffIsValid rejected the zero-page-offset case otherwise.
4082
		 */
4083
		Assert(RecPtr == &tmpRecPtr);
4084
		RecPtr->xrecoff += pageHeaderSize;
4085 4086 4087 4088
		targetRecOff = pageHeaderSize;
	}
	else if (targetRecOff < pageHeaderSize)
	{
4089
		ereport(emode_for_corrupt_record(emode, *RecPtr),
4090 4091 4092 4093
				(errmsg("invalid record offset at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
		goto next_record_is_invalid;
	}
T
Tom Lane 已提交
4094
	if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
4095
		targetRecOff == pageHeaderSize)
4096
	{
4097
		ereport(emode_for_corrupt_record(emode, *RecPtr),
4098 4099
				(errmsg("contrecord is requested by %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
4100 4101
		goto next_record_is_invalid;
	}
4102
	record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
4103

T
Tom Lane 已提交
4104
	/*
B
Bruce Momjian 已提交
4105 4106
	 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
	 * required.
T
Tom Lane 已提交
4107
	 */
4108 4109 4110 4111
	if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
	{
		if (record->xl_len != 0)
		{
4112
			ereport(emode_for_corrupt_record(emode, *RecPtr),
4113 4114 4115 4116 4117 4118
					(errmsg("invalid xlog switch record at %X/%X",
							RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
	}
	else if (record->xl_len == 0)
4119
	{
4120
		ereport(emode_for_corrupt_record(emode, *RecPtr),
4121 4122
				(errmsg("record with zero length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
4123 4124
		goto next_record_is_invalid;
	}
4125 4126 4127 4128
	if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
		record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
		XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
	{
4129
		ereport(emode_for_corrupt_record(emode, *RecPtr),
4130 4131 4132 4133
				(errmsg("invalid record length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
		goto next_record_is_invalid;
	}
4134 4135
	if (record->xl_rmid > RM_MAX_ID)
	{
4136
		ereport(emode_for_corrupt_record(emode, *RecPtr),
4137
				(errmsg("invalid resource manager ID %u at %X/%X",
B
Bruce Momjian 已提交
4138
						record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
4139 4140
		goto next_record_is_invalid;
	}
4141 4142 4143
	if (randAccess)
	{
		/*
B
Bruce Momjian 已提交
4144 4145
		 * We can't exactly verify the prev-link, but surely it should be less
		 * than the record's own address.
4146 4147 4148
		 */
		if (!XLByteLT(record->xl_prev, *RecPtr))
		{
4149
			ereport(emode_for_corrupt_record(emode, *RecPtr),
4150 4151 4152 4153 4154 4155 4156 4157 4158
					(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 已提交
4159 4160 4161
		 * 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.
4162 4163 4164
		 */
		if (!XLByteEQ(record->xl_prev, ReadRecPtr))
		{
4165
			ereport(emode_for_corrupt_record(emode, *RecPtr),
4166 4167 4168 4169 4170 4171
					(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 已提交
4172

T
Tom Lane 已提交
4173
	/*
B
Bruce Momjian 已提交
4174
	 * Allocate or enlarge readRecordBuf as needed.  To avoid useless small
4175 4176 4177 4178
	 * 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 已提交
4179
	 */
4180
	total_len = record->xl_tot_len;
4181
	if (total_len > readRecordBufSize)
4182
	{
4183 4184
		uint32		newSize = total_len;

4185 4186
		newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
		newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
4187 4188 4189 4190 4191 4192
		if (readRecordBuf)
			free(readRecordBuf);
		readRecordBuf = (char *) malloc(newSize);
		if (!readRecordBuf)
		{
			readRecordBufSize = 0;
4193 4194 4195 4196
			/* We treat this as a "bogus data" condition */
			ereport(emode_for_corrupt_record(emode, *RecPtr),
					(errmsg("record length %u at %X/%X too long",
							total_len, RecPtr->xlogid, RecPtr->xrecoff)));
4197 4198 4199
			goto next_record_is_invalid;
		}
		readRecordBufSize = newSize;
4200
	}
4201 4202

	buffer = readRecordBuf;
4203
	len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
T
Tom Lane 已提交
4204
	if (total_len > len)
4205
	{
T
Tom Lane 已提交
4206 4207
		/* Need to reassemble record */
		XLogContRecord *contrecord;
4208
		XLogRecPtr	pagelsn;
B
Bruce Momjian 已提交
4209
		uint32		gotlen = len;
4210

4211 4212 4213 4214
		/* Initialize pagelsn to the beginning of the page this record is on */
		pagelsn = *RecPtr;
		pagelsn.xrecoff = (pagelsn.xrecoff / XLOG_BLCKSZ) * XLOG_BLCKSZ;

T
Tom Lane 已提交
4215
		memcpy(buffer, record, len);
4216
		record = (XLogRecord *) buffer;
T
Tom Lane 已提交
4217
		buffer += len;
4218
		for (;;)
4219
		{
4220 4221 4222
			/* Calculate pointer to beginning of next page */
			pagelsn.xrecoff += XLOG_BLCKSZ;
			if (pagelsn.xrecoff >= XLogFileSize)
4223
			{
4224 4225
				(pagelsn.xlogid)++;
				pagelsn.xrecoff = 0;
4226
			}
4227 4228
			/* Wait for the next page to become available */
			if (!XLogPageRead(&pagelsn, emode, false, false))
T
Tom Lane 已提交
4229
			{
4230 4231 4232 4233 4234 4235 4236 4237
				/*
				 * In standby-mode, XLogPageRead returning false means that
				 * promotion has been triggered.
				 */
				if (StandbyMode)
					return NULL;
				else
					goto next_record_is_invalid;
T
Tom Lane 已提交
4238
			}
4239

4240
			/* Check that the continuation record looks valid */
T
Tom Lane 已提交
4241
			if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
4242
			{
4243
				ereport(emode_for_corrupt_record(emode, *RecPtr),
4244 4245
						(errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
								readId, readSeg, readOff)));
4246 4247
				goto next_record_is_invalid;
			}
4248 4249
			pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
			contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
B
Bruce Momjian 已提交
4250
			if (contrecord->xl_rem_len == 0 ||
T
Tom Lane 已提交
4251
				total_len != (contrecord->xl_rem_len + gotlen))
4252
			{
4253
				ereport(emode_for_corrupt_record(emode, *RecPtr),
4254 4255 4256
						(errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
								contrecord->xl_rem_len,
								readId, readSeg, readOff)));
4257 4258
				goto next_record_is_invalid;
			}
4259
			len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
T
Tom Lane 已提交
4260
			if (contrecord->xl_rem_len > len)
4261
			{
B
Bruce Momjian 已提交
4262
				memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
T
Tom Lane 已提交
4263 4264 4265 4266 4267 4268 4269 4270 4271 4272
				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;
4273
		pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
T
Tom Lane 已提交
4274 4275
		EndRecPtr.xlogid = readId;
		EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
4276 4277
			pageHeaderSize +
			MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
4278

T
Tom Lane 已提交
4279
		ReadRecPtr = *RecPtr;
4280
		/* needn't worry about XLOG SWITCH, it can't cross page boundaries */
T
Tom Lane 已提交
4281
		return record;
4282 4283
	}

T
Tom Lane 已提交
4284 4285 4286 4287 4288
	/* Record does not cross a page boundary */
	if (!RecordIsValid(record, *RecPtr, emode))
		goto next_record_is_invalid;
	EndRecPtr.xlogid = RecPtr->xlogid;
	EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
4289

T
Tom Lane 已提交
4290 4291
	ReadRecPtr = *RecPtr;
	memcpy(buffer, record, total_len);
B
Bruce Momjian 已提交
4292

4293 4294 4295 4296 4297 4298 4299 4300
	/*
	 * Special processing if it's an XLOG SWITCH record
	 */
	if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
	{
		/* Pretend it extends to end of segment */
		EndRecPtr.xrecoff += XLogSegSize - 1;
		EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
B
Bruce Momjian 已提交
4301

4302
		/*
B
Bruce Momjian 已提交
4303 4304 4305
		 * 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.
4306 4307 4308
		 */
		readOff = XLogSegSize - XLOG_BLCKSZ;
	}
4309 4310 4311 4312 4313 4314

	elogif(debug_xlog_record_read, LOG,
		   "xlog read record -- Read record %X/%X successfully with endrecptr %X/%X",
		   ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
		   EndRecPtr.xlogid, EndRecPtr.xrecoff);

T
Tom Lane 已提交
4315
	return (XLogRecord *) buffer;
4316

4317 4318 4319 4320 4321 4322 4323
next_record_is_invalid:

	elogif(debug_xlog_record_read, LOG,
		   "xlog record read -- next record is invalid.");

	failedSources |= readSource;

4324 4325
	if (readFile >= 0)
		close(readFile);
4326
	readFile = -1;
4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369

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

/*
 * Close, re-set and clean all the necessary resources used during reading
 * XLog records.
 */
void
XLogCloseReadRecord(void)
{
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
	else
		Assert(readFile == -1);

	if (readBuf)
	{
		free(readBuf);
		readBuf = NULL;
	}

	if (readRecordBuf)
	{
		free(readRecordBuf);
		readRecordBuf = NULL;
	}

	readId = 0;
	readSeg = 0;
	readOff = 0;
	readLen = 0;
	readRecordBufSize = 0;

	memset(&ReadRecPtr, 0, sizeof(XLogRecPtr));
	memset(&EndRecPtr, 0, sizeof(XLogRecPtr));
4370 4371
}

4372 4373 4374 4375
/*
 * 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 已提交
4376
 * ReadRecord.	It's not intended for use from anywhere else.
4377 4378
 */
static bool
4379
ValidXLOGHeader(XLogPageHeader hdr, int emode, bool segmentonly)
4380
{
4381 4382
	XLogRecPtr	recaddr;

4383 4384 4385
	recaddr.xlogid = readId;
	recaddr.xrecoff = readSeg * XLogSegSize + readOff;

4386 4387
	if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
	{
4388
		ereport(emode_for_corrupt_record(emode, recaddr),
4389 4390
				(errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
						hdr->xlp_magic, readId, readSeg, readOff)));
4391 4392 4393 4394
		return false;
	}
	if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
	{
4395
		ereport(emode_for_corrupt_record(emode, recaddr),
4396 4397
				(errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
						hdr->xlp_info, readId, readSeg, readOff)));
4398 4399
		return false;
	}
4400
	if (hdr->xlp_info & XLP_LONG_HEADER)
4401
	{
4402
		XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
B
Bruce Momjian 已提交
4403

4404
		if (longhdr->xlp_sysid != ControlFile->system_identifier)
4405
		{
4406 4407
			char		fhdrident_str[32];
			char		sysident_str[32];
4408

4409
			/*
B
Bruce Momjian 已提交
4410 4411
			 * Format sysids separately to keep platform-dependent format code
			 * out of the translatable message string.
4412 4413 4414 4415 4416
			 */
			snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
					 longhdr->xlp_sysid);
			snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
					 ControlFile->system_identifier);
4417
			ereport(emode_for_corrupt_record(emode, recaddr),
P
Peter Eisentraut 已提交
4418 4419
					(errmsg("WAL file is from different database system"),
					 errdetail("WAL file database system identifier is %s, pg_control database system identifier is %s.",
B
Bruce Momjian 已提交
4420
							   fhdrident_str, sysident_str)));
4421 4422 4423 4424
			return false;
		}
		if (longhdr->xlp_seg_size != XLogSegSize)
		{
4425
			ereport(emode_for_corrupt_record(emode, recaddr),
P
Peter Eisentraut 已提交
4426
					(errmsg("WAL file is from different database system"),
B
Bruce Momjian 已提交
4427
					 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
4428 4429
			return false;
		}
4430 4431
		if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
		{
4432
			ereport(emode_for_corrupt_record(emode, recaddr),
P
Peter Eisentraut 已提交
4433
					(errmsg("WAL file is from different database system"),
4434 4435 4436
					 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
			return false;
		}
4437
	}
4438 4439 4440
	else if (readOff == 0)
	{
		/* hmm, first page of file doesn't have a long header? */
4441
		ereport(emode_for_corrupt_record(emode, recaddr),
4442 4443 4444 4445 4446
				(errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
						hdr->xlp_info, readId, readSeg, readOff)));
		return false;
	}

4447 4448
	if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
	{
4449
		ereport(emode_for_corrupt_record(emode, recaddr),
4450
				(errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
B
Bruce Momjian 已提交
4451
						hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
4452 4453 4454 4455 4456 4457 4458 4459 4460
						readId, readSeg, readOff)));
		return false;
	}

	/*
	 * Check page TLI is one of the expected values.
	 */
	if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
	{
4461
		ereport(emode_for_corrupt_record(emode, recaddr),
4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472
				(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 已提交
4473
	 * Of course this check should only be applied when advancing sequentially
4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484
	 * across pages; therefore ReadRecord resets lastPageTLI and
	 * lastSegmentTLI to zero when going to a random page.
	 *
	 * Sometimes we re-open a segment that's already been partially replayed.
	 * In that case we cannot perform the normal TLI check: if there is a
	 * timeline switch within the segment, the first page has a smaller TLI
	 * than later pages following the timeline switch, and we might've read
	 * them already. As a weaker test, we still check that it's not smaller
	 * than the TLI we last saw at the beginning of a segment. Pass
	 * segmentonly = true when re-validating the first page like that, and the
	 * page you're actually interested in comes later.
4485
	 */
4486
	if (hdr->xlp_tli < (segmentonly ? lastSegmentTLI : lastPageTLI))
4487
	{
4488
		ereport(emode_for_corrupt_record(emode, recaddr),
4489 4490 4491 4492 4493 4494
				(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;
4495 4496 4497
	if (readOff == 0)
		lastSegmentTLI = hdr->xlp_tli;

4498 4499 4500 4501 4502 4503 4504
	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 已提交
4505
 * its ancestor TLIs).	If we can't find the history file, assume that the
4506 4507 4508
 * timeline has no parents, and return a list of just the specified timeline
 * ID.
 */
4509 4510
List *
XLogReadTimeLineHistory(TimeLineID targetTLI)
4511 4512 4513 4514 4515
{
	List	   *result;
	char		path[MAXPGPATH];
	char		histfname[MAXFNAMELEN];
	char		fline[MAXPGPATH];
B
Bruce Momjian 已提交
4516
	FILE	   *fd;
4517

4518 4519 4520 4521
	/* Timeline 1 does not have a history file, so no need to check */
	if (targetTLI == 1)
		return list_make1_int((int) targetTLI);

4522 4523 4524
	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, targetTLI);
4525
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
4526 4527 4528 4529
	}
	else
		TLHistoryFilePath(path, targetTLI);

B
Bruce Momjian 已提交
4530
	fd = AllocateFile(path, "r");
4531 4532 4533 4534 4535
	if (fd == NULL)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
4536
					 errmsg("could not open file \"%s\": %m", path)));
4537 4538 4539 4540 4541 4542
		/* Not there, so assume no parents */
		return list_make1_int((int) targetTLI);
	}

	result = NIL;

B
Bruce Momjian 已提交
4543 4544 4545
	/*
	 * Parse the file...
	 */
4546
	while (fgets(fline, sizeof(fline), fd) != NULL)
4547 4548
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
4549 4550 4551
		char	   *ptr;
		char	   *endptr;
		TimeLineID	tli;
4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571

		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 已提交
4572
				   errhint("Timeline IDs must be in increasing sequence.")));
4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585

		/* 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 已提交
4586
			errhint("Timeline IDs must be less than child timeline's ID.")));
4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604

	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 已提交
4605
	FILE	   *fd;
4606

4607 4608 4609 4610
	/* Timeline 1 does not have a history file, so no need to check */
	if (probeTLI == 1)
		return false;

4611 4612 4613
	if (InArchiveRecovery)
	{
		TLHistoryFileName(histfname, probeTLI);
4614
		RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629
	}
	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 已提交
4630
					 errmsg("could not open file \"%s\": %m", path)));
4631 4632 4633 4634
		return false;
	}
}

A
Asim R P 已提交
4635
#if 0
4636 4637 4638 4639 4640 4641 4642 4643 4644 4645
/*
 * Scan for new timelines that might have appeared in the archive since we
 * started recovery.
 *
 * If there are any, the function changes recovery target TLI to the latest
 * one and returns 'true'.
 */
static bool
rescanLatestTimeLine(void)
{
4646 4647
	TimeLineID	newtarget;

4648 4649 4650 4651 4652 4653
	newtarget = findNewestTimeLine(recoveryTargetTLI);
	if (newtarget != recoveryTargetTLI)
	{
		/*
		 * Determine the list of expected TLIs for the new TLI
		 */
4654 4655
		List	   *newExpectedTLIs;

A
Asim R P 已提交
4656
		newExpectedTLIs = XLogReadTimeLineHistory(newtarget);
4657 4658

		/*
4659 4660
		 * If the current timeline is not part of the history of the new
		 * timeline, we cannot proceed to it.
4661 4662 4663 4664 4665 4666
		 *
		 * XXX This isn't foolproof: The new timeline might have forked from
		 * the current one, but before the current recovery location. In that
		 * case we will still switch to the new timeline and proceed replaying
		 * from it even though the history doesn't match what we already
		 * replayed. That's not good. We will likely notice at the next online
4667 4668
		 * checkpoint, as the TLI won't match what we expected, but it's not
		 * guaranteed. The admin needs to make sure that doesn't happen.
4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692
		 */
		if (!list_member_int(newExpectedTLIs,
							 (int) recoveryTargetTLI))
			ereport(LOG,
					(errmsg("new timeline %u is not a child of database system timeline %u",
							newtarget,
							ThisTimeLineID)));
		else
		{
			/* Switch target */
			recoveryTargetTLI = newtarget;
			list_free(expectedTLIs);
			expectedTLIs = newExpectedTLIs;

			XLogCtl->RecoveryTargetTLI = recoveryTargetTLI;

			ereport(LOG,
					(errmsg("new target timeline is %u",
							recoveryTargetTLI)));
			return true;
		}
	}
	return false;
}
A
Asim R P 已提交
4693
#endif
4694

4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708
/*
 * 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 已提交
4709 4710
	 * The algorithm is just to probe for the existence of timeline history
	 * files.  XXX is it useful to allow gaps in the sequence?
4711 4712 4713
	 */
	newestTLI = startTLI;

B
Bruce Momjian 已提交
4714
	for (probeTLI = startTLI + 1;; probeTLI++)
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737
	{
		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 已提交
4738
 * considerations.	But we should be just as tense as XLogFileInit to avoid
4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753
 * 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 已提交
4754
	Assert(newTLI > parentTLI); /* else bad selection of newTLI */
4755 4756 4757 4758

	/*
	 * Write into a temp file name.
	 */
4759 4760
	snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());

4761 4762
	unlink(tmppath);

4763
	/* do not use get_sync_bit() here --- want to fsync only at end of fill */
4764 4765 4766
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
4767
		ereport(ERROR,
4768 4769 4770
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m", tmppath)));

4771
	TLHistoryFilePath(path, parentTLI);
4772 4773 4774 4775 4776

	srcfd = BasicOpenFile(path, O_RDONLY, 0);
	if (srcfd < 0)
	{
		if (errno != ENOENT)
4777
			ereport(ERROR,
4778
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
4779
					 errmsg("could not open file \"%s\": %m", path)));
4780 4781 4782 4783 4784 4785 4786 4787 4788
		/* Not there, so assume parent has no parents */
	}
	else
	{
		for (;;)
		{
			errno = 0;
			nbytes = (int) read(srcfd, buffer, sizeof(buffer));
			if (nbytes < 0 || errno != 0)
4789
				ereport(ERROR,
4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803
						(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 已提交
4804 4805

				/*
B
Bruce Momjian 已提交
4806
				 * if write didn't set errno, assume problem is no disk space
B
Bruce Momjian 已提交
4807
				 */
4808 4809
				errno = save_errno ? save_errno : ENOSPC;

4810
				ereport(ERROR,
4811
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
4812
					 errmsg("could not write to file \"%s\": %m", tmppath)));
4813 4814 4815 4816 4817 4818 4819 4820
			}
		}
		close(srcfd);
	}

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

4826
	/*
B
Bruce Momjian 已提交
4827 4828
	 * Write comment to history file to explain why and where timeline
	 * changed. Comment varies according to the recovery target used.
4829 4830 4831 4832 4833 4834 4835 4836 4837
	 */
	if (recoveryTarget == RECOVERY_TARGET_XID)
		snprintf(buffer, sizeof(buffer),
				 "%s%u\t%s\t%s transaction %u\n",
				 (srcfd < 0) ? "" : "\n",
				 parentTLI,
				 xlogfname,
				 recoveryStopAfter ? "after" : "before",
				 recoveryStopXid);
4838
	else if (recoveryTarget == RECOVERY_TARGET_TIME)
4839 4840 4841 4842 4843 4844 4845
		snprintf(buffer, sizeof(buffer),
				 "%s%u\t%s\t%s %s\n",
				 (srcfd < 0) ? "" : "\n",
				 parentTLI,
				 xlogfname,
				 recoveryStopAfter ? "after" : "before",
				 timestamptz_to_str(recoveryStopTime));
4846 4847
	else if (recoveryTarget == RECOVERY_TARGET_NAME)
		snprintf(buffer, sizeof(buffer),
4848
				 "%s%u\t%s\tat restore point \"%s\"\n",
4849 4850 4851 4852
				 (srcfd < 0) ? "" : "\n",
				 parentTLI,
				 xlogfname,
				 recoveryStopName);
4853 4854 4855 4856 4857 4858
	else
		snprintf(buffer, sizeof(buffer),
				 "%s%u\t%s\tno recovery target specified\n",
				 (srcfd < 0) ? "" : "\n",
				 parentTLI,
				 xlogfname);
4859 4860 4861 4862 4863 4864 4865 4866

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

		/*
B
Bruce Momjian 已提交
4867
		 * If we fail to make the file, delete it to release disk space
4868 4869 4870 4871 4872
		 */
		unlink(tmppath);
		/* if write didn't set errno, assume problem is no disk space */
		errno = save_errno ? save_errno : ENOSPC;

4873
		ereport(ERROR,
4874 4875 4876 4877 4878
				(errcode_for_file_access(),
				 errmsg("could not write to file \"%s\": %m", tmppath)));
	}

	if (pg_fsync(fd) != 0)
4879
		ereport(ERROR,
4880 4881 4882 4883
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
4884
		ereport(ERROR,
4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900
				(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)
4901
		ereport(ERROR,
4902 4903 4904 4905 4906 4907
				(errcode_for_file_access(),
				 errmsg("could not link file \"%s\" to \"%s\": %m",
						tmppath, path)));
	unlink(tmppath);
#else
	if (rename(tmppath, path) < 0)
4908
		ereport(ERROR,
4909 4910 4911 4912 4913 4914 4915 4916 4917 4918
				(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);
}

4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
static void
ControlFileWatcherSaveInitial(void)
{
	ControlFileWatcher->current_checkPointLoc = ControlFile->checkPoint;
	ControlFileWatcher->current_prevCheckPointLoc = ControlFile->prevCheckPoint;
	ControlFileWatcher->current_checkPointCopy_redo = ControlFile->checkPointCopy.redo;

	if (Debug_print_control_checkpoints)
		elog(LOG,"pg_control checkpoint: initial values (checkpoint loc %s, previous loc %s, copy's redo loc %s)",
			 XLogLocationToString_Long(&ControlFile->checkPoint),
			 XLogLocationToString2_Long(&ControlFile->prevCheckPoint),
			 XLogLocationToString3_Long(&ControlFile->checkPointCopy.redo));

	ControlFileWatcher->watcherInitialized = true;
}

static void
ControlFileWatcherCheckForChange(void)
{
	XLogRecPtr  writeLoc;
	XLogRecPtr  flushedLoc;

	if (!XLByteEQ(ControlFileWatcher->current_checkPointLoc,ControlFile->checkPoint) ||
		!XLByteEQ(ControlFileWatcher->current_prevCheckPointLoc,ControlFile->prevCheckPoint) ||
		!XLByteEQ(ControlFileWatcher->current_checkPointCopy_redo,ControlFile->checkPointCopy.redo))
	{
		ControlFileWatcher->current_checkPointLoc = ControlFile->checkPoint;
		ControlFileWatcher->current_prevCheckPointLoc = ControlFile->prevCheckPoint;
		ControlFileWatcher->current_checkPointCopy_redo = ControlFile->checkPointCopy.redo;

		if (XLogGetWriteAndFlushedLoc(&writeLoc, &flushedLoc))
		{
			bool problem = XLByteLE(flushedLoc,ControlFile->checkPoint);
			if (problem)
				elog(PANIC,"Checkpoint location %s for pg_control file is not flushed (write loc %s, flushed loc is %s)",
				     XLogLocationToString_Long(&ControlFile->checkPoint),
				     XLogLocationToString2_Long(&writeLoc),
				     XLogLocationToString3_Long(&flushedLoc));

			if (Debug_print_control_checkpoints)
				elog(LOG,"pg_control checkpoint: change (checkpoint loc %s, previous loc %s, copy's redo loc %s, write loc %s, flushed loc %s)",
					 XLogLocationToString_Long(&ControlFile->checkPoint),
					 XLogLocationToString2_Long(&ControlFile->prevCheckPoint),
					 XLogLocationToString3_Long(&ControlFile->checkPointCopy.redo),
					 XLogLocationToString4_Long(&writeLoc),
					 XLogLocationToString5_Long(&flushedLoc));
		}
		else
		{
			if (Debug_print_control_checkpoints)
				elog(LOG,"pg_control checkpoint: change (checkpoint loc %s, previous loc %s, copy's redo loc %s)",
					 XLogLocationToString_Long(&ControlFile->checkPoint),
					 XLogLocationToString2_Long(&ControlFile->prevCheckPoint),
					 XLogLocationToString3_Long(&ControlFile->checkPointCopy.redo));
		}
	}
}

4977 4978
/*
 * I/O routines for pg_control
4979 4980
 *
 * *ControlFile is a buffer in shared memory that holds an image of the
B
Bruce Momjian 已提交
4981
 * contents of pg_control.	WriteControlFile() initializes pg_control
4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
 * 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)
{
4994
	int			fd;
B
Bruce Momjian 已提交
4995
	char		buffer[PG_CONTROL_SIZE];		/* need not be aligned */
4996 4997

	/*
T
Tom Lane 已提交
4998
	 * Initialize version and compatibility-check fields
4999
	 */
T
Tom Lane 已提交
5000 5001
	ControlFile->pg_control_version = PG_CONTROL_VERSION;
	ControlFile->catalog_version_no = CATALOG_VERSION_NO;
5002 5003 5004 5005

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

5006 5007
	ControlFile->blcksz = BLCKSZ;
	ControlFile->relseg_size = RELSEG_SIZE;
5008
	ControlFile->xlog_blcksz = XLOG_BLCKSZ;
5009
	ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
5010 5011

	ControlFile->nameDataLen = NAMEDATALEN;
5012
	ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
5013

5014 5015
	ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;

5016
#ifdef HAVE_INT64_TIMESTAMP
5017
	ControlFile->enableIntTimes = true;
5018
#else
5019
	ControlFile->enableIntTimes = false;
5020
#endif
5021 5022
	ControlFile->float4ByVal = FLOAT4PASSBYVAL;
	ControlFile->float8ByVal = FLOAT8PASSBYVAL;
5023

T
Tom Lane 已提交
5024
	/* Contents are protected with a CRC */
5025 5026
	INIT_CRC32C(ControlFile->crc);
	COMP_CRC32C(ControlFile->crc,
5027 5028
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
5029
	FIN_CRC32C(ControlFile->crc);
T
Tom Lane 已提交
5030

5031
	/*
5032 5033 5034 5035 5036
	 * 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".
5037
	 */
5038 5039
	if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
		elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
5040

5041
	memset(buffer, 0, PG_CONTROL_SIZE);
5042 5043
	memcpy(buffer, ControlFile, sizeof(ControlFileData));

5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not create control file \"%s\": %m",
						XLOG_CONTROL_FILE)));

	errno = 0;
	if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not write to control file: %m")));
	}

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

	if (close(fd))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close control file: %m")));
5073 5074

	ControlFileWatcherSaveInitial();
5075 5076 5077 5078 5079
}

static void
ReadControlFile(void)
{
5080
	pg_crc32	crc;
5081 5082 5083 5084 5085
	int			fd;

	/*
	 * Read data...
	 */
5086 5087 5088
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
5089
	if (fd < 0)
5090 5091 5092
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
5093
						XLOG_CONTROL_FILE)));
5094 5095

	if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
5096 5097
		ereport(PANIC,
				(errcode_for_file_access(),
5098
				 errmsg("could not read from control file: %m")));
5099 5100 5101

	close(fd);

T
Tom Lane 已提交
5102
	/*
B
Bruce Momjian 已提交
5103 5104 5105 5106
	 * 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 已提交
5107
	 */
5108 5109 5110 5111 5112

	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),"
5113 5114
		 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
			ControlFile->pg_control_version, ControlFile->pg_control_version,
5115 5116 5117
						   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 已提交
5118
	if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
5119 5120 5121
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
B
Bruce Momjian 已提交
5122 5123
				  " but the server was compiled with PG_CONTROL_VERSION %d.",
						ControlFile->pg_control_version, PG_CONTROL_VERSION),
5124
				 errhint("It looks like you need to initdb.")));
5125

T
Tom Lane 已提交
5126
	/* Now check the CRC. */
5127 5128
	INIT_CRC32C(crc);
	COMP_CRC32C(crc,
5129 5130
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
5131
	FIN_CRC32C(crc);
5132

5133
	if (!EQ_CRC32C(crc, ControlFile->crc))
5134 5135
		ereport(FATAL,
				(errmsg("incorrect checksum in control file")));
5136

5137
	/*
5138
	 * Do compatibility checking immediately.  If the database isn't
5139 5140
	 * compatible with the backend executable, we want to abort before we can
	 * possibly do any damage.
5141
	 */
5142
	if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
5143 5144 5145
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
B
Bruce Momjian 已提交
5146 5147
				  " but the server was compiled with CATALOG_VERSION_NO %d.",
						ControlFile->catalog_version_no, CATALOG_VERSION_NO),
5148
				 errhint("It looks like you need to initdb.")));
5149 5150 5151
	if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5152 5153 5154 5155
		   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.")));
5156 5157 5158
	if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
P
Peter Eisentraut 已提交
5159
				 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
5160
				 errhint("It looks like you need to initdb.")));
5161
	if (ControlFile->blcksz != BLCKSZ)
5162 5163
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5164 5165 5166 5167
			 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.")));
5168
	if (ControlFile->relseg_size != RELSEG_SIZE)
5169 5170
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5171 5172 5173 5174
		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.")));
5175 5176 5177
	if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5178 5179 5180
		errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
				  " but the server was compiled with XLOG_BLCKSZ %d.",
				  ControlFile->xlog_blcksz, XLOG_BLCKSZ),
5181
				 errhint("It looks like you need to recompile or initdb.")));
5182 5183 5184 5185
	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 已提交
5186
					   " but the server was compiled with XLOG_SEG_SIZE %d.",
5187
						   ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
B
Bruce Momjian 已提交
5188
				 errhint("It looks like you need to recompile or initdb.")));
5189
	if (ControlFile->nameDataLen != NAMEDATALEN)
5190 5191
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5192 5193 5194 5195
		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.")));
5196
	if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
5197 5198
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
5199
				 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
B
Bruce Momjian 已提交
5200
					  " but the server was compiled with INDEX_MAX_KEYS %d.",
5201
						   ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
B
Bruce Momjian 已提交
5202
				 errhint("It looks like you need to recompile or initdb.")));
5203 5204 5205 5206
	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 已提交
5207 5208
				" but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
			  ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
5209
				 errhint("It looks like you need to recompile or initdb.")));
5210 5211

#ifdef HAVE_INT64_TIMESTAMP
5212
	if (ControlFile->enableIntTimes != true)
5213 5214 5215
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
5216 5217
				  " but the server was compiled with HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
5218
#else
5219
	if (ControlFile->enableIntTimes != false)
5220 5221 5222
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
5223 5224
			   " but the server was compiled without HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
5225 5226
#endif

5227 5228 5229 5230 5231
#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"
5232
					  " but the server was compiled with USE_FLOAT4_BYVAL."),
5233 5234 5235 5236 5237
				 errhint("It looks like you need to recompile or initdb.")));
#else
	if (ControlFile->float4ByVal != false)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
5238 5239
		errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
				  " but the server was compiled without USE_FLOAT4_BYVAL."),
5240 5241 5242 5243 5244 5245 5246 5247
				 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"
5248
					  " but the server was compiled with USE_FLOAT8_BYVAL."),
5249 5250 5251 5252 5253
				 errhint("It looks like you need to recompile or initdb.")));
#else
	if (ControlFile->float8ByVal != false)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
5254 5255
		errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
				  " but the server was compiled without USE_FLOAT8_BYVAL."),
5256 5257 5258
				 errhint("It looks like you need to recompile or initdb.")));
#endif

5259 5260 5261 5262
	/* Make the initdb settings visible as GUC variables, too */
	SetConfigOption("data_checksums", DataChecksumsEnabled() ? "yes" : "no",
					PGC_INTERNAL, PGC_S_OVERRIDE);

5263 5264 5265 5266 5267 5268 5269 5270
	if (!ControlFileWatcher->watcherInitialized)
	{
		ControlFileWatcherSaveInitial();
	}
	else
	{
		ControlFileWatcherCheckForChange();
	}
5271 5272
}

5273 5274
static bool
XLogGetWriteAndFlushedLoc(XLogRecPtr *writeLoc, XLogRecPtr *flushedLoc)
5275
{
5276 5277
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
5278

5279 5280 5281 5282
	SpinLockAcquire(&xlogctl->info_lck);
	*writeLoc = xlogctl->LogwrtResult.Write;
	*flushedLoc = xlogctl->LogwrtResult.Flush;
	SpinLockRelease(&xlogctl->info_lck);
5283

5284 5285
	return (writeLoc->xlogid != 0 || writeLoc->xrecoff != 0);
}
5286

5287 5288 5289
void
UpdateControlFile(void)
{
5290
	int			fd;
5291

5292 5293
	INIT_CRC32C(ControlFile->crc);
	COMP_CRC32C(ControlFile->crc,
5294 5295
				   (char *) ControlFile,
				   offsetof(ControlFileData, crc));
5296
	FIN_CRC32C(ControlFile->crc);
5297

5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
						XLOG_CONTROL_FILE)));

	errno = 0;
	if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not write to control file: %m")));
	}
5317

5318 5319 5320 5321 5322 5323 5324 5325 5326
	if (pg_fsync(fd) != 0)
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not fsync control file: %m")));

	if (close(fd))
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not close control file: %m")));
5327

5328
	Assert (ControlFileWatcher->watcherInitialized);
5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339
	ControlFileWatcherCheckForChange();
}

/*
 * Returns the unique system identifier from control file.
 */
uint64
GetSystemIdentifier(void)
{
	Assert(ControlFile != NULL);
	return ControlFile->system_identifier;
5340 5341
}

5342 5343 5344
/*
 * Auto-tune the number of XLOG buffers.
 *
5345 5346 5347 5348 5349 5350 5351
 * The preferred setting for wal_buffers is about 3% of shared_buffers, with
 * a maximum of one XLOG segment (there is little reason to think that more
 * is helpful, at least so long as we force an fsync when switching log files)
 * and a minimum of 8 blocks (which was the default value prior to PostgreSQL
 * 9.1, when auto-tuning was added).
 *
 * This should not be called until NBuffers has received its final value.
5352
 */
5353 5354
static int
XLOGChooseNumBuffers(void)
5355
{
5356 5357 5358 5359 5360 5361 5362 5363 5364
	int			xbuffers;

	xbuffers = NBuffers / 32;
	if (xbuffers > XLOG_SEG_SIZE / XLOG_BLCKSZ)
		xbuffers = XLOG_SEG_SIZE / XLOG_BLCKSZ;
	if (xbuffers < 8)
		xbuffers = 8;
	return xbuffers;
}
5365

5366 5367 5368 5369 5370 5371 5372 5373 5374 5375
/*
 * GUC check_hook for wal_buffers
 */
bool
check_wal_buffers(int *newval, void **extra, GucSource source)
{
	/*
	 * -1 indicates a request for auto-tune.
	 */
	if (*newval == -1)
5376
	{
5377 5378
		/*
		 * If we haven't yet changed the boot_val default of -1, just let it
5379
		 * be.	We'll fix it when XLOGShmemSize is called.
5380 5381 5382
		 */
		if (XLOGbuffers == -1)
			return true;
5383

5384 5385
		/* Otherwise, substitute the auto-tune value */
		*newval = XLOGChooseNumBuffers();
5386
	}
5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398

	/*
	 * We clamp manually-set values to at least 4 blocks.  Prior to PostgreSQL
	 * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
	 * the case, we just silently treat such values as a request for the
	 * minimum.  (We could throw an error instead, but that doesn't seem very
	 * helpful.)
	 */
	if (*newval < 4)
		*newval = 4;

	return true;
5399 5400
}

5401
/*
T
Tom Lane 已提交
5402
 * Initialization of shared memory for XLOG
5403
 */
5404
Size
5405
XLOGShmemSize(void)
5406
{
5407
	Size		size;
5408

5409 5410 5411
	/*
	 * If the value of wal_buffers is -1, use the preferred auto-tune value.
	 * This isn't an amazingly clean place to do this, but we must wait till
5412 5413
	 * NBuffers has received its final value, and must do it before using the
	 * value of XLOGbuffers to do anything important.
5414 5415 5416 5417 5418 5419 5420 5421
	 */
	if (XLOGbuffers == -1)
	{
		char		buf[32];

		snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
		SetConfigOption("wal_buffers", buf, PGC_POSTMASTER, PGC_S_OVERRIDE);
	}
5422 5423
	Assert(XLOGbuffers > 0);

5424 5425 5426 5427 5428 5429 5430
	/* 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 */
5431
	size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
5432 5433

	/*
B
Bruce Momjian 已提交
5434 5435 5436
	 * 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.
5437 5438
	 */

5439 5440 5441 5442
	/*
	 * Similary, we also don't PgControlWatch for the above reasons, too.
	 */

5443
	return size;
5444 5445 5446 5447 5448
}

void
XLOGShmemInit(void)
{
5449
	bool		foundCFile,
5450 5451
				foundXLog,
				foundCFileWatcher;
5452
	char	   *allocptr;
5453

5454
	ControlFile = (ControlFileData *)
5455
		ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
5456 5457
	ControlFileWatcher = (ControlFileWatch *)
		ShmemInitStruct("Control File Watcher", sizeof(ControlFileWatch), &foundCFileWatcher);
5458 5459
	XLogCtl = (XLogCtlData *)
		ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
5460

5461
	if (foundCFile || foundXLog || foundCFileWatcher)
5462 5463
	{
		/* both should be present or neither */
5464
		Assert(foundCFile && foundXLog && foundCFileWatcher);
5465 5466
		return;
	}
5467

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

T
Tom Lane 已提交
5470
	/*
B
Bruce Momjian 已提交
5471 5472 5473
	 * 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 已提交
5474
	 */
5475 5476
	allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
	XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
T
Tom Lane 已提交
5477
	memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
5478
	allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
B
Bruce Momjian 已提交
5479

T
Tom Lane 已提交
5480
	/*
5481
	 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
T
Tom Lane 已提交
5482
	 */
5483 5484
	allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
	XLogCtl->pages = allocptr;
5485
	memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
T
Tom Lane 已提交
5486 5487

	/*
B
Bruce Momjian 已提交
5488 5489
	 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
	 * in additional info.)
T
Tom Lane 已提交
5490 5491
	 */
	XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
5492
	XLogCtl->SharedRecoveryInProgress = true;
5493
	XLogCtl->SharedHotStandbyActive = false;
T
Tom Lane 已提交
5494
	XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
5495
	SpinLockInit(&XLogCtl->info_lck);
5496 5497 5498 5499 5500
	InitSharedLatch(&XLogCtl->recoveryWakeupLatch);

	XLogCtl->haveLastCheckpointLoc = false;
	memset(&XLogCtl->lastCheckpointLoc, 0, sizeof(XLogRecPtr));
	memset(&XLogCtl->lastCheckpointEndLoc, 0, sizeof(XLogRecPtr));
T
Tom Lane 已提交
5501

5502
	/*
B
Bruce Momjian 已提交
5503 5504 5505
	 * 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).
5506 5507 5508
	 */
	if (!IsBootstrapProcessingMode())
		ReadControlFile();
5509 5510
}

5511 5512 5513 5514 5515 5516 5517 5518 5519 5520
/*
 * Are checksums enabled for data pages?
 */
bool
DataChecksumsEnabled(void)
{
	Assert(ControlFile != NULL);
	return (ControlFile->data_checksum_version > 0);
}

5521
/*
T
Tom Lane 已提交
5522 5523
 * This func must be called ONCE on system install.  It creates pg_control
 * and the initial XLOG segment.
5524 5525
 */
void
T
Tom Lane 已提交
5526
BootStrapXLOG(void)
5527
{
5528
	CheckPoint	checkPoint;
T
Tom Lane 已提交
5529 5530
	char	   *buffer;
	XLogPageHeader page;
5531
	XLogLongPageHeader longpage;
5532
	XLogRecord *record;
B
Bruce Momjian 已提交
5533
	bool		use_existent;
5534 5535
	uint64		sysidentifier;
	struct timeval tv;
5536
	pg_crc32	crc;
5537

5538
	/*
B
Bruce Momjian 已提交
5539 5540 5541 5542 5543 5544 5545 5546 5547 5548
	 * 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.
5549 5550 5551 5552 5553
	 */
	gettimeofday(&tv, NULL);
	sysidentifier = ((uint64) tv.tv_sec) << 32;
	sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);

5554 5555 5556
	/* First timeline ID is always 1 */
	ThisTimeLineID = 1;

5557
	/* page buffer must be aligned suitably for O_DIRECT */
5558
	buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
5559
	page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
5560
	memset(page, 0, XLOG_BLCKSZ);
T
Tom Lane 已提交
5561

5562 5563 5564 5565 5566 5567 5568
	/*
	 * Set up information for the initial checkpoint record
	 *
	 * The initial checkpoint record is written to the beginning of the WAL
	 * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
	 * used, so that we can use 0/0 to mean "before any valid WAL segment".
	 */
5569
	checkPoint.redo.xlogid = 0;
5570
	checkPoint.redo.xrecoff = XLogSegSize + SizeOfXLogLongPHD;
5571
	checkPoint.ThisTimeLineID = ThisTimeLineID;
5572
	checkPoint.nextXidEpoch = 0;
5573
	checkPoint.nextXid = FirstNormalTransactionId;
5574
	checkPoint.nextOid = FirstBootstrapObjectId;
5575
	checkPoint.nextRelfilenode = FirstBootstrapObjectId;
5576
	checkPoint.nextMulti = FirstMultiXactId;
5577
	checkPoint.nextMultiOffset = 0;
5578 5579
	checkPoint.oldestXid = FirstNormalTransactionId;
	checkPoint.oldestXidDB = TemplateDbOid;
5580
	checkPoint.time = (pg_time_t) time(NULL);
5581
	checkPoint.oldestActiveXid = InvalidTransactionId;
5582

5583 5584 5585
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
	ShmemVariableCache->oidCount = 0;
5586 5587
	ShmemVariableCache->nextRelfilenode = checkPoint.nextRelfilenode;
	ShmemVariableCache->relfilenodeCount = 0;
5588
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5589
	SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5590

5591
	/* Set up the XLOG page header */
5592
	page->xlp_magic = XLOG_PAGE_MAGIC;
5593 5594
	page->xlp_info = XLP_LONG_HEADER;
	page->xlp_tli = ThisTimeLineID;
5595
	page->xlp_pageaddr.xlogid = 0;
5596
	page->xlp_pageaddr.xrecoff = XLogSegSize;
5597 5598 5599
	longpage = (XLogLongPageHeader) page;
	longpage->xlp_sysid = sysidentifier;
	longpage->xlp_seg_size = XLogSegSize;
5600
	longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5601 5602

	/* Insert the initial checkpoint record */
5603
	record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
5604
	record->xl_prev.xlogid = 0;
5605
	record->xl_prev.xrecoff = XLogSegSize;
5606
	record->xl_xid = InvalidTransactionId;
5607
	record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
5608
	record->xl_len = sizeof(checkPoint);
T
Tom Lane 已提交
5609
	record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
5610
	record->xl_rmid = RM_XLOG_ID;
T
Tom Lane 已提交
5611
	memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
5612

5613 5614 5615
	INIT_CRC32C(crc);
	COMP_CRC32C(crc, &checkPoint, sizeof(checkPoint));
	COMP_CRC32C(crc, (char *) record + sizeof(pg_crc32),
5616
			   SizeOfXLogRecord - sizeof(pg_crc32));
5617
	FIN_CRC32C(crc);
5618

5619 5620
	record->xl_crc = crc;

5621
	/* Create first XLOG segment file */
5622
	use_existent = false;
5623
	openLogFile = XLogFileInit(0, 1, &use_existent, false);
5624

5625
	/* Write the first page with the initial record */
5626
	errno = 0;
5627
	if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5628
	{
5629 5630 5631
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
5632 5633
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
5634
			  errmsg("could not write bootstrap transaction log file: %m")));
5635
	}
5636

5637
	if (pg_fsync(openLogFile) != 0)
5638 5639
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
5640
			  errmsg("could not fsync bootstrap transaction log file: %m")));
5641

5642 5643 5644 5645 5646 5647
	if (close(openLogFile))
		ereport(PANIC,
				(errcode_for_file_access(),
			  errmsg("could not close bootstrap transaction log file: %m")));

	openLogFile = -1;
5648

5649 5650
	/* Now create pg_control */

5651
	memset(ControlFile, 0, sizeof(ControlFileData));
T
Tom Lane 已提交
5652
	/* Initialize pg_control status fields */
5653
	ControlFile->system_identifier = sysidentifier;
T
Tom Lane 已提交
5654 5655
	ControlFile->state = DB_SHUTDOWNED;
	ControlFile->time = checkPoint.time;
5656
	ControlFile->checkPoint = checkPoint.redo;
T
Tom Lane 已提交
5657
	ControlFile->checkPointCopy = checkPoint;
5658 5659 5660 5661 5662 5663

	/* Set important parameter values for use when replaying WAL */
	ControlFile->MaxConnections = MaxConnections;
	ControlFile->max_prepared_xacts = max_prepared_xacts;
	ControlFile->max_locks_per_xact = max_locks_per_xact;
	ControlFile->wal_level = wal_level;
5664 5665
	ControlFile->data_checksum_version = bootstrap_data_checksum_version;

5666
	/* some additional ControlFile fields are set in WriteControlFile() */
5667

5668
	WriteControlFile();
5669 5670 5671

	/* Bootstrap the commit log, too */
	BootStrapCLOG();
5672
	BootStrapSUBTRANS();
5673
	BootStrapMultiXact();
5674
	DistributedLog_BootStrap();
5675

5676
	pfree(buffer);
5677 5678
}

5679
static char *
5680
str_time(pg_time_t tnow)
5681
{
5682
	static char buf[128];
5683

5684
	pg_strftime(buf, sizeof(buf),
5685 5686
				"%Y-%m-%d %H:%M:%S %Z",
				pg_localtime(&tnow, log_timezone));
5687

5688
	return buf;
5689 5690
}

5691 5692
/*
 * See if there is a recovery command file (recovery.conf), and if so
5693
 * read in parameters for archive recovery and XLOG streaming.
5694
 *
5695
 * The file is parsed using the main configuration parser.
5696
 */
5697 5698
void
XLogReadRecoveryCommandFile(int emode)
5699
{
B
Bruce Momjian 已提交
5700 5701 5702
	FILE	   *fd;
	TimeLineID	rtli = 0;
	bool		rtliGiven = false;
5703
	ConfigVariable *item,
5704 5705
			   *head = NULL,
			   *tail = NULL;
B
Bruce Momjian 已提交
5706

5707
	fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
5708 5709 5710
	if (fd == NULL)
	{
		if (errno == ENOENT)
5711
			return;				/* not there, so no recovery in standby mode */
5712
		ereport(FATAL,
B
Bruce Momjian 已提交
5713
				(errcode_for_file_access(),
5714
				 errmsg("could not open recovery command file \"%s\": %m",
5715
						RECOVERY_COMMAND_FILE)));
5716 5717
	}

5718 5719 5720
	ereport(emode,
			(errmsg("Found recovery.conf file, checking appropriate parameters "
					" for recovery in standby mode")));
5721

B
Bruce Momjian 已提交
5722
	/*
5723 5724
	 * Since we're asking ParseConfigFp() to error out at FATAL, there's no
	 * need to check the return value.
5725
	 */
5726
	ParseConfigFp(fd, RECOVERY_COMMAND_FILE, 0, FATAL, &head, &tail);
5727

5728 5729
	for (item = head; item; item = item->next)
	{
5730
		if (strcmp(item->name, "restore_command") == 0)
B
Bruce Momjian 已提交
5731
		{
5732
			recoveryRestoreCommand = pstrdup(item->value);
5733
			ereport(DEBUG2,
5734
					(errmsg("restore_command = '%s'",
5735 5736
							recoveryRestoreCommand)));
		}
5737
		else if (strcmp(item->name, "recovery_end_command") == 0)
5738
		{
5739 5740
			recoveryEndCommand = pstrdup(item->value);
			ereport(DEBUG2,
5741 5742 5743
					(errmsg("recovery_end_command = '%s'",
							recoveryEndCommand)));
		}
5744
		else if (strcmp(item->name, "archive_cleanup_command") == 0)
5745
		{
5746
			archiveCleanupCommand = pstrdup(item->value);
5747
			ereport(DEBUG2,
5748 5749
					(errmsg("archive_cleanup_command = '%s'",
							archiveCleanupCommand)));
5750
		}
5751 5752 5753 5754 5755 5756 5757 5758 5759
		else if (strcmp(item->name, "pause_at_recovery_target") == 0)
		{
			if (!parse_bool(item->value, &recoveryPauseAtTarget))
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("parameter \"%s\" requires a Boolean value", "pause_at_recovery_target")));
			ereport(DEBUG2,
					(errmsg("pause_at_recovery_target = '%s'", item->value)));
		}
5760
		else if (strcmp(item->name, "recovery_target_timeline") == 0)
B
Bruce Momjian 已提交
5761
		{
5762
			rtliGiven = true;
5763
			if (strcmp(item->value, "latest") == 0)
5764 5765 5766 5767
				rtli = 0;
			else
			{
				errno = 0;
5768
				rtli = (TimeLineID) strtoul(item->value, NULL, 0);
5769 5770 5771
				if (errno == EINVAL || errno == ERANGE)
					ereport(FATAL,
							(errmsg("recovery_target_timeline is not a valid number: \"%s\"",
5772
									item->value)));
5773 5774
			}
			if (rtli)
5775
				ereport(DEBUG2,
5776 5777
						(errmsg("recovery_target_timeline = %u", rtli)));
			else
5778
				ereport(DEBUG2,
5779 5780
						(errmsg("recovery_target_timeline = latest")));
		}
5781
		else if (strcmp(item->name, "recovery_target_xid") == 0)
B
Bruce Momjian 已提交
5782
		{
5783
			errno = 0;
5784
			recoveryTargetXid = (TransactionId) strtoul(item->value, NULL, 0);
5785 5786
			if (errno == EINVAL || errno == ERANGE)
				ereport(FATAL,
B
Bruce Momjian 已提交
5787
				 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
5788 5789
						 item->value)));
			ereport(DEBUG2,
5790 5791
					(errmsg("recovery_target_xid = %u",
							recoveryTargetXid)));
5792
			recoveryTarget = RECOVERY_TARGET_XID;
5793
		}
5794
		else if (strcmp(item->name, "recovery_target_time") == 0)
B
Bruce Momjian 已提交
5795
		{
5796
			/*
5797 5798
			 * if recovery_target_xid or recovery_target_name specified, then
			 * this overrides recovery_target_time
5799
			 */
5800
			if (recoveryTarget == RECOVERY_TARGET_XID ||
5801
				recoveryTarget == RECOVERY_TARGET_NAME)
5802
				continue;
5803
			recoveryTarget = RECOVERY_TARGET_TIME;
B
Bruce Momjian 已提交
5804

5805
			/*
5806
			 * Convert the time string given by the user to TimestampTz form.
5807
			 */
5808 5809
			recoveryTargetTime =
				DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
5810
												CStringGetDatum(item->value),
5811 5812
												ObjectIdGetDatum(InvalidOid),
														Int32GetDatum(-1)));
5813
			ereport(DEBUG2,
5814
					(errmsg("recovery_target_time = '%s'",
5815
							timestamptz_to_str(recoveryTargetTime))));
5816
		}
5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830
		else if (strcmp(item->name, "recovery_target_name") == 0)
		{
			/*
			 * if recovery_target_xid specified, then this overrides
			 * recovery_target_name
			 */
			if (recoveryTarget == RECOVERY_TARGET_XID)
				continue;
			recoveryTarget = RECOVERY_TARGET_NAME;

			recoveryTargetName = pstrdup(item->value);
			if (strlen(recoveryTargetName) >= MAXFNAMELEN)
				ereport(FATAL,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5831
						 errmsg("recovery_target_name is too long (maximum %d characters)", MAXFNAMELEN - 1)));
5832 5833 5834 5835 5836

			ereport(DEBUG2,
					(errmsg("recovery_target_name = '%s'",
							recoveryTargetName)));
		}
5837
		else if (strcmp(item->name, "recovery_target_inclusive") == 0)
5838 5839 5840 5841
		{
			/*
			 * does nothing if a recovery_target is not also set
			 */
5842
			if (!parse_bool(item->value, &recoveryTargetInclusive))
5843 5844
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5845 5846 5847
						 errmsg("parameter \"%s\" requires a Boolean value", "recovery_target_inclusive")));
			ereport(DEBUG2,
					(errmsg("recovery_target_inclusive = %s", item->value)));
5848
		}
5849
		else if (strcmp(item->name, "standby_mode") == 0)
5850
		{
5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863
			if (!parse_bool(item->value, &StandbyModeRequested))
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("parameter \"%s\" requires a Boolean value", "standby_mode")));
			ereport(DEBUG2,
					(errmsg("standby_mode = '%s'", item->value)));
		}
		else if (strcmp(item->name, "primary_conninfo") == 0)
		{
			PrimaryConnInfo = pstrdup(item->value);
			ereport(DEBUG2,
					(errmsg("primary_conninfo = '%s'",
							PrimaryConnInfo)));
5864
		}
5865
		else if (strcmp(item->name, "trigger_file") == 0)
5866
		{
5867
			TriggerFile = pstrdup(item->value);
5868
			ereport(DEBUG2,
5869 5870 5871
					(errmsg("trigger_file = '%s'",
							TriggerFile)));
		}
5872 5873 5874
		else
			ereport(FATAL,
					(errmsg("unrecognized recovery parameter \"%s\"",
5875
							item->name)));
5876 5877 5878
	}

	/*
5879
	 * Check for compulsory parameters
5880
	 */
5881
	if (StandbyModeRequested)
5882
	{
5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894
		if (PrimaryConnInfo == NULL)
			ereport(FATAL,
					(errmsg("recovery command file \"%s\" primary_conninfo not specified",
							RECOVERY_COMMAND_FILE),
					 errhint("The database server in standby mode needs primary_connection to connect to primary.")));
	}
	else
	{
		/* Currently, standby mode request is a must if recovery.conf file exists */
		ereport(FATAL,
				(errmsg("recovery command file \"%s\" request for standby mode not specified",
						RECOVERY_COMMAND_FILE)));
5895
	}
5896 5897 5898

	FreeConfigVariables(head);
	FreeFile(fd);
5899 5900
}

5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913
static void
renameRecoveryFile()
{
	/*
	 * Rename the config file out of the way, so that we don't accidentally
	 * re-enter archive recovery mode in a subsequent crash.
	 */
	unlink(RECOVERY_COMMAND_DONE);
	if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
		ereport(FATAL,
				(errcode_for_file_access(),
				 errmsg("could not rename file \"%s\" to \"%s\": %m",
						RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
5914 5915 5916 5917 5918 5919 5920 5921
	/*
	 * Response to FTS probes after this point will not indicate that we are a
	 * mirror because the am_mirror flag is set based on existence of
	 * RECOVERY_COMMAND_FILE.  New libpq connections to the postmaster should
	 * no longer return CAC_MIRROR_READY as response because we are no longer a
	 * mirror.
	 */
	ResetMirrorReadyFlag();
5922 5923
}

5924 5925 5926 5927
/*
 * Exit archive-recovery state
 */
static void
5928
exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
5929
{
B
Bruce Momjian 已提交
5930 5931
	char		recoveryPath[MAXPGPATH];
	char		xlogpath[MAXPGPATH];
5932
	XLogRecPtr	InvalidXLogRecPtr = {0, 0};
5933 5934

	/*
5935
	 * We are no longer in archive recovery state.
5936 5937 5938
	 */
	InArchiveRecovery = false;

5939 5940 5941 5942
	/*
	 * Update min recovery point one last time.
	 */
	UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
5943 5944

	/*
B
Bruce Momjian 已提交
5945 5946
	 * If the ending log segment is still open, close it (to avoid problems on
	 * Windows with trying to rename or delete an open file).
5947
	 */
5948 5949 5950 5951 5952
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
5953 5954

	/*
B
Bruce Momjian 已提交
5955 5956 5957 5958 5959 5960 5961
	 * 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.
5962
	 *
5963 5964
	 * 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
5965 5966
	 * of overwriting any existing file.  (This is, in fact, always the case
	 * at present.)
5967
	 */
5968
	snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
5969
	XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
5970 5971 5972 5973 5974 5975 5976 5977 5978 5979

	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(),
5980
					 errmsg("could not rename file \"%s\" to \"%s\": %m",
5981 5982 5983 5984 5985 5986 5987 5988 5989 5990
							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 已提交
5991

5992
		/*
B
Bruce Momjian 已提交
5993 5994 5995
		 * 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.
5996 5997 5998 5999
		 *
		 * Notify the archiver that the last WAL segment of the old timeline
		 * is ready to copy to archival storage. Otherwise, it is not archived
		 * for a while.
6000 6001
		 */
		if (endTLI != ThisTimeLineID)
6002
		{
6003 6004
			XLogFileCopy(endLogId, endLogSeg,
						 endTLI, endLogId, endLogSeg);
6005 6006 6007 6008 6009 6010 6011

			if (XLogArchivingActive())
			{
				XLogFileName(xlogpath, endTLI, endLogId, endLogSeg);
				XLogArchiveNotify(xlogpath);
			}
		}
6012 6013 6014
	}

	/*
B
Bruce Momjian 已提交
6015 6016
	 * Let's just make real sure there are not .ready or .done flags posted
	 * for the new segment.
6017
	 */
6018 6019
	XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
	XLogArchiveCleanup(xlogpath);
6020

6021
	/* Get rid of any remaining recovered timeline-history file, too */
6022
	snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
B
Bruce Momjian 已提交
6023
	unlink(recoveryPath);		/* ignore any error */
6024
	renameRecoveryFile();
6025 6026 6027 6028 6029 6030 6031 6032
}

/*
 * 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.
6033
 *
6034
 * We also track the timestamp of the latest applied COMMIT/ABORT
6035
 * record in XLogCtl->recoveryLastXTime, for logging purposes.
6036 6037
 * Also, some information is saved in recoveryStopXid et al for use in
 * annotating the new timeline's history file.
6038 6039 6040 6041 6042
 */
static bool
recoveryStopsHere(XLogRecord *record, bool *includeThis)
{
	bool		stopsHere;
B
Bruce Momjian 已提交
6043
	uint8		record_info;
B
Bruce Momjian 已提交
6044
	TimestampTz recordXtime;
6045
	char		recordRPName[MAXFNAMELEN];
6046

6047 6048
	/* We only consider stopping at COMMIT, ABORT or RESTORE POINT records */
	if (record->xl_rmid != RM_XACT_ID && record->xl_rmid != RM_XLOG_ID)
6049 6050
		return false;
	record_info = record->xl_info & ~XLR_INFO_MASK;
6051
	if (record->xl_rmid == RM_XACT_ID && record_info == XLOG_XACT_COMMIT)
6052
	{
B
Bruce Momjian 已提交
6053
		xl_xact_commit *recordXactCommitData;
6054 6055

		recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
6056
		recordXtime = recordXactCommitData->xact_time;
6057
	}
6058
	else if (record->xl_rmid == RM_XACT_ID && record_info == XLOG_XACT_ABORT)
6059
	{
B
Bruce Momjian 已提交
6060
		xl_xact_abort *recordXactAbortData;
6061 6062

		recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
6063
		recordXtime = recordXactAbortData->xact_time;
6064
	}
6065
	else if (record->xl_rmid == RM_XLOG_ID && record_info == XLOG_RESTORE_POINT)
6066 6067 6068 6069 6070 6071 6072
	{
		xl_restore_point *recordRestorePointData;

		recordRestorePointData = (xl_restore_point *) XLogRecGetData(record);
		recordXtime = recordRestorePointData->rp_time;
		strncpy(recordRPName, recordRestorePointData->rp_name, MAXFNAMELEN);
	}
6073 6074 6075
	else
		return false;

6076
	/* Do we have a PITR target at all? */
6077
	if (recoveryTarget == RECOVERY_TARGET_UNSET)
6078
	{
6079
		/*
6080 6081
		 * Save timestamp of latest transaction commit/abort if this is a
		 * transaction record
6082 6083 6084
		 */
		if (record->xl_rmid == RM_XACT_ID)
			SetLatestXTime(recordXtime);
6085
		return false;
6086
	}
6087

6088
	if (recoveryTarget == RECOVERY_TARGET_XID)
6089 6090
	{
		/*
6091
		 * There can be only one transaction end record with this exact
B
Bruce Momjian 已提交
6092
		 * transactionid
6093
		 *
B
Bruce Momjian 已提交
6094
		 * when testing for an xid, we MUST test for equality only, since
B
Bruce Momjian 已提交
6095 6096 6097
		 * 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...
6098 6099 6100 6101 6102
		 */
		stopsHere = (record->xl_xid == recoveryTargetXid);
		if (stopsHere)
			*includeThis = recoveryTargetInclusive;
	}
6103 6104 6105
	else if (recoveryTarget == RECOVERY_TARGET_NAME)
	{
		/*
6106 6107
		 * There can be many restore points that share the same name, so we
		 * stop at the first one
6108 6109 6110 6111
		 */
		stopsHere = (strcmp(recordRPName, recoveryTargetName) == 0);

		/*
6112
		 * Ignore recoveryTargetInclusive because this is not a transaction
6113 6114 6115 6116
		 * record
		 */
		*includeThis = false;
	}
6117 6118 6119
	else
	{
		/*
6120
		 * There can be many transactions that share the same commit time, so
B
Bruce Momjian 已提交
6121 6122
		 * we stop after the last one, if we are inclusive, or stop at the
		 * first one if we are exclusive
6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133
		 */
		if (recoveryTargetInclusive)
			stopsHere = (recordXtime > recoveryTargetTime);
		else
			stopsHere = (recordXtime >= recoveryTargetTime);
		if (stopsHere)
			*includeThis = false;
	}

	if (stopsHere)
	{
6134 6135 6136 6137
		recoveryStopXid = record->xl_xid;
		recoveryStopTime = recordXtime;
		recoveryStopAfter = *includeThis;

6138 6139
		if (record_info == XLOG_XACT_COMMIT)
		{
6140
			if (recoveryStopAfter)
6141 6142
				ereport(LOG,
						(errmsg("recovery stopping after commit of transaction %u, time %s",
6143 6144
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
6145 6146 6147
			else
				ereport(LOG,
						(errmsg("recovery stopping before commit of transaction %u, time %s",
6148 6149
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
6150
		}
6151
		else if (record_info == XLOG_XACT_ABORT)
6152
		{
6153
			if (recoveryStopAfter)
6154 6155
				ereport(LOG,
						(errmsg("recovery stopping after abort of transaction %u, time %s",
6156 6157
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
6158 6159 6160
			else
				ereport(LOG,
						(errmsg("recovery stopping before abort of transaction %u, time %s",
6161 6162
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
6163
		}
6164 6165 6166 6167 6168
		else
		{
			strncpy(recoveryStopName, recordRPName, MAXFNAMELEN);

			ereport(LOG,
6169 6170 6171
				(errmsg("recovery stopping at restore point \"%s\", time %s",
						recoveryStopName,
						timestamptz_to_str(recoveryStopTime))));
6172
		}
6173

6174
		/*
6175 6176
		 * Note that if we use a RECOVERY_TARGET_TIME then we can stop at a
		 * restore point since they are timestamped, though the latest
6177 6178 6179
		 * transaction time is not updated.
		 */
		if (record->xl_rmid == RM_XACT_ID && recoveryStopAfter)
6180
			SetLatestXTime(recordXtime);
6181
	}
6182
	else if (record->xl_rmid == RM_XACT_ID)
6183
		SetLatestXTime(recordXtime);
6184 6185 6186 6187

	return stopsHere;
}

6188

6189 6190 6191 6192 6193 6194 6195 6196
/*
 * Recheck shared recoveryPause by polling.
 *
 * XXX Can also be done with shared latch.
 */
static void
recoveryPausesHere(void)
{
6197 6198 6199 6200
	ereport(LOG,
			(errmsg("recovery has paused"),
			 errhint("Execute pg_xlog_replay_resume() to continue.")));

6201
	while (RecoveryIsPaused())
6202
	{
6203
		pg_usleep(1000000L);	/* 1000 ms */
6204
		HandleStartupProcInterrupts();
6205
	}
6206 6207 6208 6209 6210 6211 6212
}

static bool
RecoveryIsPaused(void)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
6213
	bool		recoveryPause;
6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241

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

	return recoveryPause;
}

static void
SetRecoveryPause(bool recoveryPause)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

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

/*
 * pg_xlog_replay_pause - pause recovery now
 */
Datum
pg_xlog_replay_pause(PG_FUNCTION_ARGS)
{
	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6242
				 (errmsg("must be superuser to control recovery"))));
6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263

	if (!RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is not in progress"),
				 errhint("Recovery control functions can only be executed during recovery.")));

	SetRecoveryPause(true);

	PG_RETURN_VOID();
}

/*
 * pg_xlog_replay_resume - resume recovery now
 */
Datum
pg_xlog_replay_resume(PG_FUNCTION_ARGS)
{
	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6264
				 (errmsg("must be superuser to control recovery"))));
6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285

	if (!RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is not in progress"),
				 errhint("Recovery control functions can only be executed during recovery.")));

	SetRecoveryPause(false);

	PG_RETURN_VOID();
}

/*
 * pg_is_xlog_replay_paused
 */
Datum
pg_is_xlog_replay_paused(PG_FUNCTION_ARGS)
{
	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6286
				 (errmsg("must be superuser to control recovery"))));
6287 6288 6289 6290 6291 6292 6293 6294 6295 6296

	if (!RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is not in progress"),
				 errhint("Recovery control functions can only be executed during recovery.")));

	PG_RETURN_BOOL(RecoveryIsPaused());
}

6297
/*
6298
 * Save timestamp of latest processed commit/abort record.
6299 6300
 *
 * We keep this in XLogCtl, not a simple static variable, so that it can be
6301 6302
 * seen by processes other than the startup process.  Note in particular
 * that CreateRestartPoint is executed in the checkpointer.
6303
 */
6304
static void
6305
SetLatestXTime(TimestampTz xtime)
6306
{
6307 6308 6309 6310
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

	SpinLockAcquire(&xlogctl->info_lck);
6311
	xlogctl->recoveryLastXTime = xtime;
6312 6313 6314
	SpinLockRelease(&xlogctl->info_lck);
}

6315 6316 6317 6318 6319
/*
 * Fetch timestamp of latest processed commit/abort record.
 */
static TimestampTz
GetLatestXTime(void)
6320
{
6321 6322 6323
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	TimestampTz xtime;
6324

6325 6326 6327
	SpinLockAcquire(&xlogctl->info_lck);
	xtime = xlogctl->recoveryLastXTime;
	SpinLockRelease(&xlogctl->info_lck);
6328

6329 6330
	return xtime;
}
6331

6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363
/*
 * Save timestamp of the next chunk of WAL records to apply.
 *
 * We keep this in XLogCtl, not a simple static variable, so that it can be
 * seen by all backends.
 */
static void
SetCurrentChunkStartTime(TimestampTz xtime)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

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

static void
printEndOfXLogFile(XLogRecPtr	*loc)
{
	uint32 seg = loc->xrecoff / XLogSegSize;

	XLogRecPtr roundedDownLoc;

	XLogRecord *record;
	XLogRecPtr	LastRec;

	/*
	 * Go back to the beginning of the log file and read forward to find
	 * the end of the transaction log.
	 */
	roundedDownLoc.xlogid = loc->xlogid;
6364
	roundedDownLoc.xrecoff = (seg * XLogSegSize) + SizeOfXLogLongPHD;
6365

6366
	XLogCloseReadRecord();
6367

6368
	record = XLogReadRecord(&roundedDownLoc, LOG, false);
6369 6370 6371 6372 6373 6374
	if (record == NULL)
	{
		elog(LOG,"Couldn't read transaction log file (logid %d, seg %d)",
			 loc->xlogid, seg);
		return;
	}
6375

6376 6377 6378 6379
	do
	{
		LastRec = ReadRecPtr;

6380
		record = XLogReadRecord(NULL, DEBUG5, false);
6381 6382
	} while (record != NULL);

6383
	record = XLogReadRecord(&LastRec, ERROR, false);
6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398

	elog(LOG,"found end of transaction log file %s",
		 XLogLocationToString_Long(&EndRecPtr));

	XLogCloseReadRecord();
}

static void
ApplyStartupRedo(
	XLogRecPtr		*beginLoc,

	XLogRecPtr		*lsn,

	XLogRecord		*record)
{
6399 6400
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421
	RedoErrorCallBack redoErrorCallBack;

	ErrorContextCallback errcontext;

	/* Setup error traceback support for ereport() */
	redoErrorCallBack.location = *beginLoc;
	redoErrorCallBack.record = record;

	errcontext.callback = rm_redo_error_callback;
	errcontext.arg = (void *) &redoErrorCallBack;
	errcontext.previous = error_context_stack;
	error_context_stack = &errcontext;

	/* nextXid must be beyond record's xid */
	if (TransactionIdFollowsOrEquals(record->xl_xid,
									 ShmemVariableCache->nextXid))
	{
		ShmemVariableCache->nextXid = record->xl_xid;
		TransactionIdAdvance(ShmemVariableCache->nextXid);
	}

T
Tom Lane 已提交
6422
	/*
6423 6424
	 * Update shared replayEndRecPtr before replaying this record,
	 * so that XLogFlush will update minRecoveryPoint correctly.
T
Tom Lane 已提交
6425
	 */
6426 6427 6428
	SpinLockAcquire(&xlogctl->info_lck);
	xlogctl->replayEndRecPtr = EndRecPtr;
	SpinLockRelease(&xlogctl->info_lck);
6429 6430 6431

	RmgrTable[record->xl_rmid].rm_redo(*beginLoc, *lsn, record);

6432 6433 6434 6435 6436 6437 6438 6439
	/*
	 * After redo, check whether the backup pages associated with
	 * the WAL record are consistent with the existing pages. This
	 * check is done only if consistency check is enabled for this
	 * record.
	 */
	if ((record->xl_extended_info & XLR_CHECK_CONSISTENCY) != 0)
		checkXLogConsistency(record, *lsn);
6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454
	/* Pop the error context stack */
	error_context_stack = errcontext.previous;

}

/*
 * Process passed checkpoint record either during normal recovery or
 * in standby mode.
 *
 * If in standby mode, master mirroring information stored by the checkpoint
 * record is processed as well.
 */
static void
XLogProcessCheckpointRecord(XLogRecord *rec, XLogRecPtr loc)
{
6455
	CheckpointExtendedRecord ckptExtended;
6456

6457
	UnpackCheckPointRecord(rec, &ckptExtended);
6458

6459
	if (ckptExtended.dtxCheckpoint)
6460
	{
6461
		/* Handle the DTX information. */
6462
		UtilityModeFindOrCreateDtmRedoFile();
6463
		redoDtxCheckPoint(ckptExtended.dtxCheckpoint);
6464 6465 6466 6467
		UtilityModeCloseDtmRedoFile();
	}
}

X
Xin Zhang 已提交
6468 6469 6470 6471 6472 6473 6474
DBState
GetCurrentDBState(void)
{
	Assert(ControlFile);
	return ControlFile->state;
}

6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528
static void
UpdateCatalogForStandbyPromotion(void)
{
	/*
	 * NOTE: The following initialization logic was borrowed from ftsprobe.
	 */
	SetProcessingMode(InitProcessing);

	/*
	 * Create a resource owner to keep track of our resources (currently only
	 * buffer pins).
	 */
	CurrentResourceOwner = ResourceOwnerCreate(NULL, "Startup Pass 4");

	/*
	 * NOTE: AuxiliaryProcessMain has already called:
	 * NOTE:      BaseInit,
	 * NOTE:      InitAuxiliaryProcess instead of InitProcess, and
	 * NOTE:      InitBufferPoolBackend.
	 */

	InitXLOGAccess();

	SetProcessingMode(NormalProcessing);

	/*
	 * Add my PGPROC struct to the ProcArray.
	 *
	 * Once I have done this, I am visible to other backends!
	 */
	InitProcessPhase2();

	/*
	 * Initialize my entry in the shared-invalidation manager's array of
	 * per-backend data.
	 *
	 * Sets up MyBackendId, a unique backend identifier.
	 */
	MyBackendId = InvalidBackendId;

	/*
	 * Though this is a startup process and currently no one sends invalidation
	 * messages concurrently, we set sendOnly = false, since we have relcaches.
	 */
	SharedInvalBackendInit(false);

	if (MyBackendId > MaxBackends || MyBackendId <= 0)
			elog(FATAL, "bad backend id: %d", MyBackendId);

	/*
	 * bufmgr needs another initialization call too
	 */
	InitBufferPoolBackend();

D
Daniel Gustafsson 已提交
6529 6530
	/*
	 * heap access requires the rel-cache.
6531 6532 6533 6534 6535 6536 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 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578
	 *
	 * Pass 4 needs RelationCacheInitializePhase3() to do catalog
	 * validation, after xlog replay is complete.
	 */
	RelationCacheInitialize();
	InitCatalogCache();

	/*
	 * It's now possible to do real access to the system catalogs.
	 *
	 * Load relcache entries for the system catalogs.  This must create at
	 * least the minimum set of "nailed-in" cache entries.
	 */
	RelationCacheInitializePhase2();

	char *fullpath;

	/*
	 * In order to access the catalog, we need a database, and a
	 * tablespace; our access to the heap is going to be slightly
	 * limited, so we'll just use some defaults.
	 */
	MyDatabaseId = TemplateDbOid;
	MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;

	/*
	 * Now we can mark our PGPROC entry with the database ID
	 * (We assume this is an atomic store so no lock is needed)
	 */
	MyProc->databaseId = MyDatabaseId;

	fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);

	SetDatabasePath(fullpath);

	RelationCacheInitializePhase3();

	/*
	 * Now, finally, update the catalog.
	 */
	GpRoleValue old_role = Gp_role;

	/* I am privileged */
	InitializeSessionUserIdStandalone();
	/* Start transaction locally */
	Gp_role = GP_ROLE_UTILITY;
	StartTransactionCommand();
	GetTransactionSnapshot();
6579
	gp_activate_standby();
6580 6581 6582 6583 6584 6585 6586
	/* close the transaction we started above */
	CommitTransactionCommand();
	Gp_role = old_role;

	ereport(LOG, (errmsg("Updated catalog to support standby promotion")));
}

6587 6588 6589 6590
/*
 * Returns timestamp of latest processed commit/abort record.
 *
 * When the server has been started normally without recovery the function
6591
 * returns NULL.
6592 6593 6594 6595
 */
Datum
pg_last_xact_replay_timestamp(PG_FUNCTION_ARGS)
{
6596
	TimestampTz xtime;
6597 6598 6599 6600 6601 6602 6603 6604

	xtime = GetLatestXTime();
	if (xtime == 0)
		PG_RETURN_NULL();

	PG_RETURN_TIMESTAMPTZ(xtime);
}

6605 6606 6607 6608 6609 6610 6611
/*
 * Returns bool with current recovery mode, a global state.
 */
Datum
pg_is_in_recovery(PG_FUNCTION_ARGS)
{
	PG_RETURN_BOOL(RecoveryInProgress());
6612 6613
}

6614 6615 6616 6617 6618 6619 6620 6621
/*
 * Returns time of receipt of current chunk of XLOG data, as well as
 * whether it was received from streaming replication or from archives.
 */
void
GetXLogReceiptTime(TimestampTz *rtime, bool *fromStream)
{
	/*
B
Bruce Momjian 已提交
6622 6623
	 * This must be executed in the startup process, since we don't export the
	 * relevant state to shared memory.
6624 6625 6626 6627 6628 6629 6630
	 */
	Assert(InRecovery);

	*rtime = XLogReceiptTime;
	*fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
}

6631
/*
6632 6633
 * Note that text field supplied is a parameter name and does not require
 * translation
6634
 */
6635
#define RecoveryRequiresIntParameter(param_name, currValue, minValue) \
6636
do { \
6637
	if (currValue < minValue) \
6638
		ereport(ERROR, \
6639 6640 6641 6642 6643 6644 6645
				(errmsg("hot standby is not possible because " \
						"%s = %d is a lower setting than on the master server " \
						"(its value was %d)", \
						param_name, \
						currValue, \
						minValue))); \
} while(0)
6646 6647 6648 6649 6650 6651

/*
 * Check to see if required parameters are set high enough on this server
 * for various aspects of recovery operation.
 */
static void
6652
CheckRequiredParameterValues(void)
6653
{
6654
	/*
B
Bruce Momjian 已提交
6655 6656
	 * For archive recovery, the WAL must be generated with at least 'archive'
	 * wal_level.
6657 6658 6659 6660
	 */
	if (InArchiveRecovery && ControlFile->wal_level == WAL_LEVEL_MINIMAL)
	{
		ereport(WARNING,
6661 6662
				(errmsg("WAL was generated with wal_level=minimal, data may be missing"),
				 errhint("This happens if you temporarily set wal_level=minimal without taking a new base backup.")));
6663
	}
6664

6665
	/*
B
Bruce Momjian 已提交
6666 6667
	 * For Hot Standby, the WAL must be generated with 'hot_standby' mode, and
	 * we must have at least as many backend slots as the primary.
6668
	 */
6669
	if (InArchiveRecovery && EnableHotStandby)
6670 6671 6672
	{
		if (ControlFile->wal_level < WAL_LEVEL_HOT_STANDBY)
			ereport(ERROR,
6673 6674
					(errmsg("hot standby is not possible because wal_level was not set to \"hot_standby\" on the master server"),
					 errhint("Either set wal_level to \"hot_standby\" on the master, or turn off hot_standby here.")));
6675

6676 6677
		/* We ignore autovacuum_max_workers when we make this test. */
		RecoveryRequiresIntParameter("max_connections",
6678 6679
									 MaxConnections,
									 ControlFile->MaxConnections);
6680
		RecoveryRequiresIntParameter("max_prepared_xacts",
6681 6682
									 max_prepared_xacts,
									 ControlFile->max_prepared_xacts);
6683
		RecoveryRequiresIntParameter("max_locks_per_xact",
6684 6685
									 max_locks_per_xact,
									 ControlFile->max_locks_per_xact);
6686
	}
6687
}
6688

6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706
/*
 * This must be called ONCE during postmaster or standalone-backend startup
 */
void
StartupXLOG(void)
{
	XLogCtlInsert *Insert;
	CheckPoint	checkPoint;
	bool		wasShutdown;
	bool		reachedStopPoint = false;
	bool		haveBackupLabel = false;
	XLogRecPtr	RecPtr,
				checkPointLoc,
				EndOfLog;
	uint32		endLogId;
	uint32		endLogSeg;
	XLogRecord *record;
	uint32		freespace;
6707
	TransactionId oldestActiveXID;
6708
	bool		backupEndRequired = false;
6709
	bool		bgwriterLaunched = false;
6710 6711 6712 6713 6714 6715 6716 6717 6718

	/*
	 * Read control file and check XLOG status looks valid.
	 *
	 * 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.
	 */
	ReadControlFile();

6719
	if (ControlFile->state < DB_SHUTDOWNED ||
6720 6721 6722 6723 6724 6725 6726 6727 6728
		ControlFile->state > DB_IN_PRODUCTION ||
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
		ereport(FATAL,
				(errmsg("control file contains invalid data")));

	if (ControlFile->state == DB_SHUTDOWNED)
		ereport(LOG,
				(errmsg("database system was shut down at %s",
						str_time(ControlFile->time))));
6729 6730 6731 6732
	else if (ControlFile->state == DB_SHUTDOWNED_IN_RECOVERY)
		ereport(LOG,
				(errmsg("database system was shut down in recovery at %s",
						str_time(ControlFile->time))));
6733 6734
	else if (ControlFile->state == DB_SHUTDOWNING)
		ereport(LOG,
6735
				(errmsg("database system shutdown was interrupted; last known up at %s",
6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759
						str_time(ControlFile->time))));
	else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
		ereport(LOG,
		   (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."),
			errSendAlert(true)));
	else if (ControlFile->state == DB_IN_STANDBY_MODE)
		ereport(LOG,
				(errmsg("database system was interrupted while in standby mode at  %s",
						str_time(ControlFile->checkPointCopy.time)),
						errhint("This probably means something unexpected happened either"
								" during replay at standby or receipt of XLog from primary."),
				 errSendAlert(true)));
	else if (ControlFile->state == DB_IN_STANDBY_PROMOTED)
		ereport(LOG,
				(errmsg("database system was interrupted after standby was promoted at %s",
						str_time(ControlFile->checkPointCopy.time)),
				 errhint("If this has occurred more than once something unexpected is happening"
				" after standby has been promoted"),
				 errSendAlert(true)));
	else if (ControlFile->state == DB_IN_PRODUCTION)
		ereport(LOG,
6760
				(errmsg("database system was interrupted; last known up at %s",
6761 6762 6763 6764 6765 6766 6767 6768
						str_time(ControlFile->time))));

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

6769
	/*
6770 6771 6772
	 * Verify that pg_xlog and pg_xlog/archive_status exist.  In cases where
	 * someone has performed a copy for PITR, these directories may have been
	 * excluded and need to be re-created.
6773
	 */
6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796
	ValidateXLOGDirectoryStructure();

	/*
	 * Clear out any old relcache cache files.	This is *necessary* if we do
	 * any WAL replay, since that would probably result in the cache files
	 * being out of sync with database reality.  In theory we could leave them
	 * in place if the database had been cleanly shut down, but it seems
	 * safest to just remove them always and let them be rebuilt during the
	 * first backend startup.
	 */
	RelationCacheInitFileRemove();

	/*
	 * Initialize on the assumption we want to recover to the same timeline
	 * that's active according to pg_control.
	 */
	recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;

	/*
	 * Check for recovery control file, and if so set up state for offline
	 * recovery
	 */
	XLogReadRecoveryCommandFile(LOG);
6797

6798
	if (StandbyModeRequested)
T
Tom Lane 已提交
6799
	{
6800
		Assert(ControlFile->state != DB_IN_CRASH_RECOVERY);
6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825

		/*
		 * If the standby was promoted (last time) and recovery.conf
		 * is still found this time with standby mode request,
		 * it means the standby crashed post promotion but before recovery.conf
		 * cleanup. Hence, it is not considered a standby request this time.
		 */
		if (ControlFile->state == DB_IN_STANDBY_PROMOTED)
			StandbyModeRequested = false;
	}

	/* Now we can determine the list of expected TLIs */
	expectedTLIs = XLogReadTimeLineHistory(recoveryTargetTLI);

	/*
	 * 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,
						 (int) ControlFile->checkPointCopy.ThisTimeLineID))
		ereport(FATAL,
				(errmsg("requested timeline %u is not a child of database system timeline %u",
						recoveryTargetTLI,
						ControlFile->checkPointCopy.ThisTimeLineID)));
6826

6827
	/*
B
Bruce Momjian 已提交
6828 6829 6830
	 * Save the selected recovery target timeline ID and
	 * archive_cleanup_command in shared memory so that other processes can
	 * see them
6831 6832
	 */
	XLogCtl->RecoveryTargetTLI = recoveryTargetTLI;
6833 6834 6835
	strncpy(XLogCtl->archiveCleanupCommand,
			archiveCleanupCommand ? archiveCleanupCommand : "",
			sizeof(XLogCtl->archiveCleanupCommand));
6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847

	if (StandbyModeRequested)
		ereport(LOG,
				(errmsg("entering standby mode")));

	/*
	 * Take ownership of the wakeup latch if we're going to sleep during
	 * recovery.
	 */
	if (StandbyModeRequested)
		OwnLatch(&XLogCtl->recoveryWakeupLatch);

6848 6849 6850 6851 6852 6853 6854
	/*
	 * Allocate pages dedicated to WAL consistency checks, those had better
	 * be aligned.
	 */
	replay_image_masked = (char *) palloc(BLCKSZ);
	master_image_masked = (char *) palloc(BLCKSZ);

6855
	/*
6856
	 * Take ownership of the wakeup latch if we're going to sleep during
6857 6858 6859 6860 6861
	 * recovery.
	 */
	if (StandbyMode)
		OwnLatch(&XLogCtl->recoveryWakeupLatch);

6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877
	if (read_backup_label(&checkPointLoc, &backupEndRequired))
	{
		/*
		 * Currently, it is assumed that a backup file exists iff a base backup
		 * has been performed and then the recovery.conf file is generated, thus
		 * standby mode has to be requested
		 */
		if (!StandbyModeRequested)
			ereport(FATAL,
					(errmsg("Found backup.label file without any standby mode request")));

		/* Activate recovery in standby mode */
		StandbyMode = true;

		Assert(backupEndRequired);

6878
		/*
B
Bruce Momjian 已提交
6879 6880
		 * When a backup_label file is present, we want to roll forward from
		 * the checkpoint it identifies, rather than using pg_control.
6881
		 */
6882
		record = ReadCheckpointRecord(checkPointLoc, 0);
6883 6884
		if (record != NULL)
		{
6885 6886
			memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
			wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
6887
			ereport(DEBUG1,
6888
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
6889
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
6890
			InRecovery = true;	/* force recovery even if SHUTDOWNED */
6891 6892

			/*
6893 6894 6895 6896
			 * Make sure that REDO location exists. This may not be the case
			 * if there was a crash during an online backup, which left a
			 * backup_label around that references a WAL segment that's
			 * already been archived.
6897 6898 6899
			 */
			if (XLByteLT(checkPoint.redo, checkPointLoc))
			{
6900
				if (!XLogReadRecord(&(checkPoint.redo), LOG, false))
6901 6902 6903 6904
					ereport(FATAL,
							(errmsg("could not find redo location referenced by checkpoint record"),
							 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
			}
6905 6906 6907
		}
		else
		{
6908
			ereport(FATAL,
B
Bruce Momjian 已提交
6909 6910
					(errmsg("could not locate required checkpoint record"),
					 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6911
			wasShutdown = false;	/* keep compiler quiet */
6912
		}
6913 6914
		/* set flag to delete it later */
		haveBackupLabel = true;
T
Tom Lane 已提交
6915 6916 6917
	}
	else
	{
6918 6919 6920 6921 6922 6923
		if (StandbyModeRequested)
		{
			/* Activate recovery in standby mode */
			StandbyMode = true;
		}

6924
		/*
B
Bruce Momjian 已提交
6925 6926
		 * Get the last valid checkpoint record.  If the latest one according
		 * to pg_control is broken, try the next-to-last one.
6927 6928
		 */
		checkPointLoc = ControlFile->checkPoint;
6929
		RedoStartLSN = ControlFile->checkPointCopy.redo;
6930
		record = ReadCheckpointRecord(checkPointLoc, 1);
T
Tom Lane 已提交
6931 6932
		if (record != NULL)
		{
6933
			ereport(DEBUG1,
6934
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
6935
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
T
Tom Lane 已提交
6936
		}
6937 6938 6939 6940 6941 6942 6943 6944 6945
		else if (StandbyMode)
		{
			/*
			 * The last valid checkpoint record required for a streaming
			 * recovery exists in neither standby nor the primary.
			 */
			ereport(PANIC,
					(errmsg("could not locate a valid checkpoint record")));
		}
T
Tom Lane 已提交
6946
		else
6947
		{
6948 6949
			printEndOfXLogFile(&checkPointLoc);

6950
			checkPointLoc = ControlFile->prevCheckPoint;
6951
			record = ReadCheckpointRecord(checkPointLoc, 2);
6952 6953 6954
			if (record != NULL)
			{
				ereport(LOG,
B
Bruce Momjian 已提交
6955 6956 6957
						(errmsg("using previous checkpoint record at %X/%X",
							  checkPointLoc.xlogid, checkPointLoc.xrecoff)));
				InRecovery = true;		/* force recovery even if SHUTDOWNED */
6958 6959
			}
			else
6960 6961
			{
				printEndOfXLogFile(&checkPointLoc);
6962
				ereport(PANIC,
B
Bruce Momjian 已提交
6963
					 (errmsg("could not locate a valid checkpoint record")));
6964
			}
6965
		}
6966 6967
		memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
		wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
T
Tom Lane 已提交
6968
	}
6969

T
Tom Lane 已提交
6970
	LastRec = RecPtr = checkPointLoc;
6971

6972 6973 6974 6975
	CheckpointExtendedRecord ckptExtended;
	UnpackCheckPointRecord(record, &ckptExtended);
	if (ckptExtended.ptas)
		SetupCheckpointPreparedTransactionList(ckptExtended.ptas);
6976 6977 6978 6979 6980 6981

	/*
	 * Find Xacts that are distributed committed from the checkpoint record and
	 * store them such that they can utilized later during DTM recovery.
	 */
	XLogProcessCheckpointRecord(record, checkPointLoc);
6982

6983
	ereport(DEBUG1,
B
Bruce Momjian 已提交
6984 6985 6986
			(errmsg("redo record is at %X/%X; shutdown %s",
					checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
					wasShutdown ? "TRUE" : "FALSE")));
6987
	ereport(DEBUG1,
6988
			(errmsg("next transaction ID: %u/%u; next OID: %u; next relfilenode: %u",
6989
					checkPoint.nextXidEpoch, checkPoint.nextXid,
6990
					checkPoint.nextOid, checkPoint.nextRelfilenode)));
6991
	ereport(DEBUG1,
6992 6993
			(errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
					checkPoint.nextMulti, checkPoint.nextMultiOffset)));
6994 6995 6996
	ereport(DEBUG1,
			(errmsg("oldest unfrozen transaction ID: %u, in database %u",
					checkPoint.oldestXid, checkPoint.oldestXidDB)));
6997
	if (!TransactionIdIsNormal(checkPoint.nextXid))
6998
		ereport(PANIC,
6999
				(errmsg("invalid next transaction ID")));
7000

7001
	/* initialize shared memory variables from the checkpoint record */
7002 7003
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
7004
	ShmemVariableCache->oidCount = 0;
7005 7006
	ShmemVariableCache->nextRelfilenode = checkPoint.nextRelfilenode;
	ShmemVariableCache->relfilenodeCount = 0;
7007
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
7008
	SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
7009 7010
	XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
	XLogCtl->ckptXid = checkPoint.nextXid;
7011

7012
	/*
B
Bruce Momjian 已提交
7013 7014 7015
	 * 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()).
7016
	 */
7017
	ThisTimeLineID = checkPoint.ThisTimeLineID;
7018

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

7021
	if (XLByteLT(RecPtr, checkPoint.redo))
7022 7023
		ereport(PANIC,
				(errmsg("invalid redo in checkpoint record")));
7024

7025
	/*
B
Bruce Momjian 已提交
7026
	 * Check whether we need to force recovery from WAL.  If it appears to
B
Bruce Momjian 已提交
7027 7028
	 * have been a clean shutdown and we did not have a recovery.conf file,
	 * then assume no recovery needed.
7029
	 */
7030
	if (XLByteLT(checkPoint.redo, RecPtr))
7031
	{
T
Tom Lane 已提交
7032
		if (wasShutdown)
7033
			ereport(PANIC,
B
Bruce Momjian 已提交
7034
					(errmsg("invalid redo record in shutdown checkpoint")));
V
WAL  
Vadim B. Mikheev 已提交
7035
		InRecovery = true;
7036
	}
7037
	else if (StandbyModeRequested)
7038 7039
	{
		/* force recovery due to presence of recovery.conf */
7040 7041
		ereport(LOG,
				(errmsg("setting recovery standby mode active")));
7042 7043
		InRecovery = true;
	}
7044 7045 7046 7047 7048 7049 7050 7051 7052 7053
	else if (ControlFile->state != DB_SHUTDOWNED)
		InRecovery = true;

	if (InRecovery && !IsUnderPostmaster)
	{
		ereport(FATAL,
				(errmsg("Database must be shutdown cleanly when using single backend start")));
	}

	/* Recovery from xlog */
7054
	if (InRecovery)
7055
	{
B
Bruce Momjian 已提交
7056
		int			rmid;
7057

7058 7059 7060
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

7061
		/*
B
Bruce Momjian 已提交
7062 7063
		 * 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
7064
		 * pg_control with any minimum recovery stop point
7065
		 */
7066
		if (StandbyMode)
7067
		{
7068
			ereport(LOG,
7069 7070
					(errmsg("recovery in standby mode in progress")));
			ControlFile->state = DB_IN_STANDBY_MODE;
7071
		}
7072
		else
7073
		{
7074
			ereport(LOG,
7075 7076
					(errmsg("database system was not properly shut down; "
							"automatic recovery in progress")));
7077

7078
			if (ControlFile->state != DB_IN_STANDBY_PROMOTED)
7079
				ControlFile->state = DB_IN_CRASH_RECOVERY;
7080
		}
7081

7082 7083 7084
		ControlFile->prevCheckPoint = ControlFile->checkPoint;
		ControlFile->checkPoint = checkPointLoc;
		ControlFile->checkPointCopy = checkPoint;
7085 7086 7087 7088 7089 7090 7091 7092

		if (StandbyMode)
		{
			/* initialize minRecoveryPoint if not set yet */
			if (XLByteLT(ControlFile->minRecoveryPoint, checkPoint.redo))
				ControlFile->minRecoveryPoint = checkPoint.redo;
		}

7093
		/*
7094
		 * set backupStartPoint if we're starting recovery from a base backup
7095
		 */
7096 7097 7098 7099 7100 7101 7102
		if (haveBackupLabel)
		{
			Assert(ControlFile->state == DB_IN_STANDBY_MODE);
			ControlFile->backupStartPoint = checkPoint.redo;
			ControlFile->backupEndRequired = backupEndRequired;
		}

7103
		ControlFile->time = (pg_time_t) time(NULL);
7104
		/* No need to hold ControlFileLock yet, we aren't up far enough */
7105 7106
		UpdateControlFile();

7107 7108
		/* initialize our local copy of minRecoveryPoint */
		minRecoveryPoint = ControlFile->minRecoveryPoint;
7109

7110 7111 7112
		/*
		 * Reset pgstat data, because it may be invalid after recovery.
		 */
7113 7114
		pgstat_reset_all();

7115
		/*
B
Bruce Momjian 已提交
7116 7117 7118 7119 7120 7121
		 * 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.
7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132
		 */
		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)));
		}

7133 7134 7135
		/* Check that the GUCs used to generate the WAL allow recovery */
		CheckRequiredParameterValues();

7136
		UtilityModeFindOrCreateDtmRedoFile();
7137
		
R
Robert Haas 已提交
7138 7139
		/*
		 * We're in recovery, so unlogged relations relations may be trashed
7140 7141 7142
		 * and must be reset.  This should be done BEFORE allowing Hot Standby
		 * connections, so that read-only backends don't try to read whatever
		 * garbage is left over from before.
R
Robert Haas 已提交
7143 7144 7145
		 */
		ResetUnloggedRelations(UNLOGGED_RELATION_CLEANUP);

7146
		/*
B
Bruce Momjian 已提交
7147 7148
		 * Initialize for Hot Standby, if enabled. We won't let backends in
		 * yet, not until we've reached the min recovery point specified in
B
Bruce Momjian 已提交
7149
		 * control file and we've established a recovery snapshot from a
7150 7151
		 * running-xacts WAL record.
		 */
7152
		if (InArchiveRecovery && EnableHotStandby)
7153 7154
		{
			TransactionId *xids;
B
Bruce Momjian 已提交
7155
			int			nxids;
7156

7157
			ereport(DEBUG1,
7158
					(errmsg("initializing for hot standby")));
7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171

			InitRecoveryTransactionEnvironment();

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

			/* Startup commit log and related stuff */
			StartupCLOG();
			StartupSUBTRANS(oldestActiveXID);
			StartupMultiXact();
7172 7173
			DistributedLog_Startup(oldestActiveXID,
								   ShmemVariableCache->nextXid);
7174

7175 7176
			/*
			 * If we're beginning at a shutdown checkpoint, we know that
B
Bruce Momjian 已提交
7177 7178 7179
			 * nothing was running on the master at this point. So fake-up an
			 * empty running-xacts record and use that here and now. Recover
			 * additional standby state for prepared transactions.
7180 7181 7182 7183
			 */
			if (wasShutdown)
			{
				RunningTransactionsData running;
7184
				TransactionId latestCompletedXid;
7185 7186

				/*
B
Bruce Momjian 已提交
7187 7188 7189 7190
				 * Construct a RunningTransactions snapshot representing a
				 * shut down server, with only prepared transactions still
				 * alive. We're never overflowed at this point because all
				 * subxids are listed with their parent prepared transactions.
7191 7192 7193 7194 7195
				 */
				running.xcnt = nxids;
				running.subxid_overflow = false;
				running.nextXid = checkPoint.nextXid;
				running.oldestRunningXid = oldestActiveXID;
7196 7197
				latestCompletedXid = checkPoint.nextXid;
				TransactionIdRetreat(latestCompletedXid);
7198
				Assert(TransactionIdIsNormal(latestCompletedXid));
7199
				running.latestCompletedXid = latestCompletedXid;
7200 7201 7202 7203 7204 7205
				running.xids = xids;

				ProcArrayApplyRecoveryInfo(&running);

				StandbyRecoverPreparedTransactions(false);
			}
7206
		}
7207

7208
		/* Initialize resource managers */
7209 7210 7211 7212 7213 7214
		for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
		{
			if (RmgrTable[rmid].rm_startup != NULL)
				RmgrTable[rmid].rm_startup();
		}

7215
		/*
7216 7217 7218
		 * Initialize shared variables for tracking progress of WAL replay,
		 * as if we had just replayed the record before the REDO location
		 * (or the checkpoint record itself, if it's a shutdown checkpoint).
7219 7220
		 */
		SpinLockAcquire(&xlogctl->info_lck);
7221 7222 7223 7224 7225
		if (XLByteLT(checkPoint.redo, RecPtr))
			xlogctl->replayEndRecPtr = checkPoint.redo;
		else
			xlogctl->replayEndRecPtr = EndRecPtr;
		xlogctl->lastReplayedEndRecPtr = xlogctl->replayEndRecPtr;
7226
		xlogctl->recoveryLastXTime = 0;
7227
		xlogctl->currentChunkStartTime = 0;
7228
		xlogctl->recoveryPause = false;
7229 7230 7231 7232 7233
		SpinLockRelease(&xlogctl->info_lck);

		/* Also ensure XLogReceiptTime has a sane value */
		XLogReceiptTime = GetCurrentTimestamp();

7234
		/*
B
Bruce Momjian 已提交
7235 7236 7237 7238 7239
		 * Let postmaster know we've started redo now, so that it can launch
		 * bgwriter to perform restartpoints.  We don't bother during crash
		 * recovery as restartpoints can only be performed during archive
		 * recovery.  And we'd like to keep crash recovery simple, to avoid
		 * introducing bugs that could affect you when recovering after crash.
7240 7241 7242 7243 7244 7245 7246
		 *
		 * After this point, we can no longer assume that we're the only
		 * process in addition to postmaster!  Also, fsync requests are
		 * subsequently to be handled by the bgwriter, not locally.
		 */
		if (InArchiveRecovery && IsUnderPostmaster)
		{
7247
			PublishStartupProcessInformation();
7248 7249 7250 7251 7252 7253
			SetForwardFsyncRequests();
			SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED);
			bgwriterLaunched = true;
		}

		/*
B
Bruce Momjian 已提交
7254 7255
		 * Allow read-only connections immediately if we're consistent
		 * already.
7256 7257 7258
		 */
		CheckRecoveryConsistency();

7259 7260
		/*
		 * Find the first record that logically follows the checkpoint --- it
B
Bruce Momjian 已提交
7261
		 * might physically precede it, though.
7262
		 */
7263
		if (XLByteLT(checkPoint.redo, RecPtr))
7264 7265
		{
			/* back up to find the record */
7266
			record = XLogReadRecord(&(checkPoint.redo), PANIC, false);
7267
		}
B
Bruce Momjian 已提交
7268
		else
7269
		{
7270
			/* just have to read next record after CheckPoint */
7271
			record = XLogReadRecord(NULL, LOG, false);
7272 7273 7274 7275 7276
		}

		/*
		 * main redo apply loop, executed if we have record after checkpoint
		 */
T
Tom Lane 已提交
7277
		if (record != NULL)
7278
		{
7279 7280
			bool		recoveryContinue = true;
			bool		recoveryApply = true;
7281
			bool		recoveryPause = false;
7282
			TimestampTz xtime;
7283

7284
			InRedo = true;
7285

7286 7287 7288
			ereport(LOG,
					(errmsg("redo starts at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
7289

7290 7291 7292
			/*
			 * main redo apply loop
			 */
7293 7294
			do
			{
A
Asim R P 已提交
7295 7296
				// GPDB_91_MERGE_FIXME
#if 0
7297
#ifdef WAL_DEBUG
7298
				if (XLOG_DEBUG ||
B
Bruce Momjian 已提交
7299
				 (rmid == RM_XACT_ID && trace_recovery_messages <= DEBUG2) ||
7300
					(rmid != RM_XACT_ID && trace_recovery_messages <= DEBUG3))
7301
				{
B
Bruce Momjian 已提交
7302
					StringInfoData buf;
V
WAL  
Vadim B. Mikheev 已提交
7303

7304 7305
					initStringInfo(&buf);
					appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
B
Bruce Momjian 已提交
7306 7307
									 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
									 EndRecPtr.xlogid, EndRecPtr.xrecoff);
7308 7309 7310
					xlog_outrec(&buf, record);
					appendStringInfo(&buf, " - ");
					RmgrTable[record->xl_rmid].rm_desc(&buf,
B
Bruce Momjian 已提交
7311
													 XLogRecGetData(record));
7312 7313
					elog(LOG, "%s", buf.data);
					pfree(buf.data);
7314
				}
7315
#endif
A
Asim R P 已提交
7316
#endif
7317 7318
				/* Handle interrupt signals of startup process */
				HandleStartupProcInterrupts();
7319

7320 7321 7322 7323 7324
				/*
				 * Have we reached our recovery target?
				 */
				if (recoveryStopsHere(record, &recoveryApply))
				{
7325
					/*
7326 7327
					 * Pause only if users can connect to send a resume
					 * message
7328 7329
					 */
					if (recoveryPauseAtTarget && standbyState == STANDBY_SNAPSHOT_READY)
7330 7331 7332 7333
					{
						SetRecoveryPause(true);
						recoveryPausesHere();
					}
B
Bruce Momjian 已提交
7334
					reachedStopPoint = true;	/* see below */
7335 7336 7337 7338 7339
					recoveryContinue = false;
					if (!recoveryApply)
						break;
				}

7340
				/*
7341 7342 7343
				 * See if this record is a checkpoint, if yes then uncover it to
				 * find distributed committed Xacts.
				 * No need to unpack checkpoint in crash recovery mode
7344
				 */
7345 7346 7347 7348 7349 7350
				uint8 xlogRecInfo = record->xl_info & ~XLR_INFO_MASK;

				if (IsStandbyMode() &&
					record->xl_rmid == RM_XLOG_ID &&
					(xlogRecInfo == XLOG_CHECKPOINT_SHUTDOWN
					 || xlogRecInfo == XLOG_CHECKPOINT_ONLINE))
7351
				{
7352 7353 7354
					XLogProcessCheckpointRecord(record, ReadRecPtr);
					memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
				}
7355

7356 7357 7358 7359 7360 7361
				/*
				 * Update shared replayEndRecPtr before replaying this record,
				 * so that XLogFlush will update minRecoveryPoint correctly.
				 */
				SpinLockAcquire(&xlogctl->info_lck);
				xlogctl->replayEndRecPtr = EndRecPtr;
7362
				recoveryPause = xlogctl->recoveryPause;
7363
				SpinLockRelease(&xlogctl->info_lck);
7364

7365 7366 7367 7368
				/*
				 * Pause only if users can connect to send a resume message
				 */
				if (recoveryPause && standbyState == STANDBY_SNAPSHOT_READY)
7369 7370
					recoveryPausesHere();

B
Bruce Momjian 已提交
7371 7372 7373 7374
				/*
				 * If we are attempting to enter Hot Standby mode, process
				 * XIDs we see
				 */
7375 7376
				if (standbyState >= STANDBY_INITIALIZED &&
					TransactionIdIsValid(record->xl_xid))
7377 7378
					RecordKnownAssignedTransactionIds(record->xl_xid);

7379
				ApplyStartupRedo(&ReadRecPtr, &EndRecPtr, record);
7380

7381 7382 7383 7384 7385 7386 7387
				/*
				 * Update lastReplayedEndRecPtr after this record has been
				 * successfully replayed.
				 */
				SpinLockAcquire(&xlogctl->info_lck);
				xlogctl->lastReplayedEndRecPtr = EndRecPtr;
				SpinLockRelease(&xlogctl->info_lck);
7388

7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401
				/*
				 * GPDB_84_MERGE_FIXME: Create restartpoints aggressively.
				 *
				 * In PostgreSQL, the bgwriter creates restartpoints during archive
				 * recovery at its own leisure. In GDPB, with WAL replication based
				 * mirroring, that was tripping the gp_replica_check checks, because
				 * it bypasses the shared buffer cache and reads directly from disk.
				 * For now, restore the old behavior, before the upstream change
				 * to start bgwriter during archive recovery, and create a
				 * restartpoint immediately after replaying a checkpoint record.
				 */
				{
					uint8 xlogRecInfo = record->xl_info & ~XLR_INFO_MASK;
7402

7403 7404 7405
					if (record->xl_rmid == RM_XLOG_ID &&
						(xlogRecInfo == XLOG_CHECKPOINT_SHUTDOWN ||
						 xlogRecInfo == XLOG_CHECKPOINT_ONLINE))
7406
					{
7407 7408 7409 7410
						if (bgwriterLaunched)
							RequestCheckpoint(CHECKPOINT_IMMEDIATE | CHECKPOINT_WAIT);
						else
							CreateRestartPoint(CHECKPOINT_IMMEDIATE);
7411
					}
7412
				}
7413

7414 7415 7416 7417 7418 7419 7420 7421
				/*
				 * Update shared recoveryLastRecPtr after this record has been
				 * replayed.
				 */
				SpinLockAcquire(&xlogctl->info_lck);
				xlogctl->recoveryLastRecPtr = EndRecPtr;
				SpinLockRelease(&xlogctl->info_lck);

7422 7423
				LastRec = ReadRecPtr;

7424 7425
				/* Allow read-only connections if we're consistent now */
				CheckRecoveryConsistency();
B
Bruce Momjian 已提交
7426

7427
				record = XLogReadRecord(NULL, LOG, false);
7428
			} while (record != NULL && recoveryContinue);
7429

7430 7431 7432
			ereport(LOG,
					(errmsg("redo done at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
7433 7434
			xtime = GetLatestXTime();
			if (xtime)
7435
				ereport(LOG,
B
Bruce Momjian 已提交
7436
					 (errmsg("last completed transaction was at log time %s",
7437
							 timestamptz_to_str(xtime))));
V
WAL  
Vadim B. Mikheev 已提交
7438
			InRedo = false;
7439
		}
7440 7441 7442
		/*
		 * end of main redo apply loop
		 */
V
WAL  
Vadim B. Mikheev 已提交
7443 7444
	}

T
Tom Lane 已提交
7445
	/*
7446 7447 7448
	 * Kill WAL receiver, if it's still running, before we continue to write
	 * the startup checkpoint record. It will trump over the checkpoint and
	 * subsequent records if it's still alive when we start writing WAL.
T
Tom Lane 已提交
7449
	 */
7450
	ShutdownWalRcv();
7451

7452
	/*
7453 7454 7455 7456 7457 7458 7459 7460
	 * We don't need the latch anymore. It's not strictly necessary to disown
	 * it, but let's do it for the sake of tidiness.
	 */
	if (StandbyModeRequested)
		DisownLatch(&XLogCtl->recoveryWakeupLatch);

	/*
	 * We are now done reading the xlog from stream.
7461
	 */
7462
	if (StandbyMode)
7463
	{
7464 7465 7466
		Assert(ControlFile->state == DB_IN_STANDBY_MODE);
		StandbyMode = false;

7467 7468
		elog(LOG, "updating pg_control to state DB_IN_STANDBY_PROMOTED");

7469 7470
		/* Transition to promoted mode */
		ControlFile->state = DB_IN_STANDBY_PROMOTED;
7471
		ControlFile->time = (pg_time_t) time(NULL);
7472
		UpdateControlFile();
7473 7474
	}

7475
	/*
7476 7477 7478
	 * Kill WAL receiver, if it's still running, before we continue to write
	 * the startup checkpoint record. It will trump over the checkpoint and
	 * subsequent records if it's still alive when we start writing WAL.
7479
	 */
7480
	ShutdownWalRcv();
7481

7482 7483
	/*
	 * We don't need the latch anymore. It's not strictly necessary to disown
7484
	 * it, but let's do it for the sake of tidiness.
7485
	 */
7486 7487
	if (StandbyMode)
		DisownLatch(&XLogCtl->recoveryWakeupLatch);
7488 7489 7490

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

7496
	/*
7497 7498 7499
	 * 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.
	 */
7500
	record = XLogReadRecord(&LastRec, PANIC, false);
7501 7502 7503 7504 7505 7506 7507 7508
	EndOfLog = EndRecPtr;
	XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);

	elog(LOG,"end of transaction log location is %s",
		 XLogLocationToString(&EndOfLog));

	/*
	 * Complain if we did not roll forward far enough to render the backup
7509 7510 7511 7512
	 * dump consistent.  Note: it is indeed okay to look at the local variable
	 * minRecoveryPoint here, even though ControlFile->minRecoveryPoint might
	 * be further ahead --- ControlFile->minRecoveryPoint cannot have been
	 * advanced beyond the WAL we processed.
7513
	 */
7514 7515 7516
	if (InRecovery &&
		(XLByteLT(EndOfLog, ControlFile->minRecoveryPoint) ||
		 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint)))
7517
	{
7518 7519 7520
		if (reachedStopPoint)
		{
			/* stopped because of stop request */
7521
			ereport(FATAL,
7522
					(errmsg("requested recovery stop point is before consistent recovery point")));
7523
		}
7524

7525 7526 7527 7528 7529 7530 7531 7532 7533
		/*
		 * Ran off end of WAL before reaching end-of-backup WAL record, or
		 * minRecoveryPoint. That's usually a bad sign, indicating that you
		 * tried to recover from an online backup but never called
		 * pg_stop_backup(), or you didn't archive all the WAL up to that
		 * point. However, this also happens in crash recovery, if the system
		 * crashes while an online backup is in progress. We must not treat
		 * that as an error, or the database will refuse to start up.
		 */
7534
		// WALREP_FIXME: But we should probably do this check in standby mode, too
7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548
		if (StandbyModeRequested || ControlFile->backupEndRequired)
		{
			if (ControlFile->backupEndRequired)
				ereport(FATAL,
						(errmsg("WAL ends before end of online backup"),
						 errhint("All WAL generated while online backup was taken must be available at recovery.")));
			else if (!XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
				ereport(FATAL,
						(errmsg("WAL ends before end of online backup"),
						 errhint("Online backup should be complete, and all WAL up to that point must be available at recovery.")));
			else
				ereport(FATAL,
					  (errmsg("WAL ends before consistent recovery point")));
		}
7549 7550
	}

7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574
	/*
	 * Consider whether we need to assign a new timeline ID.
	 *
	 * 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
	 * 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
	 * current last segment is problematic because it may result in trying to
	 * overwrite an already-archived copy of that segment, and we encourage
	 * 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.
	 *
	 * GPDB: Greenplum doesn't support archive recovery.
	 */
	if (InArchiveRecovery)
	{
		ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
		ereport(LOG,
				(errmsg("selected new timeline ID: %u", ThisTimeLineID)));
		writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
							 curFileTLI, endLogId, endLogSeg);
	}
7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587
	else if (ControlFile->state == DB_IN_STANDBY_PROMOTED)
	{
		/*
		 * If standby is promoted, we should advance timeline ID.
		 */
		ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
		ereport(LOG,
				(errmsg("selected new timeline ID: %u", ThisTimeLineID)));
		writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
							 curFileTLI, endLogId, endLogSeg);

		XLogFileCopy(endLogId, endLogSeg, curFileTLI, endLogId, endLogSeg);
	}
7588

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

7592 7593 7594 7595 7596 7597 7598 7599 7600
	/*
	 * 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.)
	 */
	if (InArchiveRecovery)
		exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);

7601 7602 7603 7604 7605 7606
	/*
	 * Recovery command file must be deleted during promotion to prevent
	 * StartupXLOG from incorrectly concluding that we are still a standby.
	 * This could happen if the promoted standby goes through a restart.
	 */
	if (ControlFile->state == DB_IN_STANDBY_PROMOTED)
7607 7608
	{
		elog(LOG, "pg_control state is DB_IN_STANDBY_PROMOTED hence renaming recovery file");
7609
		renameRecoveryFile();
7610
	}
7611

7612 7613 7614 7615 7616 7617 7618
	/*
	 * 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;
7619
	openLogFile = XLogFileOpen(openLogId, openLogSeg);
T
Tom Lane 已提交
7620
	openLogOff = 0;
V
WAL  
Vadim B. Mikheev 已提交
7621
	Insert = &XLogCtl->Insert;
7622
	Insert->PrevRecord = LastRec;
7623 7624
	XLogCtl->xlblocks[0].xlogid = openLogId;
	XLogCtl->xlblocks[0].xrecoff =
7625
		((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
B
Bruce Momjian 已提交
7626 7627

	/*
B
Bruce Momjian 已提交
7628 7629 7630
	 * 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 已提交
7631
	 */
7632 7633
	Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
	memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
7634
	Insert->currpos = (char *) Insert->currpage +
7635
		(EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
V
WAL  
Vadim B. Mikheev 已提交
7636

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

T
Tom Lane 已提交
7639 7640 7641
	XLogCtl->Write.LogwrtResult = LogwrtResult;
	Insert->LogwrtResult = LogwrtResult;
	XLogCtl->LogwrtResult = LogwrtResult;
V
WAL  
Vadim B. Mikheev 已提交
7642

T
Tom Lane 已提交
7643 7644
	XLogCtl->LogwrtRqst.Write = EndOfLog;
	XLogCtl->LogwrtRqst.Flush = EndOfLog;
7645

7646 7647 7648 7649 7650 7651 7652 7653 7654 7655
	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 已提交
7656 7657
		 * Whenever Write.LogwrtResult points to exactly the end of a page,
		 * Write.curridx must point to the *next* page (see XLogWrite()).
7658
		 *
B
Bruce Momjian 已提交
7659
		 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
B
Bruce Momjian 已提交
7660
		 * this is sufficient.	The first actual attempt to insert a log
7661
		 * record will advance the insert state.
7662 7663 7664 7665
		 */
		XLogCtl->Write.curridx = NextBufIdx(0);
	}

7666
	/* Pre-scan prepared transactions to find out the range of XIDs present */
7667
	oldestActiveXID = PrescanPreparedTransactions(NULL, NULL);
7668

V
WAL  
Vadim B. Mikheev 已提交
7669
	if (InRecovery)
7670
	{
7671 7672 7673
		/*
		 * Close down Recovery for Startup PASS 1.
		 */
B
Bruce Momjian 已提交
7674
		int			rmid;
7675

7676 7677 7678 7679 7680 7681 7682
		/*
		 * Resource managers might need to write WAL records, eg, to record
		 * index cleanup actions.  So temporarily enable XLogInsertAllowed in
		 * this process only.
		 */
		LocalSetXLogInsertAllowed();

7683 7684 7685 7686 7687 7688 7689 7690 7691
		/*
		 * 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();
		}

7692 7693 7694
		/* Disallow XLogInsert again */
		LocalXLogInsertAllowed = -1;

7695 7696 7697 7698 7699 7700
		/*
		 * Check to see if the XLOG sequence contained any unresolved
		 * references to uninitialized pages.
		 */
		XLogCheckInvalidPages();

7701 7702 7703 7704 7705
		/*
		 * Reset pgstat data, because it may be invalid after recovery.
		 */
		pgstat_reset_all();

T
Tom Lane 已提交
7706
		/*
7707
		 * Perform a checkpoint to update all our recovery activity to disk.
7708
		 *
7709 7710 7711 7712 7713
		 * 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 已提交
7714
		 */
7715 7716 7717 7718 7719 7720
		if (bgwriterLaunched)
			RequestCheckpoint(CHECKPOINT_END_OF_RECOVERY |
							  CHECKPOINT_IMMEDIATE |
							  CHECKPOINT_WAIT);
		else
			CreateCheckPoint(CHECKPOINT_END_OF_RECOVERY | CHECKPOINT_IMMEDIATE);
7721

7722
		UtilityModeCloseDtmRedoFile();
7723

T
Tom Lane 已提交
7724 7725 7726
		/*
		 * And finally, execute the recovery_end_command, if any.
		 */
7727
#if 0
7728
		if (recoveryEndCommand)
7729 7730 7731
			ExecuteRecoveryCommand(recoveryEndCommand,
								   "recovery_end_command",
								   true);
7732
#endif
7733
	}
7734

T
Tom Lane 已提交
7735 7736 7737
	/*
	 * Preallocate additional log files, if wanted.
	 */
7738
	PreallocXlogFiles(EndOfLog);
7739

R
Robert Haas 已提交
7740 7741 7742 7743 7744 7745 7746 7747
	/*
	 * Reset initial contents of unlogged relations.  This has to be done
	 * AFTER recovery is complete so that any unlogged relations created
	 * during recovery also get picked up.
	 */
	if (InRecovery)
		ResetUnloggedRelations(UNLOGGED_RELATION_INIT);

7748
	/*
7749
	 * Okay, we're officially UP.
7750
	 */
V
WAL  
Vadim B. Mikheev 已提交
7751
	InRecovery = false;
7752

7753
	/* start the archive_timeout timer running */
7754
	XLogCtl->Write.lastSegSwitchTime = (pg_time_t) time(NULL);
7755

7756 7757 7758 7759 7760 7761
	/* also initialize latestCompletedXid, to nextXid - 1 */
	ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
	TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);
	elog(LOG, "latest completed transaction id is %u and next transaction id is %u",
		ShmemVariableCache->latestCompletedXid,
		ShmemVariableCache->nextXid);
T
Tom Lane 已提交
7762 7763

	/*
B
Bruce Momjian 已提交
7764 7765
	 * Start up the commit log and related stuff, too. In hot standby mode we
	 * did this already before WAL replay.
T
Tom Lane 已提交
7766
	 */
7767 7768 7769 7770 7771
	if (standbyState == STANDBY_DISABLED)
	{
		StartupCLOG();
		StartupSUBTRANS(oldestActiveXID);
		StartupMultiXact();
7772 7773
		DistributedLog_Startup(oldestActiveXID,
							   ShmemVariableCache->nextXid);
7774
	}
7775

7776 7777
	/* Reload shared-memory state for prepared transactions */
	RecoverPreparedTransactions();
7778

7779 7780 7781 7782 7783 7784
	/*
	 * If we are a standby with contentid -1 and undergoing promotion,
	 * update ourselves as the new master in catalog.  This does not
	 * apply to a mirror (standby of a GPDB segment) because it is
	 * managed by FTS.
	 */
7785
	bool needToPromoteCatalog = (IS_QUERY_DISPATCHER() &&
7786
								 ControlFile->state == DB_IN_STANDBY_PROMOTED);
7787

7788
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7789 7790 7791 7792
	ControlFile->state = DB_IN_PRODUCTION;
	ControlFile->time = (pg_time_t) time(NULL);
	UpdateControlFile();
	ereport(LOG, (errmsg("database system is ready")));
7793
	LWLockRelease(ControlFileLock);
V
Vadim B. Mikheev 已提交
7794

7795 7796 7797 7798 7799 7800 7801
	/*
	 * Shutdown the recovery environment. This must occur after
	 * RecoverPreparedTransactions(), see notes for lock_twophase_recover()
	 */
	if (standbyState != STANDBY_DISABLED)
		ShutdownRecoveryTransactionEnvironment();

T
Tom Lane 已提交
7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812
	/* Shut down readFile facility, free space */
	if (readFile >= 0)
	{
		close(readFile);
		readFile = -1;
	}
	if (readBuf)
	{
		free(readBuf);
		readBuf = NULL;
	}
7813
	if (readRecordBuf)
7814
	{
7815
		char version[512];
7816

7817
		strcpy(version, PG_VERSION_STR " compiled on " __DATE__ " " __TIME__);
7818

7819 7820 7821 7822
#ifdef USE_ASSERT_CHECKING
		strcat(version, " (with assert checking)");
#endif
		ereport(LOG,(errmsg("%s", version)));
7823

7824
	}
T
Tom Lane 已提交
7825

7826 7827 7828 7829 7830 7831 7832
	/*
	 * If any of the critical GUCs have changed, log them before we allow
	 * backends to write WAL.
	 */
	LocalSetXLogInsertAllowed();
	XLogReportParameters();

7833
	/*
7834 7835 7836 7837
	 * All done.  Allow backends to write WAL.	(Although the bool flag is
	 * probably atomic in itself, we use the info_lck here to ensure that
	 * there are no race conditions concerning visibility of other recent
	 * updates to shared memory.)
7838
	 */
7839
	{
7840 7841
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;
7842

7843 7844 7845
		SpinLockAcquire(&xlogctl->info_lck);
		xlogctl->SharedRecoveryInProgress = false;
		SpinLockRelease(&xlogctl->info_lck);
7846 7847
	}

7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858
	/*
	 * Now we can update the catalog to tell the system is fully-promoted,
	 * if was standby.  This should be done after all WAL-replay finished
	 * otherwise we'll be in inconsistent state where catalog says I'm in
	 * primary state while the recovery is trying to stream.
	 */
	if (needToPromoteCatalog)
	{
		UpdateCatalogForStandbyPromotion();
	}

7859
	XLogCloseReadRecord();
7860
}
7861 7862

/*
7863 7864 7865 7866 7867 7868 7869 7870 7871 7872
 * Determine the recovery redo start location from the pg_control file.
 *
 *    1) Only uses information from the pg_control file.
 *    2) This simplified routine does not examine the offline recovery file or
 *       the online backup labels, etc.
 *    3) This routine is a heavily reduced version of StartXLOG.
 *    4) IMPORTANT NOTE: This routine sets global variables that establish
 *       the timeline context necessary to do ReadRecord.  The ThisTimeLineID
 *       and expectedTLIs globals are set.
 *
7873
 */
7874 7875
void
XLogGetRecoveryStart(char *callerStr, char *reasonStr, XLogRecPtr *redoCheckPointLoc, CheckPoint *redoCheckPoint)
7876
{
7877 7878 7879 7880 7881
	CheckPoint	checkPoint;
	XLogRecPtr	checkPointLoc;
	XLogRecord *record;
	bool previous;
	XLogRecPtr checkPointLSN;
7882

7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893
	Assert(redoCheckPointLoc != NULL);
	Assert(redoCheckPoint != NULL);

	XLogCloseReadRecord();

	/*
	 * Read control file and verify XLOG status looks valid.
	 *
	 */
	ReadControlFile();

7894
	if (ControlFile->state < DB_SHUTDOWNED ||
7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917
		ControlFile->state > DB_IN_PRODUCTION ||
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
		ereport(FATAL,
				(errmsg("%s: control file contains invalid data", callerStr)));

	/*
	 * Get the last valid checkpoint record.  If the latest one according
	 * to pg_control is broken, try the next-to-last one.
	 */
	checkPointLoc = ControlFile->checkPoint;
	ThisTimeLineID = ControlFile->checkPointCopy.ThisTimeLineID;

	/*
	 * Check for recovery control file, and if so set up state for offline
	 * recovery
	 */
	XLogReadRecoveryCommandFile(DEBUG5);

	/* Now we can determine the list of expected TLIs */
	expectedTLIs = XLogReadTimeLineHistory(ThisTimeLineID);

	record = ReadCheckpointRecord(checkPointLoc, 1);
	if (record != NULL)
7918
	{
7919
		previous = false;
7920
	}
7921
	else
7922
	{
7923 7924 7925 7926 7927
		previous = true;
		checkPointLoc = ControlFile->prevCheckPoint;
		record = ReadCheckpointRecord(checkPointLoc, 2);
		if (record != NULL)
		{
7928
			ereport(LOG,
7929 7930 7931 7932 7933 7934 7935 7936 7937 7938
					(errmsg("%s: using previous checkpoint record at %s (LSN %s)",
						    callerStr,
							XLogLocationToString(&checkPointLoc),
						    XLogLocationToString2(&EndRecPtr))));
		}
		else
		{
			ereport(ERROR,
				 (errmsg("%s: could not locate a valid checkpoint record", callerStr)));
		}
7939
	}
7940 7941 7942 7943 7944

	memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
	checkPointLSN = EndRecPtr;

	if (XLByteEQ(checkPointLoc,checkPoint.redo))
7945
	{
7946
		{
7947 7948 7949 7950 7951
			elog(LOG,
				 "control file has restart '%s' and redo start checkpoint at location(lsn) '%s(%s)' ",
				 (previous ? "previous " : ""),
				 XLogLocationToString3(&checkPointLoc),
				 XLogLocationToString4(&checkPointLSN));
7952
		}
7953
	}
7954
 	else if (XLByteLT(checkPointLoc, checkPoint.redo))
7955
	{
7956 7957
		ereport(ERROR,
				(errmsg("%s: invalid redo in checkpoint record", callerStr)));
7958 7959
	}
	else
7960 7961
	{
		XLogRecord *record;
7962

7963
		record = XLogReadRecord(&checkPoint.redo, LOG, false);
7964 7965 7966 7967 7968 7969
		if (record == NULL)
		{
			ereport(ERROR,
			 (errmsg("%s: first redo record before checkpoint not found at %s",
					 callerStr, XLogLocationToString(&checkPoint.redo))));
		}
7970

7971
		{
7972 7973 7974 7975 7976 7977 7978
			elog(LOG,
				 "control file has restart '%s' checkpoint at location(lsn) '%s(%s)', redo starts at location(lsn) '%s(%s)' ",
				 (previous ? "previous " : ""),
				 XLogLocationToString3(&checkPointLoc),
				 XLogLocationToString4(&checkPointLSN),
				 XLogLocationToString(&checkPoint.redo),
				 XLogLocationToString2(&EndRecPtr));
7979 7980
		}
	}
7981

7982
	XLogCloseReadRecord();
7983

7984 7985 7986 7987
	*redoCheckPointLoc = checkPointLoc;
	*redoCheckPoint = checkPoint;

}
7988

7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010
/*
 * Checks if recovery has reached a consistent state. When consistency is
 * reached and we have a valid starting standby snapshot, tell postmaster
 * that it can start accepting read-only connections.
 */
static void
CheckRecoveryConsistency(void)
{
	/*
	 * Have we passed our safe starting point?
	 */
	if (!reachedMinRecoveryPoint &&
		XLByteLE(minRecoveryPoint, EndRecPtr) &&
		XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
	{
		reachedMinRecoveryPoint = true;
		ereport(LOG,
				(errmsg("consistent recovery state reached at %X/%X",
						EndRecPtr.xlogid, EndRecPtr.xrecoff)));
	}

	/*
B
Bruce Momjian 已提交
8011 8012 8013
	 * Have we got a valid starting snapshot that will allow queries to be
	 * run? If so, we can tell postmaster that the database is consistent now,
	 * enabling connections.
8014 8015
	 */
	if (standbyState == STANDBY_SNAPSHOT_READY &&
8016
		!LocalHotStandbyActive &&
8017 8018 8019
		reachedMinRecoveryPoint &&
		IsUnderPostmaster)
	{
8020 8021 8022 8023 8024 8025 8026 8027 8028
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		SpinLockAcquire(&xlogctl->info_lck);
		xlogctl->SharedHotStandbyActive = true;
		SpinLockRelease(&xlogctl->info_lck);

		LocalHotStandbyActive = true;

8029
		SendPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY);
8030 8031 8032
	}
}

8033
/*
8034 8035 8036 8037 8038 8039 8040
 * Is the system still in recovery?
 *
 * Unlike testing InRecovery, this works in any process that's connected to
 * shared memory.
 *
 * As a side-effect, we initialize the local TimeLineID and RedoRecPtr
 * variables the first time we see that recovery is finished.
8041
 */
8042 8043
bool
RecoveryInProgress(void)
8044
{
8045 8046 8047 8048 8049 8050 8051 8052
	/*
	 * We check shared state each time only until we leave recovery mode. We
	 * can't re-enter recovery, so there's no need to keep checking after the
	 * shared variable has once been seen false.
	 */
	if (!LocalRecoveryInProgress)
		return false;
	else
8053
	{
8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

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

		/*
		 * Initialize TimeLineID and RedoRecPtr when we discover that recovery
		 * is finished. InitPostgres() relies upon this behaviour to ensure
		 * that InitXLOGAccess() is called at backend startup.	(If you change
		 * this, see also LocalSetXLogInsertAllowed.)
		 */
		if (!LocalRecoveryInProgress)
			InitXLOGAccess();

		return LocalRecoveryInProgress;
	}
8073 8074
}

8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087
/*
 * Is HotStandby active yet? This is only important in special backends
 * since normal backends won't ever be able to connect until this returns
 * true. Postmaster knows this by way of signal, not via shared memory.
 *
 * Unlike testing standbyState, this works in any process that's connected to
 * shared memory.
 */
bool
HotStandbyActive(void)
{
	/*
	 * We check shared state each time only until Hot Standby is active. We
8088 8089
	 * can't de-activate Hot Standby, so there's no need to keep checking
	 * after the shared variable has once been seen true.
8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106
	 */
	if (LocalHotStandbyActive)
		return true;
	else
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		/* spinlock is essential on machines with weak memory ordering! */
		SpinLockAcquire(&xlogctl->info_lck);
		LocalHotStandbyActive = xlogctl->SharedHotStandbyActive;
		SpinLockRelease(&xlogctl->info_lck);

		return LocalHotStandbyActive;
	}
}

8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117
/*
 * Is this process allowed to insert new WAL records?
 *
 * Ordinarily this is essentially equivalent to !RecoveryInProgress().
 * But we also have provisions for forcing the result "true" or "false"
 * within specific processes regardless of the global state.
 */
bool
XLogInsertAllowed(void)
{
	/*
B
Bruce Momjian 已提交
8118 8119 8120
	 * If value is "unconditionally true" or "unconditionally false", just
	 * return it.  This provides the normal fast path once recovery is known
	 * done.
8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131
	 */
	if (LocalXLogInsertAllowed >= 0)
		return (bool) LocalXLogInsertAllowed;

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

	/*
B
Bruce Momjian 已提交
8132 8133
	 * On exit from recovery, reset to "unconditionally true", since there is
	 * no need to keep checking.
8134 8135 8136 8137 8138 8139 8140
	 */
	LocalXLogInsertAllowed = 1;
	return true;
}

/*
 * Make XLogInsertAllowed() return true in the current process only.
8141 8142 8143
 *
 * Note: it is allowed to switch LocalXLogInsertAllowed back to -1 later,
 * and even call LocalSetXLogInsertAllowed() again after that.
8144 8145 8146 8147 8148 8149 8150 8151 8152
 */
static void
LocalSetXLogInsertAllowed(void)
{
	Assert(LocalXLogInsertAllowed == -1);
	LocalXLogInsertAllowed = 1;

	/* Initialize as RecoveryInProgress() would do when switching state */
	InitXLOGAccess();
8153 8154 8155 8156 8157 8158 8159 8160
}

/*
 * Subroutine to try to fetch and validate a prior checkpoint record.
 *
 * whichChkpt identifies the checkpoint (merely for reporting purposes).
 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
 */
8161
static XLogRecord *
8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194
ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
{
	XLogRecord *record;
	bool sizeOk;
	uint32 delta_xl_tot_len;		/* delta of total len of entire record */
	uint32 delta_xl_len;			/* delta of total len of rmgr data */

	if (!XRecOffIsValid(RecPtr.xrecoff))
	{
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
				(errmsg("invalid primary checkpoint link in control file")));
				break;
			case 2:
				ereport(LOG,
						(errmsg("invalid secondary checkpoint link in control file")));
				break;
			default:
				ereport(LOG,
				   (errmsg("invalid checkpoint link in backup_label file")));
				break;
		}
		return NULL;
	}

	/*
	 * Set fetching_ckpt to true here, so that XLogReadRecord()
	 * uses RedoStartLSN as the start replication location used
	 * by WAL receiver (when StandbyMode is on). See comments
	 * for fetching_ckpt in XLogReadPage()
	 */
8195
	record = XLogReadRecord(&RecPtr, LOG, true /* fetching_checkpoint */);
8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310

	if (record == NULL)
	{
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
						(errmsg("invalid primary checkpoint record at location %s",
						        XLogLocationToString_Long(&RecPtr))));
				break;
			case 2:
				ereport(LOG,
						(errmsg("invalid secondary checkpoint record at location %s",
						        XLogLocationToString_Long(&RecPtr))));
				break;
			default:
				ereport(LOG,
						(errmsg("invalid checkpoint record at location %s",
						        XLogLocationToString_Long(&RecPtr))));
				break;
		}
		return NULL;
	}
	if (record->xl_rmid != RM_XLOG_ID)
	{
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
						(errmsg("invalid resource manager ID in primary checkpoint record at location %s",
						        XLogLocationToString_Long(&RecPtr))));
				break;
			case 2:
				ereport(LOG,
						(errmsg("invalid resource manager ID in secondary checkpoint record at location %s",
						        XLogLocationToString_Long(&RecPtr))));
				break;
			default:
				ereport(LOG,
				(errmsg("invalid resource manager ID in checkpoint record at location %s",
				        XLogLocationToString_Long(&RecPtr))));
				break;
		}
		return NULL;
	}
	if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
		record->xl_info != XLOG_CHECKPOINT_ONLINE)
	{
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
				   (errmsg("invalid xl_info in primary checkpoint record at location %s",
				           XLogLocationToString_Long(&RecPtr))));
				break;
			case 2:
				ereport(LOG,
				 (errmsg("invalid xl_info in secondary checkpoint record at location %s",
				         XLogLocationToString_Long(&RecPtr))));
				break;
			default:
				ereport(LOG,
						(errmsg("invalid xl_info in checkpoint record at location %s",
						        XLogLocationToString_Long(&RecPtr))));
				break;
		}
		return NULL;
	}

	sizeOk = false;
	if (record->xl_len == sizeof(CheckPoint) &&
		record->xl_tot_len == SizeOfXLogRecord + sizeof(CheckPoint))
	{
		sizeOk = true;
	}
	else if (record->xl_len > sizeof(CheckPoint) &&
		record->xl_tot_len > SizeOfXLogRecord + sizeof(CheckPoint))
	{
		delta_xl_len = record->xl_len - sizeof(CheckPoint);
		delta_xl_tot_len = record->xl_tot_len - (SizeOfXLogRecord + sizeof(CheckPoint));

		if (delta_xl_len == delta_xl_tot_len)
		{
			sizeOk = true;
		}
	}

	if (!sizeOk)
	{
		switch (whichChkpt)
		{
			case 1:
				ereport(LOG,
					(errmsg("invalid length of primary checkpoint at location %s",
					        XLogLocationToString_Long(&RecPtr))));
				break;
			case 2:
				ereport(LOG,
				  (errmsg("invalid length of secondary checkpoint record at location %s",
				          XLogLocationToString_Long(&RecPtr))));
				break;
			default:
				ereport(LOG,
						(errmsg("invalid length of checkpoint record at location %s",
						        XLogLocationToString_Long(&RecPtr))));
				break;
		}
		return NULL;
	}
	return record;
}

static void
UnpackCheckPointRecord(
	XLogRecord			*record,
8311
	CheckpointExtendedRecord *ckptExtended)
8312
{
8313 8314
	char *current_record_ptr;
	int remainderLen;
8315

8316
	if (record->xl_len == sizeof(CheckPoint))
8317
	{
8318 8319 8320 8321 8322 8323
		/* Special (for bootstrap, xlog switch, maybe others) */
		ckptExtended->dtxCheckpoint = NULL;
		ckptExtended->dtxCheckpointLen = 0;
		ckptExtended->ptas = NULL;
		return;
	}
8324

8325 8326
	/* Normal checkpoint Record */
	Assert(record->xl_len > sizeof(CheckPoint));
8327

8328 8329
	current_record_ptr = ((char*)XLogRecGetData(record)) + sizeof(CheckPoint);
	remainderLen = record->xl_len - sizeof(CheckPoint);
8330

8331 8332 8333 8334
	/* Start of distributed transaction information */
	ckptExtended->dtxCheckpoint = (TMGXACT_CHECKPOINT *)current_record_ptr;
	ckptExtended->dtxCheckpointLen =
		TMGXACT_CHECKPOINT_BYTES((ckptExtended->dtxCheckpoint)->committedCount);
8335

8336
	/*
8337
	 * The master prepared transaction aggregate state (ptas) will be skipped
8338 8339 8340 8341 8342 8343
	 * when gp_before_filespace_setup is ON.
	 */
	if (remainderLen > ckptExtended->dtxCheckpointLen)
	{
		current_record_ptr = current_record_ptr + ckptExtended->dtxCheckpointLen;
		remainderLen -= ckptExtended->dtxCheckpointLen;
8344

8345 8346 8347 8348 8349 8350
		/* Finally, point to prepared transaction information */
		ckptExtended->ptas = (prepared_transaction_agg_state *) current_record_ptr;
		Assert(remainderLen == PREPARED_TRANSACTION_CHECKPOINT_BYTES(ckptExtended->ptas->count));
	}
	else
	{
8351
		Assert(remainderLen == ckptExtended->dtxCheckpointLen);
8352 8353
		ckptExtended->ptas = NULL;
	}
8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370
}

/*
 * This must be called during startup of a backend process, except that
 * it need not be called in a standalone backend (which does StartupXLOG
 * instead).  We need to initialize the local copies of ThisTimeLineID and
 * RedoRecPtr.
 *
 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
 * process's copies of ThisTimeLineID and RedoRecPtr valid too.  This was
 * unnecessary however, since the postmaster itself never touches XLOG anyway.
 */
void
InitXLOGAccess(void)
{
	/* ThisTimeLineID doesn't change so we need no lock to copy it */
	ThisTimeLineID = XLogCtl->ThisTimeLineID;
8371
	Assert(ThisTimeLineID != 0 || IsBootstrapProcessingMode());
8372

8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439
	/* Use GetRedoRecPtr to copy the RedoRecPtr safely */
	(void) GetRedoRecPtr();
}

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

	SpinLockAcquire(&xlogctl->info_lck);
	Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
	RedoRecPtr = xlogctl->Insert.RedoRecPtr;
	SpinLockRelease(&xlogctl->info_lck);

	return RedoRecPtr;
}

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

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

	return recptr;
}

/*
 * GetFlushRecPtr -- Returns the current flush position, ie, the last WAL
 * position known to be fsync'd to disk.
 */
XLogRecPtr
GetFlushRecPtr(void)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	XLogRecPtr	recptr;

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

	return recptr;
}

/*
 * Get the time of the last xlog segment switch
 */
8440
pg_time_t
8441 8442
GetLastSegSwitchTime(void)
{
8443
	pg_time_t	result;
8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492

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

	return result;
}

/*
 * 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)
{
	uint32		ckptXidEpoch;
	TransactionId ckptXid;
	TransactionId nextXid;

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

8493
/*
8494
 * GetRecoveryTargetTLI - get the current recovery target timeline ID
8495 8496 8497 8498
 */
TimeLineID
GetRecoveryTargetTLI(void)
{
8499 8500 8501 8502 8503 8504 8505 8506 8507
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	TimeLineID result;

	SpinLockAcquire(&xlogctl->info_lck);
	result = xlogctl->RecoveryTargetTLI;
	SpinLockRelease(&xlogctl->info_lck);

	return result;
8508 8509
}

8510 8511 8512 8513 8514 8515 8516 8517 8518
/*
 * This must be called ONCE during postmaster or standalone-backend shutdown
 */
void
ShutdownXLOG(int code __attribute__((unused)) , Datum arg __attribute__((unused)) )
{
	ereport(LOG,
			(errmsg("shutting down")));

8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530
	if (RecoveryInProgress())
		CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
	else
	{
		/*
		 * If archiving is enabled, rotate the last XLOG file so that all the
		 * remaining records are archived (postmaster wakes up the archiver
		 * process one more time at the end of shutdown). The checkpoint
		 * record will go to the next XLOG file and won't be archived (yet).
		 */
		if (XLogArchivingActive() && XLogArchiveCommandSet())
			RequestXLogSwitch();
8531

8532 8533
		CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
	}
8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600
	ShutdownCLOG();
	ShutdownSUBTRANS();
	ShutdownMultiXact();
	DistributedLog_Shutdown();

	ereport(LOG,
			(errmsg("database system is shut down"),
					errSendAlert(true)));
}

/*
 * Calculate the last segment that we need to retain because of
 * keep_wal_segments, by subtracting keep_wal_segments from the passed
 * xlog location
 */
static void
CheckKeepWalSegments(XLogRecPtr recptr, uint32 *_logId, uint32 *_logSeg)
{
	uint32	log;
	uint32	seg;
	uint32	keep_log;
	uint32	keep_seg;

	if (keep_wal_segments <= 0)
		return;

	XLByteToSeg(recptr, log, seg);

	keep_seg = keep_wal_segments % XLogSegsPerFile;
	keep_log = keep_wal_segments / XLogSegsPerFile;
	ereport(DEBUG1,
			(errmsg("%s: Input %d %d (Keep %d %d) (current %d %d)",
					PG_FUNCNAME_MACRO, *_logId, *_logSeg, keep_log,
					keep_seg, log, seg)));
	if (seg < keep_seg)
	{
		keep_log += 1;
		seg = seg - keep_seg + XLogSegsPerFile;
	}
	else
	{
		seg = seg - keep_seg;
	}

	/* Avoid underflow, don't go below (0,1) */
	if (log < keep_log || (log == keep_log && seg == 0))
	{
		log = 0;
		seg = 1;
	}
	else
	{
		log = log - keep_log;
	}

	/* check not to delete WAL segments newer than the calculated segment */
	if (log < *_logId || (log == *_logId && seg < *_logSeg))
	{
		*_logId = log;
		*_logSeg = seg;
	}

	ereport(DEBUG1,
			(errmsg("%s: Output %d %d",
					PG_FUNCNAME_MACRO, *_logId, *_logSeg)));
}

8601 8602 8603 8604
/*
 * Log start of a checkpoint.
 */
static void
8605
LogCheckpointStart(int flags, bool restartpoint)
8606
{
8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618
	const char *msg;

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

	elog(LOG, msg,
8619
		 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
8620
		 (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631
		 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
		 (flags & CHECKPOINT_FORCE) ? " force" : "",
		 (flags & CHECKPOINT_WAIT) ? " wait" : "",
		 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
		 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
}

/*
 * Log end of a checkpoint.
 */
static void
8632
LogCheckpointEnd(bool restartpoint)
8633 8634 8635
{
	long		write_secs,
				sync_secs,
R
Robert Haas 已提交
8636 8637 8638
				total_secs,
				longest_secs,
				average_secs;
8639 8640
	int			write_usecs,
				sync_usecs,
R
Robert Haas 已提交
8641 8642 8643 8644
				total_usecs,
				longest_usecs,
				average_usecs;
	uint64		average_sync_time;
8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659

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

R
Robert Haas 已提交
8660 8661 8662 8663 8664 8665 8666
	/*
	 * Timing values returned from CheckpointStats are in microseconds.
	 * Convert to the second plus microsecond form that TimestampDifference
	 * returns for homogeneous printing.
	 */
	longest_secs = (long) (CheckpointStats.ckpt_longest_sync / 1000000);
	longest_usecs = CheckpointStats.ckpt_longest_sync -
8667
		(uint64) longest_secs *1000000;
R
Robert Haas 已提交
8668 8669

	average_sync_time = 0;
8670
	if (CheckpointStats.ckpt_sync_rels > 0)
R
Robert Haas 已提交
8671 8672 8673
		average_sync_time = CheckpointStats.ckpt_agg_sync_time /
			CheckpointStats.ckpt_sync_rels;
	average_secs = (long) (average_sync_time / 1000000);
8674
	average_usecs = average_sync_time - (uint64) average_secs *1000000;
R
Robert Haas 已提交
8675

8676 8677
	if (restartpoint)
		elog(LOG, "restartpoint complete: wrote %d buffers (%.1f%%); "
8678
			 "%d transaction log file(s) added, %d removed, %d recycled; "
R
Robert Haas 已提交
8679 8680
			 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s; "
			 "sync files=%d, longest=%ld.%03d s, average=%ld.%03d s",
8681 8682
			 CheckpointStats.ckpt_bufs_written,
			 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
8683 8684 8685
			 CheckpointStats.ckpt_segs_added,
			 CheckpointStats.ckpt_segs_removed,
			 CheckpointStats.ckpt_segs_recycled,
8686 8687
			 write_secs, write_usecs / 1000,
			 sync_secs, sync_usecs / 1000,
R
Robert Haas 已提交
8688 8689 8690 8691
			 total_secs, total_usecs / 1000,
			 CheckpointStats.ckpt_sync_rels,
			 longest_secs, longest_usecs / 1000,
			 average_secs, average_usecs / 1000);
8692 8693 8694
	else
		elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
			 "%d transaction log file(s) added, %d removed, %d recycled; "
R
Robert Haas 已提交
8695 8696
			 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s; "
			 "sync files=%d, longest=%ld.%03d s, average=%ld.%03d s",
8697 8698 8699 8700 8701 8702 8703
			 CheckpointStats.ckpt_bufs_written,
			 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
			 CheckpointStats.ckpt_segs_added,
			 CheckpointStats.ckpt_segs_removed,
			 CheckpointStats.ckpt_segs_recycled,
			 write_secs, write_usecs / 1000,
			 sync_secs, sync_usecs / 1000,
R
Robert Haas 已提交
8704 8705 8706 8707
			 total_secs, total_usecs / 1000,
			 CheckpointStats.ckpt_sync_rels,
			 longest_secs, longest_usecs / 1000,
			 average_secs, average_usecs / 1000);
8708 8709
}

8710 8711 8712
/*
 * Perform a checkpoint --- either during shutdown, or on-the-fly
 *
8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724
 * flags is a bitwise OR of the following:
 *	CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
 *	CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
 *	CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
 *		ignoring checkpoint_completion_target parameter.
 *	CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
 *		since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
 *		CHECKPOINT_END_OF_RECOVERY).
 *
 * Note: flags contains other bits, of interest here only for logging purposes.
 * In particular note that this routine is synchronous and does not pay
 * attention to CHECKPOINT_WAIT.
8725 8726
 */
void
8727
CreateCheckPoint(int flags)
8728
{
8729
	bool		shutdown;
8730 8731 8732 8733 8734 8735 8736 8737 8738
	CheckPoint	checkPoint;
	XLogRecPtr	recptr;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecData rdata[6];
	char* 		dtxCheckPointInfo;
	int			dtxCheckPointInfoSize;
	uint32		freespace;
	uint32		_logId;
	uint32		_logSeg;
8739
	VirtualTransactionId *vxids;
8740 8741 8742 8743 8744 8745 8746 8747 8748 8749
	int     	nvxids;

	/*
	 * An end-of-recovery checkpoint is really a shutdown checkpoint, just
	 * issued at a different time.
	 */
	if (flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY))
		shutdown = true;
	else
		shutdown = false;
8750 8751 8752 8753 8754 8755 8756

	if (shutdown && ControlFile->state == DB_STARTUP)
	{
		return;
	}

#ifdef FAULT_INJECTOR
8757 8758 8759 8760 8761 8762
	if (FaultInjector_InjectFaultIfSet(
			Checkpoint,
			DDLNotSpecified,
			"" /* databaseName */,
			"" /* tableName */) == FaultInjectorTypeSkip)
		return;  // skip checkpoint
8763 8764
#endif

8765 8766 8767 8768
	/* sanity check */
	if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
		elog(ERROR, "can't create a checkpoint during recovery");

8769 8770 8771 8772 8773 8774 8775 8776
	/*
	 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
	 * (This is just pro forma, since in the present system structure there is
	 * only one process that is allowed to issue checkpoints at any given
	 * time.)
	 */
	LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);

8777 8778 8779 8780 8781 8782 8783 8784 8785 8786
	/*
	 * 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();

8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799
	/*
	 * Use a critical section to force system panic if we have trouble.
	 */
	START_CRIT_SECTION();

	if (shutdown)
	{
		/*
		 * This is an ugly fix to dis-allow changing the pg_control
		 * state for standby promotion continuity.
		 *
		 * Refer to Startup_InProduction() for more details
		 */
8800
		if (ControlFile->state != DB_IN_STANDBY_PROMOTED)
8801
		{
8802
			LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8803
			ControlFile->state = DB_SHUTDOWNING;
8804
			ControlFile->time = (pg_time_t) time(NULL);
8805
			UpdateControlFile();
8806
			LWLockRelease(ControlFileLock);
8807 8808 8809
		}
	}

8810 8811 8812 8813 8814 8815 8816 8817
	/*
	 * 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.
	 */
	smgrpreckpt();

	/* Begin filling in the checkpoint WAL record */
8818
	MemSet(&checkPoint, 0, sizeof(checkPoint));
8819
	checkPoint.time = (pg_time_t) time(NULL);
8820 8821 8822 8823 8824

	/*
	 * The WRITE_PERSISTENT_STATE_ORDERED_LOCK gets these locks:
	 *    MirroredLock SHARED, and
	 *    PersistentObjLock EXCLUSIVE.
8825
	 * as well as set MyProc->inCommit = true.
8826 8827 8828 8829 8830 8831 8832 8833 8834
	 *
	 * The READ_PERSISTENT_STATE_ORDERED_LOCK gets this lock:
	 *    PersistentObjLock SHARED.
	 *
	 * They do this to prevent Persistent object changes during checkpoint and
	 * prevent persistent object reads while writing.  And acquire the MirroredLock
	 * at a level that blocks DDL during FileRep statechanges...
	 */

8835 8836 8837 8838
	/*
	 * We must hold WALInsertLock while examining insert state to determine
	 * the checkpoint REDO pointer.
	 */
8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);

	/*
	 * 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?)
	 *
	 * 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.
	 */
8856 8857
	if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
				  CHECKPOINT_FORCE)) == 0)
8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889
	{
		XLogRecPtr	curInsert;

		INSERT_RECPTR(curInsert, Insert, Insert->curridx);
#ifdef originalCheckpointChecking
		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)
#else
		/*
		 * GP: Modified since the checkpoint record is not fixed length
		 * so we keep track of the last checkpoint locations (beginning and
		 * end) and use thoe values for comparison.
		 */
		if (XLogCtl->haveLastCheckpointLoc &&
			XLByteEQ(XLogCtl->lastCheckpointLoc,ControlFile->checkPoint) &&
			XLByteEQ(curInsert,XLogCtl->lastCheckpointEndLoc) &&
			XLByteEQ(ControlFile->checkPoint,ControlFile->checkPointCopy.redo))
#endif
		{
			LWLockRelease(WALInsertLock);
			LWLockRelease(CheckpointLock);

			END_CRIT_SECTION();
			return;
		}
	}

8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900
	/*
	 * An end-of-recovery checkpoint is created before anyone is allowed to
	 * write WAL. To allow us to write the checkpoint record, temporarily
	 * enable XLogInsertAllowed.  (This also ensures ThisTimeLineID is
	 * initialized, which we need here and in AdvanceXLInsertBuffer.)
	 */
	if (flags & CHECKPOINT_END_OF_RECOVERY)
		LocalSetXLogInsertAllowed();

	checkPoint.ThisTimeLineID = ThisTimeLineID;

8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938
	/*
	 * Compute new REDO record ptr = location of next XLOG record.
	 *
	 * 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?
	 */
	freespace = INSERT_FREESPACE(Insert);
	if (freespace < SizeOfXLogRecord)
	{
		(void) AdvanceXLInsertBuffer(false);
		/* OK to ignore update return flag, since we will do flush anyway */
		freespace = INSERT_FREESPACE(Insert);
	}
	INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);

	/*
	 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
	 * must be done while holding the insert lock AND the info_lck.
	 *
	 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
	 * 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.
	 */
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

		SpinLockAcquire(&xlogctl->info_lck);
		RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
		SpinLockRelease(&xlogctl->info_lck);
	}

	/*
8939 8940
	 * Now we can release WAL insert lock, allowing other xacts to proceed
	 * while we are flushing disk buffers.
8941 8942 8943
	 */
	LWLockRelease(WALInsertLock);

8944 8945 8946 8947 8948
	/*
	 * If enabled, log checkpoint start.  We postpone this until now so as not
	 * to log anything if we decided to skip the checkpoint.
	 */
	if (log_checkpoints)
8949
		LogCheckpointStart(flags, false);
8950

8951 8952
	TRACE_POSTGRESQL_CHECKPOINT_START(flags);

8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976
	/*
	 * 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
	 * protected by different locks, but again that seems best on grounds of
	 * minimizing lock contention.)
	 *
	 * 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
	 * 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.
	 */
8977 8978
	vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
	if (nvxids > 0)
8979 8980 8981
	{
		do
		{
8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992
			/*
			 * GPDB needs to AbsorbFsyncRequests() here to avoid deadlock when
			 * fsync request queue is full while backend is in commit and
			 * performing ForgetRelationFsyncRequests() or
			 * ForgetDatabaseFsyncRequests(). Since for GPDB the mdlink
			 * happens through persistent tables cleanup, during which
			 * inCommit flag is set to avoid checkpoint from happening.
			 * PostgreSQL doesn't need this as ForgetRelationFsyncRequests()
			 * or ForgetDatabaseFsyncRequests() are not under inCommit=true.
			 */
			AbsorbFsyncRequests();
8993
			pg_usleep(10000L);	/* wait for 10 msec */
8994
		} while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
8995
	}
8996
	pfree(vxids);
8997

G
Gang Xiong 已提交
8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023
	/*
	 * When the crash happens, we need to handle the transactions that have
	 * already inserted 'commit' record and haven't inserted 'forget' record.
	 *
	 * If the 'commit' record is logically before the checkpoint REDO pointer,
	 * we save the transactions in checkpoint record, and these transactions
	 * will be load into shared memory and mark as 'crash committed' during
	 * redo checkpoint.
	 * If the 'commit' record is logically after the checkpoint REDO pointer,
	 * the transactions will be added to shared memory and mark as 'crash
	 * committed' during redo xact.
	 * All these transactions will be stored in the shutdown checkpoint record
	 * after recovery, and they will be finally recovered in recoverTM().
	 *
	 * So if it's a shutdown checkpoint here, we should include all 'crash
	 * committed' transactions, and if it's a normal checkpoint should include
	 * all transactions whose 'commit' record is logically before checkpoint
	 * REDO pointer.
	 *
	 * We don't hold the WALInsertLock, so there's a time window that allows
	 * transactions insert 'commit' record and/or 'forget' record after
	 * checkpoint REDO pointer. That's fine, resend 'commit prepared' to already
	 * finished transactions is handled.
	 */
	getDtxCheckPointInfo(&dtxCheckPointInfo, &dtxCheckPointInfoSize);

9024 9025 9026 9027 9028
	/*
	 * Get the other info we need for the checkpoint record.
	 */
	LWLockAcquire(XidGenLock, LW_SHARED);
	checkPoint.nextXid = ShmemVariableCache->nextXid;
9029 9030
	checkPoint.oldestXid = ShmemVariableCache->oldestXid;
	checkPoint.oldestXidDB = ShmemVariableCache->oldestXidDB;
9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043
	LWLockRelease(XidGenLock);

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

	LWLockAcquire(OidGenLock, LW_SHARED);
	checkPoint.nextOid = ShmemVariableCache->nextOid;
	if (!shutdown)
		checkPoint.nextOid += ShmemVariableCache->oidCount;
	LWLockRelease(OidGenLock);

9044 9045 9046 9047 9048 9049
	LWLockAcquire(RelfilenodeGenLock, LW_SHARED);
	checkPoint.nextRelfilenode = ShmemVariableCache->nextRelfilenode;
	if (!shutdown)
		checkPoint.nextRelfilenode += ShmemVariableCache->relfilenodeCount;
	LWLockRelease(RelfilenodeGenLock);

9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063
	MultiXactGetCheckptMulti(shutdown,
							 &checkPoint.nextMulti,
							 &checkPoint.nextMultiOffset);

	/*
	 * Having constructed the checkpoint record, ensure all shmem disk buffers
	 * and commit-log buffers are flushed to disk.
	 *
	 * 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
	 * panic. Accordingly, exit critical section while doing it.
	 */
	END_CRIT_SECTION();

9064
	CheckPointGuts(checkPoint.redo, flags);
9065

9066
	/*
B
Bruce Momjian 已提交
9067 9068 9069
	 * Take a snapshot of running transactions and write this to WAL. This
	 * allows us to reconstruct the state of running transactions during
	 * archive recovery, if required. Skip, if this info disabled.
9070 9071 9072 9073 9074 9075 9076
	 *
	 * If we are shutting down, or Startup process is completing crash
	 * recovery we don't need to write running xact data.
	 *
	 * Update checkPoint.nextXid since we have a later value
	 */
	if (!shutdown && XLogStandbyInfoActive())
B
Bruce Momjian 已提交
9077
		LogStandbySnapshot(&checkPoint.oldestActiveXid, &checkPoint.nextXid);
9078 9079 9080
	else
		checkPoint.oldestActiveXid = InvalidTransactionId;

9081 9082 9083 9084
	START_CRIT_SECTION();

	/*
	 * Now insert the checkpoint record into XLOG.
9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108
	 *
	 * Here is the locking order and scope:
	 *
	 * 	READ_PERSISTENT_STATE_ORDERED_LOCK (i.e. PersistentObjLock)
	 * 		mmxlog_append_checkpoint_data
	 * 		XLogInsert
	 * 	READ_PERSISTENT_STATE_ORDERED_UNLOCK
	 * XLogFlush
	 *
	 * We get the PersistentObjLock to prevent Persistent Object writers as
	 * we collect the Master Mirroring information from mmxlog_append_checkpoint_data()
	 * until finally after the checkpoint record is inserted into the XLOG to prevent the
	 * persistent information from changing.
	 *
	 * For example, if we don't hold the PersistentObjLock across mmxlog_append_checkpoint_data()
	 * and XLogInsert(), another xlog activity like drop tablespace could happen in between, which
	 * might caused wrong behavior when master standby replay checkpoint record.
	 *
	 * Master standby replay (mmxlog_read_checkpoint_data) the mmxlog information stored in the checkpoint
	 * record to recreate those persistent objects like filespace, tablespace, database dir, etc. If those
	 * objects dropped after checkpoint collected persistent objects information, but before checkpoint
	 * record write to XLOG, then the standby replay would first drop the object based on mmxlog record,
	 * then recreated based on the checkpoint record. That will ends-up left behind the directories already
	 * dropped on the master, break the consistency between the master and the standby.
9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150
	 */

	rdata[0].data = (char *) (&checkPoint);
	rdata[0].len = sizeof(checkPoint);
	rdata[0].buffer = InvalidBuffer;
	rdata[0].next = &(rdata[1]);

	rdata[1].data = (char *) dtxCheckPointInfo;
	rdata[1].len = dtxCheckPointInfoSize;
	rdata[1].buffer = InvalidBuffer;
	rdata[1].next = NULL;

	prepared_transaction_agg_state *p = NULL;

	getTwoPhasePreparedTransactionData(&p, "CreateCheckPoint");
	rdata[5].data = (char*)p;
	rdata[5].buffer = InvalidBuffer;
	rdata[5].len = PREPARED_TRANSACTION_CHECKPOINT_BYTES(p->count);
	rdata[4].next = &(rdata[5]);
	rdata[5].next = NULL;

	/*
	 * Need to save the oldest prepared transaction XLogRecPtr for use later.
	 * It is not sufficient to just save the pointer because we may remove the
	 * space after it is written in XLogInsert.
	 */
	XLogRecPtr *ptrd_oldest_ptr = NULL;
	XLogRecPtr ptrd_oldest;

	memset(&ptrd_oldest, 0, sizeof(ptrd_oldest));

	ptrd_oldest_ptr = getTwoPhaseOldestPreparedTransactionXLogRecPtr(&rdata[5]);

	if (ptrd_oldest_ptr != NULL)
		memcpy(&ptrd_oldest, ptrd_oldest_ptr, sizeof(ptrd_oldest));

	recptr = XLogInsert(RM_XLOG_ID,
			            shutdown ? XLOG_CHECKPOINT_SHUTDOWN : XLOG_CHECKPOINT_ONLINE,
			            rdata);

	XLogFlush(recptr);

9151
	/*
B
Bruce Momjian 已提交
9152 9153 9154 9155
	 * We mustn't write any new WAL after a shutdown checkpoint, or it will be
	 * overwritten at next startup.  No-one should even try, this just allows
	 * sanity-checking.  In the case of an end-of-recovery checkpoint, we want
	 * to just temporarily disable writing until the system has exited
9156 9157 9158 9159 9160
	 * recovery.
	 */
	if (shutdown)
	{
		if (flags & CHECKPOINT_END_OF_RECOVERY)
B
Bruce Momjian 已提交
9161
			LocalXLogInsertAllowed = -1;		/* return to "check" state */
9162
		else
B
Bruce Momjian 已提交
9163
			LocalXLogInsertAllowed = 0; /* never again write WAL */
9164 9165
	}

9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192
	/*
	 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
	 * = end of actual checkpoint record.
	 */
	if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
		ereport(PANIC,
				(errmsg("concurrent transaction log activity while database system is shutting down")));

	/*
	 * Select point at which we can truncate the log, which we base on the
	 * prior checkpoint's earliest info or the oldest prepared transaction xlog record's info.
	 */
	if (ptrd_oldest_ptr != NULL && XLByteLE(ptrd_oldest, ControlFile->checkPointCopy.redo))
		XLByteToSeg(ptrd_oldest, _logId, _logSeg);
	else
		XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);

	/*
	 * Update the control file.
	 */
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
	if (shutdown)
	{
		/*
		 * Ugly fix to dis-allow changing pg_control state
		 * for standby promotion continuity
		 */
9193
		if (ControlFile->state != DB_IN_STANDBY_PROMOTED)
9194 9195 9196 9197 9198 9199 9200 9201
			ControlFile->state = DB_SHUTDOWNED;
	}

	ControlFile->prevCheckPoint = ControlFile->checkPoint;
	ControlFile->checkPoint = ProcLastRecPtr;
	ControlFile->checkPointCopy = checkPoint;
	/* crash recovery should always recover to the end of WAL */
	MemSet(&ControlFile->minRecoveryPoint, 0, sizeof(XLogRecPtr));
9202
	ControlFile->time = (pg_time_t) time(NULL);
9203 9204 9205 9206 9207 9208

	/*
	 * Save the last checkpoint position.
	 */
	XLogCtl->haveLastCheckpointLoc = true;
	XLogCtl->lastCheckpointLoc = ProcLastRecPtr;
9209
	XLogCtl->lastCheckpointEndLoc = XactLastRecEnd;
9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226

	UpdateControlFile();
	LWLockRelease(ControlFileLock);

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

	/*
	 * We are now done with critical updates; no need for system panic if we
9227
	 * have trouble while fooling with old log segments.
9228 9229 9230 9231
	 */
	END_CRIT_SECTION();

	/*
9232 9233 9234 9235 9236 9237
	 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
	 */
	smgrpostckpt();

	/*
	 * Delete old log files (those no longer needed even for previous
9238
	 * checkpoint or the standbys in XLOG streaming).
9239 9240 9241
	 */
	if (gp_keep_all_xlog == false && (_logId || _logSeg))
	{
9242
		GetXLogCleanUpTo(recptr, &_logId, &_logSeg);
9243
		PrevLogSeg(_logId, _logSeg);
9244
		RemoveOldXlogFiles(_logId, _logSeg, recptr);
9245 9246 9247 9248 9249 9250 9251
	}

	/*
	 * Make more log segments if needed.  (Do this after deleting offline log
	 * segments, to avoid having peak disk space usage higher than necessary.)
	 */
	if (!shutdown)
9252
		PreallocXlogFiles(recptr);
9253 9254 9255 9256 9257 9258 9259 9260

	/*
	 * 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.
	 */
9261
	if (!RecoveryInProgress())
9262
		TruncateSUBTRANS(GetLocalOldestXmin(true, false));
9263

9264 9265
	/* All real work is done, but log before releasing lock. */
	if (log_checkpoints)
9266
		LogCheckpointEnd(false);
9267

9268
	TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
9269 9270
									 NBuffers,
									 CheckpointStats.ckpt_segs_added,
9271 9272 9273
									 CheckpointStats.ckpt_segs_removed,
									 CheckpointStats.ckpt_segs_recycled);

9274 9275 9276 9277 9278 9279 9280 9281 9282 9283
	LWLockRelease(CheckpointLock);
}

/*
 * Flush all data in shared memory to disk, and fsync
 *
 * This is the common code shared between regular checkpoints and
 * recovery restartpoints.
 */
static void
9284
CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
9285 9286 9287 9288
{
	CheckPointCLOG();
	CheckPointSUBTRANS();
	CheckPointMultiXact();
9289
	CheckPointPredicate();
9290
	CheckPointRelationMap();
9291
	DistributedLog_CheckPoint();
9292
	CheckPointBuffers(flags);	/* performs all required fsyncs */
9293 9294 9295 9296 9297
	/* We deliberately delay 2PC checkpointing as long as possible */
	CheckPointTwoPhase(checkPointRedo);
}

/*
9298
 * Save a checkpoint for recovery restart if appropriate
9299
 *
9300 9301 9302 9303 9304 9305
 * This function is called each time a checkpoint record is read from XLOG.
 * It must determine whether the checkpoint represents a safe restartpoint or
 * not.  If so, the checkpoint record is stashed in shared memory so that
 * CreateRestartPoint can consult it.  (Note that the latter function is
 * executed by the bgwriter, while this one will be executed by the startup
 * process.)
9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324
 */
static void
RecoveryRestartPoint(const CheckPoint *checkPoint)
{
	int			rmid;

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

	/*
	 * 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()))
9325
			{
9326
				elog(trace_recovery(DEBUG2), "RM %d not safe to record restart point at %X/%X",
9327 9328 9329
					 rmid,
					 checkPoint->redo.xlogid,
					 checkPoint->redo.xrecoff);
9330
				return;
9331
			}
9332 9333 9334 9335 9336 9337 9338 9339
	}

	/* Update the shared RedoRecPtr */
	 SpinLockAcquire(&xlogctl->info_lck);
	 xlogctl->Insert.RedoRecPtr = checkPoint->redo;
	 SpinLockRelease(&xlogctl->info_lck);

	/*
9340 9341
	 * Copy the checkpoint record to shared memory, so that bgwriter can use
	 * it the next time it wants to perform a restartpoint.
9342
	 */
9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366
	SpinLockAcquire(&xlogctl->info_lck);
	XLogCtl->lastCheckPointRecPtr = ReadRecPtr;
	memcpy(&XLogCtl->lastCheckPoint, checkPoint, sizeof(CheckPoint));
	SpinLockRelease(&xlogctl->info_lck);
}

/*
 * Establish a restartpoint if possible.
 *
 * This is similar to CreateCheckPoint, but is used during WAL recovery
 * to establish a point from which recovery can roll forward without
 * replaying the entire recovery log.
 *
 * Returns true if a new restartpoint was established. We can only establish
 * a restartpoint if we have replayed a safe checkpoint record since last
 * restartpoint.
 */
bool
CreateRestartPoint(int flags)
{
	XLogRecPtr	lastCheckPointRecPtr;
	CheckPoint	lastCheckPoint;
	uint32		_logId = 0;
	uint32		_logSeg = 0;
B
Bruce Momjian 已提交
9367
	TimestampTz xtime;
9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382

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

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

	/* Get a local copy of the last safe checkpoint record. */
	SpinLockAcquire(&xlogctl->info_lck);
	lastCheckPointRecPtr = xlogctl->lastCheckPointRecPtr;
	memcpy(&lastCheckPoint, &XLogCtl->lastCheckPoint, sizeof(CheckPoint));
	SpinLockRelease(&xlogctl->info_lck);
9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393

	if (IsStandbyMode())
	{
		/*
		 * Select point at which we can truncate the log, which we base on the
		 * prior checkpoint's earliest info.
		*/
		XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
	}

	/*
9394 9395
	 * Check that we're still in recovery mode. It's ok if we exit recovery
	 * mode after this check, the restart point is valid anyway.
9396
	 */
9397 9398 9399 9400 9401 9402 9403
	if (!RecoveryInProgress())
	{
		ereport(DEBUG2,
			  (errmsg("skipping restartpoint, recovery has already ended")));
		LWLockRelease(CheckpointLock);
		return false;
	}
9404 9405

	/*
9406 9407 9408 9409
	 * If the last checkpoint record we've replayed is already our last
	 * restartpoint, we can't perform a new restart point. We still update
	 * minRecoveryPoint in that case, so that if this is a shutdown restart
	 * point, we won't start up earlier than before. That's not strictly
B
Bruce Momjian 已提交
9410 9411 9412 9413
	 * necessary, but when hot standby is enabled, it would be rather weird if
	 * the database opened up for read-only connections at a point-in-time
	 * before the last shutdown. Such time travel is still possible in case of
	 * immediate shutdown, though.
9414 9415 9416 9417
	 *
	 * We don't explicitly advance minRecoveryPoint when we do create a
	 * restartpoint. It's assumed that flushing the buffers will do that as a
	 * side-effect.
9418
	 */
9419 9420 9421 9422
	if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
		XLByteLE(lastCheckPoint.redo, ControlFile->checkPointCopy.redo))
	{
		XLogRecPtr	InvalidXLogRecPtr = {0, 0};
9423

9424 9425 9426 9427 9428
		ereport(DEBUG2,
				(errmsg("skipping restartpoint, already performed at %X/%X",
				  lastCheckPoint.redo.xlogid, lastCheckPoint.redo.xrecoff)));

		UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
9429 9430 9431 9432 9433 9434 9435 9436
		if (flags & CHECKPOINT_IS_SHUTDOWN)
		{
			LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
			ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
			ControlFile->time = (pg_time_t) time(NULL);
			UpdateControlFile();
			LWLockRelease(ControlFileLock);
		}
9437 9438 9439 9440
		LWLockRelease(CheckpointLock);
		return false;
	}

9441
	/*
B
Bruce Momjian 已提交
9442 9443 9444
	 * Update the shared RedoRecPtr so that the startup process can calculate
	 * the number of segments replayed since last restartpoint, and request a
	 * restartpoint if it exceeds checkpoint_segments.
9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455
	 *
	 * You need to hold WALInsertLock and info_lck to update it, although
	 * during recovery acquiring WALInsertLock is just pro forma, because
	 * there is no other processes updating Insert.RedoRecPtr.
	 */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
	SpinLockAcquire(&xlogctl->info_lck);
	xlogctl->Insert.RedoRecPtr = lastCheckPoint.redo;
	SpinLockRelease(&xlogctl->info_lck);
	LWLockRelease(WALInsertLock);

9456 9457 9458 9459 9460 9461 9462 9463 9464
	/*
	 * 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();
9465

9466
	if (log_checkpoints)
9467
		LogCheckpointStart(flags, true);
9468

9469 9470
	CheckPointGuts(lastCheckPoint.redo, flags);

9471 9472 9473 9474 9475 9476
	/*
	 * Select point at which we can truncate the xlog, which we base on the
	 * prior checkpoint's earliest info.
	 */
	XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);

9477 9478 9479
	/*
	 * Update pg_control, using current time.  Check that it still shows
	 * IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
B
Bruce Momjian 已提交
9480 9481
	 * this is a quick hack to make sure nothing really bad happens if somehow
	 * we get here after the end-of-recovery checkpoint.
9482 9483 9484 9485 9486 9487 9488 9489
	 *
	 * GPDB allows replay to also change the control file during
	 * DB_IN_STANDBY_MODE so that mirror can be restarted from the latest
	 * checkpoint location. This will save the recovery time of mirror, and also
	 * allow mirror to remove already replayed xlogs.
	 *
	 * FIXME: need to consider consolidating the DB_IN_ARCHIVE_RECOVERY (upstream)
	 * and DB_IN_STANDBY_MODE (GPDB only)
9490 9491
	 */
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9492 9493
	if ((ControlFile->state == DB_IN_ARCHIVE_RECOVERY
		     || ControlFile->state == DB_IN_STANDBY_MODE) &&
9494 9495 9496 9497 9498 9499
		XLByteLT(ControlFile->checkPointCopy.redo, lastCheckPoint.redo))
	{
		ControlFile->prevCheckPoint = ControlFile->checkPoint;
		ControlFile->checkPoint = lastCheckPointRecPtr;
		ControlFile->checkPointCopy = lastCheckPoint;
		ControlFile->time = (pg_time_t) time(NULL);
9500 9501
		if (flags & CHECKPOINT_IS_SHUTDOWN)
			ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
9502 9503 9504 9505 9506
		UpdateControlFile();
	}
	LWLockRelease(ControlFileLock);

	/*
9507 9508 9509 9510 9511 9512
	 * Delete old log files (those no longer needed even for previous
	 * checkpoint/restartpoint) to prevent the disk holding the xlog from
	 * growing full. We don't need do this during normal recovery, but during
	 * streaming recovery we have to or the disk will eventually fill up from
	 * old log files streamed from master.
	 */
9513
	if (WalRcvInProgress() && (_logId || _logSeg))
9514 9515 9516 9517
	{
		XLogRecPtr	endptr;

		/* Get the current (or recent) end of xlog */
9518
		endptr = GetWalRcvWriteRecPtr(NULL);
9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529

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

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

9530
	/*
9531 9532 9533 9534 9535
	 * 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).	When hot standby is disabled, though, we mustn't do
	 * this because StartupSUBTRANS hasn't been called yet.
9536
	 */
9537 9538
	if (EnableHotStandby)
		TruncateSUBTRANS(GetOldestXmin(true, false));
9539 9540 9541 9542 9543

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

9544
	xtime = GetLatestXTime();
9545
	ereport((log_checkpoints ? LOG : DEBUG2),
9546
			(errmsg("recovery restart point at %X/%X",
9547
					lastCheckPoint.redo.xlogid, lastCheckPoint.redo.xrecoff),
B
Bruce Momjian 已提交
9548 9549
		   xtime ? errdetail("last completed transaction was at log time %s",
							 timestamptz_to_str(xtime)) : 0));
9550

9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568
	elog((Debug_print_qd_mirroring ? LOG : DEBUG1), "RecoveryRestartPoint: checkpoint copy redo location %s, previous checkpoint location %s",
		 XLogLocationToString(&ControlFile->checkPointCopy.redo),
		 XLogLocationToString2(&ControlFile->prevCheckPoint));

	if (IsStandbyMode())
	{
		/*
		 * Delete offline log files (those no longer needed even for previous
		 * checkpoint).
		 */
		if (gp_keep_all_xlog == false && (_logId || _logSeg))
		{
			XLogRecPtr endptr;

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

			PrevLogSeg(_logId, _logSeg);
9569
			RemoveOldXlogFiles(_logId, _logSeg, endptr);
9570 9571
		}
	}
9572 9573

	LWLockRelease(CheckpointLock);
9574 9575

	/*
9576
	 * Finally, execute archive_cleanup_command, if any.
9577
	 */
9578
#if 0
9579 9580 9581
	if (XLogCtl->archiveCleanupCommand[0])
		ExecuteRecoveryCommand(XLogCtl->archiveCleanupCommand,
							   "archive_cleanup_command",
9582
							   false);
9583
#endif
9584

9585
	return true;
9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610
}

/*
 * Write a NEXTOID log record
 */
void
XLogPutNextOid(Oid nextOid)
{
	XLogRecData rdata;

	rdata.data = (char *) (&nextOid);
	rdata.len = sizeof(Oid);
	rdata.buffer = InvalidBuffer;
	rdata.next = NULL;
	(void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);

	/*
	 * We need not flush the NEXTOID record immediately, because any of the
	 * 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.
	 *
	 * Note, however, that the above statement only covers state "within" the
9611 9612
	 * 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
9613
	 * change may reach disk before the NEXTOID WAL record does.  The impact
9614 9615 9616 9617 9618
	 * 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.
9619 9620 9621
	 */
}

9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636
/*
 * Write a NEXTRELFILENODE log record similar to XLogPutNextOid
 */
void
XLogPutNextRelfilenode(Oid nextRelfilenode)
{
	XLogRecData rdata;

	rdata.data = (char *) (&nextRelfilenode);
	rdata.len = sizeof(Oid);
	rdata.buffer = InvalidBuffer;
	rdata.next = NULL;
	(void) XLogInsert(RM_XLOG_ID, XLOG_NEXTRELFILENODE, &rdata);
}

9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663
/*
 * 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.
 */
XLogRecPtr
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;
}

9664 9665 9666 9667 9668 9669
/*
 * Write a backup block if needed when we are setting a hint. Note that
 * this may be called for a variety of page types, not just heaps.
 *
 * Callable while holding just share lock on the buffer content.
 *
9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686
 * We can't use the plain backup block mechanism since that relies on the
 * Buffer being exclusively locked. Since some modifications (setting LSN, hint
 * bits) are allowed in a sharelocked buffer that can lead to wal checksum
 * failures. So instead we copy the page and insert the copied data as normal
 * record data.
 *
 * We only need to do something if page has not yet been full page written in
 * this checkpoint round. The LSN of the inserted wal record is returned if we
 * had to write, InvalidXLogRecPtr otherwise.
 *
 * It is possible that multiple concurrent backends could attempt to write WAL
 * records. In that case, multiple copies of the same block would be recorded
 * in separate WAL records by different backends, though that is still OK from
 * a correctness perspective.
 *
 * Note that this only works for buffers that fit the standard page model,
 * i.e. those for which buffer_std == true
9687 9688
 */
XLogRecPtr
9689
XLogSaveBufferForHint(Buffer buffer) 
9690
{
9691 9692 9693
	XLogRecPtr recptr = InvalidXLogRecPtr;
	XLogRecPtr lsn;
	XLogRecData rdata[2];
9694
	BkpBlock	bkpb;
9695

9696
	/*
9697
	 * Ensure no checkpoint can change our view of RedoRecPtr.
9698
	 */
9699
	Assert(MyProc->inCommit);
9700 9701

	/*
9702
	 * Update RedoRecPtr so XLogCheckBuffer can make the right decision
9703
	 */
9704
	GetRedoRecPtr();
9705

9706 9707 9708 9709 9710 9711 9712
	/*
	 * Setup phony rdata element for use within XLogCheckBuffer only.
	 * We reuse and reset rdata for any actual WAL record insert.
	 */
	rdata[0].buffer = buffer;
	rdata[0].buffer_std = true;

9713 9714 9715
	/*
	 * Check buffer while not holding an exclusive lock.
	 */
9716
	if (XLogCheckBuffer(rdata, false, false, &lsn, &bkpb))
9717 9718 9719
	{
		char copied_buffer[BLCKSZ];
		char *origdata = (char *) BufferGetBlock(buffer);
9720

9721 9722 9723 9724 9725
		/*
		 * Copy buffer so we don't have to worry about concurrent hint bit or
		 * lsn updates. We assume pd_lower/upper cannot be changed without an
		 * exclusive lock, so the contents bkp are not racy.
		 */
9726 9727 9728 9729
		memcpy(copied_buffer, origdata, bkpb.hole_offset);
		memcpy(copied_buffer + bkpb.hole_offset,
			   origdata + bkpb.hole_offset + bkpb.hole_length,
			   BLCKSZ - bkpb.hole_offset - bkpb.hole_length);
9730 9731 9732 9733

		/*
		 * Header for backup block.
		 */
9734 9735
		rdata[0].data = (char *) &bkpb;
		rdata[0].len = sizeof(BkpBlock);
9736 9737 9738 9739 9740 9741 9742
		rdata[0].buffer = InvalidBuffer;
		rdata[0].next = &(rdata[1]);

		/*
		 * Save copy of the buffer.
		 */
		rdata[1].data = copied_buffer;
9743
		rdata[1].len = BLCKSZ - bkpb.hole_length;
9744 9745 9746 9747 9748 9749 9750
		rdata[1].buffer = InvalidBuffer;
		rdata[1].next = NULL;

		recptr = XLogInsert(RM_XLOG_ID, XLOG_HINT, rdata);
	}

	return recptr;
9751 9752
}

9753 9754 9755 9756 9757 9758
/*
 * Write a RESTORE POINT record
 */
XLogRecPtr
XLogRestorePoint(const char *rpName)
{
9759 9760 9761
	XLogRecPtr	RecPtr;
	XLogRecData rdata;
	xl_restore_point xlrec;
9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772

	xlrec.rp_time = GetCurrentTimestamp();
	strncpy(xlrec.rp_name, rpName, MAXFNAMELEN);

	rdata.buffer = InvalidBuffer;
	rdata.data = (char *) &xlrec;
	rdata.len = sizeof(xl_restore_point);
	rdata.next = NULL;

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

R
Robert Haas 已提交
9773 9774
	ereport(LOG,
			(errmsg("restore point \"%s\" created at %X/%X",
9775
					rpName, RecPtr.xlogid, RecPtr.xrecoff)));
R
Robert Haas 已提交
9776

9777 9778 9779
	return RecPtr;
}

9780
/*
9781 9782
 * Check if any of the GUC parameters that are critical for hot standby
 * have changed, and update the value in pg_control file if necessary.
9783
 */
9784 9785
static void
XLogReportParameters(void)
9786
{
9787 9788 9789
	if (wal_level != ControlFile->wal_level ||
		MaxConnections != ControlFile->MaxConnections ||
		max_prepared_xacts != ControlFile->max_prepared_xacts ||
9790
		max_locks_per_xact != ControlFile->max_locks_per_xact)
9791 9792
	{
		/*
B
Bruce Momjian 已提交
9793 9794 9795 9796 9797
		 * The change in number of backend slots doesn't need to be WAL-logged
		 * if archiving is not enabled, as you can't start archive recovery
		 * with wal_level=minimal anyway. We don't really care about the
		 * values in pg_control either if wal_level=minimal, but seems better
		 * to keep them up-to-date to avoid confusion.
9798 9799 9800 9801 9802
		 */
		if (wal_level != ControlFile->wal_level || XLogIsNeeded())
		{
			XLogRecData rdata;
			xl_parameter_change xlrec;
9803

9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815
			xlrec.MaxConnections = MaxConnections;
			xlrec.max_prepared_xacts = max_prepared_xacts;
			xlrec.max_locks_per_xact = max_locks_per_xact;
			xlrec.wal_level = wal_level;

			rdata.buffer = InvalidBuffer;
			rdata.data = (char *) &xlrec;
			rdata.len = sizeof(xlrec);
			rdata.next = NULL;

			XLogInsert(RM_XLOG_ID, XLOG_PARAMETER_CHANGE, &rdata);
		}
9816

9817 9818 9819 9820 9821 9822
		ControlFile->MaxConnections = MaxConnections;
		ControlFile->max_prepared_xacts = max_prepared_xacts;
		ControlFile->max_locks_per_xact = max_locks_per_xact;
		ControlFile->wal_level = wal_level;
		UpdateControlFile();
	}
9823 9824
}

9825 9826 9827 9828
/*
 * XLOG resource manager's routines
 *
 * Definitions of info values are in include/catalog/pg_control.h, though
9829
 * not all record types are related to control file updates.
9830 9831 9832 9833 9834 9835
 */
void
xlog_redo(XLogRecPtr beginLoc __attribute__((unused)), XLogRecPtr lsn __attribute__((unused)), XLogRecord *record)
{
	uint8		info = record->xl_info & ~XLR_INFO_MASK;

9836
	/* Backup blocks are not used in xlog records */
9837
	Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
9838

9839 9840 9841 9842
	if (info == XLOG_NEXTOID)
	{
		Oid			nextOid;

9843 9844 9845 9846 9847 9848
		/*
		 * We used to try to take the maximum of ShmemVariableCache->nextOid
		 * and the recorded nextOid, but that fails if the OID counter wraps
		 * around.  Since no OID allocation should be happening during replay
		 * anyway, better to just believe the record exactly.
		 */
9849
		memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
9850 9851
		ShmemVariableCache->nextOid = nextOid;
		ShmemVariableCache->oidCount = 0;
9852
	}
9853 9854 9855 9856 9857 9858 9859 9860
	if (info == XLOG_NEXTRELFILENODE)
	{
		Oid			nextRelfilenode;

		memcpy(&nextRelfilenode, XLogRecGetData(record), sizeof(Oid));
		ShmemVariableCache->nextRelfilenode = nextRelfilenode;
		ShmemVariableCache->relfilenodeCount = 0;
	}
9861 9862 9863 9864 9865 9866 9867 9868 9869
	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;
9870 9871
		ShmemVariableCache->nextRelfilenode = checkPoint.nextRelfilenode;
		ShmemVariableCache->relfilenodeCount = 0;
9872 9873
		MultiXactSetNextMXact(checkPoint.nextMulti,
							  checkPoint.nextMultiOffset);
9874
		SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
B
Bruce Momjian 已提交
9875

9876
		/*
B
Bruce Momjian 已提交
9877 9878 9879
		 * If we see a shutdown checkpoint while waiting for an end-of-backup
		 * record, the backup was cancelled and the end-of-backup record will
		 * never arrive.
9880 9881 9882 9883 9884 9885
		 */
		if (InArchiveRecovery &&
			!XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
			ereport(ERROR,
					(errmsg("online backup was cancelled, recovery cannot continue")));

9886
		/*
B
Bruce Momjian 已提交
9887 9888 9889 9890
		 * If we see a shutdown checkpoint, we know that nothing was running
		 * on the master at this point. So fake-up an empty running-xacts
		 * record and use that here and now. Recover additional standby state
		 * for prepared transactions.
9891
		 */
9892 9893
		if (standbyState >= STANDBY_INITIALIZED)
		{
9894 9895 9896
			TransactionId *xids;
			int			nxids;
			TransactionId oldestActiveXID;
9897
			TransactionId latestCompletedXid;
9898 9899 9900 9901
			RunningTransactionsData running;

			oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);

9902
			/*
9903
			 * Construct a RunningTransactions snapshot representing a shut
B
Bruce Momjian 已提交
9904 9905 9906
			 * down server, with only prepared transactions still alive. We're
			 * never overflowed at this point because all subxids are listed
			 * with their parent prepared transactions.
9907
			 */
9908 9909 9910 9911
			running.xcnt = nxids;
			running.subxid_overflow = false;
			running.nextXid = checkPoint.nextXid;
			running.oldestRunningXid = oldestActiveXID;
9912 9913
			latestCompletedXid = checkPoint.nextXid;
			TransactionIdRetreat(latestCompletedXid);
9914
			Assert(TransactionIdIsNormal(latestCompletedXid));
9915
			running.latestCompletedXid = latestCompletedXid;
9916 9917 9918 9919 9920
			running.xids = xids;

			ProcArrayApplyRecoveryInfo(&running);

			StandbyRecoverPreparedTransactions(true);
9921
		}
9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969

		/*
		 * If we see a shutdown checkpoint while waiting for an end-of-backup
		 * record, the backup was canceled and the end-of-backup record will
		 * never arrive.
		 */
		if (StandbyMode &&
			!XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
			ereport(PANIC,
			(errmsg("online backup was canceled, recovery cannot continue")));

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

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

		/*
		 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
		 */
		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",
								checkPoint.ThisTimeLineID, ThisTimeLineID)));
			/* Following WAL records should be run with new TLI */
			ThisTimeLineID = checkPoint.ThisTimeLineID;
		}

		RecoveryRestartPoint(&checkPoint);
	}
	else if (info == XLOG_CHECKPOINT_ONLINE)
	{
		CheckPoint	checkPoint;

		memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9970
		/* In an ONLINE checkpoint, treat the XID counter as a minimum */
9971 9972 9973
		if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
								  checkPoint.nextXid))
			ShmemVariableCache->nextXid = checkPoint.nextXid;
9974 9975 9976
		/* ... but still treat OID counter as exact */
		ShmemVariableCache->nextOid = checkPoint.nextOid;
		ShmemVariableCache->oidCount = 0;
9977 9978
		ShmemVariableCache->nextRelfilenode = checkPoint.nextRelfilenode;
		ShmemVariableCache->relfilenodeCount = 0;
9979 9980
		MultiXactAdvanceNextMXact(checkPoint.nextMulti,
								  checkPoint.nextMultiOffset);
9981 9982
		if (TransactionIdPrecedes(ShmemVariableCache->oldestXid,
								  checkPoint.oldestXid))
9983 9984
			SetTransactionIdLimit(checkPoint.oldestXid,
								  checkPoint.oldestXidDB);
9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008

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

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

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

		RecoveryRestartPoint(&checkPoint);
	}
10009 10010 10011 10012
	else if (info == XLOG_NOOP)
	{
		/* nothing to do here */
	}
10013 10014 10015 10016
	else if (info == XLOG_SWITCH)
	{
		/* nothing to do here */
	}
10017 10018
	else if (info == XLOG_HINT)
	{
10019
		char *data;
10020
		BkpBlock bkpb;
10021 10022

		/*
10023 10024 10025 10026
		 * Hint bit records contain a backup block stored "inline" in the normal
		 * data since the locking when writing hint records isn't sufficient to
		 * use the normal backup block mechanism, which assumes exclusive lock
		 * on the buffer supplied.
10027
		 *
10028 10029
		 * Since the only change in these backup block are hint bits, there are
		 * no recovery conflicts generated.
10030 10031 10032 10033 10034
		 *
		 * This also means there is no corresponding API call for this,
		 * so an smgr implementation has no need to implement anything.
		 * Which means nothing is needed in md.c etc
		 */
10035
		data = XLogRecGetData(record);
10036 10037
		memcpy(&bkpb, data, sizeof(BkpBlock));
		data += sizeof(BkpBlock);
10038

10039
		RestoreBackupBlockContents(lsn, bkpb, data, false, false);
10040
	}
10041 10042 10043 10044
	else if (info == XLOG_RESTORE_POINT)
	{
		/* nothing to do here */
	}
10045 10046 10047 10048 10049 10050 10051 10052 10053 10054
	else if (info == XLOG_BACKUP_END)
	{
		XLogRecPtr	startpoint;

		memcpy(&startpoint, XLogRecGetData(record), sizeof(startpoint));

		if (XLByteEQ(ControlFile->backupStartPoint, startpoint))
		{
			/*
			 * We have reached the end of base backup, the point where
10055
			 * pg_stop_backup() was done. The data on disk is now consistent.
10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072
			 * Reset backupStartPoint, and update minRecoveryPoint to make
			 * sure we don't allow starting up at an earlier point even if
			 * recovery is stopped and restarted soon after this.
			 */
			elog(DEBUG1, "end of backup reached");

			LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);

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

			LWLockRelease(ControlFileLock);
		}
	}
10073
	else if (info == XLOG_PARAMETER_CHANGE)
10074
	{
10075 10076 10077 10078 10079
		xl_parameter_change xlrec;

		/* Update our copy of the parameters in pg_control */
		memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_parameter_change));

10080
		LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
10081 10082 10083 10084
		ControlFile->MaxConnections = xlrec.MaxConnections;
		ControlFile->max_prepared_xacts = xlrec.max_prepared_xacts;
		ControlFile->max_locks_per_xact = xlrec.max_locks_per_xact;
		ControlFile->wal_level = xlrec.wal_level;
B
Bruce Momjian 已提交
10085

10086
		/*
B
Bruce Momjian 已提交
10087 10088 10089 10090 10091 10092
		 * Update minRecoveryPoint to ensure that if recovery is aborted, we
		 * recover back up to this point before allowing hot standby again.
		 * This is particularly important if wal_level was set to 'archive'
		 * before, and is now 'hot_standby', to ensure you don't run queries
		 * against the WAL preceding the wal_level change. Same applies to
		 * decreasing max_* settings.
10093 10094 10095 10096 10097 10098 10099 10100
		 */
		minRecoveryPoint = ControlFile->minRecoveryPoint;
		if ((minRecoveryPoint.xlogid != 0 || minRecoveryPoint.xrecoff != 0)
			&& XLByteLT(minRecoveryPoint, lsn))
		{
			ControlFile->minRecoveryPoint = lsn;
		}

10101
		UpdateControlFile();
10102
		LWLockRelease(ControlFileLock);
10103 10104 10105

		/* Check to see if any changes to max_connections give problems */
		CheckRequiredParameterValues();
10106
	}
10107 10108 10109
}

void
10110
xlog_desc(StringInfo buf, XLogRecord *record)
10111 10112 10113 10114 10115 10116 10117 10118 10119
{
	uint8		info = record->xl_info & ~XLR_INFO_MASK;
	char		*rec = XLogRecGetData(record);

	if (info == XLOG_CHECKPOINT_SHUTDOWN ||
		info == XLOG_CHECKPOINT_ONLINE)
	{
		CheckPoint *checkpoint = (CheckPoint *) rec;

10120
		CheckpointExtendedRecord ckptExtended;
10121

10122
		appendStringInfo(buf, "checkpoint: redo %X/%X; "
10123
						 "tli %u; xid %u/%u; oid %u; relfilenode %u; multi %u; offset %u; "
10124
						 "oldest xid %u in DB %u; oldest running xid %u; %s",
10125 10126 10127 10128
						 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
						 checkpoint->ThisTimeLineID,
						 checkpoint->nextXidEpoch, checkpoint->nextXid,
						 checkpoint->nextOid,
10129
						 checkpoint->nextRelfilenode,
10130 10131
						 checkpoint->nextMulti,
						 checkpoint->nextMultiOffset,
10132 10133
						 checkpoint->oldestXid,
						 checkpoint->oldestXidDB,
10134
						 checkpoint->oldestActiveXid,
10135 10136
				 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");

10137 10138 10139
		UnpackCheckPointRecord(record, &ckptExtended);

		if (ckptExtended.dtxCheckpointLen > 0)
10140 10141
		{
			appendStringInfo(buf,
10142
				 ", checkpoint record data length = %u, DTX committed count %d, DTX data length %u",
10143 10144
							 record->xl_len,
							 ckptExtended.dtxCheckpoint->committedCount,
10145
							 ckptExtended.dtxCheckpointLen);
10146 10147 10148 10149
			if (ckptExtended.ptas != NULL)
				appendStringInfo(buf,
								 ", prepared transaction agg state count = %d",
								 ckptExtended.ptas->count);
10150 10151
		}
	}
10152 10153 10154 10155
	else if (info == XLOG_NOOP)
	{
		appendStringInfo(buf, "xlog no-op");
	}
10156 10157 10158 10159 10160 10161 10162
	else if (info == XLOG_NEXTOID)
	{
		Oid			nextOid;

		memcpy(&nextOid, rec, sizeof(Oid));
		appendStringInfo(buf, "nextOid: %u", nextOid);
	}
10163 10164
	else if (info == XLOG_HINT)
	{
10165
		BkpBlock *bkpb = (BkpBlock *) rec;
10166
		appendStringInfo(buf, "page hint: %u/%u/%u block %u",
10167 10168 10169 10170
						 bkpb->node.spcNode,
						 bkpb->node.dbNode,
						 bkpb->node.relNode,
						 bkpb->block);
10171
	}
10172 10173 10174 10175 10176 10177 10178
	else if (info == XLOG_NEXTRELFILENODE)
	{
		Oid			nextRelfilenode;

		memcpy(&nextRelfilenode, rec, sizeof(Oid));
		appendStringInfo(buf, "nextRelfilenode: %u", nextRelfilenode);
	}
10179 10180 10181 10182
	else if (info == XLOG_SWITCH)
	{
		appendStringInfo(buf, "xlog switch");
	}
10183 10184 10185 10186 10187 10188 10189
	else if (info == XLOG_RESTORE_POINT)
	{
		xl_restore_point *xlrec = (xl_restore_point *) rec;

		appendStringInfo(buf, "restore point: %s", xlrec->rp_name);

	}
10190 10191
	else if (info == XLOG_BACKUP_END)
	{
B
Bruce Momjian 已提交
10192
		XLogRecPtr	startpoint;
10193 10194 10195 10196 10197

		memcpy(&startpoint, rec, sizeof(XLogRecPtr));
		appendStringInfo(buf, "backup end: %X/%X",
						 startpoint.xlogid, startpoint.xrecoff);
	}
10198
	else if (info == XLOG_PARAMETER_CHANGE)
10199
	{
10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215
		xl_parameter_change xlrec;
		const char *wal_level_str;
		const struct config_enum_entry *entry;

		memcpy(&xlrec, rec, sizeof(xl_parameter_change));

		/* Find a string representation for wal_level */
		wal_level_str = "?";
		for (entry = wal_level_options; entry->name; entry++)
		{
			if (entry->val == xlrec.wal_level)
			{
				wal_level_str = entry->name;
				break;
			}
		}
10216

10217 10218 10219 10220 10221
		appendStringInfo(buf, "parameter change: max_connections=%d max_prepared_xacts=%d max_locks_per_xact=%d wal_level=%s",
						 xlrec.MaxConnections,
						 xlrec.max_prepared_xacts,
						 xlrec.max_locks_per_xact,
						 wal_level_str);
10222
	}
10223 10224 10225 10226
	else
		appendStringInfo(buf, "UNKNOWN");
}

10227 10228
static void
xlog_outrec(StringInfo buf, XLogRecord *record)
10229 10230 10231 10232 10233 10234 10235
{
	int			i;

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

10236 10237 10238
	appendStringInfo(buf, "; len %u",
					 record->xl_len);

10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
	{
		if (record->xl_info & XLR_SET_BKP_BLOCK(i))
			appendStringInfo(buf, "; bkpb%d", i + 1);
	}

	appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
}


/*
10250 10251
 * Return the (possible) sync flag used for opening a file, depending on the
 * value of the GUC wal_sync_method.
10252
 */
10253 10254
static int
get_sync_bit(int method)
10255
{
B
Bruce Momjian 已提交
10256
	int			o_direct_flag = 0;
10257

10258 10259 10260
	/* If fsync is disabled, never open in sync mode */
	if (!enableFsync)
		return 0;
10261

10262
	/*
10263
	 * Optimize writes by bypassing kernel cache with O_DIRECT when using
10264
	 * O_SYNC/O_FSYNC and O_DSYNC.	But only if archiving and streaming are
B
Bruce Momjian 已提交
10265 10266 10267 10268 10269
	 * disabled, otherwise the archive command or walsender process will read
	 * the WAL soon after writing it, which is guaranteed to cause a physical
	 * read if we bypassed the kernel cache. We also skip the
	 * posix_fadvise(POSIX_FADV_DONTNEED) call in XLogFileClose() for the same
	 * reason.
10270 10271 10272 10273 10274
	 *
	 * Never use O_DIRECT in walreceiver process for similar reasons; the WAL
	 * written by walreceiver is normally read by the startup process soon
	 * after its written. Also, walreceiver performs unaligned writes, which
	 * don't work with O_DIRECT, so it is required for correctness too.
10275
	 */
10276
	if (!XLogIsNeeded() && !AmWalReceiverProcess())
10277
		o_direct_flag = PG_O_DIRECT;
10278 10279

	switch (method)
10280
	{
10281 10282 10283 10284 10285 10286
			/*
			 * 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.
			 */
10287 10288 10289 10290
		case SYNC_METHOD_FSYNC:
		case SYNC_METHOD_FSYNC_WRITETHROUGH:
		case SYNC_METHOD_FDATASYNC:
			return 0;
10291
#ifdef OPEN_SYNC_FLAG
10292
		case SYNC_METHOD_OPEN:
10293
			return OPEN_SYNC_FLAG | o_direct_flag;
10294 10295
#endif
#ifdef OPEN_DATASYNC_FLAG
10296
		case SYNC_METHOD_OPEN_DSYNC:
10297
			return OPEN_DATASYNC_FLAG | o_direct_flag;
10298
#endif
10299 10300 10301
		default:
			/* can't happen (unless we are out of sync with option array) */
			elog(ERROR, "unrecognized wal_sync_method: %d", method);
10302
			return 0;			/* silence warning */
10303 10304
	}
}
10305

10306 10307 10308
/*
 * GUC support
 */
10309 10310
void
assign_xlog_sync_method(int new_sync_method, void *extra)
10311 10312
{
	if (sync_method != new_sync_method)
10313 10314 10315 10316 10317 10318 10319
	{
		/*
		 * To ensure that no blocks escape unsynced, force an fsync on the
		 * currently open log segment (if any).  Also, if the open flag is
		 * changing, close the log file so it will be reopened (with new flag
		 * bit) at next use.
		 */
10320
		if (openLogFile >= 0)
10321
		{
10322
			if (pg_fsync(openLogFile) != 0)
10323 10324
				ereport(PANIC,
						(errcode_for_file_access(),
10325
						 errmsg("could not fsync log file %u, segment %u: %m",
B
Bruce Momjian 已提交
10326
								openLogId, openLogSeg)));
10327
			if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
10328 10329 10330 10331 10332
				XLogFileClose();
		}
	}
}

10333

10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358
/*
 * Issue appropriate kind of fsync (if any) for an XLOG output file.
 *
 * 'fd' is a file descriptor for the XLOG file to be fsync'd.
 * 'log' and 'seg' are for error reporting purposes.
 */
void
issue_xlog_fsync(int fd, uint32 log, uint32 seg)
{
	switch (sync_method)
	{
		case SYNC_METHOD_FSYNC:
			if (pg_fsync_no_writethrough(fd) != 0)
				ereport(PANIC,
						(errcode_for_file_access(),
						 errmsg("could not fsync log file %u, segment %u: %m",
								log, seg)));
			break;
#ifdef HAVE_FSYNC_WRITETHROUGH
		case SYNC_METHOD_FSYNC_WRITETHROUGH:
			if (pg_fsync_writethrough(fd) != 0)
				ereport(PANIC,
						(errcode_for_file_access(),
						 errmsg("could not fsync write-through log file %u, segment %u: %m",
								log, seg)));
10359 10360
			break;
#endif
10361 10362
#ifdef HAVE_FDATASYNC
		case SYNC_METHOD_FDATASYNC:
10363
			if (pg_fdatasync(fd) != 0)
10364 10365
				ereport(PANIC,
						(errcode_for_file_access(),
10366 10367 10368 10369 10370
					errmsg("could not fdatasync log file %u, segment %u: %m",
						   log, seg)));
			break;
#endif
		case SYNC_METHOD_OPEN:
10371
		case SYNC_METHOD_OPEN_DSYNC:
10372 10373 10374 10375 10376 10377 10378 10379
			/* write synced it already */
			break;
		default:
			elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
			break;
	}
}

10380

10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417
/*
 * do_pg_start_backup is the workhorse of the user-visible pg_start_backup()
 * function. It creates the necessary starting checkpoint and constructs the
 * backup label file.
 *
 * There are two kind of backups: exclusive and non-exclusive. An exclusive
 * backup is started with pg_start_backup(), and there can be only one active
 * at a time. The backup label file of an exclusive backup is written to
 * $PGDATA/backup_label, and it is removed by pg_stop_backup().
 *
 * A non-exclusive backup is used for the streaming base backups (see
 * src/backend/replication/basebackup.c). The difference to exclusive backups
 * is that the backup label file is not written to disk. Instead, its would-be
 * contents are returned in *labelfile, and the caller is responsible for
 * including it in the backup archive as 'backup_label'. There can be many
 * non-exclusive backups active at the same time, and they don't conflict
 * with an exclusive backup either.
 *
 * Every successfully started non-exclusive backup must be stopped by calling
 * do_pg_stop_backup() or do_pg_abort_backup().
 */
XLogRecPtr
do_pg_start_backup(const char *backupidstr, bool fast, char **labelfile)
{
	bool		exclusive = (labelfile == NULL);
	bool		backup_started_in_recovery = false;
	XLogRecPtr	checkpointloc;
	XLogRecPtr	startpoint;
	pg_time_t	stamp_time;
	char		strfbuf[128];
	char		xlogfilename[MAXFNAMELEN];
	uint32		_logId;
	uint32		_logSeg;
	struct stat stat_buf;
	FILE	   *fp;
	StringInfoData labelfbuf;

10418
	if (!superuser() && !is_authenticated_user_replication_role())
10419 10420 10421 10422
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
		   errmsg("must be superuser or replication role to run a backup")));

10423
	if (RecoveryInProgress())
10424
		ereport(ERROR,
10425 10426 10427
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));
10428

10429 10430 10431
	if (!XLogIsNeeded())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
B
Bruce Momjian 已提交
10432
			  errmsg("WAL level not sufficient for making an online backup"),
10433 10434
				 errhint("wal_level must be set to \"archive\" or \"hot_standby\" at server start.")));

10435 10436 10437 10438 10439
	if (strlen(backupidstr) > MAXPGPATH)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("backup label too long (max %d bytes)",
						MAXPGPATH)));
B
Bruce Momjian 已提交
10440

10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453
	/*
	 * Force an XLOG file switch before the checkpoint, to ensure that the WAL
	 * segment the checkpoint is written to doesn't contain pages with old
	 * timeline IDs. That would otherwise happen if you called
	 * pg_start_backup() right after restoring from a PITR archive: the first
	 * WAL segment containing the startup checkpoint has pages in the
	 * beginning with the old timeline ID. That can cause trouble at recovery:
	 * we won't have a history file covering the old timeline if pg_xlog
	 * directory was not included in the base backup and the WAL archive was
	 * cleared too before starting the backup.
	 */
	RequestXLogSwitch();

10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540
	/*
	 * 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
	 * 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.)
	 *
	 * Note that forcePageWrites has no effect during an online backup from
	 * the standby.
	 *
	 * We must hold WALInsertLock to change the value of forcePageWrites, to
	 * ensure adequate interlocking against XLogInsert().
	 */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
	if (exclusive)
	{
		if (XLogCtl->Insert.exclusiveBackup)
		{
			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.exclusiveBackup = true;
	}
	else
		XLogCtl->Insert.nonExclusiveBackups++;
	XLogCtl->Insert.forcePageWrites = true;
	LWLockRelease(WALInsertLock);

	/* Ensure we release forcePageWrites if fail below */
	PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) BoolGetDatum(exclusive));
	{
		bool		gotUniqueStartpoint = false;

		/*
		 * Force an XLOG file switch before the checkpoint, to ensure that the
		 * WAL segment the checkpoint is written to doesn't contain pages with
		 * old timeline IDs.  That would otherwise happen if you called
		 * pg_start_backup() right after restoring from a PITR archive: the
		 * first WAL segment containing the startup checkpoint has pages in
		 * the beginning with the old timeline ID.	That can cause trouble at
		 * recovery: we won't have a history file covering the old timeline if
		 * pg_xlog directory was not included in the base backup and the WAL
		 * archive was cleared too before starting the backup.
		 *
		 * This also ensures that we have emitted a WAL page header that has
		 * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
		 * Therefore, if a WAL archiver (such as pglesslog) is trying to
		 * compress out removable backup blocks, it won't remove any that
		 * occur after this point.
		 *
		 * During recovery, we skip forcing XLOG file switch, which means that
		 * the backup taken during recovery is not available for the special
		 * recovery case described above.
		 */
		if (!backup_started_in_recovery)
			RequestXLogSwitch();

		do
		{
			/*
			 * Force a CHECKPOINT.	Aside from being necessary to prevent torn
			 * 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.
			 *
			 * During recovery, establish a restartpoint if possible. We use
			 * the last restartpoint as the backup starting checkpoint. This
			 * means that two successive backup runs can have same checkpoint
			 * positions.
			 *
			 * Since the fact that we are executing do_pg_start_backup()
			 * during recovery means that checkpointer is running, we can use
			 * RequestCheckpoint() to establish a restartpoint.
			 *
			 * We use CHECKPOINT_IMMEDIATE only if requested by user (via
			 * passing fast = true).  Otherwise this can take awhile.
			 */
10541 10542
			RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT |
							  (fast ? CHECKPOINT_IMMEDIATE : 0));
10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689

			/*
			 * 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_SHARED);
			checkpointloc = ControlFile->checkPoint;
			startpoint = ControlFile->checkPointCopy.redo;
			LWLockRelease(ControlFileLock);

			/*
			 * If two base backups are started at the same time (in WAL sender
			 * processes), we need to make sure that they use different
			 * checkpoints as starting locations, because we use the starting
			 * WAL location as a unique identifier for the base backup in the
			 * end-of-backup WAL record and when we write the backup history
			 * file. Perhaps it would be better generate a separate unique ID
			 * for each backup instead of forcing another checkpoint, but
			 * taking a checkpoint right after another is not that expensive
			 * either because only few buffers have been dirtied yet.
			 */
			LWLockAcquire(WALInsertLock, LW_SHARED);
			if (XLByteLT(XLogCtl->Insert.lastBackupStart, startpoint))
			{
				XLogCtl->Insert.lastBackupStart = startpoint;
				gotUniqueStartpoint = true;
			}
			LWLockRelease(WALInsertLock);
		} while (!gotUniqueStartpoint);

		XLByteToSeg(startpoint, _logId, _logSeg);
		XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);

		/*
		 * Construct backup label file
		 */
		initStringInfo(&labelfbuf);

		/* 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));
		appendStringInfo(&labelfbuf, "START WAL LOCATION: %X/%X (file %s)\n",
						 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
		appendStringInfo(&labelfbuf, "CHECKPOINT LOCATION: %X/%X\n",
						 checkpointloc.xlogid, checkpointloc.xrecoff);
		appendStringInfo(&labelfbuf, "BACKUP METHOD: %s\n",
						 exclusive ? "pg_start_backup" : "streamed");
		appendStringInfo(&labelfbuf, "BACKUP FROM: %s\n",
						 backup_started_in_recovery ? "standby" : "master");
		appendStringInfo(&labelfbuf, "START TIME: %s\n", strfbuf);
		appendStringInfo(&labelfbuf, "LABEL: %s\n", backupidstr);

		elogif(debug_basebackup, LOG, "basebackup label file --\n%s", labelfbuf.data);

		/*
		 * Okay, write the file, or return its contents to caller.
		 */
		if (exclusive)
		{
			/*
			 * Check for existing backup label --- implies a backup is already
			 * running.  (XXX given that we checked exclusiveBackup 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)));

			fp = AllocateFile(BACKUP_LABEL_FILE, "w");

			if (!fp)
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not create file \"%s\": %m",
								BACKUP_LABEL_FILE)));
			if (fwrite(labelfbuf.data, labelfbuf.len, 1, fp) != 1 ||
				fflush(fp) != 0 ||
				pg_fsync(fileno(fp)) != 0 ||
				ferror(fp) ||
				FreeFile(fp))
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not write file \"%s\": %m",
								BACKUP_LABEL_FILE)));
			pfree(labelfbuf.data);
		}
		else
			*labelfile = labelfbuf.data;
	}
	PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) BoolGetDatum(exclusive));

	/*
	 * We're done.  As a convenience, return the starting WAL location.
	 */
	return startpoint;
}

/* Error cleanup callback for pg_start_backup */
static void
pg_start_backup_callback(int code, Datum arg)
{
	bool		exclusive = DatumGetBool(arg);

	/* Update backup counters and forcePageWrites on failure */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
	if (exclusive)
	{
		Assert(XLogCtl->Insert.exclusiveBackup);
		XLogCtl->Insert.exclusiveBackup = false;
	}
	else
	{
		Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
		XLogCtl->Insert.nonExclusiveBackups--;
	}

	if (!XLogCtl->Insert.exclusiveBackup &&
		XLogCtl->Insert.nonExclusiveBackups == 0)
	{
		XLogCtl->Insert.forcePageWrites = false;
	}
	LWLockRelease(WALInsertLock);
}

/*
 * do_pg_stop_backup is the workhorse of the user-visible pg_stop_backup()
 * function.

 * If labelfile is NULL, this stops an exclusive backup. Otherwise this stops
 * the non-exclusive backup specified by 'labelfile'.
 */
XLogRecPtr
10690
do_pg_stop_backup(char *labelfile, bool waitforarchive)
10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701
{
	bool		exclusive = (labelfile == NULL);
	bool		backup_started_in_recovery = false;
	XLogRecPtr	startpoint;
	XLogRecPtr	stoppoint;
	XLogRecData rdata;
	pg_time_t	stamp_time;
	char		strfbuf[128];
	char		histfilepath[MAXPGPATH];
	char		startxlogfilename[MAXFNAMELEN];
	char		stopxlogfilename[MAXFNAMELEN];
10702 10703
	char		lastxlogfilename[MAXFNAMELEN];
	char		histfilename[MAXFNAMELEN];
10704 10705 10706 10707 10708 10709
	char		backupfrom[20];
	uint32		_logId;
	uint32		_logSeg;
	FILE	   *lfp;
	FILE	   *fp;
	char		ch;
10710 10711
	int			seconds_before_warning;
	int			waits = 0;
10712
	bool		reported_waiting = false;
10713 10714 10715 10716 10717 10718
	char	   *remaining;
	char	   *ptr;

	/* Currently backup during recovery not supported */
	backup_started_in_recovery = false;

10719
	if (!superuser() && !is_authenticated_user_replication_role())
10720 10721 10722 10723
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
		 (errmsg("must be superuser or replication role to run a backup"))));

10724 10725 10726 10727 10728 10729
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

10730 10731 10732
	if (!XLogIsNeeded())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
B
Bruce Momjian 已提交
10733
			  errmsg("WAL level not sufficient for making an online backup"),
10734 10735
				 errhint("wal_level must be set to \"archive\" or \"hot_standby\" at server start.")));

10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896
	/*
	 * OK to update backup counters and forcePageWrites
	 */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
	if (exclusive)
		XLogCtl->Insert.exclusiveBackup = false;
	else
	{
		/*
		 * The user-visible pg_start/stop_backup() functions that operate on
		 * exclusive backups can be called at any time, but for non-exclusive
		 * backups, it is expected that each do_pg_start_backup() call is
		 * matched by exactly one do_pg_stop_backup() call.
		 */
		Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
		XLogCtl->Insert.nonExclusiveBackups--;
	}

	if (!XLogCtl->Insert.exclusiveBackup &&
		XLogCtl->Insert.nonExclusiveBackups == 0)
	{
		XLogCtl->Insert.forcePageWrites = false;
	}
	LWLockRelease(WALInsertLock);

	if (exclusive)
	{
		/*
		 * Read the existing label file into memory.
		 */
		struct stat statbuf;
		int			r;

		if (stat(BACKUP_LABEL_FILE, &statbuf))
		{
			if (errno != ENOENT)
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not stat file \"%s\": %m",
								BACKUP_LABEL_FILE)));
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
					 errmsg("a backup is not in progress")));
		}

		lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
		if (!lfp)
		{
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
							BACKUP_LABEL_FILE)));
		}
		labelfile = palloc(statbuf.st_size + 1);
		r = fread(labelfile, statbuf.st_size, 1, lfp);
		labelfile[statbuf.st_size] = '\0';

		/*
		 * Close and remove the backup label file
		 */
		if (r != 1 || ferror(lfp) || FreeFile(lfp))
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
							BACKUP_LABEL_FILE)));
		if (unlink(BACKUP_LABEL_FILE) != 0)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not remove file \"%s\": %m",
							BACKUP_LABEL_FILE)));
	}

	/*
	 * Read and parse the START WAL LOCATION line (this code is pretty crude,
	 * but we are not expecting any variability in the file format).
	 */
	if (sscanf(labelfile, "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),
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
	remaining = strchr(labelfile, '\n') + 1;	/* %n is not portable enough */

	/*
	 * Parse the BACKUP FROM line. If we are taking an online backup from the
	 * standby, we confirm that the standby has not been promoted during the
	 * backup.
	 */
	ptr = strstr(remaining, "BACKUP FROM:");
	if (!ptr || sscanf(ptr, "BACKUP FROM: %19s\n", backupfrom) != 1)
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
	if (strcmp(backupfrom, "standby") == 0 && !backup_started_in_recovery)
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("the standby was promoted during online backup"),
				 errhint("This means that the backup being taken is corrupt "
						 "and should not be used. "
						 "Try taking another online backup.")));

	/*
	 * Write the backup-end xlog record
	 */
	rdata.data = (char *) (&startpoint);
	rdata.len = sizeof(startpoint);
	rdata.buffer = InvalidBuffer;
	rdata.next = NULL;
	stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END, &rdata);

	elog(LOG, "Basebackup stop point is at %X/%X.",
			   stoppoint.xlogid, stoppoint.xrecoff);

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

	XLByteToPrevSeg(stoppoint, _logId, _logSeg);
	XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);

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

	/*
	 * Write the backup history file
	 */
	XLByteToSeg(startpoint, _logId, _logSeg);
	BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
						  startpoint.xrecoff % XLogSegSize);
	fp = AllocateFile(histfilepath, "w");
	if (!fp)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m",
						histfilepath)));
	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);
	/* transfer remaining lines from label to history file */
	fprintf(fp, "%s", remaining);
	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",
						histfilepath)));

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

10897
	/*
10898
	 * If archiving is enabled, wait for all the required WAL files to be
B
Bruce Momjian 已提交
10899 10900 10901 10902 10903 10904
	 * archived before returning. If archiving isn't enabled, the required WAL
	 * needs to be transported via streaming replication (hopefully with
	 * wal_keep_segments set high enough), or some more exotic mechanism like
	 * polling and copying files from pg_xlog with script. We have no
	 * knowledge of those mechanisms, so it's up to the user to ensure that he
	 * gets all the required WAL.
10905
	 *
10906
	 * We wait until both the last WAL file filled during backup and the
B
Bruce Momjian 已提交
10907 10908 10909
	 * history file have been archived, and assume that the alphabetic sorting
	 * property of the WAL files ensures any earlier WAL files are safely
	 * archived as well.
10910
	 *
10911 10912
	 * We wait forever, since archive_command is supposed to work and we
	 * assume the admin wanted his backup to work completely. If you don't
B
Bruce Momjian 已提交
10913 10914
	 * wish to wait, you can set statement_timeout.  Also, some notices are
	 * issued to clue in anyone who might be doing this interactively.
10915
	 */
10916
	if (waitforarchive && XLogArchivingActive())
T
Tom Lane 已提交
10917
	{
B
Bruce Momjian 已提交
10918 10919
		XLByteToPrevSeg(stoppoint, _logId, _logSeg);
		XLogFileName(lastxlogfilename, ThisTimeLineID, _logId, _logSeg);
T
Tom Lane 已提交
10920

B
Bruce Momjian 已提交
10921 10922 10923
		XLByteToSeg(startpoint, _logId, _logSeg);
		BackupHistoryFileName(histfilename, ThisTimeLineID, _logId, _logSeg,
							  startpoint.xrecoff % XLogSegSize);
10924

B
Bruce Momjian 已提交
10925 10926
		seconds_before_warning = 60;
		waits = 0;
10927

B
Bruce Momjian 已提交
10928 10929
		while (XLogArchiveIsBusy(lastxlogfilename) ||
			   XLogArchiveIsBusy(histfilename))
10930
		{
B
Bruce Momjian 已提交
10931
			CHECK_FOR_INTERRUPTS();
10932

B
Bruce Momjian 已提交
10933 10934 10935 10936 10937 10938
			if (!reported_waiting && waits > 5)
			{
				ereport(NOTICE,
						(errmsg("pg_stop_backup cleanup done, waiting for required WAL segments to be archived")));
				reported_waiting = true;
			}
10939

B
Bruce Momjian 已提交
10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951
			pg_usleep(1000000L);

			if (++waits >= seconds_before_warning)
			{
				seconds_before_warning *= 2;	/* This wraps in >10 years... */
				ereport(WARNING,
						(errmsg("pg_stop_backup still waiting for all required WAL segments to be archived (%d seconds elapsed)",
								waits),
						 errhint("Check that your archive_command is executing properly.  "
								 "pg_stop_backup can be cancelled safely, "
								 "but the database backup will not be usable without all the WAL segments.")));
			}
10952
		}
10953

B
Bruce Momjian 已提交
10954 10955
		ereport(NOTICE,
				(errmsg("pg_stop_backup complete, all required WAL segments have been archived")));
10956
	}
10957
	else if (waitforarchive)
10958 10959
		ereport(NOTICE,
				(errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
10960

10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997
	/*
	 * We're done.  As a convenience, return the ending WAL location.
	 */
	return stoppoint;
}

/*
 * do_pg_abort_backup: abort a running backup
 *
 * This does just the most basic steps of do_pg_stop_backup(), by taking the
 * system out of backup mode, thus making it a lot more safe to call from
 * an error handler.
 *
 * NB: This is only for aborting a non-exclusive backup that doesn't write
 * backup_label. A backup started with pg_stop_backup() needs to be finished
 * with pg_stop_backup().
 */
void
do_pg_abort_backup(void)
{
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
	Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
	XLogCtl->Insert.nonExclusiveBackups--;

	if (!XLogCtl->Insert.exclusiveBackup &&
		XLogCtl->Insert.nonExclusiveBackups == 0)
	{
		XLogCtl->Insert.forcePageWrites = false;
	}
	LWLockRelease(WALInsertLock);
}


/*
 * pg_switch_xlog: switch to next xlog file
 */
Datum
10998
pg_switch_xlog(PG_FUNCTION_ARGS)
10999 11000 11001 11002 11003 11004 11005
{
	XLogRecPtr	switchpoint;
	char		location[MAXFNAMELEN];

	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
11006
			 (errmsg("must be superuser to switch transaction log files"))));
11007

11008 11009 11010 11011 11012 11013
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

11014 11015 11016 11017 11018 11019 11020
	switchpoint = RequestXLogSwitch();

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

11024 11025 11026 11027 11028 11029
/*
 * pg_create_restore_point: a named point for restore
 */
Datum
pg_create_restore_point(PG_FUNCTION_ARGS)
{
11030 11031
	text	   *restore_name = PG_GETARG_TEXT_P(0);
	char	   *restore_name_str;
11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048
	XLogRecPtr	restorepoint;
	char		location[MAXFNAMELEN];

	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 (errmsg("must be superuser to create a restore point"))));

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

	if (!XLogIsNeeded())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11049
			 errmsg("WAL level not sufficient for creating a restore point"),
11050 11051 11052 11053 11054 11055 11056
				 errhint("wal_level must be set to \"archive\" or \"hot_standby\" at server start.")));

	restore_name_str = text_to_cstring(restore_name);

	if (strlen(restore_name_str) >= MAXFNAMELEN)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
11057
				 errmsg("value too long for restore point (maximum %d characters)", MAXFNAMELEN - 1)));
11058 11059 11060 11061 11062 11063 11064

	restorepoint = XLogRestorePoint(restore_name_str);

	/*
	 * As a convenience, return the WAL location of the restore point record
	 */
	snprintf(location, sizeof(location), "%X/%X",
11065
			 restorepoint.xlogid, restorepoint.xrecoff);
11066 11067 11068
	PG_RETURN_TEXT_P(cstring_to_text(location));
}

11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080
/*
 * 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.
 */
Datum
pg_current_xlog_location(PG_FUNCTION_ARGS __attribute__((unused)) )
{
	char		location[MAXFNAMELEN];

11081 11082 11083 11084 11085 11086
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098
	/* 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);
11099
	PG_RETURN_TEXT_P(cstring_to_text(location));
11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113
}

/*
 * 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 __attribute__((unused)) )
{
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecPtr	current_recptr;
	char		location[MAXFNAMELEN];

11114 11115 11116 11117 11118 11119
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("WAL control functions cannot be executed during recovery.")));

11120 11121 11122 11123 11124 11125 11126 11127 11128
	/*
	 * 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);
11129
	PG_RETURN_TEXT_P(cstring_to_text(location));
11130 11131
}

11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143
/*
 * Report the last WAL receive location (same format as pg_start_backup etc)
 *
 * This is useful for determining how much of WAL is guaranteed to be received
 * and synced to disk by walreceiver.
 */
Datum
pg_last_xlog_receive_location(PG_FUNCTION_ARGS)
{
	XLogRecPtr	recptr;
	char		location[MAXFNAMELEN];

11144
	recptr = GetWalRcvWriteRecPtr(NULL);
11145

11146 11147 11148
	if (recptr.xlogid == 0 && recptr.xrecoff == 0)
		PG_RETURN_NULL();

11149 11150 11151 11152 11153
	snprintf(location, sizeof(location), "%X/%X",
			 recptr.xlogid, recptr.xrecoff);
	PG_RETURN_TEXT_P(cstring_to_text(location));
}

11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213
/*
 * Get latest redo apply position.
 *
 * Optionally, returns the current recovery target timeline. Callers not
 * interested in that may pass NULL for targetTLI.
 *
 * Exported to allow WAL receiver to read the pointer directly.
 */
XLogRecPtr
GetXLogReplayRecPtr(TimeLineID *targetTLI)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	XLogRecPtr	recptr;
	uint32		freespace;

	SpinLockAcquire(&xlogctl->info_lck);
	recptr = xlogctl->lastReplayedEndRecPtr;
	if (targetTLI)
		*targetTLI = xlogctl->RecoveryTargetTLI;
	SpinLockRelease(&xlogctl->info_lck);

	/*
	 * No more records fit on this page. Report the apply location
	 * as the end of the page.
	 *
	 * GPDB_93_MERGE_FIXME: The need for this goes away in PG 9.3. After
	 * commit 061e7efb1b, the page header can be split across pages, too.
	 */
	freespace = XLOG_BLCKSZ - (recptr.xrecoff % XLOG_BLCKSZ);
	if (freespace < SizeOfXLogRecord)
	{
		XLByteAdvance(recptr, freespace);
	}

	return recptr;
}

/*
 * Get current standby flush position, ie, the last WAL position
 * known to be fsync'd to disk in standby.
 *
 * If 'targetTLI' is not NULL, it's set to the current recovery target
 * timeline.
 */
XLogRecPtr
GetStandbyFlushRecPtr(TimeLineID *targetTLI)
{
	XLogRecPtr      receivePtr;
	XLogRecPtr      replayPtr;

	receivePtr = GetWalRcvWriteRecPtr(NULL);
	replayPtr = GetXLogReplayRecPtr(targetTLI);

	if (XLByteLT(receivePtr, replayPtr))
		return replayPtr;
	else
		return receivePtr;
}

11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225
/*
 * Report the last WAL replay location (same format as pg_start_backup etc)
 *
 * This is useful for determining how much of WAL is visible to read-only
 * connections during recovery.
 */
Datum
pg_last_xlog_replay_location(PG_FUNCTION_ARGS)
{
	XLogRecPtr	recptr;
	char		location[MAXFNAMELEN];

A
Asim R P 已提交
11226
	recptr = GetXLogReplayRecPtr(NULL);
11227

11228 11229 11230
	if (recptr.xlogid == 0 && recptr.xrecoff == 0)
		PG_RETURN_NULL();

11231 11232 11233 11234 11235
	snprintf(location, sizeof(location), "%X/%X",
			 recptr.xlogid, recptr.xrecoff);
	PG_RETURN_TEXT_P(cstring_to_text(location));
}

11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261
/*
 * 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];
	Datum		values[2];
	bool		isnull[2];
	TupleDesc	resultTupleDesc;
	HeapTuple	resultHeapTuple;
	Datum		result;

11262 11263 11264 11265 11266 11267
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
				 errhint("pg_xlogfile_name_offset() cannot be executed during recovery.")));

11268 11269 11270
	/*
	 * Read input and parse
	 */
11271
	locationstr = text_to_cstring(location);
11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299

	if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("could not parse transaction log location \"%s\"",
						locationstr)));

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

	/*
	 * Construct a tuple descriptor for the result row.  This must match this
	 * function's pg_proc entry!
	 */
	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
	 */
	XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
	XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);

11300
	values[0] = CStringGetTextDatum(xlogfilename);
11301 11302 11303 11304 11305
	isnull[0] = false;

	/*
	 * offset
	 */
11306 11307
	xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;

11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318
	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);
11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336
}

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

11337 11338 11339 11340
	if (RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("recovery is in progress"),
B
Bruce Momjian 已提交
11341
		 errhint("pg_xlogfile_name() cannot be executed during recovery.")));
11342

11343
	locationstr = text_to_cstring(location);
11344 11345 11346 11347

	if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
P
Peter Eisentraut 已提交
11348
				 errmsg("could not parse transaction log location \"%s\"",
11349 11350 11351 11352 11353 11354 11355 11356
						locationstr)));

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

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

11357
	PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
11358 11359
}

11360 11361 11362 11363 11364
/*
 * 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 已提交
11365
 * identified by the label file, NOT what pg_control says.	This avoids the
11366 11367 11368 11369 11370
 * problem that pg_control might have been archived one or more checkpoints
 * later than the start of the dump, and so if we rely on it as the start
 * point, we will fail to restore a consistent database state.
 *
 * Returns TRUE if a backup_label was found (and fills the checkpoint
11371
 * location and its REDO location into *checkPointLoc and RedoStartLSN,
A
Asim R P 已提交
11372 11373
 * respectively); returns FALSE if not. If this backup_label came from a
 * streamed backup, *backupEndRequired is set to TRUE.
11374 11375
 */
static bool
A
Asim R P 已提交
11376
read_backup_label(XLogRecPtr *checkPointLoc, bool *backupEndRequired)
11377 11378 11379 11380 11381
{
	char		startxlogfilename[MAXFNAMELEN];
	TimeLineID	tli;
	FILE	   *lfp;
	char		ch;
A
Asim R P 已提交
11382 11383 11384 11385
	char		backuptype[20];
	char		backupfrom[20];

	*backupEndRequired = false;
11386 11387 11388 11389

	/*
	 * See if label file is present
	 */
11390
	lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
11391 11392 11393 11394 11395 11396
	if (!lfp)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
11397
							BACKUP_LABEL_FILE)));
11398 11399
		return false;			/* it's not there, all is fine */
	}
B
Bruce Momjian 已提交
11400

11401
	/*
A
Asim R P 已提交
11402 11403 11404
	 * Read and parse the START WAL LOCATION, CHECKPOINT and BACKUP_METHOD
	 * lines (this code is pretty crude, but we are not expecting any variability
	 * in the file format).
11405 11406
	 */
	if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
11407
			   &RedoStartLSN.xlogid, &RedoStartLSN.xrecoff, &tli,
11408 11409 11410
			   startxlogfilename, &ch) != 5 || ch != '\n')
		ereport(FATAL,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11411
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
A
Asim R P 已提交
11412

11413 11414 11415 11416 11417
	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),
11418
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
A
Asim R P 已提交
11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440

	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
	{
		/* Streaming backup method is only supported */
		if (strcmp(backuptype, "streamed") == 0)
			*backupEndRequired = true;
		else
			ereport(FATAL,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
					 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));

	}

	if (fscanf(lfp, "BACKUP FROM: %19s\n", backupfrom) == 1)
	{
		/* Backup from standby is not supported */
		if (strcmp(backupfrom, "master") != 0)
			ereport(FATAL,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
					 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
	}

11441 11442 11443 11444
	if (ferror(lfp) || FreeFile(lfp))
		ereport(FATAL,
				(errcode_for_file_access(),
				 errmsg("could not read file \"%s\": %m",
11445
						BACKUP_LABEL_FILE)));
B
Bruce Momjian 已提交
11446

11447 11448 11449
	return true;
}

11450 11451 11452 11453 11454 11455
/*
 * Error context callback for errors occurring during rm_redo().
 */
static void
rm_redo_error_callback(void *arg)
{
A
Asim R P 已提交
11456
	RedoErrorCallBack *redoErrorCallBack = (RedoErrorCallBack*) arg;
B
Bruce Momjian 已提交
11457
	StringInfoData buf;
11458 11459

	initStringInfo(&buf);
A
Asim R P 已提交
11460 11461 11462
	RmgrTable[redoErrorCallBack->record->xl_rmid].rm_desc(
												   &buf,
												   redoErrorCallBack->record);
11463 11464 11465 11466 11467 11468 11469

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

	pfree(buf.data);
}
11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506

/*
 * 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"),
11507
				 errdetail("\"%s\" was renamed to \"%s\".",
11508
						   BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
11509 11510 11511 11512 11513
	}
	else
	{
		ereport(WARNING,
				(errcode_for_file_access(),
11514 11515
				 errmsg("online backup mode was not cancelled"),
				 errdetail("Could not rename \"%s\" to \"%s\": %m.",
11516
						   BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
11517 11518 11519
	}
}

A
Asim R P 已提交
11520 11521 11522
static char *
XLogLocationToBuffer(char *buffer, XLogRecPtr *loc, bool longFormat)
{
11523

A
Asim R P 已提交
11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536
	if (longFormat)
	{
		uint32 seg = loc->xrecoff / XLogSegSize;
		uint32 offset = loc->xrecoff % XLogSegSize;
		sprintf(buffer,
			    "%X/%X (==> seg %d, offset 0x%X)",
			    loc->xlogid, loc->xrecoff,
			    seg, offset);
	}
	else
		sprintf(buffer,
			    "%X/%X",
			    loc->xlogid, loc->xrecoff);
11537

A
Asim R P 已提交
11538 11539
	return buffer;
}
11540

A
Asim R P 已提交
11541 11542 11543 11544 11545
static char xlogLocationBuffer[50];
static char xlogLocationBuffer2[50];
static char xlogLocationBuffer3[50];
static char xlogLocationBuffer4[50];
static char xlogLocationBuffer5[50];
11546

A
Asim R P 已提交
11547 11548 11549 11550 11551
char *
XLogLocationToString(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer, loc, Debug_print_qd_mirroring);
}
11552

A
Asim R P 已提交
11553 11554 11555 11556
char *
XLogLocationToString2(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer2, loc, Debug_print_qd_mirroring);
11557 11558
}

A
Asim R P 已提交
11559 11560
char *
XLogLocationToString3(XLogRecPtr *loc)
11561
{
A
Asim R P 已提交
11562 11563
	return XLogLocationToBuffer(xlogLocationBuffer3, loc, Debug_print_qd_mirroring);
}
11564

A
Asim R P 已提交
11565 11566 11567 11568 11569
char *
XLogLocationToString4(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer4, loc, Debug_print_qd_mirroring);
}
11570

A
Asim R P 已提交
11571 11572 11573 11574 11575
char *
XLogLocationToString5(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer5, loc, Debug_print_qd_mirroring);
}
11576

A
Asim R P 已提交
11577 11578 11579 11580 11581
char *
XLogLocationToString_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer, loc, true);
}
11582

A
Asim R P 已提交
11583 11584 11585 11586 11587
char *
XLogLocationToString2_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer2, loc, true);
}
11588

A
Asim R P 已提交
11589 11590 11591 11592 11593
char *
XLogLocationToString3_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer3, loc, true);
}
11594

A
Asim R P 已提交
11595 11596 11597 11598 11599 11600 11601 11602 11603 11604
char *
XLogLocationToString4_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer4, loc, true);
}

char *
XLogLocationToString5_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer5, loc, true);
11605 11606
}

A
Asim R P 已提交
11607

11608
/* ------------------------------------------------------
11609
 *	Startup Process main entry point and signal handlers
11610 11611 11612
 * ------------------------------------------------------
 */

11613
/*
11614
 * startupproc_quickdie() occurs when signalled SIGQUIT by the postmaster.
11615
 *
11616 11617
 * Some backend has bought the farm,
 * so we need to stop what we're doing and exit.
11618
 */
11619 11620
static void
startupproc_quickdie(SIGNAL_ARGS)
11621
{
11622
	PG_SETMASK(&BlockSig);
11623 11624

	/*
11625 11626 11627 11628 11629 11630
	 * We DO NOT want to run proc_exit() callbacks -- we're here because
	 * shared memory may be corrupted, so we don't want to try to clean up our
	 * transaction.  Just nail the windows shut and get out of town.  Now that
	 * there's an atexit callback to prevent third-party code from breaking
	 * things by calling exit() directly, we have to reset the callbacks
	 * explicitly to make this work as intended.
11631
	 */
11632
	on_exit_reset();
11633 11634

	/*
11635 11636 11637
	 * Note we do exit(2) not exit(0).	This is to force the postmaster into a
	 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
	 * backend.  This is necessary precisely because we don't clean up our
11638
	 * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
11639 11640
	 * should ensure the postmaster sees this as a crash, too, but no harm in
	 * being doubly sure.)
11641
	 */
11642 11643
	exit(2);
}
11644

R
Robert Haas 已提交
11645 11646 11647 11648
/* SIGUSR2: set flag to finish recovery */
static void
StartupProcTriggerHandler(SIGNAL_ARGS)
{
A
Asim R P 已提交
11649
	int			save_errno = errno;
11650

R
Robert Haas 已提交
11651 11652
	promote_triggered = true;
	WakeupRecovery();
11653

A
Asim R P 已提交
11654 11655
	errno = save_errno;
}
11656

A
Asim R P 已提交
11657 11658 11659 11660 11661
/* SIGUSR1: let latch facility handle the signal */
static void
StartupProcSigUsr1Handler(SIGNAL_ARGS)
{
	latch_sigusr1_handler();
R
Robert Haas 已提交
11662 11663
}

11664 11665 11666 11667
/* SIGHUP: set flag to re-read config file at next convenient time */
static void
StartupProcSigHupHandler(SIGNAL_ARGS)
{
A
Asim R P 已提交
11668 11669
	int			save_errno = errno;

11670
	got_SIGHUP = true;
11671
	WakeupRecovery();
A
Asim R P 已提交
11672 11673

	errno = save_errno;
11674 11675
}

11676 11677 11678 11679
/* SIGTERM: set flag to abort redo and exit */
static void
StartupProcShutdownHandler(SIGNAL_ARGS)
{
A
Asim R P 已提交
11680 11681
	int			save_errno = errno;

11682
	if (in_restore_command)
11683
		proc_exit(1);
11684 11685
	else
		shutdown_requested = true;
11686
	WakeupRecovery();
A
Asim R P 已提交
11687 11688

	errno = save_errno;
11689 11690
}

11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701
/* Handle SIGHUP and SIGTERM signals of startup process */
void
HandleStartupProcInterrupts(void)
{
	/*
	 * Check if we were requested to re-read config file.
	 */
	if (got_SIGHUP)
	{
		got_SIGHUP = false;
		ProcessConfigFile(PGC_SIGHUP);
11702 11703
	}

11704 11705 11706 11707 11708
	/*
	 * Check if we were requested to exit without finishing recovery.
	 */
	if (shutdown_requested)
		proc_exit(1);
11709

11710 11711 11712 11713 11714 11715
	/*
	 * Emergency bailout if postmaster has died.  This is to avoid the
	 * necessity for manual cleanup of all postmaster children.
	 */
	if (IsUnderPostmaster && !PostmasterIsAlive(true))
		exit(1);
11716 11717 11718
}

static void
A
Asim R P 已提交
11719
HandleCrash(SIGNAL_ARGS)
11720
{
A
Asim R P 已提交
11721 11722 11723 11724 11725 11726 11727 11728
    /**
     * Handle crash is registered as a signal handler for SIGILL/SIGBUS/SIGSEGV
     *
     * This simply calls the standard handler which will log the signal and reraise the
     *      signal if needed
     */
    StandardHandlerForSigillSigsegvSigbus_OnMainThread("a startup process", PASS_SIGNAL_ARGS);
}
11729

11730 11731 11732 11733
/* Main entry point for startup process */
void
StartupProcessMain(void)
{
A
Asim R P 已提交
11734
	am_startup = true;
11735 11736 11737 11738 11739 11740 11741 11742
	/*
	 * If possible, make this process a group leader, so that the postmaster
	 * can signal any child processes too.
	 */
#ifdef HAVE_SETSID
	if (setsid() < 0)
		elog(FATAL, "setsid() failed: %m");
#endif
11743

11744
	/*
11745 11746 11747 11748 11749
	 * Properly accept or ignore signals the postmaster might send us.
	 *
	 * Note: ideally we'd not enable handle_standby_sig_alarm unless actually
	 * doing hot standby, but we don't know that yet.  Rely on it to not do
	 * anything if it shouldn't.
11750
	 */
11751 11752
	pqsignal(SIGHUP, StartupProcSigHupHandler); /* reload config file */
	pqsignal(SIGINT, SIG_IGN);	/* ignore query cancel */
B
Bruce Momjian 已提交
11753 11754
	pqsignal(SIGTERM, StartupProcShutdownHandler);		/* request shutdown */
	pqsignal(SIGQUIT, startupproc_quickdie);	/* hard crash time */
11755
	if (EnableHotStandby)
B
Bruce Momjian 已提交
11756 11757
		pqsignal(SIGALRM, handle_standby_sig_alarm);	/* ignored unless
														 * InHotStandby */
11758 11759
	else
		pqsignal(SIGALRM, SIG_IGN);
11760
	pqsignal(SIGPIPE, SIG_IGN);
11761
	pqsignal(SIGUSR1, StartupProcSigUsr1Handler);
R
Robert Haas 已提交
11762
	pqsignal(SIGUSR2, StartupProcTriggerHandler);
11763

A
Asim R P 已提交
11764 11765 11766 11767 11768 11769 11770 11771 11772
#ifdef SIGBUS
	pqsignal(SIGBUS, HandleCrash);
#endif
#ifdef SIGILL
    pqsignal(SIGILL, HandleCrash);
#endif
#ifdef SIGSEGV
	pqsignal(SIGSEGV, HandleCrash);
#endif
11773

11774 11775 11776 11777 11778 11779 11780 11781
	/*
	 * Reset some signals that are accepted by postmaster but not here
	 */
	pqsignal(SIGCHLD, SIG_DFL);
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);
	pqsignal(SIGWINCH, SIG_DFL);
11782

11783 11784 11785 11786 11787
	/*
	 * Unblock signals (they were blocked when the postmaster forked us)
	 */
	PG_SETMASK(&UnBlockSig);

11788
	StartupXLOG();
11789

11790
	/*
A
Asim R P 已提交
11791 11792
	 * Exit normally. Exit code 0 tells postmaster that we completed
	 * recovery successfully.
11793
	 */
11794
	proc_exit(0);
V
WAL  
Vadim B. Mikheev 已提交
11795
}
B
Bruce Momjian 已提交
11796

11797
/*
11798
 * Read the XLOG page containing RecPtr into readBuf (if not read already).
11799
 * Returns true if the page is read successfully.
11800
 *
A
Asim R P 已提交
11801 11802
 * This is responsible for waiting for the requested WAL record to arrive in
 * standby mode.
11803 11804
 *
 * 'emode' specifies the log level used for reporting "file not found" or
A
Asim R P 已提交
11805 11806 11807 11808 11809 11810
 * "end of WAL" situations in standby mode when a trigger file is found.
 * If set to WARNING or below, XLogPageRead() returns false in those situations
 * on higher log levels the ereport() won't return.
 *
 * In standby mode, this only returns false if promotion has been triggered.
 * Otherwise it keeps sleeping and retrying indefinitely.
11811
 */
11812 11813 11814
static bool
XLogPageRead(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt,
			 bool randAccess)
V
WAL  
Vadim B. Mikheev 已提交
11815
{
11816 11817 11818 11819 11820 11821
	static XLogRecPtr receivedUpto = {0, 0};
	bool		switched_segment = false;
	uint32		targetPageOff;
	uint32		targetRecOff;
	uint32		targetId;
	uint32		targetSeg;
11822
	static pg_time_t last_fail_time = 0;
B
Bruce Momjian 已提交
11823

11824 11825 11826
	XLByteToSeg(*RecPtr, targetId, targetSeg);
	targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
	targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
11827

11828
	/* Fast exit if we have read the record in the current buffer already */
11829
	if (failedSources == 0 && targetId == readId && targetSeg == readSeg &&
11830
		targetPageOff == readOff && targetRecOff < readLen)
11831
	{
A
Asim R P 已提交
11832 11833 11834 11835 11836 11837
		elogif(debug_xlog_record_read, LOG,
			   "xlog page read -- Requested record %X/%X (targetlogid %u,"
			   "targetset %u, targetpageoff %u, targetrecoff %u) already"
			   "exists in current read buffer",
			   RecPtr->xlogid, RecPtr->xrecoff,
			   targetId, targetSeg, targetPageOff, targetRecOff);
11838

11839
		return true;
A
Asim R P 已提交
11840
	}
11841

11842 11843 11844 11845 11846
	/*
	 * See if we need to switch to a new segment because the requested record
	 * is not in the currently open one.
	 */
	if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
11847
	{
A
Asim R P 已提交
11848 11849 11850 11851
		elogif(debug_xlog_record_read, LOG,
			   "xlog page read -- Requested record %X/%X does not exist in"
			   "current read xlog file (readlog %u, readseg %u)",
			   RecPtr->xlogid, RecPtr->xrecoff, readId, readSeg);
11852

11853
		/*
B
Bruce Momjian 已提交
11854 11855
		 * Signal bgwriter to start a restartpoint if we've replayed too much
		 * xlog since the last one.
11856 11857 11858 11859 11860 11861 11862 11863 11864 11865
		 */
		if (StandbyMode && bgwriterLaunched)
		{
			if (XLogCheckpointNeeded(readId, readSeg))
			{
				(void) GetRedoRecPtr();
				if (XLogCheckpointNeeded(readId, readSeg))
					RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
			}
		}
11866

11867 11868
		close(readFile);
		readFile = -1;
11869
		readSource = 0;
11870
	}
11871

11872
	XLByteToSeg(*RecPtr, readId, readSeg);
11873

A
Asim R P 已提交
11874 11875 11876 11877 11878
	elogif(debug_xlog_record_read, LOG,
		   "xlog page read -- Requested record %X/%X has targetlogid %u, "
		   "targetseg %u, targetpageoff %u, targetrecoff %u",
		   RecPtr->xlogid, RecPtr->xrecoff,
		   targetId, targetSeg, targetPageOff, targetRecOff);
11879

11880
retry:
11881 11882
	/* See if we need to retrieve more data */
	if (readFile < 0 ||
11883
		(readSource == XLOG_FROM_STREAM && !XLByteLT(*RecPtr, receivedUpto)))
11884 11885 11886 11887 11888
	{
		if (StandbyMode)
		{
			/*
			 * In standby mode, wait for the requested record to become
A
Asim R P 已提交
11889
			 * available, via WAL receiver having streamed the record.
11890 11891 11892 11893 11894
			 */
			for (;;)
			{
				if (WalRcvInProgress())
				{
B
Bruce Momjian 已提交
11895
					bool		havedata;
11896

11897 11898 11899
					/*
					 * If we find an invalid record in the WAL streamed from
					 * master, something is seriously wrong. There's little
B
Bruce Momjian 已提交
11900
					 * chance that the problem will just go away, but PANIC is
A
Asim R P 已提交
11901 11902 11903
					 * not good for availability. Disconnect, and retry from
					 * pg_xlog again (That may spawn the Wal receiver again!).
					 * XXX
11904 11905 11906
					 */
					if (failedSources & XLOG_FROM_STREAM)
					{
A
Asim R P 已提交
11907 11908 11909
						elogif(debug_xlog_record_read, LOG,
							   "xlog page read -- Xlog from stream is a failed"
							   "source, hence requesting walreceiver shutdown.");
11910

11911 11912 11913
						ShutdownWalRcv();
						continue;
					}
11914

11915
					/*
A
Asim R P 已提交
11916
					 * WAL receiver is active, so see if new data has arrived.
11917 11918 11919 11920 11921
					 *
					 * We only advance XLogReceiptTime when we obtain fresh
					 * WAL from walreceiver and observe that we had already
					 * processed everything before the most recent "chunk"
					 * that it flushed to disk.  In steady state where we are
B
Bruce Momjian 已提交
11922 11923
					 * keeping up with the incoming data, XLogReceiptTime will
					 * be updated on each cycle.  When we are behind,
11924 11925
					 * XLogReceiptTime will not advance, so the grace time
					 * alloted to conflicting queries will decrease.
11926 11927
					 */
					if (XLByteLT(*RecPtr, receivedUpto))
11928 11929 11930 11931
						havedata = true;
					else
					{
						XLogRecPtr	latestChunkStart;
11932

11933 11934 11935 11936 11937
						receivedUpto = GetWalRcvWriteRecPtr(&latestChunkStart);
						if (XLByteLT(*RecPtr, receivedUpto))
						{
							havedata = true;
							if (!XLByteLT(*RecPtr, latestChunkStart))
A
Asim R P 已提交
11938
							{
11939
								XLogReceiptTime = GetCurrentTimestamp();
A
Asim R P 已提交
11940 11941
								SetCurrentChunkStartTime(XLogReceiptTime);
							}
11942 11943 11944 11945
						}
						else
							havedata = false;
					}
11946

11947
					if (havedata)
11948
					{
A
Asim R P 已提交
11949 11950 11951 11952 11953
						elogif(debug_xlog_record_read, LOG,
							   "xlog page read -- There is enough xlog data to be "
							   "read (receivedupto %X/%X, requestedrec %X/%X)",
							   receivedUpto.xlogid, receivedUpto.xrecoff,
							   RecPtr->xlogid, RecPtr->xrecoff);
11954

11955 11956
						/*
						 * Great, streamed far enough. Open the file if it's
11957 11958 11959
						 * not open already.  Use XLOG_FROM_STREAM so that
						 * source info is set correctly and XLogReceiptTime
						 * isn't changed.
11960 11961 11962 11963 11964
						 */
						if (readFile < 0)
						{
							readFile =
								XLogFileRead(readId, readSeg, PANIC,
11965
											 recoveryTargetTLI,
11966 11967
											 XLOG_FROM_STREAM, false);
							Assert(readFile >= 0);
11968
							switched_segment = true;
11969 11970 11971 11972
						}
						else
						{
							/* just make sure source info is correct... */
11973
							readSource = XLOG_FROM_STREAM;
11974
							XLogReceiptSource = XLOG_FROM_STREAM;
11975 11976 11977
						}
						break;
					}
11978

11979
					/*
11980 11981
					 * Data not here yet, so check for trigger then sleep for
					 * five seconds like in the WAL file polling case below.
11982
					 */
11983
					if (CheckForStandbyTrigger())
A
Asim R P 已提交
11984 11985 11986
					{
						elogif(debug_xlog_record_read, LOG,
							   "xlog page read -- Standby trigger was activated");
11987

11988
						goto retry;
A
Asim R P 已提交
11989
					}
11990

A
Asim R P 已提交
11991 11992 11993
					elogif(debug_xlog_record_read, LOG,
						   "xlog page read -- No xlog data to read as of now. "
						   "Will Wait on latch till some event occurs");
11994

11995
					/*
11996
					 * Wait for more WAL to arrive, or timeout to be reached
11997
					 */
A
Asim R P 已提交
11998 11999 12000
					WaitLatch(&XLogCtl->recoveryWakeupLatch,
							  WL_LATCH_SET | WL_TIMEOUT,
							  5000L);
12001
					ResetLatch(&XLogCtl->recoveryWakeupLatch);
12002 12003 12004
				}
				else
				{
B
Bruce Momjian 已提交
12005 12006
					int			sources;
					pg_time_t	now;
12007

12008 12009 12010 12011 12012
					if (readFile >= 0)
					{
						close(readFile);
						readFile = -1;
					}
12013

12014 12015 12016
					/* Reset curFileTLI if random fetch. */
					if (randAccess)
						curFileTLI = 0;
12017

A
Asim R P 已提交
12018 12019
					/* Read an existing file from pg_xlog. */
					sources = XLOG_FROM_PG_XLOG;
12020
					if (!(sources & ~failedSources))
12021
					{
A
Asim R P 已提交
12022 12023 12024 12025 12026 12027
						/*
						 * Check if we have been asked to be promoted. If yes,
						 * no use of requesting a new WAL receiver
						 */
						if (CheckForStandbyTrigger())
							goto triggered;
12028

12029
						/*
12030
						 * We've exhausted all options for retrieving the
12031
						 * file. Retry.
12032 12033
						 */
						failedSources = 0;
12034

A
Asim R P 已提交
12035 12036
						elogif(debug_xlog_record_read, LOG,
							   "xlog page read -- All read sources have failed. So, retry.");
12037

12038
						/*
12039 12040
						 * If it hasn't been long since last attempt, sleep to
						 * avoid busy-waiting.
12041
						 */
12042 12043 12044 12045 12046 12047 12048
						now = (pg_time_t) time(NULL);
						if ((now - last_fail_time) < 5)
						{
							pg_usleep(1000000L * (5 - (now - last_fail_time)));
							now = (pg_time_t) time(NULL);
						}
						last_fail_time = now;
12049

12050 12051
						/*
						 * If primary_conninfo is set, launch walreceiver to
A
Asim R P 已提交
12052
						 * try to stream the missing WAL.
12053 12054 12055
						 *
						 * If fetching_ckpt is TRUE, RecPtr points to the
						 * initial checkpoint location. In that case, we use
B
Bruce Momjian 已提交
12056 12057 12058 12059
						 * RedoStartLSN as the streaming start position
						 * instead of RecPtr, so that when we later jump
						 * backwards to start redo at RedoStartLSN, we will
						 * have the logs streamed already.
12060 12061 12062 12063
						 */
						if (PrimaryConnInfo)
						{
							RequestXLogStreaming(
B
Bruce Momjian 已提交
12064 12065
									  fetching_ckpt ? RedoStartLSN : *RecPtr,
												 PrimaryConnInfo);
12066 12067
							continue;
						}
12068
					}
12069 12070 12071 12072 12073
					/* Don't try to read from a source that just failed */
					sources &= ~failedSources;
					readFile = XLogFileReadAnyTLI(readId, readSeg, DEBUG2,
												  sources);
					switched_segment = true;
12074
					if (readFile >= 0)
12075
						break;
12076

12077
					/*
A
Asim R P 已提交
12078
					 * Nope, not found in pg_xlog.
12079 12080
					 */
					failedSources |= sources;
12081

12082
					/*
B
Bruce Momjian 已提交
12083 12084 12085
					 * Check to see if the trigger file exists. Note that we
					 * do this only after failure, so when you create the
					 * trigger file, we still finish replaying as much as we
A
Asim R P 已提交
12086
					 * can from pg_xlog before failover.
12087
					 */
12088 12089
					if (CheckForStandbyTrigger())
						goto triggered;
12090
				}
12091

12092
				/*
B
Bruce Momjian 已提交
12093 12094
				 * This possibly-long loop needs to handle interrupts of
				 * startup process.
12095 12096 12097 12098 12099 12100
				 */
				HandleStartupProcInterrupts();
			}
		}
		else
		{
A
Asim R P 已提交
12101
			/* In crash recovery. */
12102 12103
			if (readFile < 0)
			{
B
Bruce Momjian 已提交
12104
				int			sources;
12105

12106 12107 12108
				/* Reset curFileTLI if random fetch. */
				if (randAccess)
					curFileTLI = 0;
12109

12110
				sources = XLOG_FROM_PG_XLOG;
B
Bruce Momjian 已提交
12111

12112
				readFile = XLogFileReadAnyTLI(readId, readSeg, emode,
A
Asim R P 已提交
12113
											sources);
12114 12115 12116 12117 12118
				switched_segment = true;
				if (readFile < 0)
					return false;
			}
		}
12119
	}
B
Bruce Momjian 已提交
12120

12121
	/*
B
Bruce Momjian 已提交
12122 12123
	 * At this point, we have the right segment open and if we're streaming we
	 * know the requested record is in it.
12124
	 */
12125
	Assert(readFile != -1);
12126 12127

	/*
B
Bruce Momjian 已提交
12128 12129 12130 12131
	 * If the current segment is being streamed from master, calculate how
	 * much of the current page we have received already. We know the
	 * requested record has been received, but this is for the benefit of
	 * future calls, to allow quick exit at the top of this function.
12132
	 */
12133
	if (readSource == XLOG_FROM_STREAM)
12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144
	{
		if (RecPtr->xlogid != receivedUpto.xlogid ||
			(RecPtr->xrecoff / XLOG_BLCKSZ) != (receivedUpto.xrecoff / XLOG_BLCKSZ))
		{
			readLen = XLOG_BLCKSZ;
		}
		else
			readLen = receivedUpto.xrecoff % XLogSegSize - targetPageOff;
	}
	else
		readLen = XLOG_BLCKSZ;
12145

12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157
	if (switched_segment && targetPageOff != 0)
	{
		/*
		 * Whenever switching to a new WAL segment, we read the first page of
		 * the file and validate its header, even if that's not where the
		 * target record is.  This is so that we can check the additional
		 * identification info that is present in the first page's "long"
		 * header.
		 */
		readOff = 0;
		if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
		{
A
Asim R P 已提交
12158
			ereport(emode,
12159 12160 12161 12162 12163
					(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;
		}
A
Asim R P 已提交
12164 12165 12166 12167 12168 12169
		if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode, true))
		{
			ereport(emode,
					(errcode_for_file_access(),
					 errmsg("could not read from log file %u, segment %u, offset %u: %m",
							readId, readSeg, readOff)));
12170
			goto next_record_is_invalid;
A
Asim R P 已提交
12171
		}
12172
	}
12173

12174 12175 12176 12177
	/* Read the requested page */
	readOff = targetPageOff;
	if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
	{
A
Asim R P 已提交
12178
		ereport(emode,
12179
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
12180 12181
		 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
				readId, readSeg, readOff)));
12182 12183 12184 12185
		goto next_record_is_invalid;
	}
	if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
	{
A
Asim R P 已提交
12186
		ereport(emode,
12187
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
12188 12189
		 errmsg("could not read from log file %u, segment %u, offset %u: %m",
				readId, readSeg, readOff)));
12190 12191
		goto next_record_is_invalid;
	}
A
Asim R P 已提交
12192 12193 12194 12195
	if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode, false))
	{
		elogif(debug_xlog_record_read, LOG,
			   "xlog page read -- xlog page header invalid");
12196
		goto next_record_is_invalid;
A
Asim R P 已提交
12197
	}
12198

12199 12200 12201 12202
	Assert(targetId == readId);
	Assert(targetSeg == readSeg);
	Assert(targetPageOff == readOff);
	Assert(targetRecOff < readLen);
12203

12204
	return true;
12205

12206
next_record_is_invalid:
12207

A
Asim R P 已提交
12208 12209
	elogif(debug_xlog_record_read, LOG,
		   "xlog page read -- next record is invalid.");
12210

12211
	failedSources |= readSource;
12212

12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225
	if (readFile >= 0)
		close(readFile);
	readFile = -1;
	readLen = 0;
	readSource = 0;

	/* In standby-mode, keep trying */
	if (StandbyMode)
		goto retry;
	else
		return false;

triggered:
12226 12227 12228 12229
	if (readFile >= 0)
		close(readFile);
	readFile = -1;
	readLen = 0;
12230
	readSource = 0;
12231 12232

	return false;
12233 12234
}

12235
/*
12236 12237 12238 12239
 * Determine what log level should be used to report a corrupt WAL record
 * in the current WAL page, previously read by XLogPageRead().
 *
 * 'emode' is the error mode that would be used to report a file-not-found
B
Bruce Momjian 已提交
12240
 * or legitimate end-of-WAL situation.	 Generally, we use it as-is, but if
12241
 * we're retrying the exact same record that we've tried previously, only
B
Bruce Momjian 已提交
12242
 * complain the first time to keep the noise down.	However, we only do when
12243 12244 12245
 * reading from pg_xlog, because we don't expect any invalid records in archive
 * or in records streamed from master. Files in the archive should be complete,
 * and we should never hit the end of WAL because we stop and wait for more WAL
B
Bruce Momjian 已提交
12246
 * to arrive before replaying it.
12247 12248 12249 12250 12251
 *
 * NOTE: This function remembers the RecPtr value it was last called with,
 * to suppress repeated messages about the same record. Only call this when
 * you are about to ereport(), or you might cause a later message to be
 * erroneously suppressed.
12252 12253
 */
static int
12254
emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
12255
{
12256 12257
	static XLogRecPtr lastComplaint = {0, 0};

12258
	if (readSource == XLOG_FROM_PG_XLOG && emode == LOG)
12259 12260 12261 12262 12263 12264
	{
		if (XLByteEQ(RecPtr, lastComplaint))
			emode = DEBUG1;
		else
			lastComplaint = RecPtr;
	}
12265 12266 12267
	return emode;
}

12268
/*
R
Robert Haas 已提交
12269 12270 12271
 * Check to see whether the user-specified trigger file exists and whether a
 * promote request has arrived.  If either condition holds, request postmaster
 * to shut down walreceiver, wait for it to exit, and return true.
12272 12273
 */
static bool
12274
CheckForStandbyTrigger(void)
12275
{
12276
	struct stat stat_buf;
12277
	static bool triggered = false;
12278

12279 12280
	if (triggered)
		return true;
12281

12282
	if (CheckPromoteSignal(true))
12283
	{
12284 12285 12286
		ereport(LOG,
				(errmsg("received promote request")));
		ShutdownWalRcv();
A
Asim R P 已提交
12287
		unlink(TriggerFile);
R
Robert Haas 已提交
12288 12289 12290 12291
		triggered = true;
		return true;
	}

12292 12293 12294 12295 12296 12297 12298 12299 12300
	if (TriggerFile == NULL)
		return false;

	if (stat(TriggerFile, &stat_buf) == 0)
	{
		ereport(LOG,
				(errmsg("trigger file found: %s", TriggerFile)));
		ShutdownWalRcv();
		unlink(TriggerFile);
12301 12302
		triggered = true;
		return true;
12303
	}
B
Bruce Momjian 已提交
12304

12305 12306
	return false;
}
12307

12308 12309 12310 12311 12312 12313 12314 12315
/*
 * Check to see if a promote request has arrived. Should be
 * called by postmaster after receiving SIGUSR1.
 */
bool
CheckPromoteSignal(bool do_unlink)
{
	struct stat stat_buf;
12316

12317
	if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
12318 12319
	{
		/*
12320 12321
		 * Since we are in a signal handler, it's not safe to elog. We
		 * silently ignore any error from unlink.
12322
		 */
12323 12324 12325
		if (do_unlink)
			unlink(PROMOTE_SIGNAL_FILE);
		return true;
12326
	}
12327 12328
	return false;
}
12329

12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340
/*
 * True if we are running standby-mode continuous recovery.
 * Note this would return false after finishing the recovery, even if
 * we are still on standby master with a primary master running.
 * Also this only works in the startup process as the StandbyMode
 * flag is not in shared memory.
 */
bool
IsStandbyMode(void)
{
	return StandbyMode;
12341
}
12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363

static void
GetXLogCleanUpTo(XLogRecPtr recptr, uint32 *_logId, uint32 *_logSeg)
{
	/*
	 * See if we have a live WAL sender and see if it has a
	 * start xlog location (with active basebackup) or standby fsync location
	 * (with active standby). We have to compare it with prev. checkpoint
	 * location. We use the min out of them to figure out till
	 * what point we need to save the xlog seg files
	 */
	XLogRecPtr xlogCleanUpTo = WalSndCtlGetXLogCleanUpTo();
	if (!XLogRecPtrIsInvalid(xlogCleanUpTo))
	{
		if (XLByteLT(recptr, xlogCleanUpTo))
			xlogCleanUpTo = recptr;
	}
	else
		xlogCleanUpTo = recptr;

	CheckKeepWalSegments(xlogCleanUpTo, _logId, _logSeg);
}
12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420

/*
 * Checks whether the current buffer page and backup page stored in the
 * WAL record are consistent or not. Before comparing the two pages, a
 * masking can be applied to the pages to ignore certain areas like hint bits,
 * unused space between pd_lower and pd_upper among other things. This
 * function should be called once WAL replay has been completed for a
 * given record.
 */
static void
checkXLogConsistency(XLogRecord *record, XLogRecPtr EndRecPtr)
{
	RmgrId		rmid = record->xl_rmid;
	char       *blk;

	/* Records with no backup blocks have no need for consistency checks. */
	if (!(record->xl_info & XLR_BKP_BLOCK_MASK))
		return;

	Assert((record->xl_extended_info & XLR_CHECK_CONSISTENCY) != 0);

	blk = (char *) XLogRecGetData(record) + record->xl_len;
	for (int i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
	{
		BkpBlock    bkpb;
		Buffer		buf;
		Page		page;
		char       *src_buffer;

		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
		{
			/*
			 * WAL record doesn't contain a block do nothing.
			 */
			continue;
		}

		memcpy(&bkpb, blk, sizeof(BkpBlock));
		blk += sizeof(BkpBlock);
		src_buffer = blk;
		/* move on to point to next block */
		blk += BLCKSZ - bkpb.hole_length;

		if (bkpb.block_info & BLOCK_APPLY)
		{
			/*
			 * WAL record has already applied the page, so bypass the
			 * consistency check as that would result in comparing the full
			 * page stored in the record with itself.
			 */
			continue;
		}

		/*
		 * Read the contents from the current buffer and store it in a
		 * temporary page.
		 */
12421
		buf = XLogReadBuffer(bkpb.node, bkpb.block, false);
12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490
		if (!BufferIsValid(buf))
			continue;

		page = BufferGetPage(buf);

		/*
		 * Take a copy of the local page where WAL has been applied to have a
		 * comparison base before masking it...
		 */
		memcpy(replay_image_masked, page, BLCKSZ);

		/* No need for this page anymore now that a copy is in. */
		UnlockReleaseBuffer(buf);

		/*
		 * If the block LSN is already ahead of this WAL record, we can't
		 * expect contents to match.  This can happen if recovery is
		 * restarted.
		 */
		if (XLByteLT(EndRecPtr, PageGetLSN(replay_image_masked)))
			continue;

		/*
		 * Read the contents from the backup copy, stored in WAL record and
		 * store it in a temporary page. There is no need to allocate a new
		 * page here, a local buffer is fine to hold its contents and a mask
		 * can be directly applied on it.
		 */
		if (bkpb.hole_length == 0)
		{
			memcpy((char *) master_image_masked, src_buffer, BLCKSZ);
		}
		else
		{
			/* zero-fill the hole, anyways gets masked out */
			MemSet((char *) master_image_masked, 0, BLCKSZ);
			memcpy((char *) master_image_masked, src_buffer, bkpb.hole_offset);
			memcpy((char *) master_image_masked + (bkpb.hole_offset + bkpb.hole_length),
				   src_buffer + bkpb.hole_offset,
				   BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
		}

		/*
		 * If masking function is defined, mask both the master and replay
		 * images
		 */
		if (RmgrTable[rmid].rm_mask != NULL)
		{
			RmgrTable[rmid].rm_mask(replay_image_masked, bkpb.block);
			RmgrTable[rmid].rm_mask(master_image_masked, bkpb.block);
		}

		/* Time to compare the master and replay images. */
		if (memcmp(replay_image_masked, master_image_masked, BLCKSZ) != 0)
		{
			elog(FATAL,
				 "inconsistent page found, rel %u/%u/%u, blkno %u",
				 bkpb.node.spcNode, bkpb.node.dbNode, bkpb.node.relNode,
				 bkpb.block);
		}
		else
		{
			elog(DEBUG1,
				 "Consistent page for rel %u/%u/%u, blkno %u",
				 bkpb.node.spcNode, bkpb.node.dbNode, bkpb.node.relNode,
				 bkpb.block);
		}
	}
}
12491 12492 12493 12494 12495 12496 12497 12498 12499 12500

/*
 * Wake up startup process to replay newly arrived WAL, or to notice that
 * failover has been requested.
 */
void
WakeupRecovery(void)
{
	SetLatch(&XLogCtl->recoveryWakeupLatch);
}
12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518

/*
 * Report the last WAL replay location
 */
XLogRecPtr
last_xlog_replay_location()
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	Assert(xlogctl != NULL);
	XLogRecPtr	recptr;

	SpinLockAcquire(&xlogctl->info_lck);
	recptr = xlogctl->recoveryLastRecPtr;
	SpinLockRelease(&xlogctl->info_lck);

	return recptr;
}
12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532

void
wait_for_mirror()
{
	XLogwrtResult tmpLogwrtResult;
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

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

	SyncRepWaitForLSN(tmpLogwrtResult.Flush);
}