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

15 16
#include "postgres.h"

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

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

#include "cdb/cdbtm.h"
#include "cdb/cdbfilerep.h"
#include "cdb/cdbfilerepresyncmanager.h"
#include "cdb/cdbvars.h"
#include "cdb/cdbpersistentrelation.h"
#include "cdb/cdbmirroredflatfile.h"
#include "cdb/cdbpersistentrecovery.h"
#include "cdb/cdbresynchronizechangetracking.h"
#include "cdb/cdbpersistentfilesysobj.h"
#include "cdb/cdbpersistentcheck.h"
91

92 93


94 95 96
/* File path names (all relative to $PGDATA) */
#define RECOVERY_COMMAND_FILE	"recovery.conf"
#define RECOVERY_COMMAND_DONE	"recovery.done"
97
#define PROMOTE_SIGNAL_FILE "promote"
98 99


T
Tom Lane 已提交
100 101
/* User-settable parameters */
int			CheckPointSegments = 3;
V
Vadim B. Mikheev 已提交
102
int			XLOGbuffers = 8;
103
int			XLogArchiveTimeout = 0;
104
bool		XLogArchiveMode = false;
105
char	   *XLogArchiveCommand = NULL;
106 107
char	   *XLOG_sync_method = NULL;
const char	XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
108
bool		fullPageWrites = true;
109
bool		log_checkpoints = false;
T
Tom Lane 已提交
110

111 112 113 114
#ifdef WAL_DEBUG
bool		XLOG_DEBUG = false;
#endif

115
/*
116 117 118 119 120
 * 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 已提交
121
 * 2*CheckPointSegments+1.	Under normal conditions, a checkpoint will free
122 123 124
 * 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.
125 126 127 128
 */
#define XLOGfileslop	(2*CheckPointSegments + 1)


129
/* these are derived from XLOG_sync_method by assign_xlog_sync_method */
B
Bruce Momjian 已提交
130
int			sync_method = DEFAULT_SYNC_METHOD;
131 132
static int	open_sync_bit = DEFAULT_SYNC_FLAGBIT;

133 134 135 136 137 138 139 140 141 142
/*
 * walreceiver process receives xlog data from walsender process.
 * It needs to write the xlog data as soon as it receives and the amount it receives.
 * As the amount of data received by it to write cannot be guaranteed to be
 * OS/FS block size aligned, should never use O_DIRECT for the same.
 * Also, as code is not expecting O_DIRECT to be used for xlog writes on walreceiver,
 * the buffer pointer to perform xlog writes is not made usre to be OS/FS blocks size aligned.
 */
#define XLOG_SYNC_BIT  (enableFsync && (MyAuxProcType != WalReceiverProcess) ? \
						open_sync_bit : 0)
143

144
bool am_startup = false;
T
Tom Lane 已提交
145

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

159
/* Are we doing recovery from XLOG? */
T
Tom Lane 已提交
160
bool		InRecovery = false;
B
Bruce Momjian 已提交
161

162 163 164 165 166
/*
 * Local copy of SharedRecoveryInProgress variable. True actually means "not
 * known, need to check the shared state".
 */
static bool LocalRecoveryInProgress = true;
B
Bruce Momjian 已提交
167

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

171
/* options taken from recovery.conf */
172 173 174
static bool recoveryTarget = false;
static bool recoveryTargetExact = false;
static bool recoveryTargetInclusive = true;
175
static bool recoveryLogRestartpoints = false;
B
Bruce Momjian 已提交
176
static TransactionId recoveryTargetXid;
177
static TimestampTz recoveryTargetTime;
178
static TimestampTz recoveryLastXTime = 0;
179

180 181 182 183 184 185 186
/* options taken from recovery.conf for XLOG streaming */
static bool StandbyModeRequested = false;
static char *PrimaryConnInfo = NULL;

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

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

/*
 * During normal operation, the only timeline we care about is ThisTimeLineID.
 * During recovery, however, things are more complicated.  To simplify life
 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
 * scan through the WAL history (that is, it is the line that was active when
 * the currently-scanned WAL record was generated).  We also need these
 * timeline values:
 *
 * recoveryTargetTLI: the desired timeline that we want to end in.
 *
 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
 * its known parents, newest first (so recoveryTargetTLI is always the
B
Bruce Momjian 已提交
204
 * first list member).	Only these TLIs are expected to be seen in the WAL
205 206 207 208 209 210 211 212 213
 * 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 已提交
214
static TimeLineID recoveryTargetTLI;
215
List *expectedTLIs;
B
Bruce Momjian 已提交
216
static TimeLineID curFileTLI;
217

T
Tom Lane 已提交
218 219
/*
 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
220 221 222 223
 * 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 已提交
224 225
 */
static XLogRecPtr ProcLastRecPtr = {0, 0};
226

227
XLogRecPtr	XactLastRecEnd = {0, 0};
228

229 230 231 232
static uint32 ProcLastRecTotalLen = 0;

static uint32 ProcLastRecDataLen = 0;

T
Tom Lane 已提交
233 234 235
/*
 * 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 已提交
236
 * CHECKPOINT record).	We update this from the shared-memory copy,
T
Tom Lane 已提交
237
 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
B
Bruce Momjian 已提交
238
 * hold the Insert lock).  See XLogInsert for details.	We are also allowed
239
 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
240 241
 * see GetRedoRecPtr.  A freshly spawned backend obtains the value during
 * InitXLOGAccess.
T
Tom Lane 已提交
242
 */
243
static XLogRecPtr RedoRecPtr;
244

245 246 247 248 249 250 251 252 253 254 255 256
/*
 * 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 已提交
257 258 259 260 261 262 263 264 265
/*----------
 * 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.
 *
266
 * We do a lot of pushups to minimize the amount of access to lockable
T
Tom Lane 已提交
267 268 269
 * 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
270 271 272 273
 *		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 已提交
274 275 276
 *
 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
 * right", since both are updated by a write or flush operation before
277 278
 * 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 已提交
279 280 281
 * without needing to grab info_lck as well.
 *
 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
B
Bruce Momjian 已提交
282
 * but is updated when convenient.	Again, it exists for the convenience of
283
 * code that is already holding WALInsertLock but not the other locks.
T
Tom Lane 已提交
284 285 286 287 288 289 290 291 292 293
 *
 * 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".
294 295 296 297 298 299 300 301 302 303 304 305 306 307
 *
 * info_lck is only held long enough to read/update the protected variables,
 * so it's a plain spinlock.  The other locks are held longer (potentially
 * over I/O operations), so we use LWLocks for them.  These locks are:
 *
 * WALInsertLock: must be held to insert a record into the WAL buffers.
 *
 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
 * XLogFlush).
 *
 * ControlFileLock: must be held to read/update control file or create
 * new log file.
 *
 * CheckpointLock: must be held to do a checkpoint (ensures only one
308 309
 * checkpointer at a time; currently, with all checkpoints done by the
 * bgwriter, this is just pro forma).
310
 *
T
Tom Lane 已提交
311 312
 *----------
 */
313

T
Tom Lane 已提交
314
typedef struct XLogwrtRqst
315
{
T
Tom Lane 已提交
316 317
	XLogRecPtr	Write;			/* last byte + 1 to write out */
	XLogRecPtr	Flush;			/* last byte + 1 to flush */
318
} XLogwrtRqst;
319

320 321 322 323 324 325
typedef struct XLogwrtResult
{
	XLogRecPtr	Write;			/* last byte + 1 written out */
	XLogRecPtr	Flush;			/* last byte + 1 flushed */
} XLogwrtResult;

T
Tom Lane 已提交
326 327 328
/*
 * Shared state data for XLogInsert.
 */
329 330
typedef struct XLogCtlInsert
{
B
Bruce Momjian 已提交
331 332
	XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
	XLogRecPtr	PrevRecord;		/* start of previously-inserted record */
333
	int			curridx;		/* current block index in cache */
B
Bruce Momjian 已提交
334 335 336
	XLogPageHeader currpage;	/* points to header of block in cache */
	char	   *currpos;		/* current insertion point in cache */
	XLogRecPtr	RedoRecPtr;		/* current redo point for insertions */
337
	bool		forcePageWrites;	/* forcing full-page writes for PITR? */
338 339 340 341 342 343 344 345 346 347 348

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

T
Tom Lane 已提交
351 352 353
/*
 * Shared state data for XLogWrite/XLogFlush.
 */
354 355
typedef struct XLogCtlWrite
{
B
Bruce Momjian 已提交
356 357 358
	XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
	int			curridx;		/* cache index of next block to write */
	time_t		lastSegSwitchTime;		/* time of last xlog segment switch */
359 360
} XLogCtlWrite;

T
Tom Lane 已提交
361 362 363
/*
 * Total shared-memory state for XLOG.
 */
364 365
typedef struct XLogCtlData
{
366
	/* Protected by WALInsertLock: */
B
Bruce Momjian 已提交
367
	XLogCtlInsert Insert;
368

T
Tom Lane 已提交
369
	/* Protected by info_lck: */
B
Bruce Momjian 已提交
370 371
	XLogwrtRqst LogwrtRqst;
	XLogwrtResult LogwrtResult;
372 373
	uint32		ckptXidEpoch;	/* nextXID & epoch of latest checkpoint */
	TransactionId ckptXid;
B
Bruce Momjian 已提交
374
	XLogRecPtr	asyncCommitLSN; /* LSN of newest async commit */
375 376
	uint32		lastRemovedLog; /* latest removed/recycled XLOG segment */
	uint32		lastRemovedSeg;
377

378
	/* Protected by WALWriteLock: */
B
Bruce Momjian 已提交
379 380
	XLogCtlWrite Write;

381 382 383 384 385 386 387 388 389 390 391
	/* Protected by ChangeTrackingTransitionLock. */
	XLogRecPtr	lastChangeTrackingEndLoc;
								/*
								 * End + 1 of the last XLOG record inserted and
 								 * (possible) change tracked.
 								 */

	/* Resynchronize */
	bool		sendingResynchronizeTransitionMsg;
	slock_t		resynchronize_lck;		/* locks shared variables shown above */

T
Tom Lane 已提交
392
	/*
B
Bruce Momjian 已提交
393 394 395
	 * 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 已提交
396
	 */
B
Bruce Momjian 已提交
397
	char	   *pages;			/* buffers for unwritten XLOG pages */
398
	XLogRecPtr *xlblocks;		/* 1st byte ptr-s + XLOG_BLCKSZ */
399 400
	Size		XLogCacheByte;	/* # bytes in xlog buffers */
	int			XLogCacheBlck;	/* highest allocated xlog buffer index */
401
	TimeLineID	ThisTimeLineID;
T
Tom Lane 已提交
402

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
	/*
	 * SharedRecoveryInProgress indicates if we're still in crash or standby
	 * mode. Currently use of this variable is very limited for e.g. WAL receiver
	 * Protected by info_lck.
	 */
	bool		SharedRecoveryInProgress;

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

	/*
	 * the standby's dbid when it runs.  Used in mmxlog to emit standby filepath.
	 * Protected by info_lck
	 */
	int16		standbyDbid;

423
	slock_t		info_lck;		/* locks shared variables shown above */
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

	/*
	 * 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
	 * replayed.
	 */
	XLogRecPtr	lastReplayedEndRecPtr;

	/* current effective recovery target timeline */
	TimeLineID	RecoveryTargetTLI;

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

	/*
	 * Save the redo range used in Pass 1 recovery so it can be used in subsequent passes.
	 */
	bool		multipleRecoveryPassesNeeded;
	XLogRecPtr	pass1StartLoc;
	XLogRecPtr	pass1LastLoc;
	XLogRecPtr	pass1LastCheckpointLoc;

	/*=================Pass 4 PersistentTable-Cat verification================*/
	/*If true integrity checks will be performed in Pass4.*/
	bool		integrityCheckNeeded;

	/*
	 * Currently set database and tablespace to be verified for database specific
	 * PT-Cat verification in Pass4. These fields also act as implicit flags
	 * PT-Cat which indicate if there are any more databases to perform
	 * PT-Cat verifications checks on.
	 */
	Oid			currentDatabaseToVerify;
	Oid			tablespaceOfCurrentDatabaseToVerify;

	/*Indicates if pass4 PT-Cat verification checks passed*/
	bool		pass4_PTCatVerificationPassed;
	/*==========Pass 4 PersistentTable-Cat verification End===================*/

474 475
} XLogCtlData;

476
static XLogCtlData *XLogCtl = NULL;
477

478
/*
T
Tom Lane 已提交
479
 * We maintain an image of pg_control in shared memory.
480
 */
481
static ControlFileData *ControlFile = NULL;
482

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
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 已提交
501 502 503 504 505
/*
 * 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.
 */
506

T
Tom Lane 已提交
507 508
/* Free space remaining in the current xlog page buffer */
#define INSERT_FREESPACE(Insert)  \
509
	(XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
T
Tom Lane 已提交
510 511 512 513 514 515

/* Construct XLogRecPtr value for current insertion point */
#define INSERT_RECPTR(recptr,Insert,curridx)  \
	( \
	  (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
	  (recptr).xrecoff = \
B
Bruce Momjian 已提交
516
		XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
T
Tom Lane 已提交
517 518 519 520 521 522 523
	)

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

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

T
Tom Lane 已提交
525 526 527 528
/*
 * Private, possibly out-of-date copy of shared LogwrtResult.
 * See discussion above.
 */
529
static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
530

531 532 533 534 535 536 537 538 539
/*
 * 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 已提交
540 541 542 543 544 545
/*
 * 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.
 */
546
static MirroredFlatFileOpen	mirroredLogFileOpen = MirroredFlatFileOpen_Init;
T
Tom Lane 已提交
547 548 549
static uint32 openLogId = 0;
static uint32 openLogSeg = 0;
static uint32 openLogOff = 0;
550

T
Tom Lane 已提交
551 552 553 554
/*
 * 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
555 556 557
 * 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 已提交
558
 */
559 560 561 562
static int	readFile = -1;
static uint32 readId = 0;
static uint32 readSeg = 0;
static uint32 readOff = 0;
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
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 已提交
580

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

584 585 586 587
/* Buffer for current ReadRecord result (expandable) */
static char *readRecordBuf = NULL;
static uint32 readRecordBufSize = 0;

T
Tom Lane 已提交
588
/* State information for XLOG reading */
B
Bruce Momjian 已提交
589 590
static XLogRecPtr ReadRecPtr;	/* start of last record read */
static XLogRecPtr EndRecPtr;	/* end+1 of last record read */
591
static XLogRecord *nextRecord = NULL;
592
static TimeLineID lastPageTLI = 0;
593
static TimeLineID lastSegmentTLI = 0;
594

V
WAL  
Vadim B. Mikheev 已提交
595 596
static bool InRedo = false;

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
/* Aligning xlog mirrored buffer */
static int32 writeBufLen = 0;
static char	*writeBuf = NULL;

char	*writeBufAligned = NULL;

/*
 * Flag set by interrupt handlers for later service in the redo loop.
 */
static volatile sig_atomic_t got_SIGHUP = false;
static volatile sig_atomic_t shutdown_requested = false;

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

615 616
static void XLogArchiveNotify(const char *xlog);
static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
617
static bool XLogArchiveCheckDone(const char *xlog);
618
static void XLogArchiveCleanup(const char *xlog);
619
static void exitArchiveRecovery(TimeLineID endTLI,
B
Bruce Momjian 已提交
620
					uint32 endLogId, uint32 endLogSeg);
621
static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
622
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
623
static void Checkpoint_RecoveryPass(XLogRecPtr checkPointRedo);
T
Tom Lane 已提交
624

625
static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
B
Bruce Momjian 已提交
626
				XLogRecPtr *lsn, BkpBlock *bkpb);
627 628
static bool AdvanceXLInsertBuffer(bool new_segment);
static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
629 630 631
static void XLogFileInit(
			 MirroredFlatFileOpen *mirroredOpen,
			 uint32 log, uint32 seg,
B
Bruce Momjian 已提交
632
			 bool *use_existent, bool use_lock);
633 634
static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
635
					   bool use_lock, char *tmpsimpleFileName);
636
static void XLogFileClose(void);
637 638 639 640 641 642 643 644 645 646 647 648 649
static void XLogFileOpen(
				MirroredFlatFileOpen *mirroredOpen,
				uint32 log,
				uint32 seg);

static bool StartupXLOG_Pass4_CheckIfAnyInDoubtPreparedTransactions(void);
static void StartupXLOG_Pass4_NonDBSpecificPTCatVerification(void);
static void StartupXLOG_Pass4_DBSpecificPTCatVerification(void);
static bool StartupXLOG_Pass4_GetDBForPTCatVerification(void);

static bool XLogPageRead(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt,
			 bool randAccess);

650
static void PreallocXlogFiles(XLogRecPtr endptr);
651
static void UpdateLastRemovedPtr(char *filename);
652
static void CleanupBackupHistory(void);
653
static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
654 655 656 657 658 659 660 661 662 663 664
static bool ValidXLOGHeader(XLogPageHeader hdr, int emode, bool segmentonly);
static void UnpackCheckPointRecord(
	XLogRecord			*record,
	XLogRecPtr 			*location,
	TMGXACT_CHECKPOINT	**dtxCheckpoint,
	uint32				*dtxCheckpointLen,
	char				**masterMirroringCheckpoint,
	uint32				*masterMirroringCheckpointLen,
	int					errlevelMasterMirroring,
        prepared_transaction_agg_state  **ptas);

665 666 667
static bool existsTimeLineHistory(TimeLineID probeTLI);
static TimeLineID findNewestTimeLine(TimeLineID startTLI);
static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
B
Bruce Momjian 已提交
668 669
					 TimeLineID endTLI,
					 uint32 endLogId, uint32 endLogSeg);
670 671 672 673
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 已提交
674 675
static void WriteControlFile(void);
static void ReadControlFile(void);
676

677
static char *str_time(pg_time_t tnow);
678

679
static void xlog_outrec(StringInfo buf, XLogRecord *record);
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
static void pg_start_backup_callback(int code, Datum arg);
static bool read_backup_label(XLogRecPtr *checkPointLoc, bool *backupEndRequired);
static void ValidateXLOGDirectoryStructure(void);

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

696
static void rm_redo_error_callback(void *arg);
T
Tom Lane 已提交
697

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
static int XLogGetEof(XLogRecPtr *eofRecPtr);

static	int XLogFillZero(
				 uint32	logId,
				 uint32	seg,
				 uint32	startOffset,
				 uint32	endOffset);

static int XLogReconcileEofInternal(
							 XLogRecPtr	startLocation,
							 XLogRecPtr	endLocation);

void HandleStartupProcInterrupts(void);
static bool CheckForStandbyTrigger(void);

/*
 * Whether we need to always generate transaction log (XLOG), or if we can
 * bypass it and get better performance.
 *
 * For GPDB, we currently do not support XLogArchivingActive(), so we don't
 * use it as a condition.
 */
bool XLog_CanBypassWal(void)
{
	if (Debug_bulk_load_bypass_wal)
	{
		/*
		 * We need the XLOG to be transmitted to the standby master since
		 * it is not using FileRep technology yet.  Master also could skip
		 * some of the WAL operations for optimization when standby is not
		 * configured, but for now we lean towards safety.
		 */
		return GpIdentity.segindex != MASTER_CONTENT_ID;
	}
	else
	{
		return false;
	}
}

/*
 * For FileRep code that doesn't have the Bypass WAL logic yet.
 */
bool XLog_UnconvertedCanBypassWal(void)
{
	return false;
}

static char *XLogContiguousCopy(
	XLogRecord 		*record,

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

	rdt = rdata;
	len = sizeof(XLogRecord);
	while (rdt != NULL)
	{
		if (rdt->data != NULL)
		{
			len += rdt->len;
		}
		rdt = rdt->next;
	}

	buffer = (char*)palloc(len);

	memcpy(buffer, record, sizeof(XLogRecord));
	rdt = rdata;
	len = sizeof(XLogRecord);
	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 已提交
783 784 785 786

/*
 * Insert an XLOG record having the specified RMID and info bytes,
 * with the body of the record being the data chunk(s) described by
787
 * the rdata chain (see xlog.h for notes about rdata).
T
Tom Lane 已提交
788 789 790 791 792 793 794 795 796 797 798
 *
 * 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.
 */
799
XLogRecPtr
800
XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
801
{
802 803 804 805 806 807 808 809 810 811 812 813 814 815
	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 已提交
816 817
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecord *record;
T
Tom Lane 已提交
818
	XLogContRecord *contrecord;
B
Bruce Momjian 已提交
819 820 821
	XLogRecPtr	RecPtr;
	XLogRecPtr	WriteRqst;
	uint32		freespace;
822
	int			curridx;
B
Bruce Momjian 已提交
823
	XLogRecData *rdt;
824
	char 		*rdatabuf = NULL;
B
Bruce Momjian 已提交
825 826 827 828
	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];
829 830 831 832
	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 已提交
833 834 835 836
	uint32		len,
				write_len;
	unsigned	i;
	bool		updrqst;
837
	bool		doPageWrites;
838
	bool		isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
V
Vadim B. Mikheev 已提交
839

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
	bool		rdata_iscopy = false;

    /* Safety check in case our assumption is ever broken. */
	/* NOTE: This is slightly modified from the one in xact.c -- the test for */
 	/* NOTE: seqXlogWrite is omitted... */
	/* NOTE: some local-only changes are OK */
 	if (Gp_role == GP_ROLE_EXECUTE && !Gp_is_writer)
 	{
 		/*
 	     * we better only do really minor things on the reader that result
 	     * in writing to the xlog here at commit.  for now sequences
 	     * should be the only one
 	     */
		if (DistributedTransactionContext == DTX_CONTEXT_LOCAL_ONLY)
		{
			/* MPP-1687: readers may under some circumstances extend the CLOG
			 * rmid == RM_CLOG_ID and info having CLOG_ZEROPAGE set */
			elog(LOG, "Reader qExec committing LOCAL_ONLY changes. (%d %d)", rmid, info);
		}
		else
		{
			/*
			 * We are allowing the QE Reader to write to support error tables.
			 */
			elog(DEBUG1, "Reader qExec writing changes. (%d %d)", rmid, info);
#ifdef nothing
			ereport(ERROR,
					(errmsg("Reader qExec had local changes to commit! (rmid = %u)",
							rmid),
					 errdetail("A Reader qExec tried to commit local changes.  "
							   "Only the single Writer qExec can do so. "),
					 errhint("This is most likely the result of a feature being turned "
							 "on that violates the single WRITER principle")));
#endif
		}
 	}

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

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

T
Tom Lane 已提交
892
	/*
893
	 * Here we scan the rdata chain, determine which buffers must be backed
T
Tom Lane 已提交
894
	 * up, and compute the CRC values for the data.  Note that the record
B
Bruce Momjian 已提交
895 896 897 898
	 * 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 已提交
899
	 *
900 901 902 903 904
	 * 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 已提交
905 906 907 908 909
	 * 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 已提交
910
	 */
911
begin:;
T
Tom Lane 已提交
912 913 914 915 916 917
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
	{
		dtbuf[i] = InvalidBuffer;
		dtbuf_bkp[i] = false;
	}

918 919 920 921 922 923 924 925
	/*
	 * 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;

926
	INIT_CRC32C(rdata_crc);
T
Tom Lane 已提交
927
	len = 0;
B
Bruce Momjian 已提交
928
	for (rdt = rdata;;)
929 930 931
	{
		if (rdt->buffer == InvalidBuffer)
		{
T
Tom Lane 已提交
932
			/* Simple data, just include it */
933
			len += rdt->len;
934
			COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
935
		}
T
Tom Lane 已提交
936
		else
937
		{
T
Tom Lane 已提交
938 939
			/* Find info for buffer */
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
940
			{
T
Tom Lane 已提交
941
				if (rdt->buffer == dtbuf[i])
942
				{
943
					/* Buffer already referenced by earlier chain item */
T
Tom Lane 已提交
944 945 946 947 948
					if (dtbuf_bkp[i])
						rdt->data = NULL;
					else if (rdt->data)
					{
						len += rdt->len;
949
						COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
T
Tom Lane 已提交
950 951
					}
					break;
952
				}
T
Tom Lane 已提交
953
				if (dtbuf[i] == InvalidBuffer)
954
				{
T
Tom Lane 已提交
955 956
					/* OK, put it in this slot */
					dtbuf[i] = rdt->buffer;
957 958
					if (XLogCheckBuffer(rdt, doPageWrites,
										&(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
T
Tom Lane 已提交
959 960 961 962 963 964 965
					{
						dtbuf_bkp[i] = true;
						rdt->data = NULL;
					}
					else if (rdt->data)
					{
						len += rdt->len;
966
						COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
T
Tom Lane 已提交
967 968
					}
					break;
969 970
				}
			}
T
Tom Lane 已提交
971
			if (i >= XLR_MAX_BKP_BLOCKS)
972
				elog(PANIC, "can backup at most %d blocks per xlog record",
T
Tom Lane 已提交
973
					 XLR_MAX_BKP_BLOCKS);
974
		}
975
		/* Break out of loop when rdt points to last chain item */
976 977 978 979 980
		if (rdt->next == NULL)
			break;
		rdt = rdt->next;
	}

981 982 983 984 985 986 987 988 989 990
	/*
	 * 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;

991
			COMP_CRC32C(rdata_crc,
992 993 994 995 996
					   (char *) bkpb,
					   sizeof(BkpBlock));
			page = (char *) BufferGetBlock(dtbuf[i]);
			if (bkpb->hole_length == 0)
			{
997
				COMP_CRC32C(rdata_crc, page, BLCKSZ);
998 999 1000 1001
			}
			else
			{
				/* must skip the hole */
1002 1003
				COMP_CRC32C(rdata_crc, page, bkpb->hole_offset);
				COMP_CRC32C(rdata_crc,
1004 1005 1006 1007 1008 1009
						   page + (bkpb->hole_offset + bkpb->hole_length),
						   BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
			}
		}
	}

T
Tom Lane 已提交
1010
	/*
1011 1012
	 * 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 已提交
1013 1014 1015
	 * 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 已提交
1016
	 */
1017
	if (len == 0 && !isLogSwitch)
1018
		elog(PANIC, "invalid xlog record length %u", len);
1019

1020
	START_CRIT_SECTION();
1021

1022 1023 1024
	/* Now wait to get insert lock */
	LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);

T
Tom Lane 已提交
1025
	/*
B
Bruce Momjian 已提交
1026 1027 1028
	 * 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.
1029 1030
	 *
	 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
B
Bruce Momjian 已提交
1031 1032
	 * affect the contents of the XLOG record, so we'll update our local copy
	 * but not force a recomputation.
T
Tom Lane 已提交
1033 1034
	 */
	if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
1035
	{
T
Tom Lane 已提交
1036 1037 1038
		Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
		RedoRecPtr = Insert->RedoRecPtr;

1039
		if (doPageWrites)
1040
		{
1041
			for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
T
Tom Lane 已提交
1042
			{
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
				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);
1053

1054 1055 1056
					END_CRIT_SECTION();
					goto begin;
				}
T
Tom Lane 已提交
1057
			}
1058 1059 1060
		}
	}

1061
	/*
B
Bruce Momjian 已提交
1062 1063 1064 1065
	 * 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.)
1066 1067 1068 1069 1070 1071 1072 1073 1074
	 */
	if (Insert->forcePageWrites && !doPageWrites)
	{
		/* Oops, must redo it with full-page data */
		LWLockRelease(WALInsertLock);
		END_CRIT_SECTION();
		goto begin;
	}

T
Tom Lane 已提交
1075
	/*
B
Bruce Momjian 已提交
1076 1077 1078 1079
	 * 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 已提交
1080
	 *
1081 1082 1083
	 * 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 已提交
1084 1085 1086
	 */
	write_len = len;
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
1087
	{
1088 1089 1090
		BkpBlock   *bkpb;
		char	   *page;

1091
		if (!dtbuf_bkp[i])
1092 1093
			continue;

T
Tom Lane 已提交
1094
		info |= XLR_SET_BKP_BLOCK(i);
1095

1096 1097 1098 1099 1100
		bkpb = &(dtbuf_xlg[i]);
		page = (char *) BufferGetBlock(dtbuf[i]);

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

1102 1103
		rdt->data = (char *) bkpb;
		rdt->len = sizeof(BkpBlock);
T
Tom Lane 已提交
1104
		write_len += sizeof(BkpBlock);
1105

1106 1107
		rdt->next = &(dtbuf_rdt2[i]);
		rdt = rdt->next;
1108

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
		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;
		}
1131 1132
	}

1133 1134 1135 1136 1137 1138 1139
	/*
	 * 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 已提交
1140 1141
	 * defining it like this leaves the info bit free for some potential other
	 * use in records without any backup blocks.
1142 1143 1144 1145
	 */
	if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
		info |= XLR_BKP_REMOVABLE;

1146
	/*
1147
	 * If there isn't enough space on the current XLOG page for a record
B
Bruce Momjian 已提交
1148
	 * header, advance to the next page (leaving the unused space as zeroes).
1149
	 */
T
Tom Lane 已提交
1150 1151
	updrqst = false;
	freespace = INSERT_FREESPACE(Insert);
1152 1153
	if (freespace < SizeOfXLogRecord)
	{
1154
		updrqst = AdvanceXLInsertBuffer(false);
1155 1156 1157
		freespace = INSERT_FREESPACE(Insert);
	}

1158
	/* Compute record's XLOG location */
T
Tom Lane 已提交
1159
	curridx = Insert->curridx;
1160 1161 1162
	INSERT_RECPTR(RecPtr, Insert, curridx);

	/*
B
Bruce Momjian 已提交
1163 1164 1165 1166 1167
	 * 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.
1168 1169 1170 1171
	 */
	if (isLogSwitch &&
		(RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
	{
1172
		/* We can release insert lock immediately */
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
		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 已提交
1199

1200 1201
	/* Insert record header */

1202
	record = (XLogRecord *) Insert->currpos;
1203
	record->xl_prev = Insert->PrevRecord;
1204
	record->xl_xid = headerXid;
1205
	record->xl_tot_len = SizeOfXLogRecord + write_len;
T
Tom Lane 已提交
1206
	record->xl_len = len;		/* doesn't include backup blocks */
1207
	record->xl_info = info;
1208
	record->xl_rmid = rmid;
1209

1210
	/* Now we can finish computing the record's CRC */
1211
	COMP_CRC32C(rdata_crc, (char *) record + sizeof(pg_crc32),
1212
			   SizeOfXLogRecord - sizeof(pg_crc32));
1213
	FIN_CRC32C(rdata_crc);
1214 1215
	record->xl_crc = rdata_crc;

T
Tom Lane 已提交
1216 1217 1218 1219
	/* Record begin of record in appropriate places */
	ProcLastRecPtr = RecPtr;
	Insert->PrevRecord = RecPtr;

1220 1221 1222
	ProcLastRecTotalLen = record->xl_tot_len;
	ProcLastRecDataLen = write_len;

1223
	Insert->currpos += SizeOfXLogRecord;
T
Tom Lane 已提交
1224
	freespace -= SizeOfXLogRecord;
1225

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	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);
1236
		xlog_outrec(&buf, record);
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253

		contiguousCopy = XLogContiguousCopy(record, rdata);
		appendStringInfo(&buf, " - ");
		RmgrTable[record->xl_rmid].rm_desc(&buf, RecPtr, (XLogRecord*)contiguousCopy);
		pfree(contiguousCopy);

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

	/*
	 * Always copy of the relevant rdata information in case we discover below we
	 * are in 'Change Tracking' mode and need to call ChangeTracking_AddRecordFromXlog().
	 */

	rdatabuf = ChangeTracking_CopyRdataBuffers(rdata, rmid, info, &rdata_iscopy);

T
Tom Lane 已提交
1254 1255 1256 1257
	/*
	 * Append the data, including backup blocks if any
	 */
	while (write_len)
1258
	{
1259 1260 1261 1262
		while (rdata->data == NULL)
			rdata = rdata->next;

		if (freespace > 0)
1263
		{
1264 1265 1266 1267 1268
			if (rdata->len > freespace)
			{
				memcpy(Insert->currpos, rdata->data, freespace);
				rdata->data += freespace;
				rdata->len -= freespace;
T
Tom Lane 已提交
1269
				write_len -= freespace;
1270 1271 1272
			}
			else
			{
1273
				/* enough room to write whole data. do it. */
1274 1275
				memcpy(Insert->currpos, rdata->data, rdata->len);
				freespace -= rdata->len;
T
Tom Lane 已提交
1276
				write_len -= rdata->len;
1277 1278 1279 1280
				Insert->currpos += rdata->len;
				rdata = rdata->next;
				continue;
			}
1281 1282
		}

1283
		/* Use next buffer */
1284
		updrqst = AdvanceXLInsertBuffer(false);
T
Tom Lane 已提交
1285 1286 1287 1288 1289 1290
		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;
1291
		freespace = INSERT_FREESPACE(Insert);
1292
	}
1293

T
Tom Lane 已提交
1294 1295
	/* Ensure next record will be properly aligned */
	Insert->currpos = (char *) Insert->currpage +
B
Bruce Momjian 已提交
1296
		MAXALIGN(Insert->currpos - (char *) Insert->currpage);
T
Tom Lane 已提交
1297
	freespace = INSERT_FREESPACE(Insert);
1298

V
Vadim B. Mikheev 已提交
1299
	/*
B
Bruce Momjian 已提交
1300 1301
	 * 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 已提交
1302
	 */
T
Tom Lane 已提交
1303
	INSERT_RECPTR(RecPtr, Insert, curridx);
V
Vadim B. Mikheev 已提交
1304

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
	/*
	 * If the record is an XLOG_SWITCH, we must now write and flush all the
	 * existing data, and then forcibly advance to the start of the next
	 * segment.  It's not good to do this I/O while holding the insert lock,
	 * but there seems too much risk of confusion if we try to release the
	 * lock sooner.  Fortunately xlog switch needn't be a high-performance
	 * operation anyway...
	 */
	if (isLogSwitch)
	{
		XLogCtlWrite *Write = &XLogCtl->Write;
		XLogwrtRqst FlushRqst;
		XLogRecPtr	OldSegEnd;

		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);

		/*
B
Bruce Momjian 已提交
1322 1323
		 * Flush through the end of the page containing XLOG_SWITCH, and
		 * perform end-of-segment actions (eg, notifying archiver).
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
		 */
		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 */
	}
1374
	else
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
	{
		/* 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];
	}
1391

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
	/*
	 * Use this lock to make sure we add Change Tracking records correctly.
	 *
	 * IMPORTANT: Acquiring this lock must be done AFTER ALL WRITE AND FSYNC calls under
	 * WALInsertLock.  Otherwise, the write suspension that occurs as a natural part of
	 * mirror communication loss and fault handling would suspend us and cause a deadlock.
	 *
	 * When this lock is held EXCLUSIVE, we are in transition from 'In Sync' to
	 * 'Change Tracking'.  During that time other processes are initializing the
	 * 'Change Tracking' log with information since the last checkpoint.  Thus, we need to
	 * wait here before we add our information.
	 */
	LWLockAcquire(ChangeTrackingTransitionLock, LW_SHARED);

	if (Debug_print_xlog_relation_change_info && rdatabuf != NULL)
	{
		bool skipIssue;

		skipIssue =
			ChangeTracking_PrintRelationChangeInfo(
												rmid,
												info,
												(void *)rdatabuf,
												&RecPtr,
												/* weAreGeneratingXLogNow */ true,
												/* printSkipIssuesOnly */ Debug_print_xlog_relation_change_info_skip_issues_only);

		if (Debug_print_xlog_relation_change_info_backtrace_skip_issues &&
			skipIssue)
		{
			/* Code for investigating MPP-13909, will be removed as part of the fix */
			elog(WARNING, 
				 "ChangeTracking_PrintRelationChangeInfo hang skipIssue %s",
				 (skipIssue ? "true" : "false"));
			
			for (int i=0; i < 24 * 60; i++)
			{
				pg_usleep(60000000L); /* 60 sec */
			}
			Insist(0);
			debug_backtrace();
		}
	}

	/* if needed, send this record to the changetracker */
	if (ChangeTracking_ShouldTrackChanges() && rdatabuf != NULL)
	{
		ChangeTracking_AddRecordFromXlog(rmid, info, (void *)rdatabuf, &RecPtr);
	}

	/*
	 * Last LSN location has to be tracked also when no mirrors are configured
	 * in order to handle gpaddmirrors correctly
	 */
	XLogCtl->lastChangeTrackingEndLoc = RecPtr;

	if(rdata_iscopy)
	{
		if (rdatabuf != NULL)
		{
			pfree(rdatabuf);
			rdatabuf = NULL;
		}
		rdata_iscopy = false;
	}

	LWLockRelease(ChangeTrackingTransitionLock);

1460
	LWLockRelease(WALInsertLock);
1461 1462 1463

	if (updrqst)
	{
1464 1465 1466
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

1467
		SpinLockAcquire(&xlogctl->info_lck);
T
Tom Lane 已提交
1468
		/* advance global request to include new block(s) */
1469 1470
		if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
			xlogctl->LogwrtRqst.Write = WriteRqst;
T
Tom Lane 已提交
1471
		/* update local result copy while I have the chance */
1472
		LogwrtResult = xlogctl->LogwrtResult;
1473
		SpinLockRelease(&xlogctl->info_lck);
1474 1475
	}

1476
	XactLastRecEnd = RecPtr;
1477

1478
	END_CRIT_SECTION();
1479

1480
	return RecPtr;
1481
}
1482

1483 1484 1485 1486 1487 1488 1489 1490 1491
XLogRecPtr
XLogLastInsertBeginLoc(void)
{
	return ProcLastRecPtr;
}

XLogRecPtr
XLogLastInsertEndLoc(void)
{
1492
	return XactLastRecEnd;
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
}

XLogRecPtr
XLogLastChangeTrackedLoc(void)
{
	return XLogCtl->lastChangeTrackingEndLoc;
}

uint32
XLogLastInsertTotalLen(void)
{
	return ProcLastRecTotalLen;
}

uint32
XLogLastInsertDataLen(void)
{
	return ProcLastRecDataLen;
}

1513
/*
1514 1515 1516
 * 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.
1517
 */
1518
static bool
1519
XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1520
				XLogRecPtr *lsn, BkpBlock *bkpb)
1521 1522
{
	PageHeader	page;
1523 1524 1525 1526

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

	/*
B
Bruce Momjian 已提交
1527 1528 1529
	 * XXX We assume page LSN is first data on *every* page that can be passed
	 * to XLogInsert, whether it otherwise has the standard page layout or
	 * not.
1530 1531 1532
	 */
	*lsn = page->pd_lsn;

1533
	if (doPageWrites &&
1534
		XLByteLE(page->pd_lsn, RedoRecPtr))
1535
	{
1536 1537 1538 1539 1540
		/*
		 * The page needs to be backed up, so set up *bkpb
		 */
		bkpb->node = BufferGetFileNode(rdata->buffer);
		bkpb->block = BufferGetBlockNumber(rdata->buffer);
1541

1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
		if (rdata->buffer_std)
		{
			/* Assume we can omit data between pd_lower and pd_upper */
			uint16		lower = page->pd_lower;
			uint16		upper = page->pd_upper;

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

1569
		return true;			/* buffer requires backup */
1570
	}
1571 1572

	return false;				/* buffer does not need to be backed up */
1573 1574
}

1575 1576 1577 1578 1579 1580
/*
 * XLogArchiveNotify
 *
 * Create an archive notification file
 *
 * The name of the notification file is the message that will be picked up
1581
 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1582
 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1583
 * then when complete, rename it to 0000000100000001000000C6.done
1584 1585 1586 1587 1588
 */
static void
XLogArchiveNotify(const char *xlog)
{
	char		archiveStatusPath[MAXPGPATH];
B
Bruce Momjian 已提交
1589
	FILE	   *fd;
1590 1591 1592 1593

	/* insert an otherwise empty file called <XLOG>.ready */
	StatusFilePath(archiveStatusPath, xlog, ".ready");
	fd = AllocateFile(archiveStatusPath, "w");
B
Bruce Momjian 已提交
1594 1595
	if (fd == NULL)
	{
1596 1597 1598 1599 1600 1601
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not create archive status file \"%s\": %m",
						archiveStatusPath)));
		return;
	}
B
Bruce Momjian 已提交
1602 1603
	if (FreeFile(fd))
	{
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
		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];

1624
	XLogFileName(xlog, ThisTimeLineID, log, seg);
1625 1626 1627 1628
	XLogArchiveNotify(xlog);
}

/*
1629
 * XLogArchiveCheckDone
1630
 *
1631 1632 1633 1634
 * 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.
1635 1636
 *
 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1637 1638 1639 1640
 * 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.
1641 1642
 */
static bool
1643
XLogArchiveCheckDone(const char *xlog)
1644 1645 1646 1647
{
	char		archiveStatusPath[MAXPGPATH];
	struct stat stat_buf;

1648 1649 1650 1651 1652
	/* Always deletable if archiving is off */
	if (!XLogArchivingActive())
		return true;

	/* First check for .done --- this means archiver is done with it */
1653 1654 1655 1656 1657 1658 1659
	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 已提交
1660
		return false;
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674

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

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

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

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

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

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

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

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

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

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

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

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

		if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
		{
			/* OK, someone wrote it already */
			Insert->LogwrtResult = LogwrtResult;
		}
		else
1757
		{
1758 1759 1760 1761
			/* Must acquire write lock */
			LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
			LogwrtResult = Write->LogwrtResult;
			if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1762
			{
1763 1764 1765
				/* OK, someone wrote it already */
				LWLockRelease(WALWriteLock);
				Insert->LogwrtResult = LogwrtResult;
T
Tom Lane 已提交
1766
			}
1767
			else
T
Tom Lane 已提交
1768 1769
			{
				/*
B
Bruce Momjian 已提交
1770 1771
				 * Have to write buffers while holding insert lock. This is
				 * not good, so only write as much as we absolutely must.
T
Tom Lane 已提交
1772 1773 1774 1775
				 */
				WriteRqst.Write = OldPageRqstPtr;
				WriteRqst.Flush.xlogid = 0;
				WriteRqst.Flush.xrecoff = 0;
1776
				XLogWrite(WriteRqst, false, false);
1777
				LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
1778
				Insert->LogwrtResult = LogwrtResult;
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 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
/*
 * Check whether we've consumed enough xlog space that a checkpoint is needed.
 *
 * Caller must have just finished filling the open log file (so that
 * openLogId/openLogSeg are valid).  We measure the distance from RedoRecPtr
 * to the open log file and see if that exceeds CheckPointSegments.
 *
 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
 */
static bool
XLogCheckpointNeeded(void)
{
	/*
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 1872 1873 1874
	 */
	uint32		old_segno,
				new_segno;
	uint32		old_highbits,
				new_highbits;

	old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
		(RedoRecPtr.xrecoff / XLogSegSize);
	old_highbits = RedoRecPtr.xlogid / XLogSegSize;
	new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile + openLogSeg;
	new_highbits = openLogId / XLogSegSize;
	if (new_highbits != old_highbits ||
B
Bruce Momjian 已提交
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 (MirroredFlatFile_IsActive(&mirroredLogFileOpen))
1964
				XLogFileClose();
T
Tom Lane 已提交
1965 1966
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);

1967 1968
			/* create/use new log file */
			use_existent = true;
1969 1970 1971 1972 1973

			XLogFileInit(
					&mirroredLogFileOpen,
					openLogId, openLogSeg,
					&use_existent, true);
T
Tom Lane 已提交
1974
			openLogOff = 0;
1975 1976
		}

1977
		/* Make sure we have the current logfile open */
1978
		if (!MirroredFlatFile_IsActive(&mirroredLogFileOpen))
1979
		{
T
Tom Lane 已提交
1980
			XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1981 1982 1983 1984
			XLogFileOpen(
					&mirroredLogFileOpen,
					openLogId,
					openLogSeg);
T
Tom Lane 已提交
1985
			openLogOff = 0;
1986 1987
		}

1988 1989 1990 1991 1992
		/* Add current page to the set of pending pages-to-dump */
		if (npages == 0)
		{
			/* first of group */
			startidx = curridx;
1993
			startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1994 1995
		}
		npages++;
1996

T
Tom Lane 已提交
1997
		/*
B
Bruce Momjian 已提交
1998 1999 2000 2001
		 * 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 已提交
2002
		 */
2003 2004
		last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);

2005
		finishing_seg = !ispartialpage &&
2006
			(startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
2007

2008
		if (last_iteration ||
2009 2010
			curridx == XLogCtl->XLogCacheBlck ||
			finishing_seg)
T
Tom Lane 已提交
2011
		{
2012 2013
			char	   *from;
			Size		nbytes;
2014

2015 2016 2017 2018 2019 2020 2021
			/* Need to seek in the file? */
			if (openLogOff != startoffset)
			{
				openLogOff = startoffset;
			}

			/* OK to write the page(s) */
2022 2023
			from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
			nbytes = npages * (Size) XLOG_BLCKSZ;
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050

			/* The following code is a sanity check to try to catch the issue described in MPP-12611 */
			if (!IsBootstrapProcessingMode())
			  {
			  char   simpleFileName[MAXPGPATH];
			  XLogFileName(simpleFileName, ThisTimeLineID, openLogId, openLogSeg);
                          if (strcmp(simpleFileName, mirroredLogFileOpen.simpleFileName) != 0)
			    {
			      ereport( PANIC
				       , (errmsg_internal("Expected Xlog file name does not match current open xlog file name. \
                                                           Expected file = %s, \
                                                           open file = %s, \
                                                           WriteRqst.Write = %s, \
                                                           WriteRqst.Flush = %s "
							 , simpleFileName
							 , mirroredLogFileOpen.simpleFileName
							 , XLogLocationToString(&(WriteRqst.Write))
							 , XLogLocationToString(&(WriteRqst.Flush)))));
			    }
			  }

			if (MirroredFlatFile_Write(
							&mirroredLogFileOpen,
							openLogOff,
							from,
							nbytes,
							/* suppressError */ true))
2051 2052 2053 2054
			{
				ereport(PANIC,
						(errcode_for_file_access(),
						 errmsg("could not write to log file %u, segment %u "
P
Peter Eisentraut 已提交
2055
								"at offset %u, length %lu: %m",
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
								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.
			 *
2072 2073 2074
			 * We also do this if this is the last page written for an xlog
			 * switch.
			 *
2075
			 * This is also the right place to notify the Archiver that the
B
Bruce Momjian 已提交
2076
			 * segment is ready to copy to archival storage, and to update the
2077 2078 2079
			 * timer for archive_timeout, and to signal for a checkpoint if
			 * too many logfile segments have been used since the last
			 * checkpoint.
2080
			 */
2081
			if (finishing_seg || (xlog_switch && last_iteration))
2082
			{
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
				if (MirroredFlatFile_IsActive(&mirroredLogFileOpen))
					MirroredFlatFile_Flush(
									&mirroredLogFileOpen,
									/* suppressError */ false);

				elog((Debug_print_qd_mirroring ? LOG : DEBUG5),
					 "XLogWrite (#1): flush loc %s; write loc %s",
					 XLogLocationToString_Long(&LogwrtResult.Flush),
					 XLogLocationToString2_Long(&LogwrtResult.Write));

B
Bruce Momjian 已提交
2093
				LogwrtResult.Flush = LogwrtResult.Write;		/* end of page */
2094 2095 2096

				if (XLogArchivingActive())
					XLogArchiveNotifySeg(openLogId, openLogSeg);
2097 2098

				Write->lastSegSwitchTime = time(NULL);
2099 2100

				/*
2101
				 * Signal bgwriter to start a checkpoint if we've consumed too
2102
				 * much xlog since the last one.  For speed, we first check
B
Bruce Momjian 已提交
2103 2104 2105
				 * 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.
2106
				 */
2107 2108
				if (IsUnderPostmaster &&
					XLogCheckpointNeeded())
2109
				{
2110 2111
					if (Debug_print_qd_mirroring)
						elog(LOG, "time for a checkpoint, signaling bgwriter");
2112 2113
					(void) GetRedoRecPtr();
					if (XLogCheckpointNeeded())
2114
						RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
2115
				}
2116
			}
T
Tom Lane 已提交
2117
		}
2118

T
Tom Lane 已提交
2119 2120 2121 2122 2123 2124
		if (ispartialpage)
		{
			/* Only asked to write a partial page */
			LogwrtResult.Write = WriteRqst.Write;
			break;
		}
2125 2126 2127 2128 2129
		curridx = NextBufIdx(curridx);

		/* If flexible, break out of loop as soon as we wrote something */
		if (flexible && npages == 0)
			break;
2130
	}
2131 2132 2133

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

T
Tom Lane 已提交
2135 2136 2137 2138 2139
	/*
	 * If asked to flush, do so
	 */
	if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
		XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
2140
	{
T
Tom Lane 已提交
2141
		/*
B
Bruce Momjian 已提交
2142 2143 2144
		 * 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 已提交
2145
		 */
2146
		if (sync_method != SYNC_METHOD_OPEN)
T
Tom Lane 已提交
2147
		{
2148
			if (MirroredFlatFile_IsActive(&mirroredLogFileOpen) &&
B
Bruce Momjian 已提交
2149
				!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
2150
				XLogFileClose();
2151
			if (!MirroredFlatFile_IsActive(&mirroredLogFileOpen))
2152 2153
			{
				XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
2154 2155 2156 2157
				XLogFileOpen(
						&mirroredLogFileOpen,
						openLogId,
						openLogSeg);
2158 2159
				openLogOff = 0;
			}
2160 2161 2162 2163 2164 2165 2166 2167 2168
			if (MirroredFlatFile_IsActive(&mirroredLogFileOpen))
				MirroredFlatFile_Flush(
								&mirroredLogFileOpen,
								/* suppressError */ false);

			elog((Debug_print_qd_mirroring ? LOG : DEBUG5),
				 "XLogWrite (#2): flush loc %s; write loc %s",
				 XLogLocationToString_Long(&LogwrtResult.Flush),
				 XLogLocationToString2_Long(&LogwrtResult.Write));
T
Tom Lane 已提交
2169
		}
2170

T
Tom Lane 已提交
2171
		LogwrtResult.Flush = LogwrtResult.Write;
2172 2173
	}

T
Tom Lane 已提交
2174 2175 2176
	/*
	 * Update shared-memory status
	 *
B
Bruce Momjian 已提交
2177
	 * We make sure that the shared 'request' values do not fall behind the
B
Bruce Momjian 已提交
2178 2179
	 * 'result' values.  This is not absolutely essential, but it saves some
	 * code in a couple of places.
T
Tom Lane 已提交
2180
	 */
2181 2182 2183 2184
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

2185
		SpinLockAcquire(&xlogctl->info_lck);
2186 2187 2188 2189 2190
		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;
2191
		SpinLockRelease(&xlogctl->info_lck);
2192
	}
2193

T
Tom Lane 已提交
2194 2195 2196
	Write->LogwrtResult = LogwrtResult;
}

2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
/*
 * Record the LSN for an asynchronous transaction commit.
 * (This should not be called for aborts, nor for synchronous commits.)
 */
void
XLogSetAsyncCommitLSN(XLogRecPtr asyncCommitLSN)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

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

T
Tom Lane 已提交
2213 2214 2215
/*
 * Ensure that all XLOG data through the given position is flushed to disk.
 *
2216
 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
T
Tom Lane 已提交
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
 * already held, and we try to avoid acquiring it if possible.
 */
void
XLogFlush(XLogRecPtr record)
{
	XLogRecPtr	WriteRqstPtr;
	XLogwrtRqst WriteRqst;

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

2229 2230 2231 2232 2233 2234
	if (Debug_print_qd_mirroring)
		elog(LOG, "xlog flush request %s; write %s; flush %s",
			 XLogLocationToString(&record),
			 XLogLocationToString2(&LogwrtResult.Write),
			 XLogLocationToString3(&LogwrtResult.Flush));

T
Tom Lane 已提交
2235 2236 2237 2238
	/* Quick exit if already known flushed */
	if (XLByteLE(record, LogwrtResult.Flush))
		return;

2239
#ifdef WAL_DEBUG
2240
	if (XLOG_DEBUG)
2241
		elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
2242 2243 2244
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
2245
#endif
2246

T
Tom Lane 已提交
2247 2248 2249 2250
	START_CRIT_SECTION();

	/*
	 * Since fsync is usually a horribly expensive operation, we try to
B
Bruce Momjian 已提交
2251 2252 2253 2254
	 * 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 已提交
2255 2256 2257 2258 2259
	 */

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

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

2265
		SpinLockAcquire(&xlogctl->info_lck);
2266 2267 2268
		if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
			WriteRqstPtr = xlogctl->LogwrtRqst.Write;
		LogwrtResult = xlogctl->LogwrtResult;
2269
		SpinLockRelease(&xlogctl->info_lck);
2270
	}
2271 2272 2273

	/* done already? */
	if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
2274
	{
2275 2276 2277 2278
		/* now wait for the write lock */
		LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
		LogwrtResult = XLogCtl->Write.LogwrtResult;
		if (!XLByteLE(record, LogwrtResult.Flush))
T
Tom Lane 已提交
2279
		{
2280 2281 2282 2283 2284 2285
			/* 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 已提交
2286
				if (freespace < SizeOfXLogRecord)		/* buffer is full */
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
					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;
			}
2302
			XLogWrite(WriteRqst, false, false);
T
Tom Lane 已提交
2303
		}
2304
		LWLockRelease(WALWriteLock);
T
Tom Lane 已提交
2305 2306 2307
	}

	END_CRIT_SECTION();
2308 2309 2310

	/*
	 * If we still haven't flushed to the request point then we have a
B
Bruce Momjian 已提交
2311 2312
	 * 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.
2313
	 *
2314 2315 2316 2317 2318 2319 2320 2321 2322
	 * Formerly we treated this as a PANIC condition, but that hurts the
	 * system's robustness rather than helping it: we do not want to take down
	 * the whole system due to corruption on one data page.  In particular, if
	 * the bad page is encountered again during recovery then we would be
	 * unable to restart the database at all!  (This scenario has actually
	 * happened in the field several times with 7.1 releases. Note that we
	 * cannot get here while InRedo is true, but if the bad page is brought in
	 * and marked dirty during recovery then CreateCheckPoint will try to
	 * flush it at the end of recovery.)
2323
	 *
2324 2325 2326 2327
	 * The current approach is to ERROR under normal conditions, but only
	 * WARNING during recovery, so that the system can be brought up even if
	 * there's a corrupt LSN.  Note that for calls from xact.c, the ERROR will
	 * be promoted to PANIC since xact.c calls this routine inside a critical
B
Bruce Momjian 已提交
2328 2329
	 * 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.
2330 2331
	 */
	if (XLByteLT(LogwrtResult.Flush, record))
B
Bruce Momjian 已提交
2332
		elog(InRecovery ? WARNING : ERROR,
B
Bruce Momjian 已提交
2333
		"xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
2334 2335
			 record.xlogid, record.xrecoff,
			 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
2336 2337
}

2338
/*
2339

2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
 * TODO: This is just for the matter of WAL receiver build.  We cannot
 * expose MirroredFlatFileOpen in xlog.h.
 */
int
XLogFileInitExt(uint32 log, uint32 seg, bool *use_existent, bool use_lock)
{
	MirroredFlatFileOpen mirroredOpen;

	XLogFileInit(&mirroredOpen, log, seg, use_existent, use_lock);
	return mirroredOpen.primaryFile;
}

2352 2353 2354 2355 2356 2357
/*
 * 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 已提交
2358
 * are not being used, we will flush complete blocks only.	We can guarantee
2359
 * that async commits reach disk after at most three cycles; normally only
B
Bruce Momjian 已提交
2360
 * one or two.	(We allow XLogWrite to write "flexibly", meaning it can stop
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
 * at the end of the buffer ring; this makes a difference only with very high
 * load or long wal_writer_delay, but imposes one extra cycle for the worst
 * case for async commits.)
 *
 * This routine is invoked periodically by the background walwriter process.
 */
void
XLogBackgroundFlush(void)
{
	XLogRecPtr	WriteRqstPtr;
	bool		flexible = true;

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

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

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

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

2393
		SpinLockAcquire(&xlogctl->info_lck);
2394
		WriteRqstPtr = xlogctl->asyncCommitLSN;
2395
		SpinLockRelease(&xlogctl->info_lck);
2396 2397 2398
		flexible = false;		/* ensure it all gets written */
	}

2399 2400 2401 2402 2403
	/*
	 * 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.
	 */
2404
	if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
2405
	{
2406 2407
		if (MirroredFlatFile_IsActive(&mirroredLogFileOpen))
		{
2408 2409 2410 2411 2412
			if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
			{
				XLogFileClose();
			}
		}
2413
		return;
2414
	}
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441

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

2442 2443
/*
 * Flush any previous asynchronously-committed transactions' commit records.
2444 2445 2446 2447
 *
 * NOTE: it is unwise to assume that this provides any strong guarantees.
 * In particular, because of the inexact LSN bookkeeping used by clog.c,
 * we cannot assume that hint bits will be settable for these transactions.
2448 2449 2450 2451 2452
 */
void
XLogAsyncCommitFlush(void)
{
	XLogRecPtr	WriteRqstPtr;
B
Bruce Momjian 已提交
2453

2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;

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

	XLogFlush(WriteRqstPtr);
}

2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
/*
 * Test whether XLOG data has been flushed up to (at least) the given position.
 *
 * Returns true if a flush is still needed.  (It may be that someone else
 * is already in process of flushing that far, however.)
 */
bool
XLogNeedsFlush(XLogRecPtr record)
{
	/* Quick exit if already known flushed */
	if (XLByteLE(record, LogwrtResult.Flush))
		return false;

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

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

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

	return true;
}

T
Tom Lane 已提交
2494 2495 2496
/*
 * Create a new XLOG file segment, or open a pre-existing one.
 *
2497 2498 2499
 * log, seg: identify segment to be created/opened.
 *
 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
B
Bruce Momjian 已提交
2500
 * pre-existing file will be deleted).	On return, TRUE if a pre-existing
2501 2502
 * file was used.
 *
2503
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2504
 * place.  This should be TRUE except during bootstrap log creation.  The
2505
 * caller must *not* hold the lock at call.
2506
 *
T
Tom Lane 已提交
2507
 * Returns FD of opened file.
2508 2509 2510 2511 2512
 *
 * 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 已提交
2513
 */
2514 2515 2516 2517 2518
static void
XLogFileInit(
	MirroredFlatFileOpen *mirroredOpen,
	uint32 log, uint32 seg,
	bool *use_existent, bool use_lock)
2519
{
2520 2521
	char		simpleFileName[MAXPGPATH];
	char		tmpsimple[MAXPGPATH];
2522
	char		tmppath[MAXPGPATH];
2523
	MirroredFlatFileOpen tmpMirroredOpen;
2524
	char	   *zbuffer;
2525 2526 2527
	uint32		installed_log;
	uint32		installed_seg;
	int			max_advance;
2528
	int			nbytes;
2529
	char			*xlogDir = NULL;
2530

2531
	XLogFileName(simpleFileName, ThisTimeLineID, log, seg);
V
Vadim B. Mikheev 已提交
2532 2533

	/*
B
Bruce Momjian 已提交
2534
	 * Try to use existent file (checkpoint maker may have created it already)
V
Vadim B. Mikheev 已提交
2535
	 */
2536
	if (*use_existent)
V
Vadim B. Mikheev 已提交
2537
	{
2538 2539 2540 2541 2542 2543 2544 2545 2546
		if (MirroredFlatFile_Open(
							mirroredOpen,
							XLOGDIR,
							simpleFileName,
							O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
						    S_IRUSR | S_IWUSR,
						    /* suppressError */ true,
							/* atomic operation */ false,
							/*isMirrorRecovery */ false))
V
Vadim B. Mikheev 已提交
2547
		{
2548 2549 2550 2551
			char		path[MAXPGPATH];

			XLogFilePath(path, ThisTimeLineID, log, seg);

V
Vadim B. Mikheev 已提交
2552
			if (errno != ENOENT)
2553
				ereport(ERROR,
2554
						(errcode_for_file_access(),
2555
						 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2556
								path, log, seg)));
V
Vadim B. Mikheev 已提交
2557 2558
		}
		else
2559
			return;
V
Vadim B. Mikheev 已提交
2560 2561
	}

2562
	/*
B
Bruce Momjian 已提交
2563 2564 2565 2566
	 * 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.
2567
	 */
2568 2569
	elog(DEBUG2, "creating and filling new WAL file");

2570 2571 2572 2573
	xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
		
	if (snprintf(tmpsimple, MAXPGPATH, "xlogtemp.%d", (int) getpid()) > MAXPGPATH)
	{
2574 2575 2576
		ereport(ERROR,
				(errmsg("could not generate filename xlogtemp.%d", (int)getpid())));
	}
2577

2578 2579
	if (snprintf(tmppath, MAXPGPATH, "%s/%s", xlogDir, tmpsimple) > MAXPGPATH)
	{
2580 2581 2582
		ereport(ERROR,
				(errmsg("could not generate filename %s/%s", xlogDir, tmpsimple)));
	}
2583 2584 2585 2586 2587 2588

	MirroredFlatFile_Drop(
						  XLOGDIR,
						  tmpsimple,
						  /* suppressError */ true,
						  /*isMirrorRecovery */ false);
2589

2590
	/* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2591 2592 2593 2594 2595 2596 2597 2598 2599
	MirroredFlatFile_Open(
						&tmpMirroredOpen,
						XLOGDIR,
						tmpsimple,
						O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
					    S_IRUSR | S_IWUSR,
					    /* suppressError */ false,
						/* atomic operation */ false,
						/*isMirrorRecovery */ false);
2600

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

B
Bruce Momjian 已提交
2626
			/*
B
Bruce Momjian 已提交
2627
			 * If we fail to make the file, delete it to release disk space
B
Bruce Momjian 已提交
2628
			 */
2629 2630 2631 2632 2633 2634
			MirroredFlatFile_Drop(
							XLOGDIR,
							tmpsimple,
							/* suppressError */ false,
							/*isMirrorRecovery */ false);

2635 2636
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;
T
Tom Lane 已提交
2637

2638
			ereport(ERROR,
2639
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2640
					 errmsg("could not write to file \"%s\": %m", tmppath)));
T
Tom Lane 已提交
2641
		}
2642
	}
2643
	pfree(zbuffer);
2644

2645 2646 2647
	MirroredFlatFile_Flush(
				&tmpMirroredOpen,
				/* suppressError */ false);
2648

2649
	MirroredFlatFile_Close(&tmpMirroredOpen);
T
Tom Lane 已提交
2650

2651
	/*
2652 2653
	 * Now move the segment into place with its final name.
	 *
2654
	 * If caller didn't want to use a pre-existing file, get rid of any
B
Bruce Momjian 已提交
2655 2656 2657
	 * 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.
2658
	 */
2659 2660 2661 2662 2663
	installed_log = log;
	installed_seg = seg;
	max_advance = XLOGfileslop;
	if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
								*use_existent, &max_advance,
2664
								use_lock, tmpsimple))
2665
	{
2666 2667 2668 2669 2670
		/*
		 * 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.
		 */
2671 2672 2673 2674 2675
		MirroredFlatFile_Drop(
						XLOGDIR,
						tmpsimple,
						/* suppressError */ false,
						/*isMirrorRecovery */ false);
2676 2677 2678 2679 2680 2681
	}

	/* 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) */
2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
	MirroredFlatFile_Open(
						mirroredOpen,
						XLOGDIR,
						simpleFileName,
						O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
					    S_IRUSR | S_IWUSR,
					    /* suppressError */ false,
						/* atomic operation */ false,
						/*isMirrorRecovery */ false);

	pfree(xlogDir);
2693

2694
	elog(DEBUG2, "done creating and filling new WAL file");
2695 2696
}

2697 2698 2699 2700 2701 2702 2703 2704 2705
/*
 * 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 已提交
2706
 * considerations.	But we should be just as tense as XLogFileInit to avoid
2707 2708 2709 2710 2711 2712 2713 2714
 * emplacing a bogus file.
 */
static void
XLogFileCopy(uint32 log, uint32 seg,
			 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
{
	char		path[MAXPGPATH];
	char		tmppath[MAXPGPATH];
2715
	char		buffer[XLOG_BLCKSZ];
2716 2717 2718
	int			srcfd;
	int			fd;
	int			nbytes;
2719
	char		*xlogDir = NULL;
2720 2721 2722 2723 2724 2725 2726

	/*
	 * Open the source file
	 */
	XLogFilePath(path, srcTLI, srclog, srcseg);
	srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
	if (srcfd < 0)
2727
		ereport(ERROR,
2728 2729 2730 2731 2732 2733
				(errcode_for_file_access(),
				 errmsg("could not open file \"%s\": %m", path)));

	/*
	 * Copy into a temp file name.
	 */
2734 2735 2736 2737 2738 2739 2740
	xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
	if (snprintf(tmppath, MAXPGPATH, "%s/xlogtemp.%d",
				 xlogDir, (int) getpid()) > MAXPGPATH)
		ereport(ERROR,
				(errmsg("could not generate filename %s/xlogtemp.%d",
						xlogDir, (int) getpid())));
	pfree(xlogDir);	
2741 2742
	unlink(tmppath);

2743 2744 2745
	elog((Debug_print_qd_mirroring ? LOG : DEBUG5), "Master Mirroring: copying xlog file '%s' to '%s'",
		 path, tmppath);

2746 2747 2748 2749
	/* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
2750
		ereport(ERROR,
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
				(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)
2763
				ereport(ERROR,
2764 2765 2766
						(errcode_for_file_access(),
						 errmsg("could not read file \"%s\": %m", path)));
			else
2767
				ereport(ERROR,
B
Bruce Momjian 已提交
2768
						(errmsg("not enough data in file \"%s\"", path)));
2769 2770 2771 2772 2773 2774 2775
		}
		errno = 0;
		if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
		{
			int			save_errno = errno;

			/*
B
Bruce Momjian 已提交
2776
			 * If we fail to make the file, delete it to release disk space
2777 2778 2779 2780 2781
			 */
			unlink(tmppath);
			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;

2782
			ereport(ERROR,
2783
					(errcode_for_file_access(),
B
Bruce Momjian 已提交
2784
					 errmsg("could not write to file \"%s\": %m", tmppath)));
2785 2786 2787 2788
		}
	}

	if (pg_fsync(fd) != 0)
2789
		ereport(ERROR,
2790 2791 2792 2793
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

	if (close(fd))
2794
		ereport(ERROR,
2795 2796 2797 2798 2799 2800 2801 2802
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m", tmppath)));

	close(srcfd);

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

2807 2808 2809 2810 2811 2812
/*
 * 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.
 *
2813 2814 2815
 * *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.
2816 2817 2818 2819 2820 2821 2822
 *
 * 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.
 *
2823 2824 2825 2826
 * *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.)
2827
 *
2828
 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2829
 * place.  This should be TRUE except during bootstrap log creation.  The
2830
 * caller must *not* hold the lock at call.
2831
 *
2832 2833 2834
 * 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.
2835 2836
 */
static bool
2837 2838
InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
					   bool find_free, int *max_advance,
2839
					   bool use_lock, char* tmpsimpleFileName)
2840 2841
{
	char		path[MAXPGPATH];
2842
	char		simpleFileName[MAXPGPATH];
2843
	struct stat stat_buf;
2844 2845 2846 2847 2848
	int retval = 0;

	errno = 0;

	XLogFileName(simpleFileName, ThisTimeLineID, *log, *seg);
2849

2850
	XLogFilePath(path, ThisTimeLineID, *log, *seg);
2851 2852 2853 2854 2855

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

2858 2859 2860
	if (!find_free)
	{
		/* Force installation: get rid of any pre-existing segment file */
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
		if (tmpsimpleFileName) {

			MirroredFlatFile_Drop(
								  XLOGDIR,
								  simpleFileName,
								  /* suppressError */ true,
								  /*isMirrorRecovery */ false);
		} else {
			unlink(path);
		}
2871
	}
2872 2873
	else
	{
2874
		/* Find a free slot to put it in */
2875
		while (stat(path, &stat_buf) == 0)
2876
		{
2877
			if (*max_advance <= 0)
2878 2879 2880
			{
				/* Failed to find a free slot within specified range */
				if (use_lock)
2881
					LWLockRelease(ControlFileLock);
2882 2883
				return false;
			}
2884 2885
			NextLogSeg(*log, *seg);
			(*max_advance)--;
2886 2887

			XLogFileName(simpleFileName, ThisTimeLineID, *log, *seg);
2888
			XLogFilePath(path, ThisTimeLineID, *log, *seg);
2889 2890 2891 2892 2893 2894 2895
		}
	}

	/*
	 * 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.
2896
	 */
2897
#if HAVE_WORKING_LINK
2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910

	if (tmpsimpleFileName) {
		retval = MirroredFlatFile_Rename(
										 XLOGDIR,
										 /* old name */ tmpsimpleFileName,
										 /* new name */ simpleFileName,
										 /* can exist? */ false,
										 /* isMirrorRecovery */ false);
	} else {
		retval = link(tmppath, path);
	}

	if (retval < 0)
2911 2912 2913 2914
	{
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
2915
				(errcode_for_file_access(),
2916
				 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2917
						tmppath, path, *log, *seg)));
2918 2919
		return false;
	}
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931

	if (tmpsimpleFileName) {

		MirroredFlatFile_Drop(
						  XLOGDIR,
						  tmpsimpleFileName,
						  /* suppressError */ true,
						  /*isMirrorRecovery */ false);
	} else {
		unlink(tmppath);
	}

2932
#else
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
	if (tmpsimpleFileName) {
		retval = MirroredFlatFile_Rename(
						  XLOGDIR,
						  /* old name */ tmpsimpleFileName,
						  /* new name */ simpleFileName,
						  /* can exist */ false,
							/* isMirrorRecovery */ false);
	} else {
		retval = rename(tmppath, path);
	}

	if (retval < 0)
2945
	{
2946 2947 2948
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
2949
				(errcode_for_file_access(),
2950
				 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2951
						tmppath, path, *log, *seg)));
2952
		return false;
2953
	}
2954
#endif
V
Vadim B. Mikheev 已提交
2955

2956
	if (use_lock)
2957
		LWLockRelease(ControlFileLock);
2958

2959
	return true;
2960 2961
}

T
Tom Lane 已提交
2962
/*
2963
 * Open a pre-existing logfile segment for writing.
T
Tom Lane 已提交
2964
 */
2965 2966 2967 2968 2969
static void
XLogFileOpen(
	MirroredFlatFileOpen *mirroredOpen,
	uint32 log,
	uint32 seg)
2970
{
2971
	char		simpleFileName[MAXPGPATH];
2972

2973
	XLogFileName(simpleFileName, ThisTimeLineID, log, seg);
2974

2975 2976 2977 2978 2979 2980 2981 2982 2983
	if (MirroredFlatFile_Open(
					mirroredOpen,
					XLOGDIR,
					simpleFileName,
					O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
					S_IRUSR | S_IWUSR,
					/* suppressError */ false,
					/* atomic operation */ false,
					/*isMirrorRecovery */ false))
2984
	{
2985
		char		path[MAXPGPATH];
2986

2987
		XLogFileName(path, ThisTimeLineID, log, seg);
2988

2989 2990
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2991 2992
		   errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
				  path, log, seg)));
2993
	}
2994 2995
}

2996 2997 2998
/*
 * Close the current logfile segment for writing.
 */
2999
static void
3000 3001
XLogFileClose(void)
{
3002
	Assert(MirroredFlatFile_IsActive(&mirroredLogFileOpen));
3003

3004
	/*
B
Bruce Momjian 已提交
3005 3006 3007 3008 3009 3010
	 * posix_fadvise is problematic on many platforms: on older x86 Linux it
	 * just dumps core, and there are reports of problems on PPC platforms as
	 * well.  The following is therefore disabled for the time being. We could
	 * consider some kind of configure test to see if it's safe to use, but
	 * since we lack hard evidence that there's any useful performance gain to
	 * be had, spending time on that seems unprofitable for now.
3011 3012 3013
	 */
#ifdef NOT_USED

3014
	/*
3015
	 * WAL segment files will not be re-read in normal operation, so we advise
B
Bruce Momjian 已提交
3016
	 * OS to release any cached pages.	But do not do so if WAL archiving is
3017 3018 3019
	 * active, because archiver process could use the cache to read the WAL
	 * segment.
	 *
B
Bruce Momjian 已提交
3020 3021
	 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
	 * O_SYNC, and some platforms only have posix_fadvise().
3022
	 */
3023
#if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3024 3025 3026
	if (!XLogArchivingActive())
		posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
#endif
B
Bruce Momjian 已提交
3027
#endif   /* NOT_USED */
3028

3029
	MirroredFlatFile_Close(&mirroredLogFileOpen);
3030 3031
}

V
Vadim B. Mikheev 已提交
3032
/*
3033 3034 3035 3036 3037 3038 3039 3040
 * 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 已提交
3041
 */
3042
static void
T
Tom Lane 已提交
3043 3044 3045 3046
PreallocXlogFiles(XLogRecPtr endptr)
{
	uint32		_logId;
	uint32		_logSeg;
3047 3048 3049

	MirroredFlatFileOpen	mirroredOpen;

3050
	bool		use_existent;
T
Tom Lane 已提交
3051 3052

	XLByteToPrevSeg(endptr, _logId, _logSeg);
B
Bruce Momjian 已提交
3053
	if ((endptr.xrecoff - 1) % XLogSegSize >=
B
Bruce Momjian 已提交
3054
		(uint32) (0.75 * XLogSegSize))
T
Tom Lane 已提交
3055 3056
	{
		NextLogSeg(_logId, _logSeg);
3057
		use_existent = true;
3058 3059 3060 3061
		XLogFileInit(
			&mirroredOpen,
			_logId, _logSeg, &use_existent, true);
		MirroredFlatFile_Close(&mirroredOpen);
3062
		if (!use_existent)
3063
			CheckpointStats.ckpt_segs_added++;
T
Tom Lane 已提交
3064 3065 3066
	}
}

3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
/*
 * Get the log/seg of the latest removed or recycled WAL segment.
 * Returns 0/0 if no WAL segments have been removed since startup.
 */
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 已提交
3108
/*
3109
 * Recycle or remove all log files older or equal to passed log/seg#
3110 3111 3112
 *
 * 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 已提交
3113 3114
 */
static void
3115
RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
V
Vadim B. Mikheev 已提交
3116
{
3117 3118
	uint32		endlogId;
	uint32		endlogSeg;
3119
	int			max_advance;
B
Bruce Momjian 已提交
3120 3121
	DIR		   *xldir;
	struct dirent *xlde;
3122
	char		lastoff[MAXFNAMELEN];
B
Bruce Momjian 已提交
3123
	char		path[MAXPGPATH];
3124
	char		*xlogDir = NULL;
V
Vadim B. Mikheev 已提交
3125

3126 3127
#ifdef WIN32
	char		newpath[MAXPGPATH];
3128
	char		newfilename[MAXPGPATH];
3129
#endif
3130
	struct stat statbuf;
3131

3132 3133 3134 3135
	/*
	 * Initialize info about where to try to recycle to.  We allow recycling
	 * segments up to XLOGfileslop segments beyond the current XLOG location.
	 */
3136
	XLByteToPrevSeg(endptr, endlogId, endlogSeg);
3137
	max_advance = XLOGfileslop;
V
Vadim B. Mikheev 已提交
3138

3139 3140
	xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
	xldir = AllocateDir(xlogDir);
V
Vadim B. Mikheev 已提交
3141
	if (xldir == NULL)
3142
		ereport(ERROR,
3143
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
3144
				 errmsg("could not open transaction log directory \"%s\": %m",
3145
						xlogDir)));
V
Vadim B. Mikheev 已提交
3146

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

3149
	while ((xlde = ReadDir(xldir, xlogDir)) != NULL)
V
Vadim B. Mikheev 已提交
3150
	{
3151
		/*
3152
		 * We ignore the timeline part of the XLOG segment identifiers in
B
Bruce Momjian 已提交
3153 3154 3155 3156 3157
		 * 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.
3158
		 *
B
Bruce Momjian 已提交
3159 3160
		 * We use the alphanumeric sorting property of the filenames to decide
		 * which ones are earlier than the lastoff segment.
3161
		 */
3162 3163 3164
		if (strlen(xlde->d_name) == 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
V
Vadim B. Mikheev 已提交
3165
		{
3166
			if (XLogArchiveCheckDone(xlde->d_name))
3167
			{
3168 3169 3170 3171 3172 3173 3174
				if (snprintf(path, MAXPGPATH, "%s/%s", xlogDir, xlde->d_name) > MAXPGPATH)
				{
					ereport(ERROR, (errmsg("cannot generate filename %s/%s", xlogDir, xlde->d_name)));
				}

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

3176
				/*
B
Bruce Momjian 已提交
3177
				 * Before deleting the file, see if it can be recycled as a
3178 3179 3180
				 * future log segment. Only recycle normal files, pg_standby
				 * for example can create symbolic links pointing to a
				 * separate archive directory.
3181
				 */
3182 3183
				if (lstat(path, &statbuf) == 0 && S_ISREG(statbuf.st_mode) &&
					InstallXLogFileSegment(&endlogId, &endlogSeg, path,
3184
										   true, &max_advance, true, xlde->d_name))
3185
				{
3186
					ereport(DEBUG2,
B
Bruce Momjian 已提交
3187 3188
							(errmsg("recycled transaction log file \"%s\"",
									xlde->d_name)));
3189
					CheckpointStats.ckpt_segs_recycled++;
3190 3191 3192 3193 3194 3195
					/* Needn't recheck that slot on future iterations */
					if (max_advance > 0)
					{
						NextLogSeg(endlogId, endlogSeg);
						max_advance--;
					}
3196 3197 3198 3199
				}
				else
				{
					/* No need for any more future segments... */
3200
					//int rc;
3201

3202
					ereport(DEBUG2,
B
Bruce Momjian 已提交
3203 3204
							(errmsg("removing transaction log file \"%s\"",
									xlde->d_name)));
3205

3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
#ifdef WIN32
					/*
					 * 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
					 * 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.
					 *
					 * If another process holds the file open without
					 * FILE_SHARE_DELETE flag, rename will fail. We'll try
					 * again at the next checkpoint.
					 */
					snprintf(newpath, MAXPGPATH, "%s.deleted", path);
					if (rename(path, newpath) != 0)
3222 3223
					{
						ereport(LOG,
3224
								(errcode_for_file_access(),
3225
								 errmsg("could not rename old transaction log file \"%s\": %m",
3226
										path)));
3227 3228
						continue;
					}
3229 3230 3231 3232 3233 3234
					snprintf(newfilename, MAXPGPATH, "%s.deleted", xlde->d_name);
					MirroredFlatFile_Drop(
										  XLOGDIR,
										  newfilename,
										  /* suppressError */ true,
										  /*isMirrorRecovery */ false);
3235
#else
3236 3237 3238 3239 3240
					MirroredFlatFile_Drop(
										  XLOGDIR,
										  xlde->d_name,
										  /* suppressError */ true,
										  /*isMirrorRecovery */ false);
3241
#endif
3242

3243 3244 3245
					/* GPDB_83_MERGE_FIXME: MirroredFlatFile_Drop doesn't return a return
					 * code */
#if 0
3246
					if (rc != 0)
3247 3248
					{
						ereport(LOG,
3249 3250 3251
								(errcode_for_file_access(),
								 errmsg("could not remove old transaction log file \"%s\": %m",
										path)));
3252 3253
						continue;
					}
3254
#endif
3255
					CheckpointStats.ckpt_segs_removed++;
3256
				}
3257 3258

				XLogArchiveCleanup(xlde->d_name);
3259
			}
V
Vadim B. Mikheev 已提交
3260 3261
		}
	}
B
Bruce Momjian 已提交
3262

3263
	FreeDir(xldir);
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301
	pfree(xlogDir);
}

/*
 * Print log files in the system log.
 *
 */
void
XLogPrintLogNames(void)
{
	DIR		   *xldir;
	struct dirent *xlde;
	int count = 0;
	char *xlogDir = NULL;

	xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
	xldir = AllocateDir(xlogDir);
	if (xldir == NULL)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not open transaction log directory \"%s\": %m",
						xlogDir)));

	while ((xlde = ReadDir(xldir, xlogDir)) != NULL)
	{
		if (strlen(xlde->d_name) == 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24)
		{
			elog(LOG,"found log file \"%s\"",
				 xlde->d_name);
			count++;
		}
	}

	FreeDir(xldir);
	pfree(xlogDir);

	elog(LOG,"%d files found", count);
V
Vadim B. Mikheev 已提交
3302 3303
}

3304
/*
3305 3306 3307
 * Remove previous backup history files.  This also retries creation of
 * .ready files for any backup history files for which XLogArchiveNotify
 * failed earlier.
3308 3309
 */
static void
3310
CleanupBackupHistory(void)
3311 3312 3313 3314
{
	DIR		   *xldir;
	struct dirent *xlde;
	char		path[MAXPGPATH];
3315
	char	*xlogDir = NULL;
3316

3317 3318
	xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
	xldir = AllocateDir(xlogDir);
3319 3320 3321
	if (xldir == NULL)
		ereport(ERROR,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
3322
				 errmsg("could not open transaction log directory \"%s\": %m",
3323
						xlogDir)));
3324

3325
	while ((xlde = ReadDir(xldir, xlogDir)) != NULL)
3326 3327 3328 3329 3330 3331
	{
		if (strlen(xlde->d_name) > 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
				   ".backup") == 0)
		{
3332
			if (XLogArchiveCheckDone(xlde->d_name))
3333 3334
			{
				ereport(DEBUG2,
B
Bruce Momjian 已提交
3335 3336
				(errmsg("removing transaction log backup history file \"%s\"",
						xlde->d_name)));
3337 3338 3339 3340
				if (snprintf(path, MAXPGPATH, "%s/%s", xlogDir, xlde->d_name) > MAXPGPATH)
				{
					elog(LOG, "CleanupBackupHistory: Cannot generate filename %s/%s", xlogDir, xlde->d_name);
				}
3341 3342 3343 3344 3345 3346
				unlink(path);
				XLogArchiveCleanup(xlde->d_name);
			}
		}
	}

3347
	pfree(xlogDir);
3348 3349 3350
	FreeDir(xldir);
}

T
Tom Lane 已提交
3351 3352 3353 3354
/*
 * Restore the backup blocks present in an XLOG record, if any.
 *
 * We assume all of the record has been read into memory at *record.
3355 3356 3357 3358 3359 3360 3361 3362 3363
 *
 * Note: when a backup block is available in XLOG, we restore it
 * unconditionally, even if the page in the database appears newer.
 * This is to protect ourselves against database pages that were partially
 * or incorrectly written during a crash.  We assume that the XLOG data
 * must be good because it has passed a CRC check, while the database
 * page might not be.  This will force us to replay all subsequent
 * modifications of the page that appear in XLOG, rather than possibly
 * ignoring them as already applied, but that's not a huge drawback.
T
Tom Lane 已提交
3364
 */
3365 3366 3367
static void
RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
{
3368 3369
	MIRROREDLOCK_BUFMGR_DECLARE;

3370 3371 3372 3373 3374 3375 3376
	Relation	reln;
	Buffer		buffer;
	Page		page;
	BkpBlock	bkpb;
	char	   *blk;
	int			i;

B
Bruce Momjian 已提交
3377
	blk = (char *) XLogRecGetData(record) + record->xl_len;
T
Tom Lane 已提交
3378
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3379
	{
T
Tom Lane 已提交
3380
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3381 3382
			continue;

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

3386
		reln = XLogOpenRelation(bkpb.node);
3387 3388 3389 3390

		// -------- MirroredLock ----------
		MIRROREDLOCK_BUFMGR_LOCK;

3391 3392 3393
		buffer = XLogReadBuffer(reln, bkpb.block, true);
		Assert(BufferIsValid(buffer));
		page = (Page) BufferGetPage(buffer);
3394

3395
		if (bkpb.hole_length == 0)
3396
		{
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
			memcpy((char *) page, blk, BLCKSZ);
		}
		else
		{
			/* must zero-fill the hole */
			MemSet((char *) page, 0, BLCKSZ);
			memcpy((char *) page, blk, bkpb.hole_offset);
			memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
				   blk + bkpb.hole_offset,
				   BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
3407 3408
		}

3409 3410
		PageSetLSN(page, lsn);
		PageSetTLI(page, ThisTimeLineID);
3411 3412
		MarkBufferDirty(buffer);
		UnlockReleaseBuffer(buffer);
3413

3414 3415 3416
		MIRROREDLOCK_BUFMGR_UNLOCK;
		// -------- MirroredLock ----------

3417
		blk += BLCKSZ - bkpb.hole_length;
3418 3419 3420
	}
}

T
Tom Lane 已提交
3421 3422 3423 3424 3425 3426 3427
/*
 * 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.
 */
3428 3429 3430
static bool
RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
{
3431
	pg_crc32	crc;
3432 3433
	int			i;
	uint32		len = record->xl_len;
3434
	BkpBlock	bkpb;
3435 3436
	char	   *blk;

3437 3438 3439 3440
	/*
	 * Calculate the crc using the new fast crc32c algorithm
	 */

3441
	/* First the rmgr data */
3442 3443
	INIT_CRC32C(crc);
	COMP_CRC32C(crc, XLogRecGetData(record), len);
3444

3445
	/* Add in the backup blocks, if any */
B
Bruce Momjian 已提交
3446
	blk = (char *) XLogRecGetData(record) + len;
T
Tom Lane 已提交
3447
	for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3448
	{
B
Bruce Momjian 已提交
3449
		uint32		blen;
3450

T
Tom Lane 已提交
3451
		if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3452 3453
			continue;

3454 3455
		memcpy(&bkpb, blk, sizeof(BkpBlock));
		if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
3456
		{
3457
			ereport(emode,
3458 3459 3460
					(errmsg("incorrect hole size in record at %X/%X",
							recptr.xlogid, recptr.xrecoff)));
			return false;
3461
		}
3462
		blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
3463
		COMP_CRC32C(crc, blk, blen);
3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476
		blk += blen;
	}

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

	/* Finally include the record header */
3477
	COMP_CRC32C(crc, (char *) record + sizeof(pg_crc32),
3478
			   SizeOfXLogRecord - sizeof(pg_crc32));
3479
	FIN_CRC32C(crc);
3480

3481
	if (!EQ_CRC32C(record->xl_crc, crc))
3482 3483 3484
	{
		ereport(emode,
		(errmsg("incorrect resource manager data checksum in record at %X/%X",
B
Bruce Momjian 已提交
3485
				recptr.xlogid, recptr.xrecoff)));
3486
		return false;
3487 3488
	}

3489
	return true;
3490 3491
}

T
Tom Lane 已提交
3492
/*
3493
 * Verify whether pg_xlog exists
T
Tom Lane 已提交
3494
 *
3495 3496 3497
 * 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
 * copy but omitted pg_xlog from the copy.
T
Tom Lane 已提交
3498
 */
3499 3500
static void
ValidateXLOGDirectoryStructure(void)
3501
{
3502
	struct stat stat_buf;
T
Tom Lane 已提交
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
	/* Check for pg_xlog; if it doesn't exist, error out */
	if (stat(makeRelativeToTxnFilespace(XLOGDIR), &stat_buf) != 0 ||
			!S_ISDIR(stat_buf.st_mode))
			ereport(FATAL,
					(errmsg("required WAL directory \"%s\" does not exist",
							XLOGDIR)));
}

/*
 * Open a logfile segment for reading (during recovery).
 * It's assumed to be already available in pg_xlog.
 */
static int
XLogFileRead(uint32 log, uint32 seg, int emode, TimeLineID tli,
			 int source, bool notfoundOk)
{
	char		xlogfname[MAXFNAMELEN];
	char		activitymsg[MAXFNAMELEN + 16];
	char		path[MAXPGPATH];
	int			fd;

	XLogFileName(xlogfname, tli, log, seg);

	switch (source)
T
Tom Lane 已提交
3528
	{
3529 3530 3531 3532 3533 3534 3535 3536
		case XLOG_FROM_PG_XLOG:
		case XLOG_FROM_STREAM:
			XLogFilePath(path, tli, log, seg);
			restoredFromArchive = false;
			break;

		default:
			elog(ERROR, "invalid XLogFileRead source %d", source);
T
Tom Lane 已提交
3537
	}
3538

3539 3540 3541 3542 3543 3544 3545 3546 3547
	elogif(debug_xlog_record_read, LOG,
		   "xlog file read -- File read request with log %u, seg %u,"
		   "tli %u, source = %s, notfoundok = %s",
		   log, seg, (uint32) tli,
		   source == XLOG_FROM_PG_XLOG ? "xlog" : "stream",
		   notfoundOk ? "true" : "false");

	fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
	if (fd >= 0)
3548
	{
3549 3550 3551 3552 3553 3554 3555 3556 3557
		/* Success! */
		curFileTLI = tli;

		/*
		 * Report recovery progress in PS display, if we are in
		 * startup process.  There are more cases like Filerep recovery
		 * and Prepare phase where we don't want to report it.
		 */
		if (am_startup)
3558
		{
3559 3560 3561
			snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
					 xlogfname);
			set_ps_display(activitymsg, false);
3562
		}
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620

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

		elogif(debug_xlog_record_read, LOG,
			   "xlog file read -- Read file %s (log %u, seg %u)",
			   path, log, seg);

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

	elogif(debug_xlog_record_read, LOG,
		   "xlog file read -- Couldn't read file %s (log %u, seg %u)",
		   path, log, seg);
	return -1;
}


/*
 * Open a logfile segment for reading (during recovery).
 *
 * This version searches for the segment with any TLI listed in expectedTLIs.
 */
static int
XLogFileReadAnyTLI(uint32 log, uint32 seg, int emode, int sources)
{
	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 */

		if (sources & XLOG_FROM_PG_XLOG)
3621
		{
3622 3623 3624 3625 3626 3627 3628
			elogif(debug_xlog_record_read, LOG,
				   "xlog file read (tli) -- requesting a file read (log %u, seg %u)"
				   "with currenttli %d ", log, seg, curFileTLI);

			fd = XLogFileRead(log, seg, emode, tli, XLOG_FROM_PG_XLOG, true);
			if (fd != -1)
				return fd;
3629
		}
3630
	}
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676

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


/*
 * Read the XLOG page containing RecPtr into readBuf (if not read already).
 * Returns true if the page is read successfully.
 *
 * This is responsible for waiting for the requested WAL record to arrive in
 * standby mode.
 *
 * 'emode' specifies the log level used for reporting "file not found" or
 * "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.
 */
static bool
XLogPageRead(XLogRecPtr *RecPtr, int emode, bool fetching_ckpt,
			 bool randAccess)
{
	static XLogRecPtr receivedUpto = {0, 0};
	bool		switched_segment = false;
	uint32		targetPageOff;
	uint32		targetRecOff;
	uint32		targetId;
	uint32		targetSeg;
	static pg_time_t last_fail_time = 0;

	XLByteToSeg(*RecPtr, targetId, targetSeg);
	targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
	targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;

	/* Fast exit if we have read the record in the current buffer already */
	if (failedSources == 0 && targetId == readId && targetSeg == readSeg &&
		targetPageOff == readOff && targetRecOff < readLen)
3677
	{
3678 3679 3680 3681 3682 3683
		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);
B
Bruce Momjian 已提交
3684

3685
		return true;
3686 3687
	}

3688 3689 3690 3691
	/*
	 * See if we need to switch to a new segment because the requested record
	 * is not in the currently open one.
	 */
T
Tom Lane 已提交
3692
	if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
3693
	{
3694 3695 3696 3697 3698
		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);

3699 3700
		close(readFile);
		readFile = -1;
3701
		readSource = 0;
3702
	}
3703

T
Tom Lane 已提交
3704
	XLByteToSeg(*RecPtr, readId, readSeg);
3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715

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

retry:
	/* See if we need to retrieve more data */
	if (readFile < 0 ||
		(readSource == XLOG_FROM_STREAM && !XLByteLT(*RecPtr, receivedUpto)))
3716
	{
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727
		if (StandbyMode)
		{
			/*
			 * In standby mode, wait for the requested record to become
			 * available, via WAL receiver having streamed the record.
			 */
			for (;;)
			{
				if (WalRcvInProgress())
				{
					bool		havedata;
3728

3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 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 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
					/*
					 * If we find an invalid record in the WAL streamed from
					 * master, something is seriously wrong. There's little
					 * chance that the problem will just go away, but PANIC is
					 * not good for availability. Disconnect, and retry from
					 * pg_xlog again (That may spawn the Wal receiver again!).
					 * XXX
					 */
					if (failedSources & XLOG_FROM_STREAM)
					{
						elogif(debug_xlog_record_read, LOG,
							   "xlog page read -- Xlog from stream is a failed"
							   "source, hence requesting walreceiver shutdown.");

						ShutdownWalRcv();
						continue;
					}

					/*
					 * WAL receiver is active, so see if new data has arrived.
					 *
					 * 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
					 * keeping up with the incoming data, XLogReceiptTime will
					 * be updated on each cycle.  When we are behind,
					 * XLogReceiptTime will not advance, so the grace time
					 * alloted to conflicting queries will decrease.
					 */
					if (XLByteLT(*RecPtr, receivedUpto))
						havedata = true;
					else
					{
						XLogRecPtr	latestChunkStart;

						receivedUpto = GetWalRcvWriteRecPtr(&latestChunkStart);
						if (XLByteLT(*RecPtr, receivedUpto))
						{
							havedata = true;
							if (!XLByteLT(*RecPtr, latestChunkStart))
							{
								XLogReceiptTime = GetCurrentTimestamp();
								SetCurrentChunkStartTime(XLogReceiptTime);
							}
						}
						else
							havedata = false;
					}

					if (havedata)
					{
						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);

						/*
						 * Great, streamed far enough. Open the file if it's
						 * not open already.  Use XLOG_FROM_STREAM so that
						 * source info is set correctly and XLogReceiptTime
						 * isn't changed.
						 */
						if (readFile < 0)
						{
							readFile =
								XLogFileRead(readId, readSeg, PANIC,
											 recoveryTargetTLI,
											 XLOG_FROM_STREAM, false);
							Assert(readFile >= 0);
							switched_segment = true;
						}
						else
						{
							/* just make sure source info is correct... */
							readSource = XLOG_FROM_STREAM;
							XLogReceiptSource = XLOG_FROM_STREAM;
						}
						break;
					}

					/*
					 * Data not here yet, so check for trigger then sleep for
					 * five seconds like in the WAL file polling case below.
					 */
					if (CheckForStandbyTrigger())
					{
						elogif(debug_xlog_record_read, LOG,
							   "xlog page read -- Standby trigger was activated");

						goto retry;
					}

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

					/*
					 * Wait for more WAL to arrive, or timeout to be reached
					 */
					WaitLatch(&XLogCtl->recoveryWakeupLatch,
							  WL_LATCH_SET | WL_TIMEOUT,
							  5000L);
					ResetLatch(&XLogCtl->recoveryWakeupLatch);
				}
				else
				{
					int			sources;
					pg_time_t	now;

					if (readFile >= 0)
					{
						close(readFile);
						readFile = -1;
					}

					/* Reset curFileTLI if random fetch. */
					if (randAccess)
						curFileTLI = 0;

					/* Read an existing file from pg_xlog. */
					sources = XLOG_FROM_PG_XLOG;
					if (!(sources & ~failedSources))
					{
						/*
						 * Check if we have been asked to be promoted. If yes,
						 * no use of requesting a new WAL receiver
						 */
						if (CheckForStandbyTrigger())
							goto triggered;

						/*
						 * We've exhausted all options for retrieving the
						 * file. Retry.
						 */
						failedSources = 0;

						elogif(debug_xlog_record_read, LOG,
							   "xlog page read -- All read sources have failed. So, retry.");

						/*
						 * If it hasn't been long since last attempt, sleep to
						 * avoid busy-waiting.
						 */
						now = (pg_time_t) time(NULL);
						if ((now - last_fail_time) < 5)
						{
							pg_usleep(1000000L * (5 - (now - last_fail_time)));
							now = (pg_time_t) time(NULL);
						}
						last_fail_time = now;

						/*
						 * If primary_conninfo is set, launch walreceiver to
						 * try to stream the missing WAL.
						 *
						 * If fetching_ckpt is TRUE, RecPtr points to the
						 * initial checkpoint location. In that case, we use
						 * RedoStartLSN as the streaming start position
						 * instead of RecPtr, so that when we later jump
						 * backwards to start redo at RedoStartLSN, we will
						 * have the logs streamed already.
						 */
						if (PrimaryConnInfo)
						{
							RequestXLogStreaming(
									  fetching_ckpt ? RedoStartLSN : *RecPtr,
												 PrimaryConnInfo);
							continue;
						}
					}
					/* Don't try to read from a source that just failed */
					sources &= ~failedSources;
					readFile = XLogFileReadAnyTLI(readId, readSeg, DEBUG2,
												  sources);
					switched_segment = true;
					if (readFile >= 0)
						break;

					/*
					 * Nope, not found in pg_xlog.
					 */
					failedSources |= sources;

					/*
					 * Check to see if the trigger file exists. Note that we
					 * do this only after failure, so when you create the
					 * trigger file, we still finish replaying as much as we
					 * can from pg_xlog before failover.
					 */
					if (CheckForStandbyTrigger())
						goto triggered;
				}

				/*
				 * This possibly-long loop needs to handle interrupts of
				 * startup process.
				 */
				HandleStartupProcInterrupts();
			}
		}
		else
		{
			/* In crash recovery. */
			if (readFile < 0)
			{
				int			sources;

				/* Reset curFileTLI if random fetch. */
				if (randAccess)
					curFileTLI = 0;

				sources = XLOG_FROM_PG_XLOG;

				readFile = XLogFileReadAnyTLI(readId, readSeg, emode,
											sources);
				switched_segment = true;
				if (readFile < 0)
					return false;
			}
		}
	}
3952

3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979
	/*
	 * At this point, we have the right segment open and if we're streaming we
	 * know the requested record is in it.
	 */
	Assert(readFile != -1);

	/*
	 * 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.
	 */
	if (readSource == XLOG_FROM_STREAM)
	{
		if (RecPtr->xlogid != receivedUpto.xlogid ||
			(RecPtr->xrecoff / XLOG_BLCKSZ) != (receivedUpto.xrecoff / XLOG_BLCKSZ))
		{
			readLen = XLOG_BLCKSZ;
		}
		else
			readLen = receivedUpto.xrecoff % XLogSegSize - targetPageOff;
	}
	else
		readLen = XLOG_BLCKSZ;

	if (switched_segment && targetPageOff != 0)
	{
3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995
		/*
		 * Whenever switching to a new WAL segment, we read the first page of
		 * the file and validate its header, even if that's not where the
		 * target record is.  This is so that we can check the additional
		 * identification info that is present in the first page's "long"
		 * header.
		 */
		readOff = 0;
		if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
		{
			ereport(emode,
					(errcode_for_file_access(),
					 errmsg("could not read from log file %u, segment %u, offset %u: %m",
							readId, readSeg, readOff)));
			goto next_record_is_invalid;
		}
3996
		if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode, true))
T
Tom Lane 已提交
3997
		{
3998 3999
			ereport(emode,
					(errcode_for_file_access(),
4000
					 errmsg("could not read from log file %u, segment %u, offset %u: %m",
4001
							readId, readSeg, readOff)));
T
Tom Lane 已提交
4002 4003
			goto next_record_is_invalid;
		}
4004
	}
4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116

	/* Read the requested page */
	readOff = targetPageOff;
	if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
	{
		ereport(emode,
				(errcode_for_file_access(),
		 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
				readId, readSeg, readOff)));
		goto next_record_is_invalid;
	}
	if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
	{
		ereport(emode,
				(errcode_for_file_access(),
		 errmsg("could not read from log file %u, segment %u, offset %u: %m",
				readId, readSeg, readOff)));
		goto next_record_is_invalid;
	}
	if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode, false))
	{
		elogif(debug_xlog_record_read, LOG,
			   "xlog page read -- xlog page header invalid");
		goto next_record_is_invalid;
	}

	Assert(targetId == readId);
	Assert(targetSeg == readSeg);
	Assert(targetPageOff == readOff);
	Assert(targetRecOff < readLen);

	return true;

next_record_is_invalid:

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

	failedSources |= readSource;

	if (readFile >= 0)
		close(readFile);
	readFile = -1;
	readLen = 0;
	readSource = 0;

	/* In standby-mode, keep trying */
	if (StandbyMode)
		goto retry;
	else
		return false;

triggered:
	if (readFile >= 0)
		close(readFile);
	readFile = -1;
	readLen = 0;
	readSource = 0;

	return false;
}

/*
 * Attempt to read an XLOG record.
 *
 * If RecPtr is not NULL, try to read a record at that position.  Otherwise
 * try to read a record just after the last one previously read.
 *
 * If no valid record is available, returns NULL, or fails if emode is PANIC.
 * (emode must be either PANIC or LOG.)
 *
 * The record is copied into readRecordBuf, so that on successful return,
 * the returned record pointer always points there.
 */
XLogRecord *
XLogReadRecord(XLogRecPtr *RecPtr, bool fetching_ckpt, int emode)
{
	XLogRecord *record;
	char	   *buffer;
	XLogRecPtr	tmpRecPtr = EndRecPtr;
	bool		randAccess = false;
	uint32		len,
				total_len;
	uint32		targetRecOff;
	uint32		pageHeaderSize;

	if (readBuf == NULL)
	{
		/*
		 * 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.
		 */
		readBuf = (char *) malloc(XLOG_BLCKSZ);
		if(!readBuf)
			ereport(PANIC, (errmsg("Cannot allocate memory for read log record. Out of Memory")));
	}

	if (RecPtr == NULL)
	{
		RecPtr = &tmpRecPtr;

		/*
		 * 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.
		 */
		if (nextRecord == NULL)
		{
			/* align old recptr to next page */
4117 4118 4119
			if (RecPtr->xrecoff % XLOG_BLCKSZ != 0)
				RecPtr->xrecoff += (XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ);
			if (RecPtr->xrecoff >= XLogFileSize)
4120
			{
4121 4122
				(RecPtr->xlogid)++;
				RecPtr->xrecoff = 0;
4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169
			}
		}
		/* We will account for page header size below */
	}
	else
	{
		/*
		 * In this case, the passed-in record pointer should already be
		 * pointing to a valid record starting position.
		 */
		if (!XRecOffIsValid(RecPtr->xrecoff))
			ereport(PANIC,
					(errmsg("invalid record offset at %X/%X",
							RecPtr->xlogid, RecPtr->xrecoff)));

		/*
		 * 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).
		 */
		lastPageTLI = 0;		/* see comment in ValidXLOGHeader */
		lastSegmentTLI = 0;
		randAccess = true;		/* allow curFileTLI to go backwards too */
	}

	/* This is the first try to read this page. */
	failedSources = 0;
retry:
	/* Read the page containing the record */
	if (!XLogPageRead(RecPtr, emode, fetching_ckpt, randAccess))
	{
		/*
		 * In standby mode, XLogPageRead returning false means that promotion
		 * has been triggered.
		 */
		if (StandbyMode)
			return NULL;
		else
			goto next_record_is_invalid;
	}

	/* *********Above this xlogpageread should called ***********/
	pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
	targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
	if (targetRecOff == 0)
4170 4171
	{
		/*
4172 4173 4174 4175
		 * 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.
4176
		 */
4177
		Assert(RecPtr == &tmpRecPtr);
4178
		RecPtr->xrecoff += pageHeaderSize;
4179 4180 4181 4182 4183 4184 4185 4186 4187
		targetRecOff = pageHeaderSize;
	}
	else if (targetRecOff < pageHeaderSize)
	{
		ereport(emode,
				(errmsg("invalid record offset at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
		goto next_record_is_invalid;
	}
T
Tom Lane 已提交
4188
	if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
4189
		targetRecOff == pageHeaderSize)
4190
	{
4191 4192 4193
		ereport(emode,
				(errmsg("contrecord is requested by %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
4194 4195
		goto next_record_is_invalid;
	}
4196
	record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
4197

T
Tom Lane 已提交
4198
	/*
B
Bruce Momjian 已提交
4199 4200
	 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
	 * required.
T
Tom Lane 已提交
4201
	 */
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212
	if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
	{
		if (record->xl_len != 0)
		{
			ereport(emode,
					(errmsg("invalid xlog switch record at %X/%X",
							RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
	}
	else if (record->xl_len == 0)
4213
	{
4214 4215 4216
		ereport(emode,
				(errmsg("record with zero length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
4217 4218
		goto next_record_is_invalid;
	}
4219 4220 4221 4222 4223 4224 4225 4226 4227
	if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
		record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
		XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
	{
		ereport(emode,
				(errmsg("invalid record length at %X/%X",
						RecPtr->xlogid, RecPtr->xrecoff)));
		goto next_record_is_invalid;
	}
4228 4229 4230 4231
	if (record->xl_rmid > RM_MAX_ID)
	{
		ereport(emode,
				(errmsg("invalid resource manager ID %u at %X/%X",
B
Bruce Momjian 已提交
4232
						record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
4233 4234
		goto next_record_is_invalid;
	}
4235 4236 4237
	if (randAccess)
	{
		/*
B
Bruce Momjian 已提交
4238 4239
		 * We can't exactly verify the prev-link, but surely it should be less
		 * than the record's own address.
4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252
		 */
		if (!XLByteLT(record->xl_prev, *RecPtr))
		{
			ereport(emode,
					(errmsg("record with incorrect prev-link %X/%X at %X/%X",
							record->xl_prev.xlogid, record->xl_prev.xrecoff,
							RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
	}
	else
	{
		/*
B
Bruce Momjian 已提交
4253 4254 4255
		 * 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.
4256 4257 4258 4259 4260 4261 4262 4263 4264 4265
		 */
		if (!XLByteEQ(record->xl_prev, ReadRecPtr))
		{
			ereport(emode,
					(errmsg("record with incorrect prev-link %X/%X at %X/%X",
							record->xl_prev.xlogid, record->xl_prev.xrecoff,
							RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
	}
B
Bruce Momjian 已提交
4266

T
Tom Lane 已提交
4267
	/*
B
Bruce Momjian 已提交
4268
	 * Allocate or enlarge readRecordBuf as needed.  To avoid useless small
4269 4270 4271 4272
	 * 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 已提交
4273
	 */
4274
	total_len = record->xl_tot_len;
4275
	if (total_len > readRecordBufSize)
4276
	{
4277 4278
		uint32		newSize = total_len;

4279 4280
		newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
		newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293
		if (readRecordBuf)
			free(readRecordBuf);
		readRecordBuf = (char *) malloc(newSize);
		if (!readRecordBuf)
		{
			readRecordBufSize = 0;
			/* We treat this as a "bogus data" condition */
			ereport(emode,
					(errmsg("record length %u at %X/%X too long",
							total_len, RecPtr->xlogid, RecPtr->xrecoff)));
			goto next_record_is_invalid;
		}
		readRecordBufSize = newSize;
4294
	}
4295 4296

	buffer = readRecordBuf;
4297
	nextRecord = NULL;
4298
	len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
T
Tom Lane 已提交
4299
	if (total_len > len)
4300
	{
T
Tom Lane 已提交
4301 4302
		/* Need to reassemble record */
		XLogContRecord *contrecord;
4303
		XLogRecPtr	pagelsn;
B
Bruce Momjian 已提交
4304
		uint32		gotlen = len;
4305

4306 4307 4308 4309
		/* 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 已提交
4310
		memcpy(buffer, record, len);
4311
		record = (XLogRecord *) buffer;
T
Tom Lane 已提交
4312
		buffer += len;
4313
		for (;;)
4314
		{
4315 4316 4317
			/* Calculate pointer to beginning of next page */
			pagelsn.xrecoff += XLOG_BLCKSZ;
			if (pagelsn.xrecoff >= XLogFileSize)
4318
			{
4319 4320
				(pagelsn.xlogid)++;
				pagelsn.xrecoff = 0;
4321
			}
4322 4323
			/* Wait for the next page to become available */
			if (!XLogPageRead(&pagelsn, emode, false, false))
T
Tom Lane 已提交
4324
			{
4325 4326 4327 4328 4329 4330 4331 4332
				/*
				 * 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 已提交
4333
			}
4334

T
Tom Lane 已提交
4335
			if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
4336
			{
4337 4338 4339
				ereport(emode,
						(errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
								readId, readSeg, readOff)));
4340 4341
				goto next_record_is_invalid;
			}
4342 4343
			pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
			contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
B
Bruce Momjian 已提交
4344
			if (contrecord->xl_rem_len == 0 ||
T
Tom Lane 已提交
4345
				total_len != (contrecord->xl_rem_len + gotlen))
4346
			{
4347 4348 4349 4350
				ereport(emode,
						(errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
								contrecord->xl_rem_len,
								readId, readSeg, readOff)));
4351 4352
				goto next_record_is_invalid;
			}
4353
			len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
T
Tom Lane 已提交
4354
			if (contrecord->xl_rem_len > len)
4355
			{
B
Bruce Momjian 已提交
4356
				memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
T
Tom Lane 已提交
4357 4358 4359 4360 4361 4362 4363 4364 4365 4366
				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;
4367
		pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
4368
		if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
4369
			MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
T
Tom Lane 已提交
4370
		{
B
Bruce Momjian 已提交
4371
			nextRecord = (XLogRecord *) ((char *) contrecord +
B
Bruce Momjian 已提交
4372
					MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
T
Tom Lane 已提交
4373 4374 4375
		}
		EndRecPtr.xlogid = readId;
		EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
4376 4377
			pageHeaderSize +
			MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
T
Tom Lane 已提交
4378
		ReadRecPtr = *RecPtr;
4379
		/* needn't worry about XLOG SWITCH, it can't cross page boundaries */
T
Tom Lane 已提交
4380
		return record;
4381 4382
	}

T
Tom Lane 已提交
4383 4384 4385
	/* Record does not cross a page boundary */
	if (!RecordIsValid(record, *RecPtr, emode))
		goto next_record_is_invalid;
4386
	if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
T
Tom Lane 已提交
4387 4388 4389 4390 4391 4392
		MAXALIGN(total_len))
		nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
	EndRecPtr.xlogid = RecPtr->xlogid;
	EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
	ReadRecPtr = *RecPtr;
	memcpy(buffer, record, total_len);
B
Bruce Momjian 已提交
4393

4394 4395 4396 4397 4398 4399 4400 4401 4402
	/*
	 * Special processing if it's an XLOG SWITCH record
	 */
	if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
	{
		/* Pretend it extends to end of segment */
		EndRecPtr.xrecoff += XLogSegSize - 1;
		EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
		nextRecord = NULL;		/* definitely not on same page */
B
Bruce Momjian 已提交
4403

4404
		/*
B
Bruce Momjian 已提交
4405 4406 4407
		 * 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.
4408 4409 4410
		 */
		readOff = XLogSegSize - XLOG_BLCKSZ;
	}
4411 4412 4413 4414 4415 4416

	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 已提交
4417
	return (XLogRecord *) buffer;
4418

4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466
next_record_is_invalid:

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

	failedSources |= readSource;

	nextRecord = NULL;

	/* 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;
T
Tom Lane 已提交
4467
	nextRecord = NULL;
4468 4469 4470 4471 4472

	memset(&ReadRecPtr, 0, sizeof(XLogRecPtr));
	memset(&EndRecPtr, 0, sizeof(XLogRecPtr));

	elog((Debug_print_qd_mirroring ? LOG : DEBUG1),"close read record");
4473 4474
}

4475 4476 4477 4478
/*
 * 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 已提交
4479
 * ReadRecord.	It's not intended for use from anywhere else.
4480 4481
 */
static bool
4482
ValidXLOGHeader(XLogPageHeader hdr, int emode, bool segmentonly)
4483
{
4484 4485
	XLogRecPtr	recaddr;

4486 4487
	if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
	{
4488 4489 4490
		ereport(emode,
				(errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
						hdr->xlp_magic, readId, readSeg, readOff)));
4491 4492 4493 4494
		return false;
	}
	if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
	{
4495 4496 4497
		ereport(emode,
				(errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
						hdr->xlp_info, readId, readSeg, readOff)));
4498 4499
		return false;
	}
4500
	if (hdr->xlp_info & XLP_LONG_HEADER)
4501
	{
4502
		XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
B
Bruce Momjian 已提交
4503

4504
		if (longhdr->xlp_sysid != ControlFile->system_identifier)
4505
		{
4506 4507
			char		fhdrident_str[32];
			char		sysident_str[32];
4508

4509
			/*
B
Bruce Momjian 已提交
4510 4511
			 * Format sysids separately to keep platform-dependent format code
			 * out of the translatable message string.
4512 4513 4514 4515 4516 4517 4518
			 */
			snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
					 longhdr->xlp_sysid);
			snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
					 ControlFile->system_identifier);
			ereport(emode,
					(errmsg("WAL file is from different system"),
B
Bruce Momjian 已提交
4519 4520
					 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
							   fhdrident_str, sysident_str)));
4521 4522 4523 4524 4525 4526
			return false;
		}
		if (longhdr->xlp_seg_size != XLogSegSize)
		{
			ereport(emode,
					(errmsg("WAL file is from different system"),
B
Bruce Momjian 已提交
4527
					 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
4528 4529
			return false;
		}
4530 4531 4532 4533 4534 4535 4536
		if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
		{
			ereport(emode,
					(errmsg("WAL file is from different system"),
					 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
			return false;
		}
4537
	}
4538 4539 4540 4541 4542 4543 4544 4545 4546
	else if (readOff == 0)
	{
		/* hmm, first page of file doesn't have a long header? */
		ereport(emode,
				(errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
						hdr->xlp_info, readId, readSeg, readOff)));
		return false;
	}

4547 4548 4549 4550 4551 4552
	recaddr.xlogid = readId;
	recaddr.xrecoff = readSeg * XLogSegSize + readOff;
	if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
	{
		ereport(emode,
				(errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
B
Bruce Momjian 已提交
4553
						hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574
						readId, readSeg, readOff)));
		return false;
	}

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

	/*
	 * Since child timelines are always assigned a TLI greater than their
	 * immediate parent's TLI, we should never see TLI go backwards across
	 * successive pages of a consistent WAL sequence.
	 *
B
Bruce Momjian 已提交
4575
	 * Of course this check should only be applied when advancing sequentially
4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586
	 * 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.
4587
	 */
4588
	if (hdr->xlp_tli < (segmentonly ? lastSegmentTLI : lastPageTLI))
4589 4590 4591 4592 4593 4594 4595 4596
	{
		ereport(emode,
				(errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
						hdr->xlp_tli, lastPageTLI,
						readId, readSeg, readOff)));
		return false;
	}
	lastPageTLI = hdr->xlp_tli;
4597 4598 4599
	if (readOff == 0)
		lastSegmentTLI = hdr->xlp_tli;

4600 4601 4602 4603 4604 4605 4606
	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 已提交
4607
 * its ancestor TLIs).	If we can't find the history file, assume that the
4608 4609 4610
 * timeline has no parents, and return a list of just the specified timeline
 * ID.
 */
4611 4612
List *
XLogReadTimeLineHistory(TimeLineID targetTLI)
4613 4614 4615 4616
{
	List	   *result;
	char		path[MAXPGPATH];
	char		fline[MAXPGPATH];
B
Bruce Momjian 已提交
4617
	FILE	   *fd;
4618

4619 4620 4621 4622 4623
	/* Timeline 1 does not have a history file, so no need to check */
	if (targetTLI == 1)
		return list_make1_int((int) targetTLI);

	TLHistoryFilePath(path, targetTLI);
4624

B
Bruce Momjian 已提交
4625
	fd = AllocateFile(path, "r");
4626 4627 4628 4629 4630
	if (fd == NULL)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
4631
					 errmsg("could not open file \"%s\": %m", path)));
4632 4633 4634 4635 4636 4637
		/* Not there, so assume no parents */
		return list_make1_int((int) targetTLI);
	}

	result = NIL;

B
Bruce Momjian 已提交
4638 4639 4640
	/*
	 * Parse the file...
	 */
4641
	while (fgets(fline, sizeof(fline), fd) != NULL)
4642 4643
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
4644 4645 4646
		char	   *ptr;
		char	   *endptr;
		TimeLineID	tli;
4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666

		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 已提交
4667
				   errhint("Timeline IDs must be in increasing sequence.")));
4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680

		/* 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 已提交
4681
			errhint("Timeline IDs must be less than child timeline's ID.")));
4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698

	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];
B
Bruce Momjian 已提交
4699
	FILE	   *fd;
4700

4701
	TLHistoryFilePath(path, probeTLI);
4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713

	fd = AllocateFile(path, "r");
	if (fd != NULL)
	{
		FreeFile(fd);
		return true;
	}
	else
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
4714
					 errmsg("could not open file \"%s\": %m", path)));
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732
		return false;
	}
}

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

	/*
B
Bruce Momjian 已提交
4733 4734
	 * The algorithm is just to probe for the existence of timeline history
	 * files.  XXX is it useful to allow gaps in the sequence?
4735 4736 4737
	 */
	newestTLI = startTLI;

B
Bruce Momjian 已提交
4738
	for (probeTLI = startTLI + 1;; probeTLI++)
4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761
	{
		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 已提交
4762
 * considerations.	But we should be just as tense as XLogFileInit to avoid
4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776
 * 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;
4777
	char		*xlogDir = NULL;
4778

B
Bruce Momjian 已提交
4779
	Assert(newTLI > parentTLI); /* else bad selection of newTLI */
4780 4781 4782 4783

	/*
	 * Write into a temp file name.
	 */
4784 4785 4786 4787 4788 4789
	xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
	if (snprintf(tmppath, MAXPGPATH, "%s/xlogtemp.%d", xlogDir, (int) getpid()) > MAXPGPATH)
	{
		ereport(ERROR, (errmsg("cannot generate filename %s/xlogtemp.%d", xlogDir, (int) getpid())));
	}
	pfree(xlogDir);
4790 4791 4792 4793 4794 4795
	unlink(tmppath);

	/* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
	fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
					   S_IRUSR | S_IWUSR);
	if (fd < 0)
4796
		ereport(ERROR,
4797 4798 4799
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m", tmppath)));

4800
	TLHistoryFilePath(path, parentTLI);
4801 4802 4803 4804 4805

	srcfd = BasicOpenFile(path, O_RDONLY, 0);
	if (srcfd < 0)
	{
		if (errno != ENOENT)
4806
			ereport(ERROR,
4807
					(errcode_for_file_access(),
P
Peter Eisentraut 已提交
4808
					 errmsg("could not open file \"%s\": %m", path)));
4809 4810 4811 4812 4813 4814 4815 4816 4817
		/* Not there, so assume parent has no parents */
	}
	else
	{
		for (;;)
		{
			errno = 0;
			nbytes = (int) read(srcfd, buffer, sizeof(buffer));
			if (nbytes < 0 || errno != 0)
4818
				ereport(ERROR,
4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832
						(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 已提交
4833 4834

				/*
B
Bruce Momjian 已提交
4835
				 * if write didn't set errno, assume problem is no disk space
B
Bruce Momjian 已提交
4836
				 */
4837 4838
				errno = save_errno ? save_errno : ENOSPC;

4839
				ereport(ERROR,
4840
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
4841
					 errmsg("could not write to file \"%s\": %m", tmppath)));
4842 4843 4844 4845 4846 4847 4848 4849
			}
		}
		close(srcfd);
	}

	/*
	 * Append one line with the details of this timeline split.
	 *
B
Bruce Momjian 已提交
4850 4851
	 * If we did have a parent file, insert an extra newline just in case the
	 * parent file failed to end with one.
4852 4853 4854 4855 4856 4857 4858 4859 4860 4861
	 */
	XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);

	snprintf(buffer, sizeof(buffer),
			 "%s%u\t%s\t%s transaction %u at %s\n",
			 (srcfd < 0) ? "" : "\n",
			 parentTLI,
			 xlogfname,
			 recoveryStopAfter ? "after" : "before",
			 recoveryStopXid,
4862
			 timestamptz_to_str(recoveryStopTime));
4863 4864 4865 4866 4867 4868 4869 4870

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

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

4877
		ereport(ERROR,
4878 4879 4880 4881 4882
				(errcode_for_file_access(),
				 errmsg("could not write to file \"%s\": %m", tmppath)));
	}

	if (pg_fsync(fd) != 0)
4883
		ereport(ERROR,
4884 4885 4886 4887
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m", tmppath)));

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

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 4977 4978 4979 4980
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));
		}
	}
}

4981 4982
/*
 * I/O routines for pg_control
4983 4984
 *
 * *ControlFile is a buffer in shared memory that holds an image of the
B
Bruce Momjian 已提交
4985
 * contents of pg_control.	WriteControlFile() initializes pg_control
4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997
 * 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)
{
4998 4999
	MirroredFlatFileOpen	mirroredOpen;

B
Bruce Momjian 已提交
5000
	char		buffer[PG_CONTROL_SIZE];		/* need not be aligned */
5001 5002 5003
	char	   *localeptr;

	/*
T
Tom Lane 已提交
5004
	 * Initialize version and compatibility-check fields
5005
	 */
T
Tom Lane 已提交
5006 5007
	ControlFile->pg_control_version = PG_CONTROL_VERSION;
	ControlFile->catalog_version_no = CATALOG_VERSION_NO;
5008 5009 5010 5011

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

5012 5013
	ControlFile->blcksz = BLCKSZ;
	ControlFile->relseg_size = RELSEG_SIZE;
5014
	ControlFile->xlog_blcksz = XLOG_BLCKSZ;
5015
	ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
5016 5017

	ControlFile->nameDataLen = NAMEDATALEN;
5018
	ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
5019

5020 5021
	ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;

5022 5023 5024 5025 5026 5027 5028
#ifdef HAVE_INT64_TIMESTAMP
	ControlFile->enableIntTimes = TRUE;
#else
	ControlFile->enableIntTimes = FALSE;
#endif

	ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
5029 5030
	localeptr = setlocale(LC_COLLATE, NULL);
	if (!localeptr)
5031 5032
		ereport(PANIC,
				(errmsg("invalid LC_COLLATE setting")));
5033 5034 5035
	StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
	localeptr = setlocale(LC_CTYPE, NULL);
	if (!localeptr)
5036 5037
		ereport(PANIC,
				(errmsg("invalid LC_CTYPE setting")));
5038
	StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
B
Bruce Momjian 已提交
5039

T
Tom Lane 已提交
5040
	/* Contents are protected with a CRC */
5041 5042
	INIT_CRC32C(ControlFile->crc);
	COMP_CRC32C(ControlFile->crc,
5043 5044
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
5045
	FIN_CRC32C(ControlFile->crc);
T
Tom Lane 已提交
5046

5047
	/*
5048 5049 5050 5051 5052
	 * 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".
5053
	 */
5054 5055
	if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
		elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
5056

5057
	memset(buffer, 0, PG_CONTROL_SIZE);
5058 5059
	memcpy(buffer, ControlFile, sizeof(ControlFileData));

5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083
	MirroredFlatFile_Open(
					&mirroredOpen,
					XLOG_CONTROL_FILE_SUBDIR,
					XLOG_CONTROL_FILE_SIMPLE,
					O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
					S_IRUSR | S_IWUSR,
					/* suppressError */ false,
					/* atomic operation */ false,
					/*isMirrorRecovery */ false);

	MirroredFlatFile_Write(
					&mirroredOpen,
					0,
					buffer,
					PG_CONTROL_SIZE,
					/* suppressError */ false);

	MirroredFlatFile_Flush(
					&mirroredOpen,
					/* suppressError */ false);

	MirroredFlatFile_Close(&mirroredOpen);

	ControlFileWatcherSaveInitial();
5084 5085 5086 5087 5088
}

static void
ReadControlFile(void)
{
5089
	pg_crc32	crc;
5090 5091 5092 5093 5094
	int			fd;

	/*
	 * Read data...
	 */
5095 5096 5097
	fd = BasicOpenFile(XLOG_CONTROL_FILE,
					   O_RDWR | PG_BINARY,
					   S_IRUSR | S_IWUSR);
5098
	if (fd < 0)
5099 5100 5101
		ereport(PANIC,
				(errcode_for_file_access(),
				 errmsg("could not open control file \"%s\": %m",
5102
						XLOG_CONTROL_FILE)));
5103 5104

	if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
5105 5106
		ereport(PANIC,
				(errcode_for_file_access(),
5107
				 errmsg("could not read from control file: %m")));
5108 5109 5110

	close(fd);

T
Tom Lane 已提交
5111
	/*
B
Bruce Momjian 已提交
5112 5113 5114 5115
	 * 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 已提交
5116
	 */
5117 5118 5119 5120 5121 5122 5123 5124 5125 5126

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

T
Tom Lane 已提交
5127
	if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
5128 5129 5130
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
B
Bruce Momjian 已提交
5131 5132
				  " but the server was compiled with PG_CONTROL_VERSION %d.",
						ControlFile->pg_control_version, PG_CONTROL_VERSION),
5133
				 errhint("It looks like you need to initdb.")));
5134

T
Tom Lane 已提交
5135
	/* Now check the CRC. */
5136 5137
	INIT_CRC32C(crc);
	COMP_CRC32C(crc,
5138 5139
			   (char *) ControlFile,
			   offsetof(ControlFileData, crc));
5140
	FIN_CRC32C(crc);
5141

5142
	if (!EQ_CRC32C(crc, ControlFile->crc))
5143 5144
		ereport(FATAL,
				(errmsg("incorrect checksum in control file")));
5145

5146
	/*
5147 5148
	 * Do compatibility checking immediately, except during upgrade.
	 * We do this here for 2 reasons:
5149
	 *
5150 5151
	 * (1) if the database isn't compatible with the backend executable, we
	 * want to abort before we can possibly do any damage;
5152 5153
	 *
	 * (2) this code is executed in the postmaster, so the setlocale() will
B
Bruce Momjian 已提交
5154 5155
	 * propagate to forked backends, which aren't going to read this file for
	 * themselves.	(These locale settings are considered critical
5156 5157
	 * compatibility items because they can affect sort order of indexes.)
	 */
5158
	if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
5159 5160 5161
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
B
Bruce Momjian 已提交
5162 5163
				  " but the server was compiled with CATALOG_VERSION_NO %d.",
						ControlFile->catalog_version_no, CATALOG_VERSION_NO),
5164
				 errhint("It looks like you need to initdb.")));
5165 5166 5167
	if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5168 5169 5170 5171
		   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.")));
5172 5173 5174
	if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
P
Peter Eisentraut 已提交
5175
				 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
5176
				 errhint("It looks like you need to initdb.")));
5177
	if (ControlFile->blcksz != BLCKSZ)
5178 5179
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5180 5181 5182 5183
			 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.")));
5184
	if (ControlFile->relseg_size != RELSEG_SIZE)
5185 5186
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5187 5188 5189 5190
		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.")));
5191 5192 5193
	if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5194 5195 5196
		errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
				  " but the server was compiled with XLOG_BLCKSZ %d.",
				  ControlFile->xlog_blcksz, XLOG_BLCKSZ),
5197
				 errhint("It looks like you need to recompile or initdb.")));
5198 5199 5200 5201
	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 已提交
5202
					   " but the server was compiled with XLOG_SEG_SIZE %d.",
5203
						   ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
B
Bruce Momjian 已提交
5204
				 errhint("It looks like you need to recompile or initdb.")));
5205
	if (ControlFile->nameDataLen != NAMEDATALEN)
5206 5207
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
B
Bruce Momjian 已提交
5208 5209 5210 5211
		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.")));
5212
	if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
5213 5214
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
5215
				 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
B
Bruce Momjian 已提交
5216
					  " but the server was compiled with INDEX_MAX_KEYS %d.",
5217
						   ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
B
Bruce Momjian 已提交
5218
				 errhint("It looks like you need to recompile or initdb.")));
5219 5220 5221 5222
	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 已提交
5223 5224
				" but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
			  ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
5225
				 errhint("It looks like you need to recompile or initdb.")));
5226 5227 5228

#ifdef HAVE_INT64_TIMESTAMP
	if (ControlFile->enableIntTimes != TRUE)
5229 5230 5231
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
5232 5233
				  " but the server was compiled with HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
5234 5235
#else
	if (ControlFile->enableIntTimes != FALSE)
5236 5237 5238
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
B
Bruce Momjian 已提交
5239 5240
			   " but the server was compiled without HAVE_INT64_TIMESTAMP."),
				 errhint("It looks like you need to recompile or initdb.")));
5241 5242 5243
#endif

	if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
5244 5245 5246
		ereport(FATAL,
				(errmsg("database files are incompatible with server"),
				 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
B
Bruce Momjian 已提交
5247
				  " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
5248
						   ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
B
Bruce Momjian 已提交
5249
				 errhint("It looks like you need to recompile or initdb.")));
5250
	if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
5251
		ereport(FATAL,
B
Bruce Momjian 已提交
5252 5253 5254 5255 5256
			(errmsg("database files are incompatible with operating system"),
			 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
					   " which is not recognized by setlocale().",
					   ControlFile->lc_collate),
			 errhint("It looks like you need to initdb or install locale support.")));
5257
	if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
5258
		ereport(FATAL,
B
Bruce Momjian 已提交
5259 5260 5261 5262 5263
			(errmsg("database files are incompatible with operating system"),
		errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
				  " which is not recognized by setlocale().",
				  ControlFile->lc_ctype),
			 errhint("It looks like you need to initdb or install locale support.")));
5264 5265 5266 5267 5268 5269

	/* Make the fixed locale settings visible as GUC variables, too */
	SetConfigOption("lc_collate", ControlFile->lc_collate,
					PGC_INTERNAL, PGC_S_OVERRIDE);
	SetConfigOption("lc_ctype", ControlFile->lc_ctype,
					PGC_INTERNAL, PGC_S_OVERRIDE);
5270 5271 5272 5273 5274 5275 5276 5277 5278

	if (!ControlFileWatcher->watcherInitialized)
	{
		ControlFileWatcherSaveInitial();
	}
	else
	{
		ControlFileWatcherCheckForChange();
	}
5279 5280
}

5281 5282
static bool
XLogGetWriteAndFlushedLoc(XLogRecPtr *writeLoc, XLogRecPtr *flushedLoc)
5283
{
5284 5285
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
5286

5287 5288 5289 5290
	SpinLockAcquire(&xlogctl->info_lck);
	*writeLoc = xlogctl->LogwrtResult.Write;
	*flushedLoc = xlogctl->LogwrtResult.Flush;
	SpinLockRelease(&xlogctl->info_lck);
5291

5292 5293
	return (writeLoc->xlogid != 0 || writeLoc->xrecoff != 0);
}
5294

5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355
/*
 * Very specific purpose routine for FileRep that flushes out XLOG records from the
 * XLOG memory cache to disk.
 */
void
XLogFileRepFlushCache(
	XLogRecPtr	*lastChangeTrackingEndLoc)
{
	/*
	 * We hold the ChangeTrackingTransitionLock EXCLUSIVE, thus the lastChangeTrackingEndLoc
	 * value is the previous location -- the one we want.
	 *
	 * Since the lock is acquired after ALL WRITES and FSYNCS in XLogInsert_Internal,
	 * we know this flush is safe (i.e. will not hang) and will push out all XLOG records we
	 * want to see in the next call to ChangeTracking_CreateInitialFromPreviousCheckpoint.
	 */

	*lastChangeTrackingEndLoc = XLogCtl->lastChangeTrackingEndLoc;

	if (Debug_persistent_print)
		elog(Persistent_DebugPrintLevel(),
			 "XLogFileRepFlushCache: Going flush through location %s...",
			 XLogLocationToString(lastChangeTrackingEndLoc));

	XLogFlush(*lastChangeTrackingEndLoc);
}

void
XLogInChangeTrackingTransition(void)
{
	XLogRecPtr	lastChangeTrackingEndLoc;
	XLogRecPtr      recPtrInit = {0, 0};

	if (Debug_persistent_print)
		elog(Persistent_DebugPrintLevel(),
			 "XLogInChangeTrackingTransition: Acquiring ChangeTrackingTransitionLock...");

	LWLockAcquire(ChangeTrackingTransitionLock, LW_EXCLUSIVE);

	if (Debug_persistent_print)
		elog(Persistent_DebugPrintLevel(),
			 "XLogInChangeTrackingTransition: SegmentStateInChangeTrackingTransition...");

	FileRep_SetSegmentState(SegmentStateInChangeTrackingTransition, FaultTypeNotInitialized);

	XLogFileRepFlushCache(&lastChangeTrackingEndLoc);

	if (Debug_persistent_print)
		elog(Persistent_DebugPrintLevel(),
			 "XLogInChangeTrackingTransition: Calling ChangeTracking_CreateInitialFromPreviousCheckpoint with lastChangeTrackingEndLoc %s",
			 XLogLocationToString(&lastChangeTrackingEndLoc));

	/*
	 * During gpstart the following order is followed for recovery:
	 *                      a) xlog records from last checkpoint are replayed into change tracking log file
	 *                      b) xlog is replayed by 3 pass mechanism
	 * In that case XLogCtl->lastChangeTrackingEndLoc will be still set to {0,0} and
	 * in order to insert all xlog records from last checkpoint into change tracking log file
	 * ChangeTracking_CreateInitialFromPreviousCheckpoint(NULL); has to be called.
	 */
	if (XLByteEQ(lastChangeTrackingEndLoc, recPtrInit))
5356
	{
5357 5358 5359 5360 5361
		ChangeTracking_CreateInitialFromPreviousCheckpoint(NULL);
	}
	else
	{
		ChangeTracking_CreateInitialFromPreviousCheckpoint(&lastChangeTrackingEndLoc);
5362
	}
5363

5364
	LWLockRelease(ChangeTrackingTransitionLock);
5365

5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376
	if (Debug_persistent_print)
		elog(Persistent_DebugPrintLevel(),
			 "XLogInChangeTrackingTransition: Released ChangeTrackingTransitionLock");

}

void
UpdateControlFile(void)
{
	MirroredFlatFileOpen	mirroredOpen;

5377 5378
	INIT_CRC32C(ControlFile->crc);
	COMP_CRC32C(ControlFile->crc,
5379 5380
				   (char *) ControlFile,
				   offsetof(ControlFileData, crc));
5381
	FIN_CRC32C(ControlFile->crc);
5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418

	MirroredFlatFile_Open(
					&mirroredOpen,
					XLOG_CONTROL_FILE_SUBDIR,
					XLOG_CONTROL_FILE_SIMPLE,
					O_RDWR | PG_BINARY,
					S_IRUSR | S_IWUSR,
					/* suppressError */ false,
					/* atomic operation */ false,
					/*isMirrorRecovery */ false);

	MirroredFlatFile_Write(
					&mirroredOpen,
					0,
					ControlFile,
					PG_CONTROL_SIZE,
					/* suppressError */ false);

	MirroredFlatFile_Flush(
					&mirroredOpen,
					/* suppressError */ false);

	MirroredFlatFile_Close(&mirroredOpen);

	Assert (ControlFileWatcher->watcherInitialized);

	ControlFileWatcherCheckForChange();
}

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

5421
/*
T
Tom Lane 已提交
5422
 * Initialization of shared memory for XLOG
5423
 */
5424
Size
5425
XLOGShmemSize(void)
5426
{
5427
	Size		size;
5428

5429 5430 5431 5432 5433 5434 5435
	/* 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 */
5436
	size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
5437 5438

	/*
B
Bruce Momjian 已提交
5439 5440 5441
	 * 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.
5442 5443
	 */

5444 5445 5446 5447
	/*
	 * Similary, we also don't PgControlWatch for the above reasons, too.
	 */

5448
	return size;
5449 5450 5451 5452 5453
}

void
XLOGShmemInit(void)
{
5454
	bool		foundCFile,
5455 5456
				foundXLog,
				foundCFileWatcher;
5457
	char	   *allocptr;
5458

5459
	ControlFile = (ControlFileData *)
5460
		ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
5461 5462
	ControlFileWatcher = (ControlFileWatch *)
		ShmemInitStruct("Control File Watcher", sizeof(ControlFileWatch), &foundCFileWatcher);
5463 5464
	XLogCtl = (XLogCtlData *)
		ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
5465

5466
	if (foundCFile || foundXLog || foundCFileWatcher)
5467 5468
	{
		/* both should be present or neither */
5469
		Assert(foundCFile && foundXLog && foundCFileWatcher);
5470 5471
		return;
	}
5472

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

5475 5476
	XLogCtl->pass4_PTCatVerificationPassed = true;

T
Tom Lane 已提交
5477
	/*
B
Bruce Momjian 已提交
5478 5479 5480
	 * 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 已提交
5481
	 */
5482 5483
	allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
	XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
T
Tom Lane 已提交
5484
	memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
5485
	allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
B
Bruce Momjian 已提交
5486

T
Tom Lane 已提交
5487
	/*
5488
	 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
T
Tom Lane 已提交
5489
	 */
5490 5491
	allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
	XLogCtl->pages = allocptr;
5492
	memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
T
Tom Lane 已提交
5493 5494

	/*
B
Bruce Momjian 已提交
5495 5496
	 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
	 * in additional info.)
T
Tom Lane 已提交
5497
	 */
B
Bruce Momjian 已提交
5498
	XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
B
Bruce Momjian 已提交
5499

T
Tom Lane 已提交
5500
	XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
5501
	XLogCtl->SharedRecoveryInProgress = true;
T
Tom Lane 已提交
5502
	XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
5503
	SpinLockInit(&XLogCtl->info_lck);
5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519
	InitSharedLatch(&XLogCtl->recoveryWakeupLatch);

	XLogCtl->haveLastCheckpointLoc = false;
	memset(&XLogCtl->lastCheckpointLoc, 0, sizeof(XLogRecPtr));
	memset(&XLogCtl->lastCheckpointEndLoc, 0, sizeof(XLogRecPtr));

	/*
	 * Initialize the shared memory by the parameter given to postmaster.
	 * GpStandbyDbid could be inconsistent with the catalog if the postmaster
	 * is given wrong id, but there is no chance to check it in this early
	 * stage of startup, and this is how we have been doing historically.
	 */
	XLogCtl->standbyDbid = GpStandbyDbid;

	SpinLockInit(&XLogCtl->resynchronize_lck);
}
T
Tom Lane 已提交
5520

5521 5522 5523 5524 5525 5526 5527 5528 5529
/**
 * This should be called when we are sure that it is safe to try to read the control file and BEFORE
 *  we have launched any child processes that need access to collation and ctype data.
 *
 * It is not safe to read the control file on a mirror because it may not be synchronized
 */
void
XLogStartupInit(void)
{
5530
	/*
B
Bruce Momjian 已提交
5531 5532 5533
	 * 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).
5534 5535 5536
	 */
	if (!IsBootstrapProcessingMode())
		ReadControlFile();
5537 5538 5539
}

/*
T
Tom Lane 已提交
5540 5541
 * This func must be called ONCE on system install.  It creates pg_control
 * and the initial XLOG segment.
5542 5543
 */
void
T
Tom Lane 已提交
5544
BootStrapXLOG(void)
5545
{
5546
	CheckPoint	checkPoint;
T
Tom Lane 已提交
5547 5548
	char	   *buffer;
	XLogPageHeader page;
5549
	XLogLongPageHeader longpage;
5550
	XLogRecord *record;
B
Bruce Momjian 已提交
5551
	bool		use_existent;
5552 5553
	uint64		sysidentifier;
	struct timeval tv;
5554
	pg_crc32	crc;
5555

5556
	/*
B
Bruce Momjian 已提交
5557 5558 5559 5560 5561 5562 5563 5564 5565 5566
	 * 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.
5567 5568 5569 5570 5571
	 */
	gettimeofday(&tv, NULL);
	sysidentifier = ((uint64) tv.tv_sec) << 32;
	sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);

5572 5573 5574
	/* First timeline ID is always 1 */
	ThisTimeLineID = 1;

5575
	/* page buffer must be aligned suitably for O_DIRECT */
5576
	buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
5577
	page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
5578
	memset(page, 0, XLOG_BLCKSZ);
T
Tom Lane 已提交
5579

5580 5581 5582 5583 5584 5585 5586
	/*
	 * 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".
	 */
5587
	checkPoint.redo.xlogid = 0;
5588
	checkPoint.redo.xrecoff = XLogSegSize + SizeOfXLogLongPHD;
5589
	checkPoint.ThisTimeLineID = ThisTimeLineID;
5590
	checkPoint.nextXidEpoch = 0;
5591
	checkPoint.nextXid = FirstNormalTransactionId;
5592
	checkPoint.nextOid = FirstBootstrapObjectId;
5593
	checkPoint.nextMulti = FirstMultiXactId;
5594
	checkPoint.nextMultiOffset = 0;
T
Tom Lane 已提交
5595
	checkPoint.time = time(NULL);
5596

5597 5598 5599
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
	ShmemVariableCache->oidCount = 0;
5600
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5601

5602
	/* Set up the XLOG page header */
5603
	page->xlp_magic = XLOG_PAGE_MAGIC;
5604 5605
	page->xlp_info = XLP_LONG_HEADER;
	page->xlp_tli = ThisTimeLineID;
5606
	page->xlp_pageaddr.xlogid = 0;
5607
	page->xlp_pageaddr.xrecoff = XLogSegSize;
5608 5609 5610
	longpage = (XLogLongPageHeader) page;
	longpage->xlp_sysid = sysidentifier;
	longpage->xlp_seg_size = XLogSegSize;
5611
	longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5612 5613

	/* Insert the initial checkpoint record */
5614
	record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
5615
	record->xl_prev.xlogid = 0;
5616
	record->xl_prev.xrecoff = 0;
5617
	record->xl_xid = InvalidTransactionId;
5618
	record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
5619
	record->xl_len = sizeof(checkPoint);
T
Tom Lane 已提交
5620
	record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
5621
	record->xl_rmid = RM_XLOG_ID;
T
Tom Lane 已提交
5622
	memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
5623

5624 5625 5626
	INIT_CRC32C(crc);
	COMP_CRC32C(crc, &checkPoint, sizeof(checkPoint));
	COMP_CRC32C(crc, (char *) record + sizeof(pg_crc32),
5627
			   SizeOfXLogRecord - sizeof(pg_crc32));
5628
	FIN_CRC32C(crc);
5629

5630 5631
	record->xl_crc = crc;

5632
	/* Create first XLOG segment file */
5633
	use_existent = false;
5634 5635 5636
	XLogFileInit(
		&mirroredLogFileOpen,
		0, 1, &use_existent, false);
5637

5638
	/* Write the first page with the initial record */
5639
	errno = 0;
5640 5641 5642 5643 5644
	if (MirroredFlatFile_Append(
			&mirroredLogFileOpen,
			page,
			XLOG_BLCKSZ,
			/* suppressError */ true))
5645
	{
5646 5647
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
5648
			  errmsg("could not write bootstrap transaction log file: %m")));
5649
	}
5650

5651 5652 5653
	if (MirroredFlatFile_Flush(
			&mirroredLogFileOpen,
			/* suppressError */ true))
5654 5655
		ereport(PANIC,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
5656
			  errmsg("could not fsync bootstrap transaction log file: %m")));
5657

5658 5659
	MirroredFlatFile_Close(
			&mirroredLogFileOpen);
5660

5661 5662
	/* Now create pg_control */

5663
	memset(ControlFile, 0, sizeof(ControlFileData));
T
Tom Lane 已提交
5664
	/* Initialize pg_control status fields */
5665
	ControlFile->system_identifier = sysidentifier;
T
Tom Lane 已提交
5666 5667
	ControlFile->state = DB_SHUTDOWNED;
	ControlFile->time = checkPoint.time;
5668
	ControlFile->checkPoint = checkPoint.redo;
T
Tom Lane 已提交
5669
	ControlFile->checkPointCopy = checkPoint;
5670
	/* some additional ControlFile fields are set in WriteControlFile() */
5671

5672
	WriteControlFile();
5673 5674 5675

	/* Bootstrap the commit log, too */
	BootStrapCLOG();
5676
	BootStrapSUBTRANS();
5677
	BootStrapMultiXact();
5678
	DistributedLog_BootStrap();
5679

5680
	pfree(buffer);
5681 5682
}

5683
static char *
5684
str_time(pg_time_t tnow)
5685
{
5686
	static char buf[128];
5687

5688
	pg_strftime(buf, sizeof(buf),
5689 5690
				"%Y-%m-%d %H:%M:%S %Z",
				pg_localtime(&tnow, log_timezone));
5691

5692
	return buf;
5693 5694
}

5695 5696
/*
 * See if there is a recovery command file (recovery.conf), and if so
5697
 * read in parameters for recovery in standby mode.
5698 5699 5700 5701 5702
 *
 * XXX longer term intention is to expand this to
 * cater for additional parameters and controls
 * possibly use a flex lexer similar to the GUC one
 */
5703 5704
void
XLogReadRecoveryCommandFile(int emode)
5705
{
B
Bruce Momjian 已提交
5706 5707 5708 5709
	FILE	   *fd;
	char		cmdline[MAXPGPATH];
	bool		syntaxError = false;

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

5721 5722 5723
	ereport(emode,
			(errmsg("Found recovery.conf file, checking appropriate parameters "
					" for recovery in standby mode")));
5724

B
Bruce Momjian 已提交
5725 5726 5727
	/*
	 * Parse the file...
	 */
5728
	while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
5729 5730
	{
		/* skip leading whitespace and check for # comment */
B
Bruce Momjian 已提交
5731 5732 5733
		char	   *ptr;
		char	   *tok1;
		char	   *tok2;
5734 5735 5736 5737 5738 5739 5740 5741 5742 5743

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

		/* identify the quoted parameter value */
B
Bruce Momjian 已提交
5744
		tok1 = strtok(ptr, "'");
5745 5746 5747 5748 5749
		if (!tok1)
		{
			syntaxError = true;
			break;
		}
B
Bruce Momjian 已提交
5750
		tok2 = strtok(NULL, "'");
5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763
		if (!tok2)
		{
			syntaxError = true;
			break;
		}
		/* reparse to get just the parameter name */
		tok1 = strtok(ptr, " \t=");
		if (!tok1)
		{
			syntaxError = true;
			break;
		}

5764
		if (strcmp(tok1, "primary_conninfo") == 0)
B
Bruce Momjian 已提交
5765
		{
5766 5767 5768 5769
			PrimaryConnInfo = pstrdup(tok2);
			ereport(emode,
					(errmsg("primary_conninfo = \"%s\"",
							PrimaryConnInfo)));
5770
		}
5771
		else if (strcmp(tok1, "standby_mode") == 0)
B
Bruce Momjian 已提交
5772
		{
5773 5774 5775
			/*
			 * does nothing if a recovery_target is not also set
			 */
5776 5777
			if (strcmp(tok2, "on") == 0)
				StandbyModeRequested = true;
5778 5779
			else
			{
5780
				StandbyModeRequested = false;
5781 5782
				tok2 = "false";
			}
5783 5784
			ereport(emode,
					(errmsg("StandbyModeRequested = %s", tok2)));
5785
		}
5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800
		else if (strcmp(tok1, "log_restartpoints") == 0)
		{
			/*
			 * does nothing if a recovery_target is not also set
			 */
			if (strcmp(tok2, "true") == 0)
				recoveryLogRestartpoints = true;
			else
			{
				recoveryLogRestartpoints = false;
				tok2 = "false";
			}
			ereport(LOG,
					(errmsg("log_restartpoints = %s", tok2)));
		}
5801 5802 5803 5804 5805 5806 5807 5808
		else
			ereport(FATAL,
					(errmsg("unrecognized recovery parameter \"%s\"",
							tok1)));
	}

	FreeFile(fd);

B
Bruce Momjian 已提交
5809 5810
	if (syntaxError)
		ereport(FATAL,
5811 5812
				(errmsg("syntax error in recovery command file: %s",
						cmdline),
B
Bruce Momjian 已提交
5813
			  errhint("Lines should have the format parameter = 'value'.")));
5814 5815

	/*
5816
	 * Check for compulsory parameters
5817
	 */
5818
	if (StandbyModeRequested)
5819
	{
5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831
		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)));
5832
	}
5833 5834 5835 5836 5837 5838
}

/*
 * Exit archive-recovery state
 */
static void
5839
exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
5840
{
B
Bruce Momjian 已提交
5841 5842
	char		recoveryPath[MAXPGPATH];
	char		xlogpath[MAXPGPATH];
5843
	char		*xlogDir = NULL;
5844 5845

	/*
B
Bruce Momjian 已提交
5846 5847 5848
	 * We should have the ending log segment currently open.  Verify, and then
	 * close it (to avoid problems on Windows with trying to rename or delete
	 * an open file).
5849 5850 5851 5852 5853 5854 5855 5856 5857
	 */
	Assert(readFile >= 0);
	Assert(readId == endLogId);
	Assert(readSeg == endLogSeg);

	close(readFile);
	readFile = -1;

	/*
B
Bruce Momjian 已提交
5858 5859 5860 5861 5862 5863 5864
	 * 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.
5865
	 *
5866 5867
	 * 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
5868 5869
	 * of overwriting any existing file.  (This is, in fact, always the case
	 * at present.)
5870
	 */
5871 5872 5873 5874 5875
	xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
	if (snprintf(recoveryPath, MAXPGPATH, "%s/RECOVERYXLOG", xlogDir) > MAXPGPATH)
	{
		ereport(ERROR, (errmsg("cannot generate path %s/RECOVERYXLOG", xlogDir)));	
	}
5876
	XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
5877 5878 5879 5880 5881 5882 5883 5884 5885 5886

	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(),
5887
					 errmsg("could not rename file \"%s\" to \"%s\": %m",
5888 5889 5890 5891 5892 5893 5894 5895 5896 5897
							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 已提交
5898

5899
		/*
B
Bruce Momjian 已提交
5900 5901 5902
		 * 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.
5903 5904 5905 5906
		 */
		if (endTLI != ThisTimeLineID)
			XLogFileCopy(endLogId, endLogSeg,
						 endTLI, endLogId, endLogSeg);
5907 5908 5909
	}

	/*
B
Bruce Momjian 已提交
5910 5911
	 * Let's just make real sure there are not .ready or .done flags posted
	 * for the new segment.
5912
	 */
5913 5914
	XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
	XLogArchiveCleanup(xlogpath);
5915

5916
	/* Get rid of any remaining recovered timeline-history file, too */
5917 5918 5919 5920
	if (snprintf(recoveryPath, MAXPGPATH, "%s/RECOVERYHISTORY", xlogDir) > MAXPGPATH)
	{
		ereport(ERROR, (errmsg("cannot generate path %s/RECOVERYHISTORY", xlogDir)));
	}
B
Bruce Momjian 已提交
5921
	unlink(recoveryPath);		/* ignore any error */
5922 5923

	/*
B
Bruce Momjian 已提交
5924 5925
	 * Rename the config file out of the way, so that we don't accidentally
	 * re-enter archive recovery mode in a subsequent crash.
5926
	 */
5927 5928
	unlink(RECOVERY_COMMAND_DONE);
	if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
5929 5930
		ereport(FATAL,
				(errcode_for_file_access(),
5931
				 errmsg("could not rename file \"%s\" to \"%s\": %m",
5932
						RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
5933

5934
	pfree(xlogDir);
5935 5936 5937 5938 5939 5940 5941 5942
}

/*
 * 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.
5943 5944 5945
 *
 * We also track the timestamp of the latest applied COMMIT/ABORT record
 * in recoveryLastXTime, for logging purposes.
5946 5947
 * Also, some information is saved in recoveryStopXid et al for use in
 * annotating the new timeline's history file.
5948 5949 5950 5951 5952
 */
static bool
recoveryStopsHere(XLogRecord *record, bool *includeThis)
{
	bool		stopsHere;
B
Bruce Momjian 已提交
5953
	uint8		record_info;
B
Bruce Momjian 已提交
5954
	TimestampTz recordXtime;
5955 5956 5957 5958 5959 5960 5961

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

		recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
5965
		recordXtime = recordXactCommitData->xact_time;
5966 5967 5968
	}
	else if (record_info == XLOG_XACT_ABORT)
	{
B
Bruce Momjian 已提交
5969
		xl_xact_abort *recordXactAbortData;
5970 5971

		recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
5972
		recordXtime = recordXactAbortData->xact_time;
5973 5974 5975 5976
	}
	else
		return false;

5977 5978
	/* Do we have a PITR target at all? */
	if (!recoveryTarget)
5979 5980
	{
		recoveryLastXTime = recordXtime;
5981
		return false;
5982
	}
5983

5984 5985 5986
	if (recoveryTargetExact)
	{
		/*
B
Bruce Momjian 已提交
5987 5988
		 * there can be only one transaction end record with this exact
		 * transactionid
5989
		 *
B
Bruce Momjian 已提交
5990
		 * when testing for an xid, we MUST test for equality only, since
B
Bruce Momjian 已提交
5991 5992 5993
		 * 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...
5994 5995 5996 5997 5998 5999 6000 6001
		 */
		stopsHere = (record->xl_xid == recoveryTargetXid);
		if (stopsHere)
			*includeThis = recoveryTargetInclusive;
	}
	else
	{
		/*
B
Bruce Momjian 已提交
6002 6003 6004
		 * there can be many transactions that share the same commit time, so
		 * we stop after the last one, if we are inclusive, or stop at the
		 * first one if we are exclusive
6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015
		 */
		if (recoveryTargetInclusive)
			stopsHere = (recordXtime > recoveryTargetTime);
		else
			stopsHere = (recordXtime >= recoveryTargetTime);
		if (stopsHere)
			*includeThis = false;
	}

	if (stopsHere)
	{
6016 6017 6018 6019
		recoveryStopXid = record->xl_xid;
		recoveryStopTime = recordXtime;
		recoveryStopAfter = *includeThis;

6020 6021
		if (record_info == XLOG_XACT_COMMIT)
		{
6022
			if (recoveryStopAfter)
6023 6024
				ereport(LOG,
						(errmsg("recovery stopping after commit of transaction %u, time %s",
6025 6026
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
6027 6028 6029
			else
				ereport(LOG,
						(errmsg("recovery stopping before commit of transaction %u, time %s",
6030 6031
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
6032 6033 6034
		}
		else
		{
6035
			if (recoveryStopAfter)
6036 6037
				ereport(LOG,
						(errmsg("recovery stopping after abort of transaction %u, time %s",
6038 6039
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
6040 6041 6042
			else
				ereport(LOG,
						(errmsg("recovery stopping before abort of transaction %u, time %s",
6043 6044
								recoveryStopXid,
								timestamptz_to_str(recoveryStopTime))));
6045
		}
6046 6047 6048

		if (recoveryStopAfter)
			recoveryLastXTime = recordXtime;
6049
	}
6050 6051
	else
		recoveryLastXTime = recordXtime;
6052 6053 6054 6055

	return stopsHere;
}

6056
/*
6057 6058 6059 6060
 * 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.
6061
 */
6062 6063
static void
SetCurrentChunkStartTime(TimestampTz xtime)
6064
{
6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079
	/* 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;

6080
	XLogRecord *record;
6081
	XLogRecPtr	LastRec;
6082

6083
	/*
6084 6085
	 * Go back to the beginning of the log file and read forward to find
	 * the end of the transaction log.
6086
	 */
6087 6088
	roundedDownLoc.xlogid = loc->xlogid;
	roundedDownLoc.xrecoff = (seg * XLogSegSize) + SizeOfXLogLongPHD;
6089

6090
	XLogCloseReadRecord();
6091

6092 6093 6094 6095 6096 6097 6098
	record = XLogReadRecord(&roundedDownLoc, false, LOG);
	if (record == NULL)
	{
		elog(LOG,"Couldn't read transaction log file (logid %d, seg %d)",
			 loc->xlogid, seg);
		return;
	}
6099

6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134
	do
	{
		LastRec = ReadRecPtr;

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

	record = XLogReadRecord(&LastRec, false, ERROR);

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

	XLogCloseReadRecord();
}

static void
StartupXLOG_InProduction(void)
{
	TransactionId oldestActiveXID;

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

	elog(LOG, "Oldest active transaction from prepared transactions %u", oldestActiveXID);

	/* Start up the commit log and related stuff, too */
	StartupCLOG();
	StartupSUBTRANS(oldestActiveXID);
	StartupMultiXact();
	DistributedLog_Startup(
						oldestActiveXID,
						ShmemVariableCache->nextXid);

	/* Reload shared-memory state for prepared transactions */
	RecoverPreparedTransactions();
6135

6136
	/*
6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152
	 * Perform a checkpoint to update all our recovery activity to disk.
	 *
	 * 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.
	 *
	 * Note that - Creation of shutdown checkpoint changes the state in pg_control.
	 * If that happens when we are standby who was recently promoted, the
	 * state in pg_control indicating promotion phases (e.g. DB_IN_STANDBY_PROMOTION,
	 * DB_INSTANDBY_NEW_TLI_SET) before the checkpoint creation will get
	 * overwritten posing a problem for further flow. Hence, CreateCheckpoint()
	 * has an ungly hack to avoid this situation and thus we avoid change of
	 * pg_control state just in this special situation. CreateCheckpoint() also
	 * has a comment referring this.
6153
	 */
6154
	CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
6155

6156
	/*
6157 6158 6159
	 * If this system was a standby which was promoted (or whose catalog is not
	 * yet updated after promote), we delay going into actual production till Pass4.
	 * Pass4 updates the catalog to comply with the standby promotion changes.
6160
	 */
6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175
	if (ControlFile->state == DB_IN_STANDBY_PROMOTED
		|| ControlFile->state == DB_IN_STANDBY_NEW_TLI_SET)
	{
		ControlFile->state = DB_IN_STANDBY_NEW_TLI_SET;
		ControlFile->time = time(NULL);
		UpdateControlFile();
		ereport(LOG, (errmsg("database system is almost ready")));
	}
	else
	{
		ControlFile->state = DB_IN_PRODUCTION;
		ControlFile->time = time(NULL);
		UpdateControlFile();
		ereport(LOG, (errmsg("database system is ready")));
	}
6176

6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189
	{
		char version[512];

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

#ifdef USE_ASSERT_CHECKING
		strcat(version, " (with assert checking)");
#endif
		ereport(LOG,(errmsg("%s", version)));

	}

	BuildFlatFiles(false);
6190

6191
	/*
6192 6193 6194 6195
	 * 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.)
6196
	 */
6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

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

/*
 * Error context callback for tracing or errors occurring during PASS 1 redo.
 */
static void
StartupXLOG_RedoPass1Context(void *arg)
{
	XLogRecord		*record = (XLogRecord*) arg;

	StringInfoData buf;

	initStringInfo(&buf);
	appendStringInfo(&buf, "REDO PASS 1 @ %s; LSN %s: ",
					 XLogLocationToString(&ReadRecPtr),
					 XLogLocationToString2(&EndRecPtr));
6221
	xlog_outrec(&buf, record);
6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245
	appendStringInfo(&buf, " - ");
	RmgrTable[record->xl_rmid].rm_desc(&buf,
									   ReadRecPtr,
									   record);

	errcontext("%s", buf.data);

	pfree(buf.data);
}

/*
 * Error context callback for tracing or errors occurring during PASS 1 redo.
 */
static void
StartupXLOG_RedoPass3Context(void *arg)
{
	XLogRecord		*record = (XLogRecord*) arg;

	StringInfoData buf;

	initStringInfo(&buf);
	appendStringInfo(&buf, "REDO PASS 3 @ %s; LSN %s: ",
					 XLogLocationToString(&ReadRecPtr),
					 XLogLocationToString2(&EndRecPtr));
6246
	xlog_outrec(&buf, record);
6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 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 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451
	appendStringInfo(&buf, " - ");
	RmgrTable[record->xl_rmid].rm_desc(&buf,
									   ReadRecPtr,
									   record);

	errcontext("%s", buf.data);

	pfree(buf.data);
}


static void
ApplyStartupRedo(
	XLogRecPtr		*beginLoc,

	XLogRecPtr		*lsn,

	XLogRecord		*record)
{
	MIRROREDLOCK_BUFMGR_VERIFY_NO_LOCK_LEAK_DECLARE;
	RedoErrorCallBack redoErrorCallBack;

	ErrorContextCallback errcontext;

	MIRROREDLOCK_BUFMGR_VERIFY_NO_LOCK_LEAK_ENTER;

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

	if (record->xl_info & XLR_BKP_BLOCK_MASK)
		RestoreBkpBlocks(record, *lsn);

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

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

	MIRROREDLOCK_BUFMGR_VERIFY_NO_LOCK_LEAK_EXIT;

}

/*
 * 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)
{
	TMGXACT_CHECKPOINT 	*dtxCheckpoint;
	uint32 				dtxCheckpointLen;
	char				*masterMirroringCheckpoint;
	uint32				masterMirroringCheckpointLen;
	prepared_transaction_agg_state  *ptas = NULL;

	/* In standby mode, empty all master mirroring related hash tables. */
	if (IsStandbyMode())
		mmxlog_empty_hashtables();

	UnpackCheckPointRecord(
						rec,
						&loc,
						&dtxCheckpoint,
						&dtxCheckpointLen,
						&masterMirroringCheckpoint,
						&masterMirroringCheckpointLen,
						(IsStandbyMode() ? PANIC : LOG),
						&ptas);

	if (Debug_persistent_recovery_print && dtxCheckpoint != NULL)
	{
		elog(PersistentRecovery_DebugPrintLevel(),
			 "XLogProcessCheckPoint: Checkpoint record data length = %u, DTX "
			 "committed count %d, DTX data length %u, Master Mirroring "
			 "information length %u, location %s",
			 rec->xl_len,
			 dtxCheckpoint->committedCount,
			 dtxCheckpointLen,
			 masterMirroringCheckpointLen,
			 XLogLocationToString(&loc));

		if (ptas != NULL)
		{
			elog(PersistentRecovery_DebugPrintLevel(),
			"XLogProcessCheckPoint: Checkpoint record prepared transaction "
			"agg state count = %d",
			ptas->count);
		}

		if (masterMirroringCheckpointLen > 0)
		{
			int filespaceCount;
			int tablespaceCount;
			int databaseCount;

			if (mmxlog_get_checkpoint_counts(
									masterMirroringCheckpoint,
									masterMirroringCheckpointLen,
									rec->xl_len,
									&loc,
									/* errlevel */ COMMERROR,
									&filespaceCount,
									&tablespaceCount,
									&databaseCount))
			{
				elog(PersistentRecovery_DebugPrintLevel(),
					 "XLogProcessCheckPoint: master mirroring information: %d "
					 "filespaces, %d tablespaces, %d databases, location %s",
					 filespaceCount,
					 tablespaceCount,
					 databaseCount,
					 XLogLocationToString(&loc));
			}
		}
	}

	/*
	 * Get filespace, tablespace and database info from checkpoint record (master
	 * mirroring part) and maintain them in hash tables.
	 *
	 * We'll perform this only during standby mode because during normal non-standby
	 * recovery Persistent Tables do that job.
	 */
	if (IsStandbyMode() && masterMirroringCheckpoint != NULL)
	{
		mmxlog_read_checkpoint_data(masterMirroringCheckpoint,
									masterMirroringCheckpointLen,
									rec->xl_len,
									&loc);
	}

	/* Handle the DTX information. */
	if (dtxCheckpoint != NULL)
	{
		UtilityModeFindOrCreateDtmRedoFile();
		redoDtxCheckPoint(dtxCheckpoint);
		UtilityModeCloseDtmRedoFile();
	}
}


/*
 * This must be called ONCE during postmaster or standalone-backend startup
 *
 *	How Recovery works ?
 *---------------------------------------------------------------
 *| Clean Shutdown case    	| 	Not Clean Shutdown  case|
 *|(InRecovery = false)		|	(InRecovery = true)	|
 *---------------------------------------------------------------
 *|				|		   |		|
 *|				|record after	   |record after|
 *|				|checkpoint =	   |checkpoint =|
 *|				|NULL		   |NOT NULL	|
 *|				|(bypass Redo  	   |(dont bypass|
 *|				|  	   	   |Redo	|
 *---------------------------------------------------------------
 *|				|		   |		|
 *|	No Redo			|No Redo	   |Redo done	|
 *|	No Recovery Passes	|Recovery Pass done|Recovery 	|
 *|				|		   |Pass done	|
 *---------------------------------------------------------------
 */
void
StartupXLOG(void)
{
	XLogCtlInsert *Insert;
	CheckPoint	checkPoint;
	bool		wasShutdown;
	bool		reachedStopPoint = false;
	bool		haveBackupLabel = false;
	XLogRecPtr	RecPtr,
				LastRec,
				checkPointLoc,
				EndOfLog;
	uint32		endLogId;
	uint32		endLogSeg;
	XLogRecord *record;
	uint32		freespace;
	bool		multipleRecoveryPassesNeeded = false;
	bool		backupEndRequired = false;

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

6452
	if (ControlFile->state < DB_SHUTDOWNED ||
6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463
		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))));
	else if (ControlFile->state == DB_SHUTDOWNING)
		ereport(LOG,
6464
				(errmsg("database system shutdown was interrupted; last known up at %s",
6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495
						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_STANDBY_NEW_TLI_SET)
		ereport(LOG,
				(errmsg("database system was interrupted post new TLI was setup on standby promotion at %s",
						str_time(ControlFile->checkPointCopy.time)),
						 errhint("If this has occurred more than once something unexpected is happening"
						" after standby has been promoted and new TLI has been set"),
				 errSendAlert(true)));
	else if (ControlFile->state == DB_IN_PRODUCTION)
		ereport(LOG,
6496
				(errmsg("database system was interrupted; last known up at %s",
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
						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

	/* Verify that pg_xlog exist */
	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);
6529

6530
	if (StandbyModeRequested)
T
Tom Lane 已提交
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 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592
		Assert(ControlFile->state != DB_IN_CRASH_RECOVERY
				&& ControlFile->state != DB_IN_STANDBY_NEW_TLI_SET);

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

	/*
	 * Save the selected recovery target timeline ID in shared memory so that
	 * other processes can see them
	 */
	XLogCtl->RecoveryTargetTLI = recoveryTargetTLI;

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

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

6593
		/*
B
Bruce Momjian 已提交
6594 6595
		 * When a backup_label file is present, we want to roll forward from
		 * the checkpoint it identifies, rather than using pg_control.
6596
		 */
6597
		record = ReadCheckpointRecord(checkPointLoc, 0);
6598 6599
		if (record != NULL)
		{
6600 6601
			memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
			wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
6602
			ereport(DEBUG1,
6603
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
6604
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
6605
			InRecovery = true;	/* force recovery even if SHUTDOWNED */
6606 6607

			/*
6608 6609 6610 6611
			 * 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.
6612 6613 6614 6615 6616 6617 6618 6619
			 */
			if (XLByteLT(checkPoint.redo, checkPointLoc))
			{
				if (!XLogReadRecord(&(checkPoint.redo), false, LOG))
					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)));
			}
6620 6621 6622
		}
		else
		{
6623
			ereport(FATAL,
B
Bruce Momjian 已提交
6624 6625
					(errmsg("could not locate required checkpoint record"),
					 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6626
			wasShutdown = false; /* keep compiler quiet */
6627
		}
6628 6629
		/* set flag to delete it later */
		haveBackupLabel = true;
T
Tom Lane 已提交
6630 6631 6632
	}
	else
	{
6633 6634 6635 6636 6637 6638
		if (StandbyModeRequested)
		{
			/* Activate recovery in standby mode */
			StandbyMode = true;
		}

6639
		/*
B
Bruce Momjian 已提交
6640 6641
		 * Get the last valid checkpoint record.  If the latest one according
		 * to pg_control is broken, try the next-to-last one.
6642 6643
		 */
		checkPointLoc = ControlFile->checkPoint;
6644 6645
		RedoStartLSN = ControlFile->checkPointCopy.redo;

6646
		record = ReadCheckpointRecord(checkPointLoc, 1);
T
Tom Lane 已提交
6647 6648
		if (record != NULL)
		{
6649
			ereport(DEBUG1,
6650
					(errmsg("checkpoint record is at %X/%X",
B
Bruce Momjian 已提交
6651
							checkPointLoc.xlogid, checkPointLoc.xrecoff)));
T
Tom Lane 已提交
6652
		}
6653 6654 6655 6656 6657 6658 6659 6660 6661
		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 已提交
6662
		else
6663
		{
6664 6665
			printEndOfXLogFile(&checkPointLoc);

6666
			checkPointLoc = ControlFile->prevCheckPoint;
6667
			record = ReadCheckpointRecord(checkPointLoc, 2);
6668 6669 6670
			if (record != NULL)
			{
				ereport(LOG,
B
Bruce Momjian 已提交
6671 6672 6673
						(errmsg("using previous checkpoint record at %X/%X",
							  checkPointLoc.xlogid, checkPointLoc.xrecoff)));
				InRecovery = true;		/* force recovery even if SHUTDOWNED */
6674 6675
			}
			else
6676 6677
			{
				printEndOfXLogFile(&checkPointLoc);
6678
				ereport(PANIC,
B
Bruce Momjian 已提交
6679
					 (errmsg("could not locate a valid checkpoint record")));
6680
			}
6681
		}
6682 6683
		memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
		wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
T
Tom Lane 已提交
6684
	}
6685

T
Tom Lane 已提交
6686
	LastRec = RecPtr = checkPointLoc;
6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702
	XLogCtl->pass1LastCheckpointLoc = checkPointLoc;

	/*
	 * Currently, standby mode (WAL based replication support) is not provided
	 * to segments.
	 * Hence it's okay to do the following only once on the segments as there
	 * will be only one checkpoint to be analyzed.
	 */
	if (GpIdentity.segindex != MASTER_CONTENT_ID)
		SetupCheckpointPreparedTransactionList(record);

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

6704
	ereport(DEBUG1,
B
Bruce Momjian 已提交
6705 6706 6707
			(errmsg("redo record is at %X/%X; shutdown %s",
					checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
					wasShutdown ? "TRUE" : "FALSE")));
6708
	ereport(DEBUG1,
6709 6710 6711
			(errmsg("next transaction ID: %u/%u; next OID: %u",
					checkPoint.nextXidEpoch, checkPoint.nextXid,
					checkPoint.nextOid)));
6712
	ereport(DEBUG1,
6713 6714
			(errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
					checkPoint.nextMulti, checkPoint.nextMultiOffset)));
6715

6716
	if (!TransactionIdIsNormal(checkPoint.nextXid))
6717
		ereport(PANIC,
6718
				(errmsg("invalid next transaction ID")));
6719

6720
	/* initialize shared memory variables from the checkpoint record */
6721 6722
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
6723
	ShmemVariableCache->oidCount = 0;
6724
	MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
6725 6726
	XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
	XLogCtl->ckptXid = checkPoint.nextXid;
6727

6728 6729 6730
	/* also initialize latestCompletedXid, to nextXid - 1 */
	ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
	TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);
6731

6732
	/*
B
Bruce Momjian 已提交
6733 6734 6735
	 * 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()).
6736
	 */
6737
	ThisTimeLineID = checkPoint.ThisTimeLineID;
6738

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

6741
	if (XLByteLT(RecPtr, checkPoint.redo))
6742 6743
		ereport(PANIC,
				(errmsg("invalid redo in checkpoint record")));
6744

6745
	/*
B
Bruce Momjian 已提交
6746
	 * Check whether we need to force recovery from WAL.  If it appears to
B
Bruce Momjian 已提交
6747 6748
	 * have been a clean shutdown and we did not have a recovery.conf file,
	 * then assume no recovery needed.
6749
	 */
6750
	if (XLByteLT(checkPoint.redo, RecPtr))
6751
	{
T
Tom Lane 已提交
6752
		if (wasShutdown)
6753
			ereport(PANIC,
B
Bruce Momjian 已提交
6754
					(errmsg("invalid redo record in shutdown checkpoint")));
V
WAL  
Vadim B. Mikheev 已提交
6755
		InRecovery = true;
6756
	}
6757
	else if (StandbyModeRequested)
6758 6759
	{
		/* force recovery due to presence of recovery.conf */
6760 6761
		ereport(LOG,
				(errmsg("setting recovery standby mode active")));
6762 6763
		InRecovery = true;
	}
6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777
	else if (ControlFile->state != DB_SHUTDOWNED)
		InRecovery = true;

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

	if (InRecovery && gp_before_persistence_work)
	{
		ereport(FATAL,
				(errmsg("Database must be shutdown cleanly when using gp_before_persistence_work = on")));
	}
6778

6779
	/* Recovery from xlog */
6780
	if (InRecovery)
6781
	{
B
Bruce Momjian 已提交
6782
		int			rmid;
6783

6784 6785 6786
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

6787
		/*
B
Bruce Momjian 已提交
6788 6789
		 * 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
6790
		 * pg_control with any minimum recovery stop point
6791
		 */
6792
		if (StandbyMode)
6793
		{
6794
			ereport(LOG,
6795 6796
					(errmsg("recovery in standby mode in progress")));
			ControlFile->state = DB_IN_STANDBY_MODE;
6797
		}
6798
		else
6799
		{
6800
			ereport(LOG,
6801 6802
					(errmsg("database system was not properly shut down; "
							"automatic recovery in progress")));
6803 6804 6805 6806

			if (ControlFile->state != DB_IN_STANDBY_PROMOTED
				&& ControlFile->state != DB_IN_STANDBY_NEW_TLI_SET)
				ControlFile->state = DB_IN_CRASH_RECOVERY;
6807
		}
6808

6809 6810 6811
		ControlFile->prevCheckPoint = ControlFile->checkPoint;
		ControlFile->checkPoint = checkPointLoc;
		ControlFile->checkPointCopy = checkPoint;
6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827

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

		/* Set backupStartPoint if we're starting recovery from a base backup. */
		if (haveBackupLabel)
		{
			Assert(ControlFile->state == DB_IN_STANDBY_MODE);
			ControlFile->backupStartPoint = checkPoint.redo;
			ControlFile->backupEndRequired = backupEndRequired;
		}

6828 6829 6830
		ControlFile->time = time(NULL);
		UpdateControlFile();

6831 6832
		pgstat_reset_all();

6833
		/*
B
Bruce Momjian 已提交
6834 6835 6836 6837 6838 6839
		 * 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.
6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850
		 */
		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)));
		}

6851
		/* Start up the recovery environment */
V
WAL  
Vadim B. Mikheev 已提交
6852
		XLogInitRelationCache();
V
Vadim B. Mikheev 已提交
6853

6854 6855
		UtilityModeFindOrCreateDtmRedoFile();

6856 6857 6858 6859 6860 6861
		for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
		{
			if (RmgrTable[rmid].rm_startup != NULL)
				RmgrTable[rmid].rm_startup();
		}

6862
		/*
6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882
		 * Initialize shared lastReplayedEndRecPtr.
		 *
		 * This is slightly confusing if we're starting from an online
		 * checkpoint; we've just read and replayed the chekpoint record, but
		 * we're going to start replay from its redo pointer, which precedes
		 * the location of the checkpoint record itself. So even though the
		 * last record we've replayed is indeed ReadRecPtr, we haven't
		 * replayed all the preceding records yet. That's OK for the current
		 * use of these variables.
		 */
		SpinLockAcquire(&xlogctl->info_lck);
		xlogctl->lastReplayedEndRecPtr = EndRecPtr;
		xlogctl->currentChunkStartTime = 0;
		SpinLockRelease(&xlogctl->info_lck);

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

		/*
		 * Find the first record that logically follows the checkpoint --- it
B
Bruce Momjian 已提交
6883
		 * might physically precede it, though.
6884
		 */
6885
		if (XLByteLT(checkPoint.redo, RecPtr))
6886 6887
		{
			/* back up to find the record */
6888
			record = XLogReadRecord(&(checkPoint.redo), false, PANIC);
6889
		}
B
Bruce Momjian 已提交
6890
		else
6891
		{
6892
			/* just have to read next record after CheckPoint */
6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908
			record = XLogReadRecord(NULL, false, LOG);
		}

		/*
		 * In case where its not a clean shutdown but it doesn't have a record
		 * following the checkpoint record, just proceed with the Pass 2, 3, 4
		 * to clear any inconsistent entries in Persistent Tables without
		 * doing the whole redo loop below.
		 */
		if (record == NULL)	
		{
			/*
			 * There are no WAL records following the checkpoint
			 */
			ereport(LOG,
					(errmsg("no record for redo after checkpoint, skip redo and proceed for recovery pass")));
6909
		}
6910

6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923
		XLogCtl->pass1StartLoc = ReadRecPtr;

		/*
		 * MPP-11179
		 * Recovery Passes will be done in both the cases:
		 * 1. When record after checkpoint = NULL (No redo)
		 * 2. When record after checkpoint != NULL (redo also)
		 */
		multipleRecoveryPassesNeeded = true;

		/*
		 * main redo apply loop, executed if we have record after checkpoint
		 */
T
Tom Lane 已提交
6924
		if (record != NULL)
6925
		{
6926 6927
			bool		recoveryContinue = true;
			bool		recoveryApply = true;
V
WAL  
Vadim B. Mikheev 已提交
6928
			InRedo = true;
6929 6930
			bool		lastReadRecWasCheckpoint=false;
			CurrentResourceOwner = ResourceOwnerCreate(NULL, "xlog");
6931

6932 6933 6934
			ereport(LOG,
						(errmsg("redo starts at %X/%X",
								ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
6935 6936
			do
			{
6937 6938 6939
				ErrorContextCallback errcontext;

				HandleStartupProcInterrupts();
V
WAL  
Vadim B. Mikheev 已提交
6940

6941 6942 6943 6944 6945
				/*
				 * Have we reached our recovery target?
				 */
				if (recoveryStopsHere(record, &recoveryApply))
				{
B
Bruce Momjian 已提交
6946
					reachedStopPoint = true;	/* see below */
6947 6948 6949 6950 6951
					recoveryContinue = false;
					if (!recoveryApply)
						break;
				}

6952
				errcontext.callback = StartupXLOG_RedoPass1Context;
6953 6954 6955 6956
				errcontext.arg = (void *) record;
				errcontext.previous = error_context_stack;
				error_context_stack = &errcontext;

6957 6958 6959 6960 6961 6962 6963
				/*
				 * Replay every XLog record read in continuous recovery (standby) mode
				 * But while in normal crash recovery mode apply only Persistent
				 * Tables' related XLog records
				 */
				if (IsStandbyMode() ||
					PersistentRecovery_ShouldHandlePass1XLogRec(&ReadRecPtr, &EndRecPtr, record))
6964
				{
6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981
					/*
					 * 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
					 */
					uint8 xlogRecInfo = record->xl_info & ~XLR_INFO_MASK;

					if (IsStandbyMode() &&
						record->xl_rmid == RM_XLOG_ID &&
						(xlogRecInfo == XLOG_CHECKPOINT_SHUTDOWN
						|| xlogRecInfo == XLOG_CHECKPOINT_ONLINE))
					{
						XLogProcessCheckpointRecord(record, ReadRecPtr);
						XLogCtl->pass1LastCheckpointLoc = ReadRecPtr;
						memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
						lastReadRecWasCheckpoint = true;
					}
6982

6983
					ApplyStartupRedo(&ReadRecPtr, &EndRecPtr, record);
6984

6985 6986 6987 6988 6989 6990 6991 6992
					/*
					 * Update lastReplayedEndRecPtr after this record has been
					 * successfully replayed.
					 */
					SpinLockAcquire(&xlogctl->info_lck);
					xlogctl->lastReplayedEndRecPtr = EndRecPtr;
					SpinLockRelease(&xlogctl->info_lck);
				}
6993

6994 6995 6996
				/* Pop the error context stack */
				error_context_stack = errcontext.previous;

6997 6998
				LastRec = ReadRecPtr;

6999
				record = XLogReadRecord(NULL, false, LOG);
B
Bruce Momjian 已提交
7000

7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019
				/*
				 *  If the last (actually it is last-to-last in case there is any
				 *  record after the latest checkpoint record during the reading
				 *  the Xlog records) record is a checkpoint, then startlocation
				 *  for Pass 1 should be decided
				 *
				 *  This step looks redundant in case of normal recovery (no
				 *  standby mode) but its not that costly.
				 */
				if (lastReadRecWasCheckpoint)
				{
					if (XLByteLT(checkPoint.redo, RecPtr))
						XLogCtl->pass1StartLoc = checkPoint.redo;
					else
						XLogCtl->pass1StartLoc = ReadRecPtr;
					lastReadRecWasCheckpoint = false;
				}

			} while (record != NULL && recoveryContinue);
7020

7021
			CurrentResourceOwner = NULL;
7022

7023 7024 7025
			ereport(LOG,
					(errmsg("redo done at %X/%X",
							ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
7026

7027 7028
			if (recoveryLastXTime)
				ereport(LOG,
B
Bruce Momjian 已提交
7029 7030
					 (errmsg("last completed transaction was at log time %s",
							 timestamptz_to_str(recoveryLastXTime))));
V
WAL  
Vadim B. Mikheev 已提交
7031
			InRedo = false;
7032
		}
7033 7034 7035
		/*
		 * end of main redo apply loop
		 */
V
WAL  
Vadim B. Mikheev 已提交
7036 7037
	}

T
Tom Lane 已提交
7038
	/*
7039 7040 7041
	 * 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 已提交
7042
	 */
7043
	ShutdownWalRcv();
7044

7045
	/*
7046 7047 7048 7049 7050 7051 7052 7053
	 * 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.
7054
	 */
7055
	if (StandbyMode)
7056
	{
7057 7058 7059 7060 7061 7062 7063
		Assert(ControlFile->state == DB_IN_STANDBY_MODE);
		StandbyMode = false;

		/* Transition to promoted mode */
		ControlFile->state = DB_IN_STANDBY_PROMOTED;
		ControlFile->time = time(NULL);
		UpdateControlFile();
7064 7065
	}

7066
	/*
7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080
	 * 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.
	 */
	record = XLogReadRecord(&LastRec, false, PANIC);
	EndOfLog = EndRecPtr;
	XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);

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

	XLogCtl->pass1LastLoc = ReadRecPtr;

	/*
	 * Complain if we did not roll forward far enough to render the backup
7081
	 * dump consistent.
7082
	 */
7083 7084 7085
	if (InRecovery &&
		(XLByteLT(EndOfLog, ControlFile->minRecoveryPoint) ||
		 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint)))
7086
	{
7087
		if (reachedStopPoint)	/* stopped because of stop request */
7088 7089
			ereport(FATAL,
					(errmsg("requested recovery stop point is before end time of backup dump")));
B
Bruce Momjian 已提交
7090
		else	/* ran off end of WAL */
7091 7092 7093 7094
			ereport(FATAL,
					(errmsg("WAL ends before end time of backup dump")));
	}

7095 7096 7097
	/*
	 * Consider whether we need to assign a new timeline ID.
	 *
B
Bruce Momjian 已提交
7098 7099
	 * 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
7100 7101
	 * during recovery, then we are clearly generating a new timeline and must
	 * assign it a unique new ID.  Even if we ran to the end, modifying the
B
Bruce Momjian 已提交
7102 7103
	 * current last segment is problematic because it may result in trying to
	 * overwrite an already-archived copy of that segment, and we encourage
7104 7105 7106 7107
	 * 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.
7108 7109
	 *
	 * GPDB: Greenplum doesn't support archive recovery.
7110
	 */
7111
	if (false /*InArchiveRecovery */)
7112
	{
7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135
		/*
		 * 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.
		 */
		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")));
		}
7136 7137 7138 7139 7140
	}

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

7141 7142 7143 7144 7145 7146 7147
	/*
	 * 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;
7148 7149 7150 7151
	XLogFileOpen(
			&mirroredLogFileOpen,
			openLogId,
			openLogSeg);
T
Tom Lane 已提交
7152
	openLogOff = 0;
V
WAL  
Vadim B. Mikheev 已提交
7153
	Insert = &XLogCtl->Insert;
7154
	Insert->PrevRecord = LastRec;
7155 7156
	XLogCtl->xlblocks[0].xlogid = openLogId;
	XLogCtl->xlblocks[0].xrecoff =
7157
		((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
B
Bruce Momjian 已提交
7158 7159

	/*
B
Bruce Momjian 已提交
7160 7161 7162
	 * 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 已提交
7163
	 */
7164 7165
	Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
	memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
7166
	Insert->currpos = (char *) Insert->currpage +
7167
		(EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
V
WAL  
Vadim B. Mikheev 已提交
7168

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

T
Tom Lane 已提交
7171 7172 7173
	XLogCtl->Write.LogwrtResult = LogwrtResult;
	Insert->LogwrtResult = LogwrtResult;
	XLogCtl->LogwrtResult = LogwrtResult;
V
WAL  
Vadim B. Mikheev 已提交
7174

T
Tom Lane 已提交
7175 7176
	XLogCtl->LogwrtRqst.Write = EndOfLog;
	XLogCtl->LogwrtRqst.Flush = EndOfLog;
7177

7178 7179 7180 7181 7182 7183 7184 7185 7186 7187
	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 已提交
7188 7189
		 * Whenever Write.LogwrtResult points to exactly the end of a page,
		 * Write.curridx must point to the *next* page (see XLogWrite()).
7190
		 *
B
Bruce Momjian 已提交
7191
		 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
B
Bruce Momjian 已提交
7192
		 * this is sufficient.	The first actual attempt to insert a log
7193
		 * record will advance the insert state.
7194 7195 7196 7197
		 */
		XLogCtl->Write.curridx = NextBufIdx(0);
	}

V
WAL  
Vadim B. Mikheev 已提交
7198
	if (InRecovery)
7199
	{
7200 7201 7202
		/*
		 * Close down Recovery for Startup PASS 1.
		 */
B
Bruce Momjian 已提交
7203
		int			rmid;
7204 7205 7206 7207 7208 7209 7210 7211 7212 7213

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

7214 7215 7216 7217 7218 7219
		/*
		 * Check to see if the XLOG sequence contained any unresolved
		 * references to uninitialized pages.
		 */
		XLogCheckInvalidPages();

7220 7221 7222 7223 7224
		/*
		 * Reset pgstat data, because it may be invalid after recovery.
		 */
		pgstat_reset_all();

T
Tom Lane 已提交
7225
		/*
7226 7227
		 * We are not finished with multiple passes, so we do not do a
		 * shutdown checkpoint here as we did in the past.
7228
		 *
7229
		 * We only flush out the Resource Managers.
T
Tom Lane 已提交
7230
		 */
7231
		Checkpoint_RecoveryPass(XLogCtl->pass1LastLoc);
7232 7233 7234 7235

		/*
		 * Close down recovery environment
		 */
V
WAL  
Vadim B. Mikheev 已提交
7236
		XLogCloseRelationCache();
7237 7238

		UtilityModeCloseDtmRedoFile();
7239
	}
7240

T
Tom Lane 已提交
7241 7242 7243
	/*
	 * Preallocate additional log files, if wanted.
	 */
7244
	PreallocXlogFiles(EndOfLog);
7245

7246
	/*
7247
	 * Okay, we're finished with Pass 1.
7248
	 */
V
WAL  
Vadim B. Mikheev 已提交
7249
	InRecovery = false;
7250

7251 7252 7253
	/* start the archive_timeout timer running */
	XLogCtl->Write.lastSegSwitchTime = ControlFile->time;

7254 7255 7256 7257
	/* initialize shared-memory copy of latest checkpoint XID/epoch */
	XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
	XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;

7258 7259 7260 7261 7262 7263 7264
	if (!gp_before_persistence_work)
	{
		/*
		 * Create a resource owner to keep track of our resources (currently only
		 * buffer pins).
		 */
		CurrentResourceOwner = ResourceOwnerCreate(NULL, "StartupXLOG");
7265

7266 7267 7268 7269 7270
		/*
		 * We don't have any hope of running a real relcache, but we can use the
		 * same fake-relcache facility that WAL replay uses.
		 */
		XLogInitRelationCache();
7271

A
Asim R P 已提交
7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287
		/*
		 * Setup syscache so that PT tuples may be updated using usual
		 * heap access methods.  This is safe because:
		 *
		 *   1. Catalog cache is backend local.
		 *
		 *   2. The backend handling this pass (pass 1) of recovery is
		 *   about to exit.  Rebuilding PT is the last operation
		 *   performed by this backend.
		 *
		 *   3. At the beginning of pass 2, we are initializing
		 *   catlaog cache, see StartupProcessMain()
		 */
		if (IsUnderPostmaster)
			InitCatalogCache();

7288 7289 7290 7291 7292
		/*
		 * During startup after we have performed recovery is the only place we
		 * scan in the persistent meta-data into memory on already initdb database.
		 */
		PersistentFileSysObj_StartupInitScan();
7293

7294 7295 7296 7297
		/*
		 * Close down recovery environment
		 */
		XLogCloseRelationCache();
7298
	}
T
Tom Lane 已提交
7299

7300
	if (!IsUnderPostmaster)
T
Tom Lane 已提交
7301
	{
7302
		Assert(!multipleRecoveryPassesNeeded);
T
Tom Lane 已提交
7303

7304
		StartupXLOG_InProduction();
T
Tom Lane 已提交
7305

7306 7307 7308 7309
		ereport(LOG,
				(errmsg("Finished single backend startup")));
	}
	else
T
Tom Lane 已提交
7310
	{
7311 7312 7313
		XLogCtl->multipleRecoveryPassesNeeded = multipleRecoveryPassesNeeded;

		if (!gp_startup_integrity_checks)
7314
		{
7315 7316
			ereport(LOG,
					(errmsg("Integrity checks will be skipped because gp_startup_integrity_checks = off")));
7317
		}
7318
		else
7319
		{
7320
			XLogCtl->integrityCheckNeeded = true;
7321
		}
7322 7323

		if (!XLogCtl->multipleRecoveryPassesNeeded)
7324
		{
7325 7326 7327 7328 7329
			StartupXLOG_InProduction();

			ereport(LOG,
					(errmsg("Finished normal startup for clean shutdown case")));

7330
		}
7331
		else
7332
		{
7333 7334
			ereport(LOG,
					(errmsg("Finished startup pass 1.  Proceeding to startup crash recovery passes 2 and 3.")));
7335
		}
T
Tom Lane 已提交
7336
	}
7337 7338

	XLogCloseReadRecord();
7339 7340
}

7341
bool XLogStartupMultipleRecoveryPassesNeeded(void)
V
WAL  
Vadim B. Mikheev 已提交
7342
{
7343 7344
	Assert(XLogCtl != NULL);
	return XLogCtl->multipleRecoveryPassesNeeded;
7345 7346
}

7347
bool XLogStartupIntegrityCheckNeeded(void)
7348
{
7349 7350 7351
	Assert(XLogCtl != NULL);
	return XLogCtl->integrityCheckNeeded;
}
7352

7353 7354 7355 7356 7357 7358 7359 7360 7361
static void
GetRedoRelationFileName(char *path)
{
	char *xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
	if (snprintf(path, MAXPGPATH, "%s/RedoRelationFile", xlogDir) > MAXPGPATH)
	{
		ereport(ERROR, (errmsg("cannot generate pathname %s/RedoRelationFile", xlogDir)));
	}
	pfree(xlogDir);
V
WAL  
Vadim B. Mikheev 已提交
7362 7363
}

7364 7365
static int
CreateRedoRelationFile(void)
7366
{
7367
	char	path[MAXPGPATH];
7368

7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380
	int		result;

	GetRedoRelationFileName(path);

	result = open(path, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
	if (result < 0)
	{
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create redo relation file \"%s\"",
						path)));
	}
7381 7382 7383 7384

	return result;
}

7385 7386
static int
OpenRedoRelationFile(void)
7387
{
7388
	char	path[MAXPGPATH];
7389

7390
	int		result;
7391

7392
	GetRedoRelationFileName(path);
7393

7394 7395 7396 7397 7398 7399 7400 7401
	result = open(path, O_RDONLY, S_IRUSR | S_IWUSR);
	if (result < 0)
	{
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not open redo relation file \"%s\"",
						path)));
	}
7402

7403
	return result;
7404 7405
}

7406 7407
static void
UnlinkRedoRelationFile(void)
7408
{
7409
	char	path[MAXPGPATH];
7410

7411
	GetRedoRelationFileName(path);
7412

7413 7414 7415 7416
	if (unlink(path) < 0)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not unlink redo relation file \"%s\": %m", path)));
7417 7418
}

T
Tom Lane 已提交
7419
/*
7420
 * This must be called ONCE during postmaster or standalone-backend startup
T
Tom Lane 已提交
7421
 */
7422
void
7423
StartupXLOG_Pass2(void)
7424
{
7425
	XLogRecord *record;
V
Vadim B. Mikheev 已提交
7426

7427 7428 7429 7430 7431
	int redoRelationFile;

	if (Debug_persistent_recovery_print)
		elog(PersistentRecovery_DebugPrintLevel(),
		     "Entering StartupXLOG_Pass2");
7432

7433
	/*
7434
	 * Read control file and verify XLOG status looks valid.
7435
	 */
7436
	ReadControlFile();
7437

7438
	if (ControlFile->state < DB_SHUTDOWNED ||
7439 7440 7441 7442
		ControlFile->state > DB_IN_PRODUCTION ||
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
		ereport(FATAL,
				(errmsg("Startup Pass 2: control file contains invalid data")));
T
Tom Lane 已提交
7443

7444 7445
	recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
	XLogCtl->RecoveryTargetTLI = recoveryTargetTLI;
7446

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

7450 7451 7452 7453 7454
	if (Debug_persistent_recovery_print)
		elog(PersistentRecovery_DebugPrintLevel(),
		     "ControlFile with recoveryTargetTLI %u, transaction log to start location is %s",
			 recoveryTargetTLI,
			 XLogLocationToString(&XLogCtl->pass1StartLoc));
T
Tom Lane 已提交
7455

7456
	if (GpIdentity.segindex != MASTER_CONTENT_ID)
T
Tom Lane 已提交
7457
	{
7458 7459 7460 7461 7462 7463
		if (Debug_persistent_recovery_print)
			elog(PersistentRecovery_DebugPrintLevel(),
				"Read the checkpoint record location saved from pass1, "
				"and setup the prepared transation hash list.");
		record = XLogReadRecord(&XLogCtl->pass1LastCheckpointLoc, false, PANIC);
		SetupCheckpointPreparedTransactionList(record);
T
Tom Lane 已提交
7464 7465
	}

7466
	record = XLogReadRecord(&XLogCtl->pass1StartLoc, false, PANIC);
B
Bruce Momjian 已提交
7467

T
Tom Lane 已提交
7468
	/*
7469
	 * Pass 2 XLOG scan
T
Tom Lane 已提交
7470
	 */
7471
	while (true)
7472
	{
7473
		PersistentRecovery_HandlePass2XLogRec(&ReadRecPtr, &EndRecPtr, record);
7474

7475 7476 7477 7478 7479 7480
		if (XLByteEQ(ReadRecPtr, XLogCtl->pass1LastLoc))
			break;

		Assert(XLByteLE(ReadRecPtr,XLogCtl->pass1LastLoc));

		record = XLogReadRecord(NULL, false, PANIC);
7481
	}
7482
	XLogCloseReadRecord();
B
Bruce Momjian 已提交
7483

7484
	PersistentRecovery_Scan();
7485

7486
	PersistentRecovery_CrashAbort();
7487

7488
	PersistentRecovery_Update();
7489

7490
	PersistentRecovery_Drop();
T
Tom Lane 已提交
7491

7492
	PersistentRecovery_UpdateAppendOnlyMirrorResyncEofs();
7493

7494 7495 7496
#ifdef USE_ASSERT_CHECKING
//	PersistentRecovery_VerifyTablesAgainstMemory();
#endif
7497

7498
	Checkpoint_RecoveryPass(XLogCtl->pass1LastLoc);
7499

T
Tom Lane 已提交
7500
	/*
7501
	 * Create a file that passes information to pass 3.
T
Tom Lane 已提交
7502
	 */
7503
	redoRelationFile = CreateRedoRelationFile();
7504

7505
	PersistentRecovery_SerializeRedoRelationFile(redoRelationFile);
7506

7507
	close(redoRelationFile);
7508

7509 7510
	ereport(LOG,
			(errmsg("Finished startup crash recovery pass 2")));
7511

7512 7513 7514 7515
	if (Debug_persistent_recovery_print)
		elog(PersistentRecovery_DebugPrintLevel(),
		     "Exiting StartupXLOG_Pass2");
}
T
Tom Lane 已提交
7516

7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527
/*
 * This must be called ONCE during postmaster or standalone-backend startup
 */
void
StartupXLOG_Pass3(void)
{
	int redoRelationFile;
	XLogRecord *record;
	int 		rmid;
	uint32		endLogId;
	uint32		endLogSeg;
7528

7529 7530 7531
	if (Debug_persistent_recovery_print)
		elog(PersistentRecovery_DebugPrintLevel(),
		     "Entering StartupXLOG_Pass3");
7532

7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545
	redoRelationFile = OpenRedoRelationFile();

	PersistentRecovery_DeserializeRedoRelationFile(redoRelationFile);

	close(redoRelationFile);

	UnlinkRedoRelationFile();

	if (Debug_persistent_recovery_print)
		elog(PersistentRecovery_DebugPrintLevel(),
			 "StartupXLOG_Pass3: Begin re-scanning XLOG");

	InRecovery = true;
7546

T
Tom Lane 已提交
7547
	/*
7548
	 * Read control file and verify XLOG status looks valid.
T
Tom Lane 已提交
7549
	 */
7550
	ReadControlFile();
7551

7552
	if (ControlFile->state < DB_SHUTDOWNED ||
7553 7554 7555 7556
		ControlFile->state > DB_IN_PRODUCTION ||
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
		ereport(FATAL,
				(errmsg("Startup Pass 2: control file contains invalid data")));
7557

7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572
	recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
	XLogCtl->RecoveryTargetTLI = recoveryTargetTLI;

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

	if (Debug_persistent_recovery_print)
	{
		elog(PersistentRecovery_DebugPrintLevel(),
			 "ControlFile with recoveryTargetTLI %u, transaction log to start location is %s",
			 recoveryTargetTLI,
			 XLogLocationToString(&XLogCtl->pass1StartLoc));
		elog(PersistentRecovery_DebugPrintLevel(),
		     "StartupXLOG_RedoPass3Context: Control File checkpoint location is %s",
		     XLogLocationToString(&ControlFile->checkPoint));
7573 7574
	}

7575 7576
	/* Start up the recovery environment */
	XLogInitRelationCache();
7577

7578 7579 7580
	UtilityModeFindOrCreateDtmRedoFile();

	for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
V
Vadim B. Mikheev 已提交
7581
	{
7582 7583
		if (RmgrTable[rmid].rm_startup != NULL)
			RmgrTable[rmid].rm_startup();
V
Vadim B. Mikheev 已提交
7584 7585
	}

7586 7587 7588 7589 7590 7591 7592
	if (GpIdentity.segindex != MASTER_CONTENT_ID)
	{
		record = XLogReadRecord(&XLogCtl->pass1LastCheckpointLoc, false, PANIC);
		SetupCheckpointPreparedTransactionList(record);
	}

	record = XLogReadRecord(&XLogCtl->pass1StartLoc, false, PANIC);
T
Tom Lane 已提交
7593

7594
	/*
7595
	 * Pass 3 XLOG scan
7596
	 */
7597 7598 7599
	while (true)
	{
		ErrorContextCallback errcontext;
7600

7601 7602 7603 7604 7605
		/* Setup error traceback support for ereport() */
		errcontext.callback = StartupXLOG_RedoPass3Context;
		errcontext.arg = (void *) record;
		errcontext.previous = error_context_stack;
		error_context_stack = &errcontext;
7606

7607 7608
		if (PersistentRecovery_ShouldHandlePass3XLogRec(&ReadRecPtr, &EndRecPtr, record))
			ApplyStartupRedo(&ReadRecPtr, &EndRecPtr, record);
V
WAL  
Vadim B. Mikheev 已提交
7609

7610 7611
		/* Pop the error context stack */
		error_context_stack = errcontext.previous;
7612

7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625
		/*
		 * For Pass 3, we read through the new log generated by Pass 2 in case
		 * there are Master Mirror XLOG records we need to take action on.
		 *
		 * It is obscure: Pass 3 REDO of Create fs-obj may need to be compensated for
		 * by Deletes generated in Pass 2...
		 */
		record = XLogReadRecord(NULL, false, LOG);
		if (record == NULL)
			break;
	}

	XLogCloseReadRecord();
7626 7627

	/*
7628 7629 7630 7631 7632 7633 7634 7635
	 * Consider whether we need to assign a new timeline ID.
	 *
	 * If we were in standby mode, we always assign a new ID.
	 * This currently helps for avoiding standby fail-back situation (If the original
	 * primary is down and original standby is acting as the new primary, in such
	 * a case original primary can't act as the new standby to avoid XLog mismatch)
	 *
	 * In a normal crash recovery, we can just extend the timeline we were in.
7636
	 */
7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659
	if (ControlFile->state == DB_IN_STANDBY_PROMOTED)
	{
		/* Read the last XLog record */
		record = XLogReadRecord(&XLogCtl->pass1LastLoc, false, PANIC);
		XLByteToPrevSeg(EndRecPtr, endLogId, endLogSeg);

		ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
		writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
							curFileTLI, endLogId, endLogSeg);
		ereport(LOG,
				(errmsg("selected new timeline ID: %u", ThisTimeLineID)));

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

		/*
		 * We are now done reading the old WAL. Make a writable copy of the last
		 * WAL segment.
		 */
		exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);

		XLogCloseReadRecord();
	}
7660 7661

	/*
7662
	 * Allow resource managers to do any required cleanup.
7663 7664 7665
	 */
	for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
	{
7666 7667
		if (RmgrTable[rmid].rm_cleanup != NULL)
			RmgrTable[rmid].rm_cleanup();
7668 7669 7670
	}

	/*
7671 7672
	 * Check to see if the XLOG sequence contained any unresolved
	 * references to uninitialized pages.
7673
	 */
7674 7675 7676 7677
	XLogCheckInvalidPages();

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

	/*
7680
	 * Close down recovery environment
7681
	 */
7682
	XLogCloseRelationCache();
7683

7684
	UtilityModeCloseDtmRedoFile();
7685

7686 7687 7688
	if (Debug_persistent_recovery_print)
		elog(PersistentRecovery_DebugPrintLevel(),
			 "StartupXLOG_Pass3: End re-scanning XLOG");
7689

7690
	InRecovery = false;
B
Bruce Momjian 已提交
7691

7692 7693 7694 7695 7696 7697 7698 7699
	StartupXLOG_InProduction();

	ereport(LOG,
			(errmsg("Finished startup crash recovery pass 3")));

	if (Debug_persistent_recovery_print)
		elog(PersistentRecovery_DebugPrintLevel(),
			 "Exiting StartupXLOG_Pass3");
7700 7701
}

7702
/*
7703 7704 7705 7706
 * Startup Pass 4 can perform basic integrity checks as well as
 * PersistentTable-Catalog verification (if appropriate GUC is turned on).
 * If the GUC is NOT set --
 * 1. Only basic integrity checks will be performed.
7707
 *
7708 7709 7710 7711 7712 7713 7714 7715 7716 7717
 * If the GUC is set --
 * 1. Both Non-DB specific and DB-specific verification checks
 * are executed to see if the system is consistent.
 * 2. First run of Pass 4 performs basic integrity checks and
 * non-DB specific checks. At the same time, next DB on which DB-specific
 * verifications are to be performed is selected.
 * 3. This DB selected in #2 will be used in the next cycle of Pass 4
 * as a new spawned process for verification purposes. At the same time,
 * a new database is selected for the subsequent cycle and thus this
 * continues until there are no more DBs left to be verified in the system.
7718
 */
7719 7720
void
StartupXLOG_Pass4(void)
7721
{
7722
	bool doPTCatVerification = false;
7723

7724 7725 7726 7727 7728 7729 7730
	/*
	 * Start with the basic Pass 4 integrity checks. If requested (GUC & No In-Doubt
	 * prepared Xacts) then pursue non-database specific integrity checks
	 */
	if(!XLogStartup_DoNextPTCatVerificationIteration())
	{
		PersistentFileSysObj_StartupIntegrityCheck();
7731

7732 7733 7734 7735 7736
		/*
		 * Do the check for inconsistencies in global sequence number after the catalog cache is set up
		 * MPP-17207. Inconsistent global sequence number can be fixed with setting the guc
		 * gp_persistent_repair_global_sequence
		 */
7737

7738 7739
		PersistentFileSysObj_DoGlobalSequenceScan();
		Insist(isFilespaceInfoConsistent());
7740

7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768
		/*
		 * 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 (ControlFile->state == DB_IN_STANDBY_NEW_TLI_SET)
		{
			GpRoleValue old_role = Gp_role;
	
			/* I am privileged */
			InitializeSessionUserIdStandalone();
			/* Start transaction locally */
			Gp_role = GP_ROLE_UTILITY;
			StartTransactionCommand();
			GetTransactionSnapshot();
			DirectFunctionCall1(gp_activate_standby, (Datum) 0);
			/* close the transaction we started above */
			CommitTransactionCommand();
			Gp_role = old_role;

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

			ControlFile->state = DB_IN_PRODUCTION;
			ControlFile->time = time(NULL);
			UpdateControlFile();
			ereport(LOG, (errmsg("database system is ready")));
		}
7769

7770 7771
		ereport(LOG,
			(errmsg("Finished BASIC startup integrity checking")));
7772

7773 7774 7775 7776 7777
		/*
		 * Check if the system has any in-doubt prepared transactions
		 * If No(Yes) - Do(nt) perform extra verification checks
		 */
		if (debug_persistent_ptcat_verification)
T
Tom Lane 已提交
7778
		{
7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797
			/*
			 * As the startup passes are Auxiliary processes and not pure Backeneds
			 * they don't have a user set. Hence, a concrete user id is needed.
			 * Pass 4 may perform some PersistentTable-Catalog verification, which
			 * uses SPI and hence will need a user id set
			 * Set the user id to bootstrap user id to obtain super user rights.
			 */
			if (GpIdentity.segindex != MASTER_CONTENT_ID)
				Gp_role = GP_ROLE_UTILITY;

			SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
			StartTransactionCommand();
			doPTCatVerification = !StartupXLOG_Pass4_CheckIfAnyInDoubtPreparedTransactions();

			/* Perform non-database specific verification checks */
			if (doPTCatVerification)
				StartupXLOG_Pass4_NonDBSpecificPTCatVerification();

			CommitTransactionCommand();
T
Tom Lane 已提交
7798 7799 7800
		}
	}

7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812
	/*
	 * If a database (and thus its tablespace) has already been selected, perform
	 * database specific verifications.
	 *
	 * And then get the first or the next database (and its tablespace) for the first or
	 * next cycle of Pass4 database specific extra verification checks
	 */
	if (doPTCatVerification || XLogStartup_DoNextPTCatVerificationIteration())
	{
		/* Redundant usage to maintain code readability */
		if (GpIdentity.segindex != MASTER_CONTENT_ID)
			Gp_role = GP_ROLE_UTILITY;
7813

7814 7815
		SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
		StartTransactionCommand();
7816

7817 7818
		if(XLogStartup_DoNextPTCatVerificationIteration())
			StartupXLOG_Pass4_DBSpecificPTCatVerification();
T
Tom Lane 已提交
7819

7820
		if (!StartupXLOG_Pass4_GetDBForPTCatVerification())
T
Tom Lane 已提交
7821
		{
7822 7823
			if (!XLogCtl->pass4_PTCatVerificationPassed)
				elog(FATAL,"Startup Pass 4 PersistentTable-Catalog verification failed!!!");
T
Tom Lane 已提交
7824
		}
7825 7826 7827 7828 7829 7830
		else
		{
			if (Gp_role == GP_ROLE_DISPATCH && (GpIdentity.segindex == MASTER_CONTENT_ID))
			{
				bool exists = false;
				postDTMRecv_dbTblSpc_Hash_Entry currentDbTblSpc;
7831

7832 7833 7834 7835
				if (!Persistent_PostDTMRecv_IsHashFull())
				{
					currentDbTblSpc.database = XLogCtl->currentDatabaseToVerify;
					currentDbTblSpc.tablespace = XLogCtl->tablespaceOfCurrentDatabaseToVerify;
7836

7837 7838 7839 7840 7841 7842 7843 7844
					if (Persistent_PostDTMRecv_InsertHashEntry(currentDbTblSpc.database, &currentDbTblSpc, &exists))
					{
						if (exists)
							elog(FATAL,"Database already present in the Hash Table");
					}
				}
			}
		}
7845

7846
		CommitTransactionCommand();
7847
	}
V
WAL  
Vadim B. Mikheev 已提交
7848
}
B
Bruce Momjian 已提交
7849

7850
static bool StartupXLOG_Pass4_CheckIfAnyInDoubtPreparedTransactions(void)
V
WAL  
Vadim B. Mikheev 已提交
7851
{
7852 7853
	bool retVal = false;
	Persistent_Pre_ExecuteQuery();
B
Bruce Momjian 已提交
7854

7855
	PG_TRY();
7856
	{
7857
		int ret = Persistent_ExecuteQuery("select * from pg_prepared_xacts", true);
7858

7859 7860 7861 7862 7863 7864
		if (ret > 0)
			retVal = true;
		else if(ret == 0)
			retVal = false;
		else
			Insist(0);
7865
	}
7866
	PG_CATCH();
7867
	{
7868 7869
		Persistent_ExecuteQuery_Cleanup();
		elog(FATAL, "In-Doubt transaction Check: Failure");
7870
	}
7871
	PG_END_TRY();
V
WAL  
Vadim B. Mikheev 已提交
7872

7873 7874 7875
	Persistent_Post_ExecuteQuery();
	return retVal;
}
7876

7877 7878 7879 7880 7881 7882
/*
 * Indicates if more verification cycles are needed. XLogCtl current database
 * and tablespace act as the flags and also carry database Oid and tablespace Oid
 * for the next cycle of verification.
 */
bool XLogStartup_DoNextPTCatVerificationIteration(void)
V
WAL  
Vadim B. Mikheev 已提交
7883
{
7884 7885 7886
	if (XLogCtl->currentDatabaseToVerify != InvalidOid &&
			XLogCtl->tablespaceOfCurrentDatabaseToVerify != InvalidOid)
		return true;
7887

7888 7889 7890 7891
	Insist(XLogCtl->currentDatabaseToVerify == InvalidOid &&
				XLogCtl->tablespaceOfCurrentDatabaseToVerify == InvalidOid);
		return false;
}
7892

7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915
bool
StartupXLOG_Pass4_GetDBForPTCatVerification(void)
{
	char		*filename;
	FILE		*db_file;
	char		dbName[NAMEDATALEN];
	Oid			dbId= InvalidOid;
	Oid			tblSpaceId = InvalidOid;
	Oid			selectDbId = InvalidOid;
	Oid			selectTblSpaceId = InvalidOid;
	TransactionId dbFrozenxid;
	bool		gotDatabase = false;
	bool		chooseNextDatabase = false;

	filename = database_getflatfilename();
	db_file = AllocateFile(filename, "r");
	if (db_file == NULL)
		ereport(FATAL,
				(errcode_for_file_access(),
				 errmsg("could not open file \"%s\": %m", filename)));

	while (read_pg_database_line(db_file, dbName, &dbId,
								 &tblSpaceId, &dbFrozenxid))
7916
	{
7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937
		Assert(dbId != InvalidOid && tblSpaceId != InvalidOid);
		if(XLogCtl->currentDatabaseToVerify == InvalidOid)
		{
			Assert(XLogCtl->tablespaceOfCurrentDatabaseToVerify == InvalidOid);
			selectDbId = dbId;
			selectTblSpaceId = tblSpaceId;
			gotDatabase = true;
			break;
		}
		else if (XLogCtl->currentDatabaseToVerify == dbId)
		{
			Assert(XLogCtl->tablespaceOfCurrentDatabaseToVerify == tblSpaceId);
			chooseNextDatabase = true;
		}
		else if (chooseNextDatabase)
		{
			selectDbId = dbId;
			selectTblSpaceId = tblSpaceId;
			gotDatabase = true;
			break;
		}
7938 7939
	}

7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957
	FreeFile(db_file);
	pfree(filename);

	XLogCtl->currentDatabaseToVerify = selectDbId;
	XLogCtl->tablespaceOfCurrentDatabaseToVerify = selectTblSpaceId;
	return gotDatabase;
}

/*
 * Perform Verification which is database specific
 * - Currently performed as part of Startup Pass 4
 */
void
StartupXLOG_Pass4_DBSpecificPTCatVerification()
{
	elog(LOG,"DB specific PersistentTable-Catalog Verification using DB %d", MyDatabaseId);
	if (!Persistent_DBSpecificPTCatVerification())
		XLogCtl->pass4_PTCatVerificationPassed = false;
V
WAL  
Vadim B. Mikheev 已提交
7958
}
7959

7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970
/*
 * Perform Verification which is NOT based on particular database
 * - Currently performed as part of Startup Pass 4
 */
void
StartupXLOG_Pass4_NonDBSpecificPTCatVerification(void)
{
	elog(LOG,"Non-DB specific PersistentTable-Catalog Verification using DB %d", MyDatabaseId);
	if (!Persistent_NonDBSpecificPTCatVerification())
		XLogCtl->pass4_PTCatVerificationPassed = false;
}
7971 7972

/*
7973 7974 7975 7976 7977 7978 7979 7980 7981 7982
 * 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.
 *
7983
 */
7984 7985
void
XLogGetRecoveryStart(char *callerStr, char *reasonStr, XLogRecPtr *redoCheckPointLoc, CheckPoint *redoCheckPoint)
7986
{
7987 7988 7989 7990 7991
	CheckPoint	checkPoint;
	XLogRecPtr	checkPointLoc;
	XLogRecord *record;
	bool previous;
	XLogRecPtr checkPointLSN;
7992

7993 7994 7995 7996 7997 7998 7999 8000 8001 8002
	Assert(redoCheckPointLoc != NULL);
	Assert(redoCheckPoint != NULL);

	ereport((Debug_print_qd_mirroring ? LOG : DEBUG1),
			(errmsg("%s: determine restart location %s",
			 callerStr, reasonStr)));

	XLogCloseReadRecord();

	if (Debug_print_qd_mirroring)
8003
	{
8004
		XLogPrintLogNames();
8005
	}
8006 8007 8008 8009 8010 8011 8012

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

8013
	if (ControlFile->state < DB_SHUTDOWNED ||
8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036
		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)
8037
	{
8038 8039 8040 8041 8042 8043
		previous = false;
		ereport((Debug_print_qd_mirroring ? LOG : DEBUG1),
				(errmsg("%s: checkpoint record is at %s (LSN %s)",
						callerStr,
						XLogLocationToString(&checkPointLoc),
						XLogLocationToString2(&EndRecPtr))));
8044
	}
8045
	else
8046
	{
8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064
		previous = true;
		checkPointLoc = ControlFile->prevCheckPoint;
		record = ReadCheckpointRecord(checkPointLoc, 2);
		if (record != NULL)
		{
			ereport((Debug_print_qd_mirroring ? LOG : DEBUG1),
					(errmsg("%s: using previous checkpoint record at %s (LSN %s)",
						    callerStr,
							XLogLocationToString(&checkPointLoc),
						    XLogLocationToString2(&EndRecPtr))));
		}
		else
		{
			FileRep_SetSegmentState(SegmentStateFault, FaultTypeDB);

			ereport(ERROR,
				 (errmsg("%s: could not locate a valid checkpoint record", callerStr)));
		}
8065
	}
8066 8067 8068 8069 8070

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

	if (XLByteEQ(checkPointLoc,checkPoint.redo))
8071
	{
8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082
		{
			char	tmpBuf[FILEREP_MAX_LOG_DESCRIPTION_LEN];

			snprintf(tmpBuf, sizeof(tmpBuf),
					 "control file has restart '%s' and redo start checkpoint at location(lsn) '%s(%s)' ",
					 (previous ? "previous " : ""),
					 XLogLocationToString3(&checkPointLoc),
					 XLogLocationToString4(&checkPointLSN));

			FileRep_InsertConfigLogEntry(tmpBuf);
		}
8083
	}
8084
 	else if (XLByteLT(checkPointLoc, checkPoint.redo))
8085
	{
8086 8087 8088 8089
		FileRep_SetSegmentState(SegmentStateFault, FaultTypeDB);

		ereport(ERROR,
				(errmsg("%s: invalid redo in checkpoint record", callerStr)));
8090 8091
	}
	else
8092 8093
	{
		XLogRecord *record;
8094

8095 8096 8097 8098 8099 8100 8101 8102 8103
		record = XLogReadRecord(&checkPoint.redo, false, LOG);
		if (record == NULL)
		{
			FileRep_SetSegmentState(SegmentStateFault, FaultTypeDB);

			ereport(ERROR,
			 (errmsg("%s: first redo record before checkpoint not found at %s",
					 callerStr, XLogLocationToString(&checkPoint.redo))));
		}
8104

8105
		{
8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116
			char	tmpBuf[FILEREP_MAX_LOG_DESCRIPTION_LEN];

			snprintf(tmpBuf, sizeof(tmpBuf),
					 "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));

			FileRep_InsertConfigLogEntry(tmpBuf);
8117 8118
		}
	}
8119

8120
	XLogCloseReadRecord();
8121

8122 8123 8124 8125
	*redoCheckPointLoc = checkPointLoc;
	*redoCheckPoint = checkPoint;

}
8126 8127

/*
8128 8129 8130 8131 8132 8133 8134
 * 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.
8135
 */
8136 8137
bool
RecoveryInProgress(void)
8138
{
8139 8140 8141 8142 8143 8144 8145 8146
	/*
	 * 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
8147
	{
8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174
		/* 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;
	}
}

/*
 * 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)
 */
8175
static XLogRecord *
8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 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 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 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 8440 8441 8442 8443 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 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 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 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617
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()
	 */
	record = XLogReadRecord(&RecPtr, true /* fetching_checkpoint */, LOG);

	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,

	XLogRecPtr 			*location,

	TMGXACT_CHECKPOINT	**dtxCheckpoint,

	uint32				*dtxCheckpointLen,

	char				**masterMirroringCheckpoint,

	uint32				*masterMirroringCheckpointLen,

	int					errlevelMasterMirroring,

        prepared_transaction_agg_state  **ptas)
{

	*dtxCheckpoint = NULL;
	*dtxCheckpointLen = 0;
	*masterMirroringCheckpoint = NULL;
	*masterMirroringCheckpointLen = 0;
	*ptas = NULL;


	/*********************************************************************************
	  A checkpoint can have four formats (one special, two 4.0, and one 4.1 and later).

	  Special (for bootstrap, xlog switch, maybe others).
	    Checkpoint

	  4.0 QD
	    CheckPoint
            TMGXACT_CHECKPOINT
            fspc_agg_state
            tspc_agg_state
            dbdir_agg_state


	  4.0 QE
            CheckPoint
            TMGXACT_CHECKPOINT

	 4.1 and later
            CheckPoint
            TMGXACT_CHECKPOINT
            fspc_agg_state
            tspc_agg_state
            dbdir_agg_state
            prepared_transaction_agg_state
	**********************************************************************************/

	if (record->xl_len > sizeof(CheckPoint))
	{
		uint32 remainderLen;

		remainderLen = record->xl_len - sizeof(CheckPoint);
		if (remainderLen < TMGXACT_CHECKPOINT_BYTES(0))
		{
			SUPPRESS_ERRCONTEXT_DECLARE;

			SUPPRESS_ERRCONTEXT_PUSH();

			ereport(PANIC,
				 (errmsg("Bad checkpoint record length %u (DTX information header: expected at least length %u, actual length %u) at location %s",
				 		 record->xl_len,
				 		 (uint32)TMGXACT_CHECKPOINT_BYTES(0),
				 		 remainderLen,
				 		 XLogLocationToString(location))));

			SUPPRESS_ERRCONTEXT_POP();
		}

		*dtxCheckpoint = (TMGXACT_CHECKPOINT *)(XLogRecGetData(record) + sizeof(CheckPoint));
		*dtxCheckpointLen = TMGXACT_CHECKPOINT_BYTES((*dtxCheckpoint)->committedCount);
		if (remainderLen < *dtxCheckpointLen)
		{
			SUPPRESS_ERRCONTEXT_DECLARE;

			SUPPRESS_ERRCONTEXT_PUSH();

			ereport(PANIC,
				 (errmsg("Bad checkpoint record length %u (DTX information: expected at least length %u, actual length %u) at location %s",
				 		 record->xl_len,
				 		 *dtxCheckpointLen,
				 		 remainderLen,
				 		 XLogLocationToString(location))));

			SUPPRESS_ERRCONTEXT_POP();
		}

		remainderLen -= *dtxCheckpointLen;

		int mmInfoLen = 0;

		if (remainderLen > 0)
		   {
			*masterMirroringCheckpoint = ((char*)*dtxCheckpoint) + *dtxCheckpointLen;

			/* TODO, The masterMirrongCheckpointLen actually contains the length of the master/mirroring section, */
			/* plus the new 4.1 and later prepared transaction section. This value is used else where, and needs  */
			/* to include the total length of the master/mirror section and anything that follows it.             */
			/* The code should be re-written to be more understandable.                                           */
			*masterMirroringCheckpointLen = remainderLen;

			if (!mmxlog_verify_checkpoint_info(
									*masterMirroringCheckpoint,
									*masterMirroringCheckpointLen,
									record->xl_len,
									location,
									errlevelMasterMirroring))
			   {
			        *masterMirroringCheckpoint = NULL;
			        *masterMirroringCheckpointLen = 0;
			   }
			else
			  {
			    /*
			      This appears to be either a old checkpoint with master/mirror information attached to it,
			      or it is a new (4.1) checkpoint that has the master/mirror information and the prepared
			      transaction information. In either case, get the location of the next byte past the
			      master/mirror section, and use it to determine the section's length.
			    */
			    char *nextPos = mmxlog_get_checkpoint_record_suffix(record);

			    mmInfoLen = nextPos - *masterMirroringCheckpoint;
			  }
		   }

		remainderLen -= mmInfoLen;

		/* This is a fix for MPP-12738 "Alibaba - upgrade from 4.0.4.0 to 4.1 failure"                                 */
		/* Under some circumstances, an old style checkpoint may exist (upgrade switch xlog...).                       */
		/* Check to see if it looks like a new checkpoint. A new checkpoint contains the prepared transaction section. */
		if (remainderLen > 0)
		  {
		    *ptas = (prepared_transaction_agg_state *)mmxlog_get_checkpoint_record_suffix(record);
		  }
		else
		  {
		    elog(WARNING,"UnpackCheckPointRecord: The checkpoint at %s appears to be a 4.0 checkpoint", XLogLocationToString(location));
		  }

	}  /* end if (record->xl_len > sizeof(CheckPoint)) */
}

/*
 * 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;
	/* 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
 */
time_t
GetLastSegSwitchTime(void)
{
	time_t		result;

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

	return result;
}

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

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

	/*
	 * If recovery has not finished, we should not create a checkpoint.
	 * Restart point has been updated by xlog redo in case of recovery.
	 */
	if (!RecoveryInProgress())
8618
		CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686

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

8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741
/*
 * Log start of a checkpoint.
 */
static void
LogCheckpointStart(int flags)
{
	elog(LOG, "checkpoint starting:%s%s%s%s%s%s",
		 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
		 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
		 (flags & CHECKPOINT_FORCE) ? " force" : "",
		 (flags & CHECKPOINT_WAIT) ? " wait" : "",
		 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
		 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
}

/*
 * Log end of a checkpoint.
 */
static void
LogCheckpointEnd(void)
{
	long		write_secs,
				sync_secs,
				total_secs;
	int			write_usecs,
				sync_usecs,
				total_usecs;

	CheckpointStats.ckpt_end_t = GetCurrentTimestamp();

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

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

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

	elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
		 "%d transaction log file(s) added, %d removed, %d recycled; "
		 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
		 CheckpointStats.ckpt_bufs_written,
		 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
		 CheckpointStats.ckpt_segs_added,
		 CheckpointStats.ckpt_segs_removed,
		 CheckpointStats.ckpt_segs_recycled,
		 write_secs, write_usecs / 1000,
		 sync_secs, sync_usecs / 1000,
		 total_secs, total_usecs / 1000);
}

8742 8743 8744 8745 8746 8747 8748
/*
 * Perform a checkpoint --- either during shutdown, or on-the-fly
 *
 * If force is true, we force a checkpoint regardless of whether any XLOG
 * activity has occurred since the last one.
 */
void
8749
CreateCheckPoint(int flags)
8750 8751 8752
{
	MIRRORED_LOCK_DECLARE;

8753
	bool		shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
8754 8755 8756 8757 8758 8759 8760 8761 8762
	CheckPoint	checkPoint;
	XLogRecPtr	recptr;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecData rdata[6];
	char* 		dtxCheckPointInfo;
	int			dtxCheckPointInfoSize;
	uint32		freespace;
	uint32		_logId;
	uint32		_logSeg;
8763 8764
	TransactionId *inCommitXids;
	int			nInCommit;
8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797

	if (Debug_persistent_recovery_print)
	  {
	    elog(PersistentRecovery_DebugPrintLevel(),
                         "CreateCheckPoint: entering..."
		 );
	  }
	if (shutdown && ControlFile->state == DB_STARTUP)
	{
		return;
	}

#ifdef FAULT_INJECTOR
	/* During resync checkpoint has to complete otherwise segment cannot transition into Sync state */
	if (! FileRepResync_IsTransitionFromResyncToInSync())
	{
		if (FaultInjector_InjectFaultIfSet(
										   Checkpoint,
										   DDLNotSpecified,
										   "" /* databaseName */,
										   "" /* tableName */) == FaultInjectorTypeSkip)
			return;  // skip checkpoint
	}
#endif

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

8798 8799 8800 8801 8802 8803 8804 8805 8806 8807
	/*
	 * 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();

8808 8809 8810 8811 8812 8813 8814
	if (FileRepResync_IsTransitionFromResyncToInSync())
	{
		LWLockAcquire(MirroredLock, LW_EXCLUSIVE);

		/* database transitions to suspended state, IO activity on the segment is suspended */
		primaryMirrorSetIOSuspended(TRUE);

8815
		SIMPLE_FAULT_INJECTOR(FileRepTransitionToInSyncBeforeCheckpoint);
8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846
	}
	else
	{
		/*
		 * Normal case.
		 */
		MIRRORED_LOCK;
	}

	/*
	 * 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
		 */
		if (ControlFile->state != DB_IN_STANDBY_PROMOTED
			&& ControlFile->state != DB_IN_STANDBY_NEW_TLI_SET)
		{
			ControlFile->state = DB_SHUTDOWNING;
			ControlFile->time = time(NULL);
			UpdateControlFile();
		}
	}

8847 8848 8849 8850 8851 8852 8853 8854
	/*
	 * 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 */
8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871
	MemSet(&checkPoint, 0, sizeof(checkPoint));
	checkPoint.ThisTimeLineID = ThisTimeLineID;
	checkPoint.time = time(NULL);

	/*
	 * The WRITE_PERSISTENT_STATE_ORDERED_LOCK gets these locks:
	 *    MirroredLock SHARED, and
	 *    CheckpointStartLock SHARED,
	 *    PersistentObjLock EXCLUSIVE.
	 *
	 * 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...
	 *
8872 8873 8874
	 * GPDB_83_MERGE_FIXME: CheckpointStartLock is no more. Do we need to hold something
	 * else instead?
	 * 
8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885
	 * We get the CheckpointStartLock 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, and all buffers have been flushed to disk..
	 *
	 * We must hold CheckpointStartLock while determining the checkpoint REDO
	 * pointer.  This ensures that any concurrent transaction commits will be
	 * either not yet logged, or logged and recorded in pg_clog. See notes in
	 * RecordTransactionCommit().
	 */

8886 8887 8888 8889
	/*
	 * We must hold WALInsertLock while examining insert state to determine
	 * the checkpoint REDO pointer.
	 */
8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906
	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.
	 */
8907
	if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
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 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988
	{
		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);
			if (FileRepResync_IsTransitionFromResyncToInSync())
			{
				LWLockRelease(MirroredLock);
			}
			else
			{
				/*
				 * Normal case.
				 */
				MIRRORED_UNLOCK;
			}
			LWLockRelease(CheckpointLock);

			END_CRIT_SECTION();
			return;
		}
	}

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

	/*
8989 8990
	 * Now we can release WAL insert lock, allowing other xacts to proceed
	 * while we are flushing disk buffers.
8991 8992 8993
	 */
	LWLockRelease(WALInsertLock);

8994 8995 8996 8997 8998 8999
	/*
	 * 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)
		LogCheckpointStart(flags);
9000

9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033
	/*
	 * 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.
	 */
	nInCommit = GetTransactionsInCommit(&inCommitXids);
	if (nInCommit > 0)
	{
		do
		{
			pg_usleep(10000L);	/* wait for 10 msec */
		} while (HaveTransactionsInCommit(inCommitXids, nInCommit));
	}
	pfree(inCommitXids);
9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066

	/*
	 * Get the other info we need for the checkpoint record.
	 */
	LWLockAcquire(XidGenLock, LW_SHARED);
	checkPoint.nextXid = ShmemVariableCache->nextXid;
	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);

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

9067
	CheckPointGuts(checkPoint.redo, flags);
9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 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 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 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 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214

	START_CRIT_SECTION();

	/*
	 * Now insert the checkpoint record into XLOG.
	 */

	getDtxCheckPointInfoAndLock(&dtxCheckPointInfo, &dtxCheckPointInfoSize);

	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;

	/*
	 * Have the master mirror sync code add filespace and tablespace
	 * meta data to keep the standby consistent. Safe to call on segments
	 * as this is a NOOP if we're not the master.
	 */
	mmxlog_append_checkpoint_data(rdata);

	prepared_transaction_agg_state *p = NULL;

	getTwoPhasePreparedTransactionData(&p, "CreateCheckPoint");
	elog(PersistentRecovery_DebugPrintLevel(), "CreateCheckPoint: prepared transactions = %d", p->count);
	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;

	if (Debug_persistent_recovery_print)
	{
		elog(PersistentRecovery_DebugPrintLevel(),
	        "CreateCheckPoint: Regular checkpoint length = %u"
	        ", DTX checkpoint length %u (rdata[1].next is NULL %s)"
	        ", Master mirroring filespace length = %u (rdata[2].next is NULL %s)"
	        ", Master mirroring tablespace length = %u (rdata[3].next is NULL %s)"
	       ", Master mirroring database directory length = %u",
	       rdata[0].len,
	       rdata[1].len,
	       (rdata[1].next == NULL ? "true" : "false"),
	       rdata[2].len,
	       (rdata[2].next == NULL ? "true" : "false"),
	       rdata[3].len,
	       (rdata[3].next == NULL ? "true" : "false"),
	       rdata[4].len);
		elog(PersistentRecovery_DebugPrintLevel(), "CreateCheckPoint; Prepared Transaction length = %u", rdata[5].len);
	}


	/*
	 * 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 (Debug_persistent_recovery_print)
	{
		if (ptrd_oldest_ptr == NULL)
			elog(PersistentRecovery_DebugPrintLevel(), "Oldest Prepared Record = NULL");
		else
			elog(PersistentRecovery_DebugPrintLevel(), "CreateCheckPoint: Oldest Prepared Record = %s",
					XLogLocationToString(ptrd_oldest_ptr));
	}


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

	if (Debug_persistent_recovery_print)
	{
		elog(PersistentRecovery_DebugPrintLevel(),
			 "CreateCheckPoint: Checkpoint location = %s, total length %u, data length %d",
			 XLogLocationToString(&recptr),
			 XLogLastInsertTotalLen(),
			 XLogLastInsertDataLen());
	}

	freeDtxCheckPointInfoAndUnlock(dtxCheckPointInfo, dtxCheckPointInfoSize, &recptr);

	XLogFlush(recptr);

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

	elog((Debug_print_qd_mirroring ? LOG : DEBUG1),
		 "CreateCheckPoint: previous checkpoint's earliest info (copy redo location %s, previous checkpoint location %s)",
		 XLogLocationToString(&ControlFile->checkPointCopy.redo),
		 XLogLocationToString2(&ControlFile->prevCheckPoint));

	/*
	 * Update the control file.
	 */
	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
	if (shutdown)
	{
		/*
		 * Ugly fix to dis-allow changing pg_control state
		 * for standby promotion continuity
		 */
		if (ControlFile->state != DB_IN_STANDBY_PROMOTED
			&& ControlFile->state != DB_IN_STANDBY_NEW_TLI_SET)
			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));
	ControlFile->time = time(NULL);

	/*
	 * Save the last checkpoint position.
	 */
	XLogCtl->haveLastCheckpointLoc = true;
	XLogCtl->lastCheckpointLoc = ProcLastRecPtr;
9215
	XLogCtl->lastCheckpointEndLoc = XactLastRecEnd;
9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232

	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
9233
	 * have trouble while fooling with old log segments.
9234 9235 9236 9237
	 */
	END_CRIT_SECTION();

	/*
9238 9239 9240 9241 9242 9243
	 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
	 */
	smgrpostckpt();

	/*
	 * Delete old log files (those no longer needed even for previous
9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271
	 * checkpoint).
	 */
	if (gp_keep_all_xlog == false && (_logId || _logSeg))
	{
		/* Only for MASTER check this GUC and act */
		if (GpIdentity.segindex == MASTER_CONTENT_ID)
		{
			/*
			 * 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
			 * Currently, applicable to Master only
			 */
			XLogRecPtr xlogCleanUpTo = WalSndCtlGetXLogCleanUpTo();
			if (!XLogRecPtrIsInvalid(xlogCleanUpTo))
			{
				if (XLByteLT(recptr, xlogCleanUpTo))
					xlogCleanUpTo = recptr;
			}
			else
				xlogCleanUpTo = recptr;

			CheckKeepWalSegments(xlogCleanUpTo, &_logId, &_logSeg);
		}

		PrevLogSeg(_logId, _logSeg);
9272
		RemoveOldXlogFiles(_logId, _logSeg, recptr);
9273 9274 9275 9276 9277 9278 9279
	}

	/*
	 * 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)
9280
		PreallocXlogFiles(recptr);
9281 9282 9283 9284 9285 9286 9287 9288 9289

	/*
	 * 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.
	 */
	if (!InRecovery)
9290
		TruncateSUBTRANS(GetOldestXmin(true, false));
9291

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

9296
	/* GPDB_83_MERGE_FIXME: Isn't this redundant with log_checkpoints? */
9297 9298 9299 9300
	if (Debug_persistent_recovery_print)
		elog(PersistentRecovery_DebugPrintLevel(),
			 "CreateCheckPoint: shutdown %s, force %s, checkpoint location %s, redo location %s",
			 (shutdown ? "true" : "false"),
9301
			 ((flags & CHECKPOINT_FORCE) ? "true" : "false"),
9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335
			 XLogLocationToString(&ControlFile->checkPoint),
			 XLogLocationToString2(&checkPoint.redo));

	if (FileRepResync_IsTransitionFromResyncToInSync())
	{
		RequestXLogSwitch();

		FileRepResyncManager_ResyncFlatFiles();

		UpdateControlFile();

		LWLockRelease(MirroredLock);

		/* database is resumed */
		primaryMirrorSetIOSuspended(FALSE);
	}
	else
	{
		/*
		 * Normal case.
		 */
		MIRRORED_UNLOCK;
	}

	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
9336
CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
9337 9338 9339 9340 9341 9342
{
	CheckPointCLOG();
	CheckPointSUBTRANS();
	CheckPointMultiXact();
	CheckPointChangeTracking();
	DistributedLog_CheckPoint();
9343
	CheckPointBuffers(flags);	/* performs all required fsyncs */
9344 9345 9346 9347
	/* We deliberately delay 2PC checkpointing as long as possible */
	CheckPointTwoPhase(checkPointRedo);
}

9348 9349
static void
Checkpoint_RecoveryPass(XLogRecPtr checkPointRedo)
9350
{
9351
	CheckPointGuts(checkPointRedo, CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367
}

/*
 * Set a recovery restart point if appropriate
 *
 * 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.  This function is called each time
 * a checkpoint record is read from XLOG; it must determine whether a
 * restartpoint is needed or not.
 */
static void
RecoveryRestartPoint(const CheckPoint *checkPoint)
{
//	int			elapsed_secs;
	int			rmid;
9368 9369
	uint32 _logId = 0;
	uint32 _logSeg = 0;
9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398

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

	/*
	 * Do nothing if the elapsed time since the last restartpoint is less than
	 * half of checkpoint_timeout.	(We use a value less than
	 * checkpoint_timeout so that variations in the timing of checkpoints on
	 * the master, or speed of transmission of WAL segments to a slave, won't
	 * make the slave skip a restartpoint once it's synced with the master.)
	 * Checking true elapsed time keeps us from doing restartpoints too often
	 * while rapidly scanning large amounts of WAL.
	 */

	// UNDONE: For now, turn this off!
//	elapsed_secs = time(NULL) - ControlFile->time;
//	if (elapsed_secs < CheckPointTimeout / 2)
//		return;

	/*
	 * Is it safe to checkpoint?  We must ask each of the resource managers
	 * whether they have any partial state information that might prevent a
	 * correct restart from this point.  If so, we skip this opportunity, but
	 * return at the next checkpoint record for another try.
	 */
	for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
	{
		if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
			if (!(RmgrTable[rmid].rm_safe_restartpoint()))
9399 9400 9401 9402 9403
			{
				elog(DEBUG2, "RM %d not safe to record restart point at %X/%X",
					 rmid,
					 checkPoint->redo.xlogid,
					 checkPoint->redo.xrecoff);
9404
				return;
9405
			}
9406 9407 9408 9409 9410 9411 9412 9413 9414 9415
	}

	/* Update the shared RedoRecPtr */
	 SpinLockAcquire(&xlogctl->info_lck);
	 xlogctl->Insert.RedoRecPtr = checkPoint->redo;
	 SpinLockRelease(&xlogctl->info_lck);

	/*
	 * OK, force data out to disk
	 */
9416
	CheckPointGuts(checkPoint->redo, CHECKPOINT_IMMEDIATE);
9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445

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

	/*
	 * Update pg_control so that any subsequent crash will restart from this
	 * checkpoint.	Note: ReadRecPtr gives the XLOG address of the checkpoint
	 * record itself.
	 */
	ControlFile->prevCheckPoint = ControlFile->checkPoint;
	ControlFile->checkPoint = ReadRecPtr;
	ControlFile->checkPointCopy = *checkPoint;
	ControlFile->time = time(NULL);

	/*
	 * Save the last checkpoint position.
	 */
	XLogCtl->haveLastCheckpointLoc = true;
	XLogCtl->lastCheckpointLoc = ReadRecPtr;
	XLogCtl->lastCheckpointEndLoc = EndRecPtr;

	UpdateControlFile();

9446
	ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
9447 9448
			(errmsg("recovery restart point at %X/%X",
					checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
9449 9450 9451 9452
	if (recoveryLastXTime)
		ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
				(errmsg("last completed transaction was at log time %s",
						timestamptz_to_str(recoveryLastXTime))));
9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470
	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);
9471
			RemoveOldXlogFiles(_logId, _logSeg, endptr);
9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498
		}
	}
}

/*
 * 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
9499 9500
	 * 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
9501
	 * change may reach disk before the NEXTOID WAL record does.  The impact
9502 9503 9504 9505 9506
	 * 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.
9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 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 9611 9612 9613 9614
	 */
}

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

static void
xlog_redo_print_extended_checkpoint_info(XLogRecPtr beginLoc, XLogRecord *record)
{
	TMGXACT_CHECKPOINT	*dtxCheckpoint;
	uint32				dtxCheckpointLen;
	char				*masterMirroringCheckpoint;
	uint32				masterMirroringCheckpointLen;
	prepared_transaction_agg_state  *ptas;

	/*
	 * The UnpackCheckPointRecord routine will print under the
	 * Debug_persistent_recovery_print GUC.
	 */
	UnpackCheckPointRecord(
						record,
						&beginLoc,
						&dtxCheckpoint,
						&dtxCheckpointLen,
						&masterMirroringCheckpoint,
						&masterMirroringCheckpointLen,
						/* errlevel */ -1,		// Suppress elog altogether on master mirroring checkpoint length checking.
                                                &ptas);
	if (dtxCheckpointLen > 0)
	{
  	        elog(PersistentRecovery_DebugPrintLevel(),
	             "xlog_redo_print_extended_checkpoint_info: Checkpoint record data length = %u, DTX committed count %d, DTX data length %u, Master Mirroring information length %u, location %s",
	             record->xl_len,
	             dtxCheckpoint->committedCount,
	             dtxCheckpointLen,
	             masterMirroringCheckpointLen,
	             XLogLocationToString(&beginLoc));
	        if (ptas != NULL)
  	            elog(PersistentRecovery_DebugPrintLevel(),
		         "xlog_redo_print_extended_checkpoint_info: prepared transaction agg state count = %d",
                          ptas->count);

		if (masterMirroringCheckpointLen > 0)
		{
			int filespaceCount;
			int tablespaceCount;
			int databaseCount;

			if (!mmxlog_get_checkpoint_counts(
									masterMirroringCheckpoint,
									masterMirroringCheckpointLen,
									record->xl_len,
									&beginLoc,
									/* errlevel */ -1,		// Suppress elog altogether on master mirroring checkpoint length checking.
									&filespaceCount,
									&tablespaceCount,
									&databaseCount))
			{
				elog(PersistentRecovery_DebugPrintLevel(),
					 "xlog_redo_print_extended_checkpoint_info: master mirroring information: %d filespaces, %d tablespaces, %d databases, location %s",
					 filespaceCount,
					 tablespaceCount,
					 databaseCount,
					 XLogLocationToString(&beginLoc));
			}
		}
	}
}

/*
 * XLOG resource manager's routines
 *
 * Definitions of info values are in include/catalog/pg_control.h, though
 * not all records types are related to control file processing.
 */
void
xlog_redo(XLogRecPtr beginLoc __attribute__((unused)), XLogRecPtr lsn __attribute__((unused)), XLogRecord *record)
{
	uint8		info = record->xl_info & ~XLR_INFO_MASK;

	if (info == XLOG_NEXTOID)
	{
		Oid			nextOid;

9615 9616 9617 9618 9619 9620
		/*
		 * 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.
		 */
9621
		memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
9622 9623
		ShmemVariableCache->nextOid = nextOid;
		ShmemVariableCache->oidCount = 0;
9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 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 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689
	}
	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;
		MultiXactSetNextMXact(checkPoint.nextMulti,
							  checkPoint.nextMultiOffset);

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

		// Could run into old format checkpoint redo records...
		if (Debug_persistent_recovery_print)
		{
			xlog_redo_print_extended_checkpoint_info(beginLoc, record);
		}
	}
	else if (info == XLOG_CHECKPOINT_ONLINE)
	{
		CheckPoint	checkPoint;

		memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9690
		/* In an ONLINE checkpoint, treat the XID counter as a minimum */
9691 9692 9693
		if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
								  checkPoint.nextXid))
			ShmemVariableCache->nextXid = checkPoint.nextXid;
9694 9695 9696
		/* ... but still treat OID counter as exact */
		ShmemVariableCache->nextOid = checkPoint.nextOid;
		ShmemVariableCache->oidCount = 0;
9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728
		MultiXactAdvanceNextMXact(checkPoint.nextMulti,
								  checkPoint.nextMultiOffset);

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

		// Could run into old format checkpoint redo records...
		if (Debug_persistent_recovery_print)
		{
			xlog_redo_print_extended_checkpoint_info(beginLoc, record);
		}
	}
9729 9730 9731 9732
	else if (info == XLOG_NOOP)
	{
		/* nothing to do here */
	}
9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783
	else if (info == XLOG_SWITCH)
	{
		/* nothing to do here */
	}
	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
			 * pg_stop_backup() was done.
			 * 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);
		}
	}
}

void
xlog_desc(StringInfo buf, XLogRecPtr beginLoc, XLogRecord *record)
{
	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;

		TMGXACT_CHECKPOINT	*dtxCheckpoint;
		uint32				dtxCheckpointLen;
		char				*masterMirroringCheckpoint;
		uint32				masterMirroringCheckpointLen;
		prepared_transaction_agg_state  *ptas;

9784
		appendStringInfo(buf, "checkpoint: redo %X/%X; "
9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846
						 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
						 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
						 checkpoint->ThisTimeLineID,
						 checkpoint->nextXidEpoch, checkpoint->nextXid,
						 checkpoint->nextOid,
						 checkpoint->nextMulti,
						 checkpoint->nextMultiOffset,
				 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");

		/*
		 * The UnpackCheckPointRecord routine will print under the
		 * Debug_persistent_recovery_print GUC.
		 */
		UnpackCheckPointRecord(
							record,
							&beginLoc,
							&dtxCheckpoint,
							&dtxCheckpointLen,
							&masterMirroringCheckpoint,
							&masterMirroringCheckpointLen,
							/* errlevel */ -1, 	// Suppress elog altogether on master mirroring checkpoint length checking.
                                                        &ptas);
		if (dtxCheckpointLen > 0)
		{
			appendStringInfo(buf,
				 ", checkpoint record data length = %u, DTX committed count %d, DTX data length %u, Master Mirroring information length %u",
				 record->xl_len,
				 dtxCheckpoint->committedCount,
				 dtxCheckpointLen,
				 masterMirroringCheckpointLen);
			if (ptas != NULL)
                           appendStringInfo(buf,
                                     ", prepared transaction agg state count = %d",
				      ptas->count);

			if (masterMirroringCheckpointLen > 0)
			  /* KAS this is probably always true for new twophase. */
			{
				int filespaceCount;
				int tablespaceCount;
				int databaseCount;

				if (mmxlog_get_checkpoint_counts(
										masterMirroringCheckpoint,
										masterMirroringCheckpointLen,
										record->xl_len,
										&beginLoc,
										/* errlevel */ -1,	// Suppress elog altogether on master mirroring checkpoint length checking.
										&tablespaceCount,
										&filespaceCount,
										&databaseCount))

				{
					appendStringInfo(buf,
						 ", master mirroring information: %d filespaces, %d tablespaces, %d databases",
						 filespaceCount,
						 tablespaceCount,
						 databaseCount);
				}
			}
		}
	}
9847 9848 9849 9850
	else if (info == XLOG_NOOP)
	{
		appendStringInfo(buf, "xlog no-op");
	}
9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865
	else if (info == XLOG_NEXTOID)
	{
		Oid			nextOid;

		memcpy(&nextOid, rec, sizeof(Oid));
		appendStringInfo(buf, "nextOid: %u", nextOid);
	}
	else if (info == XLOG_SWITCH)
	{
		appendStringInfo(buf, "xlog switch");
	}
	else
		appendStringInfo(buf, "UNKNOWN");
}

9866 9867
static void
xlog_outrec(StringInfo buf, XLogRecord *record)
9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 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
{
	int			i;

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

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


/*
 * GUC support
 */
const char *
assign_xlog_sync_method(const char *method, bool doit, GucSource source __attribute__((unused)) )
{
	int			new_sync_method;
	int			new_sync_bit;

	if (pg_strcasecmp(method, "fsync") == 0)
	{
		new_sync_method = SYNC_METHOD_FSYNC;
		new_sync_bit = 0;
	}
#ifdef HAVE_FSYNC_WRITETHROUGH
	else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
	{
		new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
		new_sync_bit = 0;
	}
#endif
#ifdef HAVE_FDATASYNC
	else if (pg_strcasecmp(method, "fdatasync") == 0)
	{
		new_sync_method = SYNC_METHOD_FDATASYNC;
		new_sync_bit = 0;
	}
#endif
#ifdef OPEN_SYNC_FLAG
	else if (pg_strcasecmp(method, "open_sync") == 0)
	{
		new_sync_method = SYNC_METHOD_OPEN;
		new_sync_bit = OPEN_SYNC_FLAG;
	}
#endif
#ifdef OPEN_DATASYNC_FLAG
	else if (pg_strcasecmp(method, "open_datasync") == 0)
	{
		new_sync_method = SYNC_METHOD_OPEN;
		new_sync_bit = OPEN_DATASYNC_FLAG;
	}
#endif
	else
		return NULL;

	if (!doit)
		return method;

	if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
	{
		/*
		 * 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.
		 */
		if (MirroredFlatFile_IsActive(&mirroredLogFileOpen))
		{
			if (MirroredFlatFile_Flush(
								&mirroredLogFileOpen,
								/* suppressError */ true))
9946 9947
				ereport(PANIC,
						(errcode_for_file_access(),
9948
						 errmsg("could not fsync log file %u, segment %u: %m",
B
Bruce Momjian 已提交
9949
								openLogId, openLogSeg)));
9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984
			if (open_sync_bit != new_sync_bit)
				XLogFileClose();
		}
		sync_method = new_sync_method;
		open_sync_bit = new_sync_bit;
	}

	return method;
}

/*
 * 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)));
9985 9986
			break;
#endif
9987 9988
#ifdef HAVE_FDATASYNC
		case SYNC_METHOD_FDATASYNC:
9989
			if (pg_fdatasync(fd) != 0)
9990 9991
				ereport(PANIC,
						(errcode_for_file_access(),
9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143
					errmsg("could not fdatasync log file %u, segment %u: %m",
						   log, seg)));
			break;
#endif
		case SYNC_METHOD_OPEN:
//		case SYNC_METHOD_OPEN_DSYNC:
			/* write synced it already */
			break;
		default:
			elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
			break;
	}
}

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

	/* base backup in recovery mode not currently supported */
	backup_started_in_recovery = false;

	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
		   errmsg("must be superuser or replication role to run a backup")));

	if (strlen(backupidstr) > MAXPGPATH)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("backup label too long (max %d bytes)",
						MAXPGPATH)));

	/*
	 * 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.
			 */
10144
			RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT);
10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 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 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 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 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 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

			/*
			 * 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
do_pg_stop_backup(char *labelfile)
{
	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];
	char		backupfrom[20];
	uint32		_logId;
	uint32		_logSeg;
	FILE	   *lfp;
	FILE	   *fp;
	char		ch;
	char	   *remaining;
	char	   *ptr;

	/* Currently backup during recovery not supported */
	backup_started_in_recovery = false;

	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
		 (errmsg("must be superuser or replication role to run a backup"))));

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

	/*
	 * 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
10519
pg_switch_xlog(PG_FUNCTION_ARGS)
10520 10521 10522 10523 10524 10525 10526 10527
{
	text	   *result;
	XLogRecPtr	switchpoint;
	char		location[MAXFNAMELEN];

	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
10528
			 (errmsg("must be superuser to switch transaction log files"))));
10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 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 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 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 10897 10898 10899 10900 10901 10902 10903 10904 10905

	switchpoint = RequestXLogSwitch();

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

/*
 * 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)) )
{
	text	   *result;
	char		location[MAXFNAMELEN];

	/* Make sure we have an up-to-date local LogwrtResult */
	{
		/* use volatile pointer to prevent code rearrangement */
		volatile XLogCtlData *xlogctl = XLogCtl;

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

	snprintf(location, sizeof(location), "%X/%X",
			 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);

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

/*
 * Report the current WAL insert location (same format as pg_start_backup etc)
 *
 * This function is mostly for debugging purposes.
 */
Datum
pg_current_xlog_insert_location(PG_FUNCTION_ARGS __attribute__((unused)) )
{
	text	   *result;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogRecPtr	current_recptr;
	char		location[MAXFNAMELEN];

	/*
	 * Get the current end-of-WAL position ... shared lock is sufficient
	 */
	LWLockAcquire(WALInsertLock, LW_SHARED);
	INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
	LWLockRelease(WALInsertLock);

	snprintf(location, sizeof(location), "%X/%X",
			 current_recptr.xlogid, current_recptr.xrecoff);

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

/*
 * Compute an xlog file name and decimal byte offset given a WAL location,
 * such as is returned by pg_stop_backup() or pg_xlog_switch().
 *
 * Note that a location exactly at a segment boundary is taken to be in
 * the previous segment.  This is usually the right thing, since the
 * expected usage is to determine which xlog file(s) are ready to archive.
 */
Datum
pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
{
	text	   *location = PG_GETARG_TEXT_P(0);
	char	   *locationstr;
	unsigned int uxlogid;
	unsigned int uxrecoff;
	uint32		xlogid;
	uint32		xlogseg;
	uint32		xrecoff;
	XLogRecPtr	locationpoint;
	char		xlogfilename[MAXFNAMELEN];
	Datum		values[2];
	bool		isnull[2];
	TupleDesc	resultTupleDesc;
	HeapTuple	resultHeapTuple;
	Datum		result;

	/*
	 * Read input and parse
	 */
	locationstr = DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(location)));

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

	values[0] = DirectFunctionCall1(textin,
									CStringGetDatum(xlogfilename));
	isnull[0] = false;

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

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

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

	locationstr = DatumGetCString(DirectFunctionCall1(textout,
												 PointerGetDatum(location)));

	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;

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

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

/*
 * 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
 * identified by the label file, NOT what pg_control says.	This avoids the
 * 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
 * location and its REDO location into *checkPointLoc and RedoStartLSN,
 * respectively); returns FALSE if not. If this backup_label came from a
 * streamed backup, *backupEndRequired is set to TRUE.
 */
static bool
read_backup_label(XLogRecPtr *checkPointLoc, bool *backupEndRequired)
{
	char		startxlogfilename[MAXFNAMELEN];
	TimeLineID	tli;
	FILE	   *lfp;
	char		ch;
	char		backuptype[20];
	char		backupfrom[20];

	*backupEndRequired = false;

	/*
	 * See if label file is present
	 */
	lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
	if (!lfp)
	{
		if (errno != ENOENT)
			ereport(FATAL,
					(errcode_for_file_access(),
					 errmsg("could not read file \"%s\": %m",
							BACKUP_LABEL_FILE)));
		return false;			/* it's not there, all is fine */
	}

	/*
	 * 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).
	 */
	if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
			   &RedoStartLSN.xlogid, &RedoStartLSN.xrecoff, &tli,
			   startxlogfilename, &ch) != 5 || ch != '\n')
		ereport(FATAL,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));

	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),
				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));

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

	if (ferror(lfp) || FreeFile(lfp))
		ereport(FATAL,
				(errcode_for_file_access(),
				 errmsg("could not read file \"%s\": %m",
						BACKUP_LABEL_FILE)));

	return true;
}

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

	SpinLockAcquire(&xlogctl->info_lck);
	recptr = xlogctl->lastReplayedEndRecPtr;
	if (targetTLI)
		*targetTLI = xlogctl->RecoveryTargetTLI;
	SpinLockRelease(&xlogctl->info_lck);

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

/*
 * GetRecoveryTargetTLI - get the current recovery target timeline ID
 */
TimeLineID
GetRecoveryTargetTLI(void)
{
	/* 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;
}

/*
 * Error context callback for errors occurring during rm_redo().
 */
static void
rm_redo_error_callback(void *arg)
{
	RedoErrorCallBack *redoErrorCallBack = (RedoErrorCallBack*) arg;
	StringInfoData buf;

	initStringInfo(&buf);
	RmgrTable[redoErrorCallBack->record->xl_rmid].rm_desc(
												   &buf,
												   redoErrorCallBack->location,
												   redoErrorCallBack->record);

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

	pfree(buf.data);
}

static char *
XLogLocationToBuffer(char *buffer, XLogRecPtr *loc, bool longFormat)
{

	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);
10906
	}
10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972
	else
		sprintf(buffer,
			    "%X/%X",
			    loc->xlogid, loc->xrecoff);

	return buffer;
}

static char xlogLocationBuffer[50];
static char xlogLocationBuffer2[50];
static char xlogLocationBuffer3[50];
static char xlogLocationBuffer4[50];
static char xlogLocationBuffer5[50];

char *
XLogLocationToString(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer, loc, Debug_print_qd_mirroring);
}

char *
XLogLocationToString2(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer2, loc, Debug_print_qd_mirroring);
}

char *
XLogLocationToString3(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer3, loc, Debug_print_qd_mirroring);
}

char *
XLogLocationToString4(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer4, loc, Debug_print_qd_mirroring);
}

char *
XLogLocationToString5(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer5, loc, Debug_print_qd_mirroring);
}

char *
XLogLocationToString_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer, loc, true);
}

char *
XLogLocationToString2_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer2, loc, true);
}

char *
XLogLocationToString3_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer3, loc, true);
}

char *
XLogLocationToString4_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer4, loc, true);
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 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046
char *
XLogLocationToString5_Long(XLogRecPtr *loc)
{
	return XLogLocationToBuffer(xlogLocationBuffer5, loc, true);
}


void xlog_print_redo_read_buffer_not_found(
	Relation 		reln,
	BlockNumber 	blkno,
	XLogRecPtr 		lsn,
	const char 		*funcName)
{
	if (funcName != NULL)
		elog(PersistentRecovery_DebugPrintLevel(),
			 "%s redo for %u/%u/%u did not find buffer for block %d (LSN %s)",
			 funcName,
			 reln->rd_node.spcNode,
			 reln->rd_node.dbNode,
			 reln->rd_node.relNode,
			 blkno,
			 XLogLocationToString(&lsn));
	else
		elog(PersistentRecovery_DebugPrintLevel(),
			 "Redo for %u/%u/%u did not find buffer for block %d (LSN %s)",
			 reln->rd_node.spcNode,
			 reln->rd_node.dbNode,
			 reln->rd_node.relNode,
			 blkno,
			 XLogLocationToString(&lsn));
}

void xlog_print_redo_lsn_application(
	Relation 		reln,
	BlockNumber 	blkno,
	void			*pagePtr,
	XLogRecPtr 		lsn,
	const char 		*funcName)
{
	Page page = (Page)pagePtr;
	XLogRecPtr	pageCurrentLsn = PageGetLSN(page);
	bool willApplyChange;

	willApplyChange = XLByteLT(pageCurrentLsn, lsn);

	if (funcName != NULL)
		elog(PersistentRecovery_DebugPrintLevel(),
			 "%s redo application for %u/%u/%u, block %d, willApplyChange = %s, current LSN %s, change LSN %s",
			 funcName,
			 reln->rd_node.spcNode,
			 reln->rd_node.dbNode,
			 reln->rd_node.relNode,
			 blkno,
			 (willApplyChange ? "true" : "false"),
			 XLogLocationToString(&pageCurrentLsn),
			 XLogLocationToString2(&lsn));
	else
		elog(PersistentRecovery_DebugPrintLevel(),
			 "Redo application for %u/%u/%u, block %d, willApplyChange = %s, current LSN %s, change LSN %s",
			 reln->rd_node.spcNode,
			 reln->rd_node.dbNode,
			 reln->rd_node.relNode,
			 blkno,
			 (willApplyChange ? "true" : "false"),
			 XLogLocationToString(&pageCurrentLsn),
			 XLogLocationToString2(&lsn));
}

/* ------------------------------------------------------
 *  Startup Process main entry point and signal handlers
 * ------------------------------------------------------
 */
11047 11048

/*
11049
 * startupproc_quickdie() occurs when signalled SIGQUIT by the postmaster.
11050
 *
11051 11052
 * Some backend has bought the farm,
 * so we need to stop what we're doing and exit.
11053
 */
11054 11055
static void
startupproc_quickdie(SIGNAL_ARGS __attribute__((unused)))
11056
{
11057
	PG_SETMASK(&BlockSig);
11058

11059 11060 11061 11062 11063 11064 11065 11066 11067
	/*
	 * We DO NOT want to run proc_exit() callbacks -- we're here because
	 * shared memory may be corrupted, so we don't want to try to clean up our
	 * transaction.  Just nail the windows shut and get out of town.  Now that
	 * there's an atexit callback to prevent third-party code from breaking
	 * things by calling exit() directly, we have to reset the callbacks
	 * explicitly to make this work as intended.
	 */
	on_exit_reset();
11068

11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113
	/*
	 * 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
	 * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
	 * should ensure the postmaster sees this as a crash, too, but no harm in
	 * being doubly sure.)
	 */
	exit(2);
}

/* SIGUSR2: set flag to finish recovery */
static void
StartupProcTriggerHandler(SIGNAL_ARGS)
{
	int			save_errno = errno;

	WakeupRecovery();

	errno = save_errno;
}

/* SIGHUP: set flag to re-read config file at next convenient time */
static void
StartupProcSigHupHandler(SIGNAL_ARGS)
{
	int			save_errno = errno;

	got_SIGHUP = true;
	WakeupRecovery();

	errno = save_errno;
}

/* SIGTERM: set flag to abort redo and exit */
static void
StartupProcShutdownHandler(SIGNAL_ARGS)
{
	int			save_errno = errno;

	if (in_restore_command)
		proc_exit(1);
	else
		shutdown_requested = true;
	WakeupRecovery();
11114

11115 11116
	errno = save_errno;
}
B
Bruce Momjian 已提交
11117

11118 11119 11120 11121
/* Handle SIGHUP and SIGTERM signals of startup process */
void
HandleStartupProcInterrupts(void)
{
11122
	/*
11123
	 * Check if we were requested to re-read config file.
11124
	 */
11125
	if (got_SIGHUP)
11126
	{
11127 11128
		got_SIGHUP = false;
		ProcessConfigFile(PGC_SIGHUP);
11129
	}
B
Bruce Momjian 已提交
11130

11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 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
	/*
	 * Check if we were requested to exit without finishing recovery.
	 */
	if (shutdown_requested)
		proc_exit(1);

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

static void
HandleCrash(SIGNAL_ARGS)
{
    /**
     * 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);
}

/* Main entry point for startup process */
void
StartupProcessMain(int passNum)
{
	char	   *fullpath;

	am_startup = true;
	/*
	 * If possible, make this process a group leader, so that the postmaster
	 * can signal any child processes too.
	 */
#ifdef HAVE_SETSID
	if (setsid() < 0)
		elog(FATAL, "setsid() failed: %m");
#endif

	/*
	 * Properly accept or ignore signals the postmaster might send us
	 */
	pqsignal(SIGHUP, StartupProcSigHupHandler);	 /* reload config file */
	pqsignal(SIGINT, SIG_IGN);					/* ignore query cancel */
	pqsignal(SIGTERM, StartupProcShutdownHandler); /* request shutdown */
	pqsignal(SIGQUIT, startupproc_quickdie);		/* hard crash time */
	pqsignal(SIGALRM, SIG_IGN);
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, SIG_IGN);
	if (passNum == 1)
		pqsignal(SIGUSR2, StartupProcTriggerHandler);
	else
		pqsignal(SIGUSR2, SIG_IGN);

#ifdef SIGBUS
	pqsignal(SIGBUS, HandleCrash);
#endif
#ifdef SIGILL
    pqsignal(SIGILL, HandleCrash);
#endif
#ifdef SIGSEGV
	pqsignal(SIGSEGV, HandleCrash);
#endif

	/*
	 * Reset some signals that are accepted by postmaster but not here
	 */
	pqsignal(SIGCHLD, SIG_DFL);
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);
	pqsignal(SIGWINCH, SIG_DFL);

	/*
	 * Unblock signals (they were blocked when the postmaster forked us)
	 */
	PG_SETMASK(&UnBlockSig);

	switch (passNum)
11213
	{
11214 11215 11216 11217 11218 11219
	case 1:
		StartupXLOG();
		break;

	case 2:
	case 4:
11220
		/*
11221
		 * NOTE: The following initialization logic was borrrowed from ftsprobe.
11222
		 */
11223
		SetProcessingMode(InitProcessing);
11224

11225
		/*
11226 11227
		 * Create a resource owner to keep track of our resources (currently only
		 * buffer pins).
11228
		 */
11229 11230 11231 11232 11233 11234 11235 11236 11237
		if (passNum == 2)
		{
			CurrentResourceOwner = ResourceOwnerCreate(NULL, "Startup Pass 2");
		}
		else
		{
			Assert(passNum == 4);
			CurrentResourceOwner = ResourceOwnerCreate(NULL, "Startup Pass 4");
		}
B
Bruce Momjian 已提交
11238

11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 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 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329
		/*
		 * 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();

		/* heap access requires the rel-cache */
		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();

		/*
		 * 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.
		 */
		if (!XLogStartup_DoNextPTCatVerificationIteration())
		{
			MyDatabaseId = TemplateDbOid;
			MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
		}
		else
		{
			MyDatabaseId = XLogCtl->currentDatabaseToVerify;
			MyDatabaseTableSpace = XLogCtl->tablespaceOfCurrentDatabaseToVerify;
		}

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

		if (passNum == 2)
		{
			StartupXLOG_Pass2();
		}
		else
		{
			Assert(passNum == 4);
			StartupXLOG_Pass4();
		}

		break;
B
Bruce Momjian 已提交
11330

11331
	case 3:
11332
		/*
11333
		 * Pass 3 does REDO work for all non-meta-data (i.e. not the gp_persistent_* tables).
11334
		 */
11335
		SetProcessingMode(InitProcessing);
11336 11337

		/*
11338 11339
		 * Create a resource owner to keep track of our resources (currently only
		 * buffer pins).
11340
		 */
11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474
		CurrentResourceOwner = ResourceOwnerCreate(NULL, "Startup Pass 3");

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

		InitXLOGAccess();

		SetProcessingMode(NormalProcessing);

		StartupXLOG_Pass3();

		PgVersionRecoverMirror();
		break;

	default:
		elog(PANIC, "Unexpected pass number %d", passNum);
	}

	/*
	 * Exit normally. Exit code 0 tells postmaster that we completed
	 * recovery successfully.
	 */
	proc_exit(0);
}

/*
 *
 */
static
int XLogGetEof(XLogRecPtr *eofRecPtr)
{
	int	status = STATUS_OK;

	XLogRecPtr	redoCheckpointLoc;
	CheckPoint	redoCheckpoint;

	XLogRecPtr	startLoc;

	XLogRecord	*record;
	XLogRecPtr	LastRec;

	XLogGetRecoveryStart("filerep",
						 "get checkpoint location",
						 &redoCheckpointLoc,
						 &redoCheckpoint);

	startLoc = redoCheckpoint.redo;

	XLogCloseReadRecord();

	record = XLogReadRecord(&startLoc, false, DEBUG1);
	if (record == NULL)
	{
		FileRep_SetSegmentState(SegmentStateFault, FaultTypeDB);

		elog(WARNING," couldn't read start location %s",
			 XLogLocationToString(&startLoc));
		status = STATUS_ERROR;
	}

	do
	{
		LastRec = ReadRecPtr;

		record = XLogReadRecord(NULL, false, DEBUG1);
	} while (record != NULL);

	record = XLogReadRecord(&LastRec, false, ERROR);
	*eofRecPtr = EndRecPtr;

	XLogCloseReadRecord();

	return status;
}

/*
 *
 */
static
int XLogReconcileEofInternal(
					XLogRecPtr	startLocation,
					XLogRecPtr	endLocation)
{

	uint32		startLogId;
	uint32		startSeg;

	uint32		endLogId;
	uint32		endSeg;

	uint32		logId;
	uint32		seg;

	uint32		startOffset;
	uint32		endOffset;

	int			status = STATUS_OK;

	Assert(XLByteLT(startLocation, endLocation));

	XLByteToSeg(startLocation, startLogId, startSeg);
	XLByteToSeg(endLocation, endLogId, endSeg);

	logId = startLogId;
	seg = startSeg;

	while (1) {

		if (logId == startLogId && seg == startSeg)
			startOffset = startLocation.xrecoff % XLogSegSize;
		else
			startOffset = 0;

		if (logId == endLogId && seg == endSeg)
			endOffset = endLocation.xrecoff % XLogSegSize;
		else
			endOffset = XLogSegSize;

		{
			char	tmpBuf[FILEREP_MAX_LOG_DESCRIPTION_LEN];

			snprintf(tmpBuf, sizeof(tmpBuf),
					 "xlog reconcile log id '%u' seg '%u' start offset '%d' end offset '%d' xlog size '%d' ",
					 logId, seg, startOffset, endOffset, XLogSegSize);

			FileRep_InsertConfigLogEntry(tmpBuf);
		}

		status = XLogFillZero(logId, seg, startOffset, endOffset);
		if (status != STATUS_OK)
11475
		{
11476 11477 11478
			FileRep_SetSegmentState(SegmentStateFault, FaultTypeIO);

			break;
11479 11480
		}

11481 11482
		if (logId == endLogId && seg == endSeg)
			break;
B
Bruce Momjian 已提交
11483

11484
		NextLogSeg(logId, seg);
11485
	}
B
Bruce Momjian 已提交
11486

11487
	return STATUS_OK;
11488 11489
}

11490 11491 11492 11493 11494 11495
static
int XLogFillZero(
				 uint32	logId,
				 uint32	seg,
				 uint32	startOffset,
				 uint32	endOffset)
11496
{
11497 11498 11499
	char		path[MAXPGPATH];
	char		fname[MAXPGPATH];
	char		zbuffer[XLOG_BLCKSZ];
11500

11501 11502 11503
	int			fd = 0;
	uint32		offset = startOffset;
	Size		writeLen = 0;
B
Bruce Momjian 已提交
11504

11505 11506
	int			status = STATUS_OK;
	char		*xlogDir = NULL;
11507

11508
	Assert(startOffset < endOffset);
11509

11510
	errno = 0;
B
Bruce Momjian 已提交
11511

11512
	XLogFileName(fname, ThisTimeLineID, logId, seg);
B
Bruce Momjian 已提交
11513

11514 11515 11516 11517 11518 11519 11520
	xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
	if (snprintf(path, MAXPGPATH, "%s/%s", xlogDir, fname) >= MAXPGPATH) {
		ereport(WARNING,
				(errcode_for_file_access(),
				 errmsg("could not allocate path, path too long \"%s/%s\"",
						xlogDir, fname)));
		return STATUS_ERROR;
11521
	}
11522
	pfree(xlogDir);
B
Bruce Momjian 已提交
11523

11524 11525 11526 11527 11528 11529 11530 11531
	fd = open(path, O_RDWR, 0);
	if (fd < 0) {
			ereport(WARNING,
					(errcode_for_file_access(),
					 errmsg("could not open xlog file \"%s\" : %m",
							path)));
			return STATUS_ERROR;
	}
B
Bruce Momjian 已提交
11532

11533 11534
	if (ftruncate(fd, startOffset) < 0) {
		ereport(WARNING,
11535
				(errcode_for_file_access(),
11536 11537 11538 11539 11540 11541 11542 11543
				 errmsg("could not truncate xlog file \"%s\" to position \"%d\" : %m",
						path, startOffset)));
		status = STATUS_ERROR;
		goto exit;
	}

	if (lseek(fd, (off_t) startOffset, SEEK_SET) < 0) {
		ereport(WARNING,
11544
				(errcode_for_file_access(),
11545 11546 11547 11548 11549
				 errmsg("could not seek xlog file \"%s\" to position \"%d\" : %m",
						path, startOffset)));
		status = STATUS_ERROR;
		goto exit;
	}
B
Bruce Momjian 已提交
11550

11551
	/*
11552 11553 11554 11555 11556 11557 11558
	 * 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.
11559
	 */
11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589
	MemSet(zbuffer, 0, sizeof(zbuffer));

	while (1) {
		errno = 0;
		writeLen = (Size) Min(XLOG_BLCKSZ - (offset % XLOG_BLCKSZ), endOffset - offset);

		if ((int) write(fd, zbuffer, writeLen) != (int) writeLen) {
			int			save_errno = errno;

			/*
			 * If we fail to make the file, delete it to release disk space
			 */

			/* if write didn't set errno, assume problem is no disk space */
			errno = save_errno ? save_errno : ENOSPC;

			ereport(WARNING,
					(errcode_for_file_access(),
					 errmsg("could not write to file \"%s\": %m", path)));
			status = STATUS_ERROR;
			goto exit;
		}
		offset += writeLen;
		if (offset >= endOffset) {
			break;
		}
	}

	if (pg_fsync(fd) != 0) {
		ereport(WARNING,
11590
				(errcode_for_file_access(),
11591 11592 11593
				 errmsg("could not fsync file \"%s\": %m", path)));
		status = STATUS_ERROR;
	}
B
Bruce Momjian 已提交
11594

11595 11596 11597 11598 11599 11600 11601 11602 11603
exit:
	if (fd > 0) {
		if (close(fd)) {
			ereport(WARNING,
					(errcode_for_file_access(),
					 errmsg("could not close file \"%s\": %m", path)));
			status = STATUS_ERROR;
		}
	}
B
Bruce Momjian 已提交
11604

11605
	return status;
11606
}
11607

11608

11609
/*
11610 11611 11612 11613 11614
 *
 *		a) get logical XLog EOF on primary
 *		b) send logical XLog EOF to mirror
 *		c) if mirror ahead then reconcile XLog EOF on mirror
 *		d) if primary ahead then reconcile XLog EOF on primary
11615
 */
11616 11617
int
XLogReconcileEofPrimary(void)
11618
{
11619 11620
	XLogRecPtr	primaryEof = {0, 0};
	XLogRecPtr	mirrorEof;
11621

11622 11623
	uint32		logId;
	uint32		seg;
11624

11625
	char		simpleFileName[MAXPGPATH];
11626

11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670
	int			status = STATUS_OK;

	status = XLogGetEof(&primaryEof);

	if (status != STATUS_OK) {
		return status;
	}

	XLByteToSeg(primaryEof, logId, seg);

	XLogFileName(simpleFileName, ThisTimeLineID, logId, seg);

	status = MirroredFlatFile_ReconcileXLogEof(
											   XLOGDIR,
											   simpleFileName,
											   primaryEof,
											   &mirrorEof);

	if (status != STATUS_OK) {
		return status;
	}

	if (XLByteEQ(primaryEof, mirrorEof))
	{
		FileRep_InsertConfigLogEntry("primary and mirror xlog eof match");
		return STATUS_OK;
	}

	if (XLByteLT(primaryEof, mirrorEof))
	{
		FileRep_InsertConfigLogEntry("primary is behind, xlog was truncated on mirror");

		status = MirrorFlatFile(
								XLOGDIR,
								simpleFileName);
		return STATUS_OK;
	}

	FileRep_InsertConfigLogEntry("mirror is behind, xlog will be copied to mirror");

	status = MirrorFlatFile(
							XLOGDIR,
							simpleFileName);
	return status;
11671 11672 11673
}

/*
11674
 *
11675
 */
11676 11677 11678 11679
int
XLogReconcileEofMirror(
		XLogRecPtr	primaryEof,
		XLogRecPtr	*mirrorEof)
11680
{
11681 11682
	XLogRecPtr	mirrorEofLocal = {0, 0};
	int			status = STATUS_OK;
11683

11684
	status = XLogGetEof(&mirrorEofLocal);
11685

11686 11687 11688 11689
	*mirrorEof = mirrorEofLocal;

	if (status != STATUS_OK) {
		return status;
11690 11691 11692
	}


11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713
	if (XLByteEQ(primaryEof, mirrorEofLocal)) {
		FileRep_InsertConfigLogEntry("primary and mirror xlog eof match");
		return STATUS_OK;
	}

	if (! XLByteLT(primaryEof, mirrorEofLocal)) {
		FileRep_InsertConfigLogEntry("mirror is behind, xlog will be truncated on primary");
		return STATUS_OK;
	}

	FileRep_InsertConfigLogEntry("primary is behind, xlog was truncated on mirror");

	status = XLogReconcileEofInternal(
						  primaryEof,
						  mirrorEofLocal);

	if (status != STATUS_OK) {
		return status;
	}

	return status;
11714 11715 11716
}

/*
11717 11718 11719
 * The routine recovers pg_control flat file on mirror side.
 *		a) It copies pg_control file from primary to mirror
 *      b) pg_control file is overwritten on mirror
11720
 *
11721
 * Status is not returned, If an error occurs segmentState will be set to Fault.
11722
 */
11723 11724
int
XLogRecoverMirrorControlFile(void)
11725
{
11726 11727
	MirroredFlatFileOpen	mirroredOpen;
	int						retval = 0;
11728

11729
	while (1) {
11730

11731
		ReadControlFile();
11732

11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764
		retval = MirroredFlatFile_Open(
							  &mirroredOpen,
							  XLOG_CONTROL_FILE_SUBDIR,
							  XLOG_CONTROL_FILE_SIMPLE,
							  O_CREAT | O_RDWR | PG_BINARY,
							  S_IRUSR | S_IWUSR,
							  /* suppressError */ false,
							  /* atomic operation */ false,
							  /*isMirrorRecovery */ TRUE);
		if (retval != 0)
			break;

		retval = MirroredFlatFile_Write(
							   &mirroredOpen,
							   0,
							   ControlFile,
							   PG_CONTROL_SIZE,
							   /* suppressError */ false);
		if (retval != 0)
			break;

		retval = MirroredFlatFile_Flush(
							   &mirroredOpen,
							   /* suppressError */ false);
		if (retval != 0)
			break;

		MirroredFlatFile_Close(&mirroredOpen);
		break;
	} // while(1)

	return retval;
11765 11766
}

11767 11768 11769 11770
/*
 * The ChangeTracking module will call this xlog routine in order for
 * it to gather all the xlog records since the last checkpoint and
 * add any relevant information to the change log if necessary.
11771
 *
11772 11773 11774 11775 11776
 * It returns the number of records that were found (not all of them
 * were interesting to the changetracker though).
 *
 * See ChangeTracking_CreateInitialFromPreviousCheckpoint()
 * for more information.
11777
 */
11778 11779
int XLogAddRecordsToChangeTracking(
	XLogRecPtr	*lastChangeTrackingEndLoc)
11780
{
11781 11782 11783 11784 11785 11786 11787
	XLogRecord *record;
	XLogRecPtr	redoCheckpointLoc;
	CheckPoint	redoCheckpoint;
	XLogRecPtr	startLoc;
	XLogRecPtr	lastEndLoc;
	XLogRecPtr	lastChangeTrackingLogEndLoc = {0, 0};
	int count = 0;
11788

11789
	/*
11790 11791 11792 11793 11794 11795
	 * Find latest checkpoint record and the redo record from xlog. This record
	 * will be used to find the starting point to scan xlog records to be pushed
	 * to changetracking log. This is needed either to generate/produce new change
	 * tracking log or to make the changetracking log catchup with xlog in case
	 * it has fallen behind.
	 * TODO: does this function really work for us? if so, change its name for something more global
11796
	 */
11797 11798 11799 11800
	XLogGetRecoveryStart("CHANGETRACKING",
						 "get checkpoint location",
						 &redoCheckpointLoc,
						 &redoCheckpoint);
11801

11802
	startLoc = redoCheckpoint.redo;
11803

11804 11805 11806
	XLogCloseReadRecord();
	elog(LOG, "last checkpoint location for generating initial changetracking log %s",
			XLogLocationToString(&startLoc));
11807

11808
	/*
11809 11810 11811 11812
	 * Find the last entry and thus the LSN recorded by it from the CT_FULL
	 * log. Later, it will be used to maintain the xlog and changetracking log
	 * to the same end point.
	 * We perform this when the lastChangetrackingEndLoc is not known.
11813
	 */
11814 11815 11816 11817 11818 11819
	if (lastChangeTrackingEndLoc == NULL)
	{
		ChangeTracking_GetLastChangeTrackingLogEndLoc(&lastChangeTrackingLogEndLoc);
		elog(LOG, "last changetracked location in changetracking full log %s",
				XLogLocationToString(&lastChangeTrackingLogEndLoc));
	}
11820

11821 11822 11823 11824 11825 11826
	record = XLogReadRecord(&startLoc, false, LOG);
	if (record == NULL)
	{
		elog(ERROR," couldn't read start location %s",
			 XLogLocationToString(&startLoc));
	}
11827

11828 11829 11830 11831
	if (lastChangeTrackingEndLoc != NULL &&
		XLByteLT(*lastChangeTrackingEndLoc, EndRecPtr))
	{
		XLogCloseReadRecord();
11832

11833 11834 11835 11836 11837 11838 11839
		if (Debug_persistent_print)
			elog(Persistent_DebugPrintLevel(),
				 "XLogAddRecordsToChangeTracking: Returning 0 records through end location %s",
				 XLogLocationToString(lastChangeTrackingEndLoc));

		return 0;
	}
11840 11841

	/*
11842 11843
	 * Make a pass through all xlog records from last checkpoint and
	 * gather information from the interesting ones into the change log.
11844
	 */
11845 11846 11847 11848 11849 11850
	while (true)
	{
		if (Debug_persistent_print)
			elog(Persistent_DebugPrintLevel(),
				 "XLogAddRecordsToChangeTracking: Going to add change tracking record for XLOG (end) location %s",
				 XLogLocationToString(&EndRecPtr));
11851

11852 11853 11854 11855 11856 11857 11858 11859
		ChangeTracking_AddRecordFromXlog(record->xl_rmid,
									     record->xl_info,
										 (XLogRecData *)XLogRecGetData(record),
										 &EndRecPtr);
		count++;

		lastEndLoc = EndRecPtr;

11860
		SIMPLE_FAULT_INJECTOR(FileRepTransitionToChangeTracking);
11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923

		if (filerep_inject_change_tracking_recovery_fault)
		{
			if (isDatabaseRunning() == FALSE)
			{
				filerep_inject_change_tracking_recovery_fault = FALSE;

				ereport(PANIC,
					(errmsg("change tracking failure, "
					"injected fault by guc filerep_inject_change_tracking_recovery_fault, "
					"postmaster reset requested"),
					FileRep_errcontext()));
			}
		}

		if (lastChangeTrackingEndLoc != NULL)
		{
			if (XLByteEQ(EndRecPtr, *lastChangeTrackingEndLoc))
			{
				if (Debug_persistent_print)
					elog(Persistent_DebugPrintLevel(),
						 "XLogAddRecordsToChangeTracking: Returning %d records from start location %s through end location %s",
						 count,
						 XLogLocationToString(&startLoc),
						 XLogLocationToString2(lastChangeTrackingEndLoc));
				break;
			}

			record = XLogReadRecord(NULL, false, ERROR);
			Assert (record != NULL);

			if (!XLByteLE(EndRecPtr, *lastChangeTrackingEndLoc))
			{
				if (Debug_persistent_print)
					elog(Persistent_DebugPrintLevel(),
						 "XLogAddRecordsToChangeTracking: Read beyond expected last change tracking XLOG record.  "
						 "Returning %d records. "
						 "Last change tracking XLOG record (end) position is %s; scanned XLOG record (end) position is %s (start location is %s)",
						 count,
						 XLogLocationToString(lastChangeTrackingEndLoc),
						 XLogLocationToString2(&EndRecPtr),
						 XLogLocationToString3(&startLoc));
				break;
			}
		}
		else
		{
			/*
			 * Read to end of log.
			 */
			record = XLogReadRecord(NULL, false, LOG);
			if (record == NULL)
			{
				if (Debug_persistent_print)
					elog(Persistent_DebugPrintLevel(),
						 "XLogAddRecordsToChangeTracking: Returning %d records through end of log location %s",
						 count,
						 XLogLocationToString(&lastEndLoc));

				break;
			}
		}
	}
11924 11925

	/*
11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953
	 * We now need to make sure that (in the case of crash recovery) there are no
	 * records in the change tracking logs that have lsn higher than the highest lsn in xlog.
	 *
	 *	a) Find the highest lsn in xlog
	 *	b) Find the highest lsn in change tracking log files before interesting
	 *	   xlog entries from last checkpoint onwards are appended to it
	 *	   (see above)
	 *	c) if the highest lsn in change tracking > the highest lsn in xlog then
	 *		i) store in compacting shared memory the highest lsn in xlog
	 *		ii) Flush all data into CT_LOG_FULL
	 *		iii) Rename CT_LOG_FULL to CT_LOG_TRANSIENT
	 *	d) after database is started the compacting (CT_LOG_TRANSIENT) will discard all records from
	 *	   change tracking log file that are higher than the highest lsn in xlog
	 */
	if (lastChangeTrackingEndLoc == NULL)
	{
		/* read xlog till the end to get last lsn on disk (EndRecPtr) */
		while(record != NULL)
			record = XLogReadRecord(NULL, false, LOG);

		if (! (lastChangeTrackingLogEndLoc.xlogid == 0 && lastChangeTrackingLogEndLoc.xrecoff == 0) &&
			XLByteLT(EndRecPtr, lastChangeTrackingLogEndLoc))
		{
			elog(LOG,
				 "changetracking: "
				 "found last changetracking log LSN (%s) higher than last xlog LSN, "
				 "invalid records will be discarded",
				 XLogLocationToString(&lastChangeTrackingLogEndLoc));
11954

11955
			elog(LOG, "xlog LSN (%s)", XLogLocationToString(&EndRecPtr));
11956

11957 11958 11959 11960 11961 11962 11963 11964
			ChangeTracking_FsyncDataIntoLog(CTF_LOG_FULL);
			ChangeTrackingSetXLogEndLocation(EndRecPtr);
			ChangeTracking_CreateTransientLog();
		}
	}

	XLogCloseReadRecord();
	return count;
11965 11966 11967
}

/*
11968 11969 11970 11971 11972
 * The following two gucs
 *					a) fsync=on
 *					b) wal_sync_method=open_sync
 * open XLOG files with O_DIRECT flag.
 * O_DIRECT flag requires XLOG buffer to be 512 byte aligned.
11973
 */
11974 11975
void
XLogInitMirroredAlignedBuffer(int32 bufferLen)
11976
{
11977 11978 11979 11980 11981 11982 11983 11984 11985 11986
	if (bufferLen > writeBufLen)
	{
		if (writeBuf != NULL)
		{
			pfree(writeBuf);
			writeBuf = NULL;
			writeBufAligned = NULL;
			writeBufLen = 0;
		}
	}
11987

11988 11989 11990
	if (writeBuf == NULL)
	{
		writeBufLen = bufferLen;
11991

11992 11993 11994 11995 11996 11997 11998 11999
		writeBuf = MemoryContextAlloc(TopMemoryContext, writeBufLen + ALIGNOF_XLOG_BUFFER);
		if (writeBuf == NULL)
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 (errmsg("could not allocate memory for mirrored aligned buffer"))));
		writeBufAligned = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, writeBuf);
	}
}
12000 12001


12002 12003 12004 12005 12006 12007 12008
int
XLogRecoverMirror(void)
{
  DIR                *cldir;
  struct dirent     *clde;
  int                retval = 0;
	char            *xlogDir = makeRelativeToTxnFilespace(XLOGDIR);
12009

12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025
  cldir = AllocateDir(xlogDir);
  while ((clde = ReadDir(cldir, xlogDir)) != NULL) {
    if (strlen(clde->d_name) == 24 &&
	strspn(clde->d_name, "0123456789ABCDEF") == 24) {

      retval = MirrorFlatFile( XLOGDIR, clde->d_name);

      if (retval != 0)
	break;

    }
  }
  FreeDir(cldir);
	pfree(xlogDir);

  return retval;
12026 12027
}

12028
/*
12029 12030 12031
 * 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.
12032 12033
 */
static bool
12034
CheckForStandbyTrigger(void)
12035
{
12036
	static bool triggered = false;
12037

12038 12039
	if (triggered)
		return true;
12040

12041
	if (CheckPromoteSignal(true))
12042
	{
12043 12044 12045 12046 12047
		ereport(LOG,
				(errmsg("received promote request")));
		ShutdownWalRcv();
		triggered = true;
		return true;
12048
	}
B
Bruce Momjian 已提交
12049

12050 12051
	return false;
}
12052

12053 12054 12055 12056 12057 12058 12059 12060
/*
 * 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;
12061

12062
	if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
12063 12064
	{
		/*
12065 12066
		 * Since we are in a signal handler, it's not safe to elog. We
		 * silently ignore any error from unlink.
12067
		 */
12068 12069 12070
		if (do_unlink)
			unlink(PROMOTE_SIGNAL_FILE);
		return true;
12071
	}
12072 12073
	return false;
}
12074

12075 12076 12077 12078 12079 12080 12081 12082
/*
 * Wake up startup process to replay newly arrived WAL, or to notice that
 * failover has been requested.
 */
void
WakeupRecovery(void)
{
	SetLatch(&XLogCtl->recoveryWakeupLatch);
12083 12084
}

12085
/*
12086 12087
 * Put the current standby master dbid in the shared memory, which will
 * be looked up from mmxlog.
12088
 */
12089 12090
void
SetStandbyDbid(int16 dbid)
12091
{
12092 12093
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
12094

12095 12096 12097
	SpinLockAcquire(&xlogctl->info_lck);
	xlogctl->standbyDbid = dbid;
	SpinLockRelease(&xlogctl->info_lck);
12098

12099 12100 12101 12102 12103
	/*
	 * Let postmaster know we've changed standby dbid.
	 */
	SendPostmasterSignal(PMSIGNAL_SEGCONFIG_CHANGE);
}
12104

12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132
/*
 * Returns current standby dbid.
 */
int16
GetStandbyDbid(void)
{
	/* use volatile pointer to prevent code rearrangement */
	volatile XLogCtlData *xlogctl = XLogCtl;
	int16	dbid;

	SpinLockAcquire(&xlogctl->info_lck);
	dbid = xlogctl->standbyDbid;
	SpinLockRelease(&xlogctl->info_lck);

	return dbid;
}

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