1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/access/transam/xlog.c
12 *-------------------------------------------------------------------------
24 #include "access/clog.h"
25 #include "access/multixact.h"
26 #include "access/subtrans.h"
27 #include "access/timeline.h"
28 #include "access/transam.h"
29 #include "access/tuptoaster.h"
30 #include "access/twophase.h"
31 #include "access/xact.h"
32 #include "access/xlog_internal.h"
33 #include "access/xlogreader.h"
34 #include "access/xlogutils.h"
35 #include "catalog/catversion.h"
36 #include "catalog/pg_control.h"
37 #include "catalog/pg_database.h"
38 #include "miscadmin.h"
40 #include "postmaster/bgwriter.h"
41 #include "postmaster/startup.h"
42 #include "replication/walreceiver.h"
43 #include "replication/walsender.h"
44 #include "storage/barrier.h"
45 #include "storage/bufmgr.h"
46 #include "storage/fd.h"
47 #include "storage/ipc.h"
48 #include "storage/latch.h"
49 #include "storage/pmsignal.h"
50 #include "storage/predicate.h"
51 #include "storage/proc.h"
52 #include "storage/procarray.h"
53 #include "storage/reinit.h"
54 #include "storage/smgr.h"
55 #include "storage/spin.h"
56 #include "utils/builtins.h"
57 #include "utils/guc.h"
58 #include "utils/ps_status.h"
59 #include "utils/relmapper.h"
60 #include "utils/snapmgr.h"
61 #include "utils/timestamp.h"
64 extern uint32 bootstrap_data_checksum_version;
66 /* File path names (all relative to $PGDATA) */
67 #define RECOVERY_COMMAND_FILE "recovery.conf"
68 #define RECOVERY_COMMAND_DONE "recovery.done"
69 #define PROMOTE_SIGNAL_FILE "promote"
70 #define FAST_PROMOTE_SIGNAL_FILE "fast_promote"
73 /* User-settable parameters */
74 int CheckPointSegments = 3;
75 int wal_keep_segments = 0;
77 int XLogArchiveTimeout = 0;
78 bool XLogArchiveMode = false;
79 char *XLogArchiveCommand = NULL;
80 bool EnableHotStandby = false;
81 bool fullPageWrites = true;
82 bool log_checkpoints = false;
83 int sync_method = DEFAULT_SYNC_METHOD;
84 int wal_level = WAL_LEVEL_MINIMAL;
85 int CommitDelay = 0; /* precommit delay in microseconds */
86 int CommitSiblings = 5; /* # concurrent xacts needed to sleep */
87 int num_xloginsert_slots = 8;
90 bool XLOG_DEBUG = false;
94 * XLOGfileslop is the maximum number of preallocated future XLOG segments.
95 * When we are done with an old XLOG segment file, we will recycle it as a
96 * future XLOG segment as long as there aren't already XLOGfileslop future
97 * segments; else we'll delete it. This could be made a separate GUC
98 * variable, but at present I think it's sufficient to hardwire it as
99 * 2*CheckPointSegments+1. Under normal conditions, a checkpoint will free
100 * no more than 2*CheckPointSegments log segments, and we want to recycle all
101 * of them; the +1 allows boundary cases to happen without wasting a
102 * delete/create-segment cycle.
104 #define XLOGfileslop (2*CheckPointSegments + 1)
110 const struct config_enum_entry sync_method_options[] = {
111 {"fsync", SYNC_METHOD_FSYNC, false},
112 #ifdef HAVE_FSYNC_WRITETHROUGH
113 {"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
115 #ifdef HAVE_FDATASYNC
116 {"fdatasync", SYNC_METHOD_FDATASYNC, false},
118 #ifdef OPEN_SYNC_FLAG
119 {"open_sync", SYNC_METHOD_OPEN, false},
121 #ifdef OPEN_DATASYNC_FLAG
122 {"open_datasync", SYNC_METHOD_OPEN_DSYNC, false},
128 * Statistics for current checkpoint are collected in this global struct.
129 * Because only the background writer or a stand-alone backend can perform
130 * checkpoints, this will be unused in normal backends.
132 CheckpointStatsData CheckpointStats;
135 * ThisTimeLineID will be same in all backends --- it identifies current
136 * WAL timeline for the database system.
138 TimeLineID ThisTimeLineID = 0;
141 * Are we doing recovery from XLOG?
143 * This is only ever true in the startup process; it should be read as meaning
144 * "this process is replaying WAL records", rather than "the system is in
145 * recovery mode". It should be examined primarily by functions that need
146 * to act differently when called from a WAL redo function (e.g., to skip WAL
147 * logging). To check whether the system is in recovery regardless of which
148 * process you're running in, use RecoveryInProgress() but only after shared
149 * memory startup and lock initialization.
151 bool InRecovery = false;
153 /* Are we in Hot Standby mode? Only valid in startup process, see xlog.h */
154 HotStandbyState standbyState = STANDBY_DISABLED;
156 static XLogRecPtr LastRec;
158 /* Local copy of WalRcv->receivedUpto */
159 static XLogRecPtr receivedUpto = 0;
160 static TimeLineID receiveTLI = 0;
163 * During recovery, lastFullPageWrites keeps track of full_page_writes that
164 * the replayed WAL records indicate. It's initialized with full_page_writes
165 * that the recovery starting checkpoint record indicates, and then updated
166 * each time XLOG_FPW_CHANGE record is replayed.
168 static bool lastFullPageWrites;
171 * Local copy of SharedRecoveryInProgress variable. True actually means "not
172 * known, need to check the shared state".
174 static bool LocalRecoveryInProgress = true;
177 * Local copy of SharedHotStandbyActive variable. False actually means "not
178 * known, need to check the shared state".
180 static bool LocalHotStandbyActive = false;
183 * Local state for XLogInsertAllowed():
184 * 1: unconditionally allowed to insert XLOG
185 * 0: unconditionally not allowed to insert XLOG
186 * -1: must check RecoveryInProgress(); disallow until it is false
187 * Most processes start with -1 and transition to 1 after seeing that recovery
188 * is not in progress. But we can also force the value for special cases.
189 * The coding in XLogInsertAllowed() depends on the first two of these states
190 * being numerically the same as bool true and false.
192 static int LocalXLogInsertAllowed = -1;
195 * When ArchiveRecoveryRequested is set, archive recovery was requested,
196 * ie. recovery.conf file was present. When InArchiveRecovery is set, we are
197 * currently recovering using offline XLOG archives. These variables are only
198 * valid in the startup process.
200 * When ArchiveRecoveryRequested is true, but InArchiveRecovery is false, we're
201 * currently performing crash recovery using only XLOG files in pg_xlog, but
202 * will switch to using offline XLOG archives as soon as we reach the end of
205 bool ArchiveRecoveryRequested = false;
206 bool InArchiveRecovery = false;
208 /* Was the last xlog file restored from archive, or local? */
209 static bool restoredFromArchive = false;
211 /* options taken from recovery.conf for archive recovery */
212 char *recoveryRestoreCommand = NULL;
213 static char *recoveryEndCommand = NULL;
214 static char *archiveCleanupCommand = NULL;
215 static RecoveryTargetType recoveryTarget = RECOVERY_TARGET_UNSET;
216 static bool recoveryTargetInclusive = true;
217 static bool recoveryPauseAtTarget = true;
218 static TransactionId recoveryTargetXid;
219 static TimestampTz recoveryTargetTime;
220 static char *recoveryTargetName;
222 /* options taken from recovery.conf for XLOG streaming */
223 static bool StandbyModeRequested = false;
224 static char *PrimaryConnInfo = NULL;
225 static char *TriggerFile = NULL;
227 /* are we currently in standby mode? */
228 bool StandbyMode = false;
230 /* whether request for fast promotion has been made yet */
231 static bool fast_promote = false;
233 /* if recoveryStopsHere returns true, it saves actual stop xid/time/name here */
234 static TransactionId recoveryStopXid;
235 static TimestampTz recoveryStopTime;
236 static char recoveryStopName[MAXFNAMELEN];
237 static bool recoveryStopAfter;
240 * During normal operation, the only timeline we care about is ThisTimeLineID.
241 * During recovery, however, things are more complicated. To simplify life
242 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
243 * scan through the WAL history (that is, it is the line that was active when
244 * the currently-scanned WAL record was generated). We also need these
247 * recoveryTargetTLI: the desired timeline that we want to end in.
249 * recoveryTargetIsLatest: was the requested target timeline 'latest'?
251 * expectedTLEs: a list of TimeLineHistoryEntries for recoveryTargetTLI and the timelines of
252 * its known parents, newest first (so recoveryTargetTLI is always the
253 * first list member). Only these TLIs are expected to be seen in the WAL
254 * segments we read, and indeed only these TLIs will be considered as
255 * candidate WAL files to open at all.
257 * curFileTLI: the TLI appearing in the name of the current input WAL file.
258 * (This is not necessarily the same as ThisTimeLineID, because we could
259 * be scanning data that was copied from an ancestor timeline when the current
260 * file was created.) During a sequential scan we do not allow this value
263 static TimeLineID recoveryTargetTLI;
264 static bool recoveryTargetIsLatest = false;
265 static List *expectedTLEs;
266 static TimeLineID curFileTLI;
269 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
270 * current backend. It is updated for all inserts. XactLastRecEnd points to
271 * end+1 of the last record, and is reset when we end a top-level transaction,
272 * or start a new one; so it can be used to tell if the current transaction has
273 * created any XLOG records.
275 static XLogRecPtr ProcLastRecPtr = InvalidXLogRecPtr;
277 XLogRecPtr XactLastRecEnd = InvalidXLogRecPtr;
280 * RedoRecPtr is this backend's local copy of the REDO record pointer
281 * (which is almost but not quite the same as a pointer to the most recent
282 * CHECKPOINT record). We update this from the shared-memory copy,
283 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
284 * hold an insertion slot). See XLogInsert for details. We are also allowed
285 * to update from XLogCtl->RedoRecPtr if we hold the info_lck;
286 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
289 static XLogRecPtr RedoRecPtr;
292 * RedoStartLSN points to the checkpoint's REDO location which is specified
293 * in a backup label file, backup history file or control file. In standby
294 * mode, XLOG streaming usually starts from the position where an invalid
295 * record was found. But if we fail to read even the initial checkpoint
296 * record, we use the REDO location instead of the checkpoint location as
297 * the start position of XLOG streaming. Otherwise we would have to jump
298 * backwards to the REDO location after reading the checkpoint record,
299 * because the REDO record can precede the checkpoint record.
301 static XLogRecPtr RedoStartLSN = InvalidXLogRecPtr;
304 * Shared-memory data structures for XLOG control
306 * LogwrtRqst indicates a byte position that we need to write and/or fsync
307 * the log up to (all records before that point must be written or fsynced).
308 * LogwrtResult indicates the byte positions we have already written/fsynced.
309 * These structs are identical but are declared separately to indicate their
310 * slightly different functions.
312 * To read XLogCtl->LogwrtResult, you must hold either info_lck or
313 * WALWriteLock. To update it, you need to hold both locks. The point of
314 * this arrangement is that the value can be examined by code that already
315 * holds WALWriteLock without needing to grab info_lck as well. In addition
316 * to the shared variable, each backend has a private copy of LogwrtResult,
317 * which is updated when convenient.
319 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
320 * (protected by info_lck), but we don't need to cache any copies of it.
322 * info_lck is only held long enough to read/update the protected variables,
323 * so it's a plain spinlock. The other locks are held longer (potentially
324 * over I/O operations), so we use LWLocks for them. These locks are:
326 * WALBufMappingLock: must be held to replace a page in the WAL buffer cache.
327 * It is only held while initializing and changing the mapping. If the
328 * contents of the buffer being replaced haven't been written yet, the mapping
329 * lock is released while the write is done, and reacquired afterwards.
331 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
334 * ControlFileLock: must be held to read/update control file or create
337 * CheckpointLock: must be held to do a checkpoint or restartpoint (ensures
338 * only one checkpointer at a time; currently, with all checkpoints done by
339 * the checkpointer, this is just pro forma).
344 typedef struct XLogwrtRqst
346 XLogRecPtr Write; /* last byte + 1 to write out */
347 XLogRecPtr Flush; /* last byte + 1 to flush */
350 typedef struct XLogwrtResult
352 XLogRecPtr Write; /* last byte + 1 written out */
353 XLogRecPtr Flush; /* last byte + 1 flushed */
358 * A slot for inserting to the WAL. This is similar to an LWLock, the main
359 * difference is that there is an extra xlogInsertingAt field that is protected
360 * by the same mutex. Unlike an LWLock, a slot can only be acquired in
363 * The xlogInsertingAt field is used to advertise to other processes how far
364 * the slot owner has progressed in inserting the record. When a backend
365 * acquires a slot, it initializes xlogInsertingAt to 1, because it doesn't
366 * yet know where it's going to insert the record. That's conservative
367 * but correct; the new insertion is certainly going to go to a byte position
368 * greater than 1. If another backend needs to flush the WAL, it will have to
369 * wait for the new insertion. xlogInsertingAt is updated after finishing the
370 * insert or when crossing a page boundary, which will wake up anyone waiting
371 * for it, whether the wait was necessary in the first place or not.
373 * A process can wait on a slot in two modes: LW_EXCLUSIVE or
374 * LW_WAIT_UNTIL_FREE. LW_EXCLUSIVE works like in an lwlock; when the slot is
375 * released, the first LW_EXCLUSIVE waiter in the queue is woken up. Processes
376 * waiting in LW_WAIT_UNTIL_FREE mode are woken up whenever the slot is
377 * released, or xlogInsertingAt is updated. In other words, a process in
378 * LW_WAIT_UNTIL_FREE mode is woken up whenever the inserter makes any progress
379 * copying the record in place. LW_WAIT_UNTIL_FREE waiters are always added to
380 * the front of the queue, while LW_EXCLUSIVE waiters are appended to the end.
382 * To join the wait queue, a process must set MyProc->lwWaitMode to the mode
383 * it wants to wait in, MyProc->lwWaiting to true, and link MyProc to the head
384 * or tail of the wait queue. The same mechanism is used to wait on an LWLock,
385 * see lwlock.c for details.
389 slock_t mutex; /* protects the below fields */
390 XLogRecPtr xlogInsertingAt; /* insert has completed up to this point */
392 PGPROC *owner; /* for debugging purposes */
394 bool releaseOK; /* T if ok to release waiters */
395 char exclusive; /* # of exclusive holders (0 or 1) */
396 PGPROC *head; /* head of list of waiting PGPROCs */
397 PGPROC *tail; /* tail of list of waiting PGPROCs */
398 /* tail is undefined when head is NULL */
402 * All the slots are allocated as an array in shared memory. We force the
403 * array stride to be a power of 2, which saves a few cycles in indexing, but
404 * more importantly also ensures that individual slots don't cross cache line
405 * boundaries. (Of course, we have to also ensure that the array start
406 * address is suitably aligned.)
408 typedef union XLogInsertSlotPadded
412 } XLogInsertSlotPadded;
415 * Shared state data for XLogInsert.
417 typedef struct XLogCtlInsert
419 slock_t insertpos_lck; /* protects CurrBytePos and PrevBytePos */
422 * CurrBytePos is the end of reserved WAL. The next record will be inserted
423 * at that position. PrevBytePos is the start position of the previously
424 * inserted (or rather, reserved) record - it is copied to the the prev-
425 * link of the next record. These are stored as "usable byte positions"
426 * rather than XLogRecPtrs (see XLogBytePosToRecPtr()).
431 /* insertion slots, see above for details */
432 XLogInsertSlotPadded *insertSlots;
435 * fullPageWrites is the master copy used by all backends to determine
436 * whether to write full-page to WAL, instead of using process-local one.
437 * This is required because, when full_page_writes is changed by SIGHUP,
438 * we must WAL-log it before it actually affects WAL-logging by backends.
439 * Checkpointer sets at startup or after SIGHUP.
441 * To read these fields, you must hold an insertion slot. To modify them,
442 * you must hold ALL the slots.
444 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
445 bool forcePageWrites; /* forcing full-page writes for PITR? */
449 * exclusiveBackup is true if a backup started with pg_start_backup() is
450 * in progress, and nonExclusiveBackups is a counter indicating the number
451 * of streaming base backups currently in progress. forcePageWrites is set
452 * to true when either of these is non-zero. lastBackupStart is the latest
453 * checkpoint redo location used as a starting point for an online backup.
455 bool exclusiveBackup;
456 int nonExclusiveBackups;
457 XLogRecPtr lastBackupStart;
461 * Total shared-memory state for XLOG.
463 typedef struct XLogCtlData
465 XLogCtlInsert Insert;
467 /* Protected by info_lck: */
468 XLogwrtRqst LogwrtRqst;
469 XLogRecPtr RedoRecPtr; /* a recent copy of Insert->RedoRecPtr */
470 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
471 TransactionId ckptXid;
472 XLogRecPtr asyncXactLSN; /* LSN of newest async commit/abort */
473 XLogSegNo lastRemovedSegNo; /* latest removed/recycled XLOG
476 /* Fake LSN counter, for unlogged relations. Protected by ulsn_lck. */
477 XLogRecPtr unloggedLSN;
480 /* Time of last xlog segment switch. Protected by WALWriteLock. */
481 pg_time_t lastSegSwitchTime;
484 * Protected by info_lck and WALWriteLock (you must hold either lock to
485 * read it, but both to update)
487 XLogwrtResult LogwrtResult;
490 * Latest initialized page in the cache (last byte position + 1).
492 * To change the identity of a buffer (and InitializedUpTo), you need to
493 * hold WALBufMappingLock. To change the identity of a buffer that's still
494 * dirty, the old page needs to be written out first, and for that you
495 * need WALWriteLock, and you need to ensure that there are no in-progress
496 * insertions to the page by calling WaitXLogInsertionsToFinish().
498 XLogRecPtr InitializedUpTo;
501 * These values do not change after startup, although the pointed-to pages
502 * and xlblocks values certainly do. xlblock values are protected by
505 char *pages; /* buffers for unwritten XLOG pages */
506 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
507 int XLogCacheBlck; /* highest allocated xlog buffer index */
510 * Shared copy of ThisTimeLineID. Does not change after end-of-recovery.
511 * If we created a new timeline when the system was started up,
512 * PrevTimeLineID is the old timeline's ID that we forked off from.
513 * Otherwise it's equal to ThisTimeLineID.
515 TimeLineID ThisTimeLineID;
516 TimeLineID PrevTimeLineID;
519 * archiveCleanupCommand is read from recovery.conf but needs to be in
520 * shared memory so that the checkpointer process can access it.
522 char archiveCleanupCommand[MAXPGPATH];
525 * SharedRecoveryInProgress indicates if we're still in crash or archive
526 * recovery. Protected by info_lck.
528 bool SharedRecoveryInProgress;
531 * SharedHotStandbyActive indicates if we're still in crash or archive
532 * recovery. Protected by info_lck.
534 bool SharedHotStandbyActive;
537 * WalWriterSleeping indicates whether the WAL writer is currently in
538 * low-power mode (and hence should be nudged if an async commit occurs).
539 * Protected by info_lck.
541 bool WalWriterSleeping;
544 * recoveryWakeupLatch is used to wake up the startup process to continue
545 * WAL replay, if it is waiting for WAL to arrive or failover trigger file
548 Latch recoveryWakeupLatch;
551 * During recovery, we keep a copy of the latest checkpoint record here.
552 * Used by the background writer when it wants to create a restartpoint.
554 * Protected by info_lck.
556 XLogRecPtr lastCheckPointRecPtr;
557 CheckPoint lastCheckPoint;
560 * lastReplayedEndRecPtr points to end+1 of the last record successfully
561 * replayed. When we're currently replaying a record, ie. in a redo
562 * function, replayEndRecPtr points to the end+1 of the record being
563 * replayed, otherwise it's equal to lastReplayedEndRecPtr.
565 XLogRecPtr lastReplayedEndRecPtr;
566 TimeLineID lastReplayedTLI;
567 XLogRecPtr replayEndRecPtr;
568 TimeLineID replayEndTLI;
569 /* timestamp of last COMMIT/ABORT record replayed (or being replayed) */
570 TimestampTz recoveryLastXTime;
571 /* current effective recovery target timeline */
572 TimeLineID RecoveryTargetTLI;
575 * timestamp of when we started replaying the current chunk of WAL data,
576 * only relevant for replication or archive recovery
578 TimestampTz currentChunkStartTime;
579 /* Are we requested to pause recovery? */
583 * lastFpwDisableRecPtr points to the start of the last replayed
584 * XLOG_FPW_CHANGE record that instructs full_page_writes is disabled.
586 XLogRecPtr lastFpwDisableRecPtr;
588 slock_t info_lck; /* locks shared variables shown above */
591 static XLogCtlData *XLogCtl = NULL;
594 * We maintain an image of pg_control in shared memory.
596 static ControlFileData *ControlFile = NULL;
599 * Calculate the amount of space left on the page after 'endptr'. Beware
600 * multiple evaluation!
602 #define INSERT_FREESPACE(endptr) \
603 (((endptr) % XLOG_BLCKSZ == 0) ? 0 : (XLOG_BLCKSZ - (endptr) % XLOG_BLCKSZ))
605 /* Macro to advance to next buffer index. */
606 #define NextBufIdx(idx) \
607 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
610 * XLogRecPtrToBufIdx returns the index of the WAL buffer that holds, or
611 * would hold if it was in cache, the page containing 'recptr'.
613 #define XLogRecPtrToBufIdx(recptr) \
614 (((recptr) / XLOG_BLCKSZ) % (XLogCtl->XLogCacheBlck + 1))
617 * These are the number of bytes in a WAL page and segment usable for WAL data.
619 #define UsableBytesInPage (XLOG_BLCKSZ - SizeOfXLogShortPHD)
620 #define UsableBytesInSegment ((XLOG_SEG_SIZE / XLOG_BLCKSZ) * UsableBytesInPage - (SizeOfXLogLongPHD - SizeOfXLogShortPHD))
623 * Private, possibly out-of-date copy of shared LogwrtResult.
624 * See discussion above.
626 static XLogwrtResult LogwrtResult = {0, 0};
629 * Codes indicating where we got a WAL file from during recovery, or where
630 * to attempt to get one.
634 XLOG_FROM_ANY = 0, /* request to read WAL from any source */
635 XLOG_FROM_ARCHIVE, /* restored using restore_command */
636 XLOG_FROM_PG_XLOG, /* existing file in pg_xlog */
637 XLOG_FROM_STREAM, /* streamed from master */
640 /* human-readable names for XLogSources, for debugging output */
641 static const char *xlogSourceNames[] = {"any", "archive", "pg_xlog", "stream"};
644 * openLogFile is -1 or a kernel FD for an open log file segment.
645 * When it's open, openLogOff is the current seek offset in the file.
646 * openLogSegNo identifies the segment. These variables are only
647 * used to write the XLOG, and so will normally refer to the active segment.
649 static int openLogFile = -1;
650 static XLogSegNo openLogSegNo = 0;
651 static uint32 openLogOff = 0;
654 * These variables are used similarly to the ones above, but for reading
655 * the XLOG. Note, however, that readOff generally represents the offset
656 * of the page just read, not the seek position of the FD itself, which
657 * will be just past that page. readLen indicates how much of the current
658 * page has been read into readBuf, and readSource indicates where we got
659 * the currently open file from.
661 static int readFile = -1;
662 static XLogSegNo readSegNo = 0;
663 static uint32 readOff = 0;
664 static uint32 readLen = 0;
665 static XLogSource readSource = 0; /* XLOG_FROM_* code */
668 * Keeps track of which source we're currently reading from. This is
669 * different from readSource in that this is always set, even when we don't
670 * currently have a WAL file open. If lastSourceFailed is set, our last
671 * attempt to read from currentSource failed, and we should try another source
674 static XLogSource currentSource = 0; /* XLOG_FROM_* code */
675 static bool lastSourceFailed = false;
677 typedef struct XLogPageReadPrivate
680 bool fetching_ckpt; /* are we fetching a checkpoint record? */
682 } XLogPageReadPrivate;
685 * These variables track when we last obtained some WAL data to process,
686 * and where we got it from. (XLogReceiptSource is initially the same as
687 * readSource, but readSource gets reset to zero when we don't have data
688 * to process right now. It is also different from currentSource, which
689 * also changes when we try to read from a source and fail, while
690 * XLogReceiptSource tracks where we last successfully read some WAL.)
692 static TimestampTz XLogReceiptTime = 0;
693 static XLogSource XLogReceiptSource = 0; /* XLOG_FROM_* code */
695 /* State information for XLOG reading */
696 static XLogRecPtr ReadRecPtr; /* start of last record read */
697 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
699 static XLogRecPtr minRecoveryPoint; /* local copy of
700 * ControlFile->minRecoveryPoint */
701 static TimeLineID minRecoveryPointTLI;
702 static bool updateMinRecoveryPoint = true;
705 * Have we reached a consistent database state? In crash recovery, we have
706 * to replay all the WAL, so reachedConsistency is never set. During archive
707 * recovery, the database is consistent once minRecoveryPoint is reached.
709 bool reachedConsistency = false;
711 static bool InRedo = false;
713 /* Have we launched bgwriter during recovery? */
714 static bool bgwriterLaunched = false;
716 /* For WALInsertSlotAcquire/Release functions */
717 static int MySlotNo = 0;
718 static bool holdingAllSlots = false;
720 static void readRecoveryCommandFile(void);
721 static void exitArchiveRecovery(TimeLineID endTLI, XLogSegNo endLogSegNo);
722 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
723 static void recoveryPausesHere(void);
724 static void SetLatestXTime(TimestampTz xtime);
725 static void SetCurrentChunkStartTime(TimestampTz xtime);
726 static void CheckRequiredParameterValues(void);
727 static void XLogReportParameters(void);
728 static void checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI,
730 static void LocalSetXLogInsertAllowed(void);
731 static void CreateEndOfRecoveryRecord(void);
732 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
733 static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo);
735 static bool XLogCheckBuffer(XLogRecData *rdata, bool holdsExclusiveLock,
736 XLogRecPtr *lsn, BkpBlock *bkpb);
737 static Buffer RestoreBackupBlockContents(XLogRecPtr lsn, BkpBlock bkpb,
738 char *blk, bool get_cleanup_lock, bool keep_buffer);
739 static void AdvanceXLInsertBuffer(XLogRecPtr upto, bool opportunistic);
740 static bool XLogCheckpointNeeded(XLogSegNo new_segno);
741 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible);
742 static bool InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
743 bool find_free, int *max_advance,
745 static int XLogFileRead(XLogSegNo segno, int emode, TimeLineID tli,
746 int source, bool notexistOk);
747 static int XLogFileReadAnyTLI(XLogSegNo segno, int emode, int source);
748 static int XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
749 int reqLen, XLogRecPtr targetRecPtr, char *readBuf,
750 TimeLineID *readTLI);
751 static bool WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
752 bool fetching_ckpt, XLogRecPtr tliRecPtr);
753 static int emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
754 static void XLogFileClose(void);
755 static void PreallocXlogFiles(XLogRecPtr endptr);
756 static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr endptr);
757 static void UpdateLastRemovedPtr(char *filename);
758 static void ValidateXLOGDirectoryStructure(void);
759 static void CleanupBackupHistory(void);
760 static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
761 static XLogRecord *ReadRecord(XLogReaderState *xlogreader, XLogRecPtr RecPtr,
762 int emode, bool fetching_ckpt);
763 static void CheckRecoveryConsistency(void);
764 static XLogRecord *ReadCheckpointRecord(XLogReaderState *xlogreader,
765 XLogRecPtr RecPtr, int whichChkpti, bool report);
766 static bool rescanLatestTimeLine(void);
767 static void WriteControlFile(void);
768 static void ReadControlFile(void);
769 static char *str_time(pg_time_t tnow);
770 static bool CheckForStandbyTrigger(void);
773 static void xlog_outrec(StringInfo buf, XLogRecord *record);
775 static void pg_start_backup_callback(int code, Datum arg);
776 static bool read_backup_label(XLogRecPtr *checkPointLoc,
777 bool *backupEndRequired, bool *backupFromStandby);
778 static void rm_redo_error_callback(void *arg);
779 static int get_sync_bit(int method);
781 static void CopyXLogRecordToWAL(int write_len, bool isLogSwitch,
783 XLogRecPtr StartPos, XLogRecPtr EndPos);
784 static void ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos,
785 XLogRecPtr *EndPos, XLogRecPtr *PrevPtr);
786 static bool ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos,
787 XLogRecPtr *PrevPtr);
788 static XLogRecPtr WaitXLogInsertionsToFinish(XLogRecPtr upto);
789 static void WakeupWaiters(XLogRecPtr EndPos);
790 static char *GetXLogBuffer(XLogRecPtr ptr);
791 static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos);
792 static XLogRecPtr XLogBytePosToEndRecPtr(uint64 bytepos);
793 static uint64 XLogRecPtrToBytePos(XLogRecPtr ptr);
795 static void WALInsertSlotAcquire(bool exclusive);
796 static void WALInsertSlotAcquireOne(int slotno);
797 static void WALInsertSlotRelease(void);
798 static void WALInsertSlotReleaseOne(int slotno);
801 * Insert an XLOG record having the specified RMID and info bytes,
802 * with the body of the record being the data chunk(s) described by
803 * the rdata chain (see xlog.h for notes about rdata).
805 * Returns XLOG pointer to end of record (beginning of next record).
806 * This can be used as LSN for data pages affected by the logged action.
807 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
808 * before the data page can be written out. This implements the basic
809 * WAL rule "write the log before the data".)
811 * NB: this routine feels free to scribble on the XLogRecData structs,
812 * though not on the data they reference. This is OK since the XLogRecData
813 * structs are always just temporaries in the calling code.
816 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
818 XLogCtlInsert *Insert = &XLogCtl->Insert;
820 XLogRecData *rdt_lastnormal;
821 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
822 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
823 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
824 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
825 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
826 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
827 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
834 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
836 uint8 info_orig = info;
837 static XLogRecord *rechdr;
843 rechdr = malloc(SizeOfXLogRecord);
845 elog(ERROR, "out of memory");
846 MemSet(rechdr, 0, SizeOfXLogRecord);
849 /* cross-check on whether we should be here or not */
850 if (!XLogInsertAllowed())
851 elog(ERROR, "cannot make new WAL entries during recovery");
853 /* info's high bits are reserved for use by me */
854 if (info & XLR_INFO_MASK)
855 elog(PANIC, "invalid xlog info mask %02X", info);
857 TRACE_POSTGRESQL_XLOG_INSERT(rmid, info);
860 * In bootstrap mode, we don't actually log anything but XLOG resources;
861 * return a phony record pointer.
863 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
865 EndPos = SizeOfXLogLongPHD; /* start of 1st chkpt record */
870 * Here we scan the rdata chain, to determine which buffers must be backed
873 * We may have to loop back to here if a race condition is detected below.
874 * We could prevent the race by doing all this work while holding an
875 * insertion slot, but it seems better to avoid doing CRC calculations
878 * We add entries for backup blocks to the chain, so that they don't need
879 * any special treatment in the critical section where the chunks are
880 * copied into the WAL buffers. Those entries have to be unlinked from the
881 * chain if we have to loop back here.
884 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
886 dtbuf[i] = InvalidBuffer;
887 dtbuf_bkp[i] = false;
891 * Decide if we need to do full-page writes in this XLOG record: true if
892 * full_page_writes is on or we have a PITR request for it. Since we
893 * don't yet have an insertion slot, fullPageWrites and forcePageWrites
894 * could change under us, but we'll recheck them once we have a slot.
896 doPageWrites = Insert->fullPageWrites || Insert->forcePageWrites;
901 if (rdt->buffer == InvalidBuffer)
903 /* Simple data, just include it */
908 /* Find info for buffer */
909 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
911 if (rdt->buffer == dtbuf[i])
913 /* Buffer already referenced by earlier chain item */
923 if (dtbuf[i] == InvalidBuffer)
925 /* OK, put it in this slot */
926 dtbuf[i] = rdt->buffer;
927 if (doPageWrites && XLogCheckBuffer(rdt, true,
928 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
939 if (i >= XLR_MAX_BKP_BLOCKS)
940 elog(PANIC, "can backup at most %d blocks per xlog record",
943 /* Break out of loop when rdt points to last chain item */
944 if (rdt->next == NULL)
950 * NOTE: We disallow len == 0 because it provides a useful bit of extra
951 * error checking in ReadRecord. This means that all callers of
952 * XLogInsert must supply at least some not-in-a-buffer data. However, we
953 * make an exception for XLOG SWITCH records because we don't want them to
954 * ever cross a segment boundary.
956 if (len == 0 && !isLogSwitch)
957 elog(PANIC, "invalid xlog record length %u", len);
960 * Make additional rdata chain entries for the backup blocks, so that we
961 * don't need to special-case them in the write loop. This modifies the
962 * original rdata chain, but we keep a pointer to the last regular entry,
963 * rdt_lastnormal, so that we can undo this if we have to loop back to the
966 * At the exit of this loop, write_len includes the backup block data.
968 * Also set the appropriate info bits to show which buffers were backed
969 * up. The XLR_BKP_BLOCK(N) bit corresponds to the N'th distinct buffer
970 * value (ignoring InvalidBuffer) appearing in the rdata chain.
972 rdt_lastnormal = rdt;
974 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
982 info |= XLR_BKP_BLOCK(i);
984 bkpb = &(dtbuf_xlg[i]);
985 page = (char *) BufferGetBlock(dtbuf[i]);
987 rdt->next = &(dtbuf_rdt1[i]);
990 rdt->data = (char *) bkpb;
991 rdt->len = sizeof(BkpBlock);
992 write_len += sizeof(BkpBlock);
994 rdt->next = &(dtbuf_rdt2[i]);
997 if (bkpb->hole_length == 0)
1001 write_len += BLCKSZ;
1006 /* must skip the hole */
1008 rdt->len = bkpb->hole_offset;
1009 write_len += bkpb->hole_offset;
1011 rdt->next = &(dtbuf_rdt3[i]);
1014 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
1015 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
1016 write_len += rdt->len;
1022 * Calculate CRC of the data, including all the backup blocks
1024 * Note that the record header isn't added into the CRC initially since we
1025 * don't know the prev-link yet. Thus, the CRC will represent the CRC of
1026 * the whole record in the order: rdata, then backup blocks, then record
1029 INIT_CRC32(rdata_crc);
1030 for (rdt = rdata; rdt != NULL; rdt = rdt->next)
1031 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
1034 * Construct record header (prev-link is filled in later, after reserving
1035 * the space for the record), and make that the first chunk in the chain.
1037 * The CRC calculated for the header here doesn't include prev-link,
1038 * because we don't know it yet. It will be added later.
1040 rechdr->xl_xid = GetCurrentTransactionIdIfAny();
1041 rechdr->xl_tot_len = SizeOfXLogRecord + write_len;
1042 rechdr->xl_len = len; /* doesn't include backup blocks */
1043 rechdr->xl_info = info;
1044 rechdr->xl_rmid = rmid;
1045 rechdr->xl_prev = InvalidXLogRecPtr;
1046 COMP_CRC32(rdata_crc, ((char *) rechdr), offsetof(XLogRecord, xl_prev));
1048 hdr_rdt.next = rdata;
1049 hdr_rdt.data = (char *) rechdr;
1050 hdr_rdt.len = SizeOfXLogRecord;
1051 write_len += SizeOfXLogRecord;
1055 * We have now done all the preparatory work we can without holding a
1056 * lock or modifying shared state. From here on, inserting the new WAL
1057 * record to the shared WAL buffer cache is a two-step process:
1059 * 1. Reserve the right amount of space from the WAL. The current head of
1060 * reserved space is kept in Insert->CurrBytePos, and is protected by
1063 * 2. Copy the record to the reserved WAL space. This involves finding the
1064 * correct WAL buffer containing the reserved space, and copying the
1065 * record in place. This can be done concurrently in multiple processes.
1067 * To keep track of which insertions are still in-progress, each concurrent
1068 * inserter allocates an "insertion slot", which tells others how far the
1069 * inserter has progressed. There is a small fixed number of insertion
1070 * slots, determined by the num_xloginsert_slots GUC. When an inserter
1071 * finishes, it updates the xlogInsertingAt of its slot to the end of the
1072 * record it inserted, to let others know that it's done. xlogInsertingAt
1073 * is also updated when crossing over to a new WAL buffer, to allow the
1074 * the previous buffer to be flushed.
1076 * Holding onto a slot also protects RedoRecPtr and fullPageWrites from
1077 * changing until the insertion is finished.
1079 * Step 2 can usually be done completely in parallel. If the required WAL
1080 * page is not initialized yet, you have to grab WALBufMappingLock to
1081 * initialize it, but the WAL writer tries to do that ahead of insertions
1082 * to avoid that from happening in the critical path.
1086 START_CRIT_SECTION();
1087 WALInsertSlotAcquire(isLogSwitch);
1090 * Check to see if my RedoRecPtr is out of date. If so, may have to go
1091 * back and recompute everything. This can only happen just after a
1092 * checkpoint, so it's better to be slow in this case and fast otherwise.
1094 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
1095 * affect the contents of the XLOG record, so we'll update our local copy
1096 * but not force a recomputation.
1098 if (RedoRecPtr != Insert->RedoRecPtr)
1100 Assert(RedoRecPtr < Insert->RedoRecPtr);
1101 RedoRecPtr = Insert->RedoRecPtr;
1105 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
1107 if (dtbuf[i] == InvalidBuffer)
1109 if (dtbuf_bkp[i] == false &&
1110 dtbuf_lsn[i] <= RedoRecPtr)
1113 * Oops, this buffer now needs to be backed up, but we
1114 * didn't think so above. Start over.
1116 WALInsertSlotRelease();
1118 rdt_lastnormal->next = NULL;
1127 * Also check to see if fullPageWrites or forcePageWrites was just turned
1128 * on; if we weren't already doing full-page writes then go back and
1129 * recompute. (If it was just turned off, we could recompute the record
1130 * without full pages, but we choose not to bother.)
1132 if ((Insert->fullPageWrites || Insert->forcePageWrites) && !doPageWrites)
1134 /* Oops, must redo it with full-page data. */
1135 WALInsertSlotRelease();
1137 rdt_lastnormal->next = NULL;
1143 * Reserve space for the record in the WAL. This also sets the xl_prev
1147 inserted = ReserveXLogSwitch(&StartPos, &EndPos, &rechdr->xl_prev);
1150 ReserveXLogInsertLocation(write_len, &StartPos, &EndPos,
1158 * Now that xl_prev has been filled in, finish CRC calculation of the
1161 COMP_CRC32(rdata_crc, ((char *) &rechdr->xl_prev), sizeof(XLogRecPtr));
1162 FIN_CRC32(rdata_crc);
1163 rechdr->xl_crc = rdata_crc;
1166 * All the record data, including the header, is now ready to be
1167 * inserted. Copy the record in the space reserved.
1169 CopyXLogRecordToWAL(write_len, isLogSwitch, &hdr_rdt, StartPos, EndPos);
1174 * This was an xlog-switch record, but the current insert location was
1175 * already exactly at the beginning of a segment, so there was no need
1181 * Done! Let others know that we're finished.
1183 WALInsertSlotRelease();
1188 * Update shared LogwrtRqst.Write, if we crossed page boundary.
1190 if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
1192 /* use volatile pointer to prevent code rearrangement */
1193 volatile XLogCtlData *xlogctl = XLogCtl;
1195 SpinLockAcquire(&xlogctl->info_lck);
1196 /* advance global request to include new block(s) */
1197 if (xlogctl->LogwrtRqst.Write < EndPos)
1198 xlogctl->LogwrtRqst.Write = EndPos;
1199 /* update local result copy while I have the chance */
1200 LogwrtResult = xlogctl->LogwrtResult;
1201 SpinLockRelease(&xlogctl->info_lck);
1205 * If this was an XLOG_SWITCH record, flush the record and the empty
1206 * padding space that fills the rest of the segment, and perform
1207 * end-of-segment actions (eg, notifying archiver).
1211 TRACE_POSTGRESQL_XLOG_SWITCH();
1214 * Even though we reserved the rest of the segment for us, which is
1215 * reflected in EndPos, we return a pointer to just the end of the
1216 * xlog-switch record.
1220 EndPos = StartPos + SizeOfXLogRecord;
1221 if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
1223 if (EndPos % XLOG_SEG_SIZE == EndPos % XLOG_BLCKSZ)
1224 EndPos += SizeOfXLogLongPHD;
1226 EndPos += SizeOfXLogShortPHD;
1236 initStringInfo(&buf);
1237 appendStringInfo(&buf, "INSERT @ %X/%X: ",
1238 (uint32) (EndPos >> 32), (uint32) EndPos);
1239 xlog_outrec(&buf, rechdr);
1240 if (rdata->data != NULL)
1242 appendStringInfo(&buf, " - ");
1243 RmgrTable[rechdr->xl_rmid].rm_desc(&buf, rechdr->xl_info, rdata->data);
1245 elog(LOG, "%s", buf.data);
1251 * Update our global variables
1253 ProcLastRecPtr = StartPos;
1254 XactLastRecEnd = EndPos;
1260 * Reserves the right amount of space for a record of given size from the WAL.
1261 * *StartPos is set to the beginning of the reserved section, *EndPos to
1262 * its end+1. *PrevPtr is set to the beginning of the previous record; it is
1263 * used to set the xl_prev of this record.
1265 * This is the performance critical part of XLogInsert that must be serialized
1266 * across backends. The rest can happen mostly in parallel. Try to keep this
1267 * section as short as possible, insertpos_lck can be heavily contended on a
1270 * NB: The space calculation here must match the code in CopyXLogRecordToWAL,
1271 * where we actually copy the record to the reserved space.
1274 ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos, XLogRecPtr *EndPos,
1275 XLogRecPtr *PrevPtr)
1277 volatile XLogCtlInsert *Insert = &XLogCtl->Insert;
1278 uint64 startbytepos;
1282 size = MAXALIGN(size);
1284 /* All (non xlog-switch) records should contain data. */
1285 Assert(size > SizeOfXLogRecord);
1288 * The duration the spinlock needs to be held is minimized by minimizing
1289 * the calculations that have to be done while holding the lock. The
1290 * current tip of reserved WAL is kept in CurrBytePos, as a byte position
1291 * that only counts "usable" bytes in WAL, that is, it excludes all WAL
1292 * page headers. The mapping between "usable" byte positions and physical
1293 * positions (XLogRecPtrs) can be done outside the locked region, and
1294 * because the usable byte position doesn't include any headers, reserving
1295 * X bytes from WAL is almost as simple as "CurrBytePos += X".
1297 SpinLockAcquire(&Insert->insertpos_lck);
1299 startbytepos = Insert->CurrBytePos;
1300 endbytepos = startbytepos + size;
1301 prevbytepos = Insert->PrevBytePos;
1302 Insert->CurrBytePos = endbytepos;
1303 Insert->PrevBytePos = startbytepos;
1305 SpinLockRelease(&Insert->insertpos_lck);
1307 *StartPos = XLogBytePosToRecPtr(startbytepos);
1308 *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1309 *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1312 * Check that the conversions between "usable byte positions" and
1313 * XLogRecPtrs work consistently in both directions.
1315 Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1316 Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1317 Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1321 * Like ReserveXLogInsertLocation(), but for an xlog-switch record.
1323 * A log-switch record is handled slightly differently. The rest of the
1324 * segment will be reserved for this insertion, as indicated by the returned
1325 * *EndPos_p value. However, if we are already at the beginning of the current
1326 * segment, *StartPos_p and *EndPos_p are set to the current location without
1327 * reserving any space, and the function returns false.
1330 ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
1332 volatile XLogCtlInsert *Insert = &XLogCtl->Insert;
1333 uint64 startbytepos;
1336 uint32 size = SizeOfXLogRecord;
1341 * These calculations are a bit heavy-weight to be done while holding a
1342 * spinlock, but since we're holding all the WAL insertion slots, there
1343 * are no other inserters competing for it. GetXLogInsertRecPtr() does
1344 * compete for it, but that's not called very frequently.
1346 SpinLockAcquire(&Insert->insertpos_lck);
1348 startbytepos = Insert->CurrBytePos;
1350 ptr = XLogBytePosToEndRecPtr(startbytepos);
1351 if (ptr % XLOG_SEG_SIZE == 0)
1353 SpinLockRelease(&Insert->insertpos_lck);
1354 *EndPos = *StartPos = ptr;
1358 endbytepos = startbytepos + size;
1359 prevbytepos = Insert->PrevBytePos;
1361 *StartPos = XLogBytePosToRecPtr(startbytepos);
1362 *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1364 segleft = XLOG_SEG_SIZE - ((*EndPos) % XLOG_SEG_SIZE);
1365 if (segleft != XLOG_SEG_SIZE)
1367 /* consume the rest of the segment */
1369 endbytepos = XLogRecPtrToBytePos(*EndPos);
1371 Insert->CurrBytePos = endbytepos;
1372 Insert->PrevBytePos = startbytepos;
1374 SpinLockRelease(&Insert->insertpos_lck);
1376 *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1378 Assert((*EndPos) % XLOG_SEG_SIZE == 0);
1379 Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1380 Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1381 Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1387 * Subroutine of XLogInsert. Copies a WAL record to an already-reserved
1391 CopyXLogRecordToWAL(int write_len, bool isLogSwitch, XLogRecData *rdata,
1392 XLogRecPtr StartPos, XLogRecPtr EndPos)
1398 XLogPageHeader pagehdr;
1400 /* The first chunk is the record header */
1401 Assert(rdata->len == SizeOfXLogRecord);
1404 * Get a pointer to the right place in the right WAL buffer to start
1408 currpos = GetXLogBuffer(CurrPos);
1409 freespace = INSERT_FREESPACE(CurrPos);
1412 * there should be enough space for at least the first field (xl_tot_len)
1415 Assert(freespace >= sizeof(uint32));
1417 /* Copy record data */
1419 while (rdata != NULL)
1421 char *rdata_data = rdata->data;
1422 int rdata_len = rdata->len;
1424 while (rdata_len > freespace)
1427 * Write what fits on this page, and continue on the next page.
1429 Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || freespace == 0);
1430 memcpy(currpos, rdata_data, freespace);
1431 rdata_data += freespace;
1432 rdata_len -= freespace;
1433 written += freespace;
1434 CurrPos += freespace;
1437 * Get pointer to beginning of next page, and set the xlp_rem_len
1438 * in the page header. Set XLP_FIRST_IS_CONTRECORD.
1440 * It's safe to set the contrecord flag and xlp_rem_len without a
1441 * lock on the page. All the other flags were already set when the
1442 * page was initialized, in AdvanceXLInsertBuffer, and we're the
1443 * only backend that needs to set the contrecord flag.
1445 currpos = GetXLogBuffer(CurrPos);
1446 pagehdr = (XLogPageHeader) currpos;
1447 pagehdr->xlp_rem_len = write_len - written;
1448 pagehdr->xlp_info |= XLP_FIRST_IS_CONTRECORD;
1450 /* skip over the page header */
1451 if (CurrPos % XLogSegSize == 0)
1453 CurrPos += SizeOfXLogLongPHD;
1454 currpos += SizeOfXLogLongPHD;
1458 CurrPos += SizeOfXLogShortPHD;
1459 currpos += SizeOfXLogShortPHD;
1461 freespace = INSERT_FREESPACE(CurrPos);
1464 Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || rdata_len == 0);
1465 memcpy(currpos, rdata_data, rdata_len);
1466 currpos += rdata_len;
1467 CurrPos += rdata_len;
1468 freespace -= rdata_len;
1469 written += rdata_len;
1471 rdata = rdata->next;
1473 Assert(written == write_len);
1475 /* Align the end position, so that the next record starts aligned */
1476 CurrPos = MAXALIGN(CurrPos);
1479 * If this was an xlog-switch, it's not enough to write the switch record,
1480 * we also have to consume all the remaining space in the WAL segment.
1481 * We have already reserved it for us, but we still need to make sure it's
1482 * allocated and zeroed in the WAL buffers so that when the caller (or
1483 * someone else) does XLogWrite(), it can really write out all the zeros.
1485 if (isLogSwitch && CurrPos % XLOG_SEG_SIZE != 0)
1487 /* An xlog-switch record doesn't contain any data besides the header */
1488 Assert(write_len == SizeOfXLogRecord);
1491 * We do this one page at a time, to make sure we don't deadlock
1492 * against ourselves if wal_buffers < XLOG_SEG_SIZE.
1494 Assert(EndPos % XLogSegSize == 0);
1496 /* Use up all the remaining space on the first page */
1497 CurrPos += freespace;
1499 while (CurrPos < EndPos)
1501 /* initialize the next page (if not initialized already) */
1502 WakeupWaiters(CurrPos);
1503 AdvanceXLInsertBuffer(CurrPos, false);
1504 CurrPos += XLOG_BLCKSZ;
1508 if (CurrPos != EndPos)
1509 elog(PANIC, "space reserved for WAL record does not match what was written");
1513 * Allocate a slot for insertion.
1515 * In exclusive mode, all slots are reserved for the current process. That
1516 * blocks all concurrent insertions.
1519 WALInsertSlotAcquire(bool exclusive)
1525 for (i = 0; i < num_xloginsert_slots; i++)
1526 WALInsertSlotAcquireOne(i);
1527 holdingAllSlots = true;
1530 WALInsertSlotAcquireOne(-1);
1534 * Workhorse of WALInsertSlotAcquire. Acquires the given slot, or an arbitrary
1535 * one if slotno == -1. The index of the slot that was acquired is stored in
1538 * This is more or less equivalent to LWLockAcquire().
1541 WALInsertSlotAcquireOne(int slotno)
1543 volatile XLogInsertSlot *slot;
1544 PGPROC *proc = MyProc;
1547 static int slotToTry = -1;
1550 * Try to use the slot we used last time. If the system isn't particularly
1551 * busy, it's a good bet that it's available, and it's good to have some
1552 * affinity to a particular slot so that you don't unnecessarily bounce
1553 * cache lines between processes when there is no contention.
1555 * If this is the first time through in this backend, pick a slot
1556 * (semi-)randomly. This allows the slots to be used evenly if you have a
1557 * lot of very short connections.
1563 if (slotToTry == -1)
1564 slotToTry = MyProc->pgprocno % num_xloginsert_slots;
1565 MySlotNo = slotToTry;
1569 * We can't wait if we haven't got a PGPROC. This should only occur
1570 * during bootstrap or shared memory initialization. Put an Assert here
1571 * to catch unsafe coding practices.
1573 Assert(MyProc != NULL);
1576 * Lock out cancel/die interrupts until we exit the code section protected
1577 * by the slot. This ensures that interrupts will not interfere with
1578 * manipulations of data structures in shared memory.
1580 START_CRIT_SECTION();
1583 * Loop here to try to acquire slot after each time we are signaled by
1584 * WALInsertSlotRelease.
1590 slot = &XLogCtl->Insert.insertSlots[MySlotNo].slot;
1592 /* Acquire mutex. Time spent holding mutex should be short! */
1593 SpinLockAcquire(&slot->mutex);
1595 /* If retrying, allow WALInsertSlotRelease to release waiters again */
1597 slot->releaseOK = true;
1599 /* If I can get the slot, do so quickly. */
1600 if (slot->exclusive == 0)
1609 break; /* got the lock */
1611 Assert(slot->owner != MyProc);
1614 * Add myself to wait queue.
1616 proc->lwWaiting = true;
1617 proc->lwWaitMode = LW_EXCLUSIVE;
1618 proc->lwWaitLink = NULL;
1619 if (slot->head == NULL)
1622 slot->tail->lwWaitLink = proc;
1625 /* Can release the mutex now */
1626 SpinLockRelease(&slot->mutex);
1629 * Wait until awakened.
1631 * Since we share the process wait semaphore with the regular lock
1632 * manager and ProcWaitForSignal, and we may need to acquire a slot
1633 * while one of those is pending, it is possible that we get awakened
1634 * for a reason other than being signaled by WALInsertSlotRelease. If
1635 * so, loop back and wait again. Once we've gotten the slot,
1636 * re-increment the sema by the number of additional signals received,
1637 * so that the lock manager or signal manager will see the received
1638 * signal when it next waits.
1642 /* "false" means cannot accept cancel/die interrupt here. */
1643 PGSemaphoreLock(&proc->sem, false);
1644 if (!proc->lwWaiting)
1649 /* Now loop back and try to acquire lock again. */
1656 * Normally, we initialize the xlogInsertingAt value of the slot to 1,
1657 * because we don't yet know where in the WAL we're going to insert. It's
1658 * not critical what it points to right now - leaving it to a too small
1659 * value just means that WaitXlogInsertionsToFinish() might wait on us
1660 * unnecessarily, until we update the value (when we finish the insert or
1661 * move to next page).
1663 * If we're grabbing all the slots, however, stamp all but the last one
1664 * with InvalidXLogRecPtr, meaning there is no insert in progress. The last
1665 * slot is the one that we will update as we proceed with the insert, the
1666 * rest are held just to keep off other inserters.
1668 if (slotno != -1 && slotno != num_xloginsert_slots - 1)
1669 slot->xlogInsertingAt = InvalidXLogRecPtr;
1671 slot->xlogInsertingAt = 1;
1673 /* We are done updating shared state of the slot itself. */
1674 SpinLockRelease(&slot->mutex);
1677 * Fix the process wait semaphore's count for any absorbed wakeups.
1679 while (extraWaits-- > 0)
1680 PGSemaphoreUnlock(&proc->sem);
1683 * If we couldn't get the slot immediately, try another slot next time.
1684 * On a system with more insertion slots than concurrent inserters, this
1685 * causes all the inserters to eventually migrate to a slot that no-one
1686 * else is using. On a system with more inserters than slots, it still
1687 * causes the inserters to be distributed quite evenly across the slots.
1689 if (slotno != -1 && retry)
1690 slotToTry = (slotToTry + 1) % num_xloginsert_slots;
1694 * Wait for the given slot to become free, or for its xlogInsertingAt location
1695 * to change to something else than 'waitptr'. In other words, wait for the
1696 * inserter using the given slot to finish its insertion, or to at least make
1700 WaitOnSlot(volatile XLogInsertSlot *slot, XLogRecPtr waitptr)
1702 PGPROC *proc = MyProc;
1706 * Lock out cancel/die interrupts while we sleep on the slot. There is
1707 * no cleanup mechanism to remove us from the wait queue if we got
1713 * Loop here to try to acquire lock after each time we are signaled.
1719 /* Acquire mutex. Time spent holding mutex should be short! */
1720 SpinLockAcquire(&slot->mutex);
1722 /* If I can get the lock, do so quickly. */
1723 if (slot->exclusive == 0 || slot->xlogInsertingAt != waitptr)
1729 break; /* the lock was free */
1731 Assert(slot->owner != MyProc);
1734 * Add myself to wait queue.
1736 proc->lwWaiting = true;
1737 proc->lwWaitMode = LW_WAIT_UNTIL_FREE;
1738 proc->lwWaitLink = NULL;
1740 /* waiters are added to the front of the queue */
1741 proc->lwWaitLink = slot->head;
1742 if (slot->head == NULL)
1746 /* Can release the mutex now */
1747 SpinLockRelease(&slot->mutex);
1750 * Wait until awakened.
1752 * Since we share the process wait semaphore with other things, like
1753 * the regular lock manager and ProcWaitForSignal, and we may need to
1754 * acquire an LWLock while one of those is pending, it is possible that
1755 * we get awakened for a reason other than being signaled by
1756 * LWLockRelease. If so, loop back and wait again. Once we've gotten
1757 * the LWLock, re-increment the sema by the number of additional
1758 * signals received, so that the lock manager or signal manager will
1759 * see the received signal when it next waits.
1763 /* "false" means cannot accept cancel/die interrupt here. */
1764 PGSemaphoreLock(&proc->sem, false);
1765 if (!proc->lwWaiting)
1770 /* Now loop back and try to acquire lock again. */
1773 /* We are done updating shared state of the lock itself. */
1774 SpinLockRelease(&slot->mutex);
1777 * Fix the process wait semaphore's count for any absorbed wakeups.
1779 while (extraWaits-- > 0)
1780 PGSemaphoreUnlock(&proc->sem);
1783 * Now okay to allow cancel/die interrupts.
1785 RESUME_INTERRUPTS();
1789 * Wake up all processes waiting for us with WaitOnSlot(). Sets our
1790 * xlogInsertingAt value to EndPos, without releasing the slot.
1793 WakeupWaiters(XLogRecPtr EndPos)
1795 volatile XLogInsertSlot *slot = &XLogCtl->Insert.insertSlots[MySlotNo].slot;
1801 * If we have already reported progress up to the same point, do nothing.
1802 * No other process can modify xlogInsertingAt, so we can check this before
1803 * grabbing the spinlock.
1805 if (slot->xlogInsertingAt == EndPos)
1807 /* xlogInsertingAt should not go backwards */
1808 Assert(slot->xlogInsertingAt < EndPos);
1810 /* Acquire mutex. Time spent holding mutex should be short! */
1811 SpinLockAcquire(&slot->mutex);
1813 /* we should own the slot */
1814 Assert(slot->exclusive == 1 && slot->owner == MyProc);
1816 slot->xlogInsertingAt = EndPos;
1819 * See if there are any waiters that need to be woken up.
1827 /* LW_WAIT_UNTIL_FREE waiters are always in the front of the queue */
1828 next = proc->lwWaitLink;
1829 while (next && next->lwWaitMode == LW_WAIT_UNTIL_FREE)
1832 next = next->lwWaitLink;
1835 /* proc is now the last PGPROC to be released */
1837 proc->lwWaitLink = NULL;
1840 /* We are done updating shared state of the lock itself. */
1841 SpinLockRelease(&slot->mutex);
1844 * Awaken any waiters I removed from the queue.
1846 while (head != NULL)
1849 head = proc->lwWaitLink;
1850 proc->lwWaitLink = NULL;
1851 proc->lwWaiting = false;
1852 PGSemaphoreUnlock(&proc->sem);
1857 * Release our insertion slot (or slots, if we're holding them all).
1860 WALInsertSlotRelease(void)
1864 if (holdingAllSlots)
1866 for (i = 0; i < num_xloginsert_slots; i++)
1867 WALInsertSlotReleaseOne(i);
1868 holdingAllSlots = false;
1871 WALInsertSlotReleaseOne(MySlotNo);
1875 WALInsertSlotReleaseOne(int slotno)
1877 volatile XLogInsertSlot *slot = &XLogCtl->Insert.insertSlots[slotno].slot;
1881 /* Acquire mutex. Time spent holding mutex should be short! */
1882 SpinLockAcquire(&slot->mutex);
1884 /* we must be holding it */
1885 Assert(slot->exclusive == 1 && slot->owner == MyProc);
1887 slot->xlogInsertingAt = InvalidXLogRecPtr;
1889 /* Release my hold on the slot */
1890 slot->exclusive = 0;
1894 * See if I need to awaken any waiters..
1899 if (slot->releaseOK)
1902 * Remove the to-be-awakened PGPROCs from the queue.
1904 bool releaseOK = true;
1909 * First wake up any backends that want to be woken up without
1910 * acquiring the lock. These are always in the front of the queue.
1912 while (proc->lwWaitMode == LW_WAIT_UNTIL_FREE && proc->lwWaitLink)
1913 proc = proc->lwWaitLink;
1916 * Awaken the first exclusive-waiter, if any.
1918 if (proc->lwWaitLink)
1920 Assert(proc->lwWaitLink->lwWaitMode == LW_EXCLUSIVE);
1921 proc = proc->lwWaitLink;
1924 /* proc is now the last PGPROC to be released */
1925 slot->head = proc->lwWaitLink;
1926 proc->lwWaitLink = NULL;
1928 slot->releaseOK = releaseOK;
1934 /* We are done updating shared state of the slot itself. */
1935 SpinLockRelease(&slot->mutex);
1938 * Awaken any waiters I removed from the queue.
1940 while (head != NULL)
1943 head = proc->lwWaitLink;
1944 proc->lwWaitLink = NULL;
1945 proc->lwWaiting = false;
1946 PGSemaphoreUnlock(&proc->sem);
1950 * Now okay to allow cancel/die interrupts.
1957 * Wait for any WAL insertions < upto to finish.
1959 * Returns the location of the oldest insertion that is still in-progress.
1960 * Any WAL prior to that point has been fully copied into WAL buffers, and
1961 * can be flushed out to disk. Because this waits for any insertions older
1962 * than 'upto' to finish, the return value is always >= 'upto'.
1964 * Note: When you are about to write out WAL, you must call this function
1965 * *before* acquiring WALWriteLock, to avoid deadlocks. This function might
1966 * need to wait for an insertion to finish (or at least advance to next
1967 * uninitialized page), and the inserter might need to evict an old WAL buffer
1968 * to make room for a new one, which in turn requires WALWriteLock.
1971 WaitXLogInsertionsToFinish(XLogRecPtr upto)
1974 XLogRecPtr reservedUpto;
1975 XLogRecPtr finishedUpto;
1976 volatile XLogCtlInsert *Insert = &XLogCtl->Insert;
1980 elog(PANIC, "cannot wait without a PGPROC structure");
1982 /* Read the current insert position */
1983 SpinLockAcquire(&Insert->insertpos_lck);
1984 bytepos = Insert->CurrBytePos;
1985 SpinLockRelease(&Insert->insertpos_lck);
1986 reservedUpto = XLogBytePosToEndRecPtr(bytepos);
1989 * No-one should request to flush a piece of WAL that hasn't even been
1990 * reserved yet. However, it can happen if there is a block with a bogus
1991 * LSN on disk, for example. XLogFlush checks for that situation and
1992 * complains, but only after the flush. Here we just assume that to mean
1993 * that all WAL that has been reserved needs to be finished. In this
1994 * corner-case, the return value can be smaller than 'upto' argument.
1996 if (upto > reservedUpto)
1998 elog(LOG, "request to flush past end of generated WAL; request %X/%X, currpos %X/%X",
1999 (uint32) (upto >> 32), (uint32) upto,
2000 (uint32) (reservedUpto >> 32), (uint32) reservedUpto);
2001 upto = reservedUpto;
2005 * finishedUpto is our return value, indicating the point upto which
2006 * all the WAL insertions have been finished. Initialize it to the head
2007 * of reserved WAL, and as we iterate through the insertion slots, back it
2008 * out for any insertion that's still in progress.
2010 finishedUpto = reservedUpto;
2013 * Loop through all the slots, sleeping on any in-progress insert older
2016 for (i = 0; i < num_xloginsert_slots; i++)
2018 volatile XLogInsertSlot *slot = &XLogCtl->Insert.insertSlots[i].slot;
2019 XLogRecPtr insertingat;
2023 * We can check if the slot is in use without grabbing the spinlock.
2024 * The spinlock acquisition of insertpos_lck before this loop acts
2025 * as a memory barrier. If someone acquires the slot after that, it
2026 * can't possibly be inserting to anything < reservedUpto. If it was
2027 * acquired before that, an unlocked test will return true.
2029 if (!slot->exclusive)
2032 SpinLockAcquire(&slot->mutex);
2033 /* re-check now that we have the lock */
2034 if (!slot->exclusive)
2036 SpinLockRelease(&slot->mutex);
2039 insertingat = slot->xlogInsertingAt;
2040 SpinLockRelease(&slot->mutex);
2042 if (insertingat == InvalidXLogRecPtr)
2045 * slot is reserved just to hold off other inserters, there is no
2046 * actual insert in progress.
2052 * This insertion is still in progress. Do we need to wait for it?
2054 * When an inserter acquires a slot, it doesn't reset 'insertingat', so
2055 * it will initially point to the old value of some already-finished
2056 * insertion. The inserter will update the value as soon as it finishes
2057 * the insertion, moves to the next page, or has to do I/O to flush an
2058 * old dirty buffer. That means that when we see a slot with
2059 * insertingat value < upto, we don't know if that insertion is still
2060 * truly in progress, or if the slot is reused by a new inserter that
2061 * hasn't updated the insertingat value yet. We have to assume it's the
2064 if (insertingat < upto)
2066 WaitOnSlot(slot, insertingat);
2072 * We don't need to wait for this insertion, but update the
2075 if (insertingat < finishedUpto)
2076 finishedUpto = insertingat;
2079 return finishedUpto;
2083 * Get a pointer to the right location in the WAL buffer containing the
2086 * If the page is not initialized yet, it is initialized. That might require
2087 * evicting an old dirty buffer from the buffer cache, which means I/O.
2089 * The caller must ensure that the page containing the requested location
2090 * isn't evicted yet, and won't be evicted. The way to ensure that is to
2091 * hold onto an XLogInsertSlot with the xlogInsertingAt position set to
2092 * something <= ptr. GetXLogBuffer() will update xlogInsertingAt if it needs
2093 * to evict an old page from the buffer. (This means that once you call
2094 * GetXLogBuffer() with a given 'ptr', you must not access anything before
2095 * that point anymore, and must not call GetXLogBuffer() with an older 'ptr'
2096 * later, because older buffers might be recycled already)
2099 GetXLogBuffer(XLogRecPtr ptr)
2103 static uint64 cachedPage = 0;
2104 static char *cachedPos = NULL;
2105 XLogRecPtr expectedEndPtr;
2108 * Fast path for the common case that we need to access again the same
2109 * page as last time.
2111 if (ptr / XLOG_BLCKSZ == cachedPage)
2113 Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
2114 Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
2115 return cachedPos + ptr % XLOG_BLCKSZ;
2119 * The XLog buffer cache is organized so that a page is always loaded
2120 * to a particular buffer. That way we can easily calculate the buffer
2121 * a given page must be loaded into, from the XLogRecPtr alone.
2123 idx = XLogRecPtrToBufIdx(ptr);
2126 * See what page is loaded in the buffer at the moment. It could be the
2127 * page we're looking for, or something older. It can't be anything newer
2128 * - that would imply the page we're looking for has already been written
2129 * out to disk and evicted, and the caller is responsible for making sure
2130 * that doesn't happen.
2132 * However, we don't hold a lock while we read the value. If someone has
2133 * just initialized the page, it's possible that we get a "torn read" of
2134 * the XLogRecPtr if 64-bit fetches are not atomic on this platform. In
2135 * that case we will see a bogus value. That's ok, we'll grab the mapping
2136 * lock (in AdvanceXLInsertBuffer) and retry if we see anything else than
2137 * the page we're looking for. But it means that when we do this unlocked
2138 * read, we might see a value that appears to be ahead of the page we're
2139 * looking for. Don't PANIC on that, until we've verified the value while
2142 expectedEndPtr = ptr;
2143 expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
2145 endptr = XLogCtl->xlblocks[idx];
2146 if (expectedEndPtr != endptr)
2149 * Let others know that we're finished inserting the record up
2150 * to the page boundary.
2152 WakeupWaiters(expectedEndPtr - XLOG_BLCKSZ);
2154 AdvanceXLInsertBuffer(ptr, false);
2155 endptr = XLogCtl->xlblocks[idx];
2157 if (expectedEndPtr != endptr)
2158 elog(PANIC, "could not find WAL buffer for %X/%X",
2159 (uint32) (ptr >> 32) , (uint32) ptr);
2164 * Make sure the initialization of the page is visible to us, and
2165 * won't arrive later to overwrite the WAL data we write on the page.
2167 pg_memory_barrier();
2171 * Found the buffer holding this page. Return a pointer to the right
2172 * offset within the page.
2174 cachedPage = ptr / XLOG_BLCKSZ;
2175 cachedPos = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
2177 Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
2178 Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
2180 return cachedPos + ptr % XLOG_BLCKSZ;
2184 * Converts a "usable byte position" to XLogRecPtr. A usable byte position
2185 * is the position starting from the beginning of WAL, excluding all WAL
2189 XLogBytePosToRecPtr(uint64 bytepos)
2197 fullsegs = bytepos / UsableBytesInSegment;
2198 bytesleft = bytepos % UsableBytesInSegment;
2200 if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
2202 /* fits on first page of segment */
2203 seg_offset = bytesleft + SizeOfXLogLongPHD;
2207 /* account for the first page on segment with long header */
2208 seg_offset = XLOG_BLCKSZ;
2209 bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2211 fullpages = bytesleft / UsableBytesInPage;
2212 bytesleft = bytesleft % UsableBytesInPage;
2214 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2217 XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, result);
2223 * Like XLogBytePosToRecPtr, but if the position is at a page boundary,
2224 * returns a pointer to the beginning of the page (ie. before page header),
2225 * not to where the first xlog record on that page would go to. This is used
2226 * when converting a pointer to the end of a record.
2229 XLogBytePosToEndRecPtr(uint64 bytepos)
2237 fullsegs = bytepos / UsableBytesInSegment;
2238 bytesleft = bytepos % UsableBytesInSegment;
2240 if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
2242 /* fits on first page of segment */
2246 seg_offset = bytesleft + SizeOfXLogLongPHD;
2250 /* account for the first page on segment with long header */
2251 seg_offset = XLOG_BLCKSZ;
2252 bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2254 fullpages = bytesleft / UsableBytesInPage;
2255 bytesleft = bytesleft % UsableBytesInPage;
2258 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
2260 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2263 XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, result);
2269 * Convert an XLogRecPtr to a "usable byte position".
2272 XLogRecPtrToBytePos(XLogRecPtr ptr)
2279 XLByteToSeg(ptr, fullsegs);
2281 fullpages = (ptr % XLOG_SEG_SIZE) / XLOG_BLCKSZ;
2282 offset = ptr % XLOG_BLCKSZ;
2286 result = fullsegs * UsableBytesInSegment;
2289 Assert(offset >= SizeOfXLogLongPHD);
2290 result += offset - SizeOfXLogLongPHD;
2295 result = fullsegs * UsableBytesInSegment +
2296 (XLOG_BLCKSZ - SizeOfXLogLongPHD) + /* account for first page */
2297 (fullpages - 1) * UsableBytesInPage; /* full pages */
2300 Assert(offset >= SizeOfXLogShortPHD);
2301 result += offset - SizeOfXLogShortPHD;
2309 * Determine whether the buffer referenced by an XLogRecData item has to
2310 * be backed up, and if so fill a BkpBlock struct for it. In any case
2311 * save the buffer's LSN at *lsn.
2314 XLogCheckBuffer(XLogRecData *rdata, bool holdsExclusiveLock,
2315 XLogRecPtr *lsn, BkpBlock *bkpb)
2319 page = BufferGetPage(rdata->buffer);
2322 * We assume page LSN is first data on *every* page that can be passed to
2323 * XLogInsert, whether it has the standard page layout or not. We don't
2324 * need to take the buffer header lock for PageGetLSN if we hold an
2325 * exclusive lock on the page and/or the relation.
2327 if (holdsExclusiveLock)
2328 *lsn = PageGetLSN(page);
2330 *lsn = BufferGetLSNAtomic(rdata->buffer);
2332 if (*lsn <= RedoRecPtr)
2335 * The page needs to be backed up, so set up *bkpb
2337 BufferGetTag(rdata->buffer, &bkpb->node, &bkpb->fork, &bkpb->block);
2339 if (rdata->buffer_std)
2341 /* Assume we can omit data between pd_lower and pd_upper */
2342 uint16 lower = ((PageHeader) page)->pd_lower;
2343 uint16 upper = ((PageHeader) page)->pd_upper;
2345 if (lower >= SizeOfPageHeaderData &&
2349 bkpb->hole_offset = lower;
2350 bkpb->hole_length = upper - lower;
2354 /* No "hole" to compress out */
2355 bkpb->hole_offset = 0;
2356 bkpb->hole_length = 0;
2361 /* Not a standard page header, don't try to eliminate "hole" */
2362 bkpb->hole_offset = 0;
2363 bkpb->hole_length = 0;
2366 return true; /* buffer requires backup */
2369 return false; /* buffer does not need to be backed up */
2373 * Initialize XLOG buffers, writing out old buffers if they still contain
2374 * unwritten data, upto the page containing 'upto'. Or if 'opportunistic' is
2375 * true, initialize as many pages as we can without having to write out
2376 * unwritten data. Any new pages are initialized to zeros, with pages headers
2377 * initialized properly.
2380 AdvanceXLInsertBuffer(XLogRecPtr upto, bool opportunistic)
2382 XLogCtlInsert *Insert = &XLogCtl->Insert;
2384 XLogRecPtr OldPageRqstPtr;
2385 XLogwrtRqst WriteRqst;
2386 XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
2387 XLogRecPtr NewPageBeginPtr;
2388 XLogPageHeader NewPage;
2391 LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2394 * Now that we have the lock, check if someone initialized the page
2397 while (upto >= XLogCtl->InitializedUpTo || opportunistic)
2399 nextidx = XLogRecPtrToBufIdx(XLogCtl->InitializedUpTo);
2402 * Get ending-offset of the buffer page we need to replace (this may
2403 * be zero if the buffer hasn't been used yet). Fall through if it's
2404 * already written out.
2406 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
2407 if (LogwrtResult.Write < OldPageRqstPtr)
2410 * Nope, got work to do. If we just want to pre-initialize as much
2411 * as we can without flushing, give up now.
2416 /* Before waiting, get info_lck and update LogwrtResult */
2418 /* use volatile pointer to prevent code rearrangement */
2419 volatile XLogCtlData *xlogctl = XLogCtl;
2421 SpinLockAcquire(&xlogctl->info_lck);
2422 if (xlogctl->LogwrtRqst.Write < OldPageRqstPtr)
2423 xlogctl->LogwrtRqst.Write = OldPageRqstPtr;
2424 LogwrtResult = xlogctl->LogwrtResult;
2425 SpinLockRelease(&xlogctl->info_lck);
2429 * Now that we have an up-to-date LogwrtResult value, see if we
2430 * still need to write it or if someone else already did.
2432 if (LogwrtResult.Write < OldPageRqstPtr)
2435 * Must acquire write lock. Release WALBufMappingLock first,
2436 * to make sure that all insertions that we need to wait for
2437 * can finish (up to this same position). Otherwise we risk
2440 LWLockRelease(WALBufMappingLock);
2442 WaitXLogInsertionsToFinish(OldPageRqstPtr);
2444 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2446 LogwrtResult = XLogCtl->LogwrtResult;
2447 if (LogwrtResult.Write >= OldPageRqstPtr)
2449 /* OK, someone wrote it already */
2450 LWLockRelease(WALWriteLock);
2454 /* Have to write it ourselves */
2455 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2456 WriteRqst.Write = OldPageRqstPtr;
2457 WriteRqst.Flush = 0;
2458 XLogWrite(WriteRqst, false);
2459 LWLockRelease(WALWriteLock);
2460 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
2462 /* Re-acquire WALBufMappingLock and retry */
2463 LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2469 * Now the next buffer slot is free and we can set it up to be the next
2472 NewPageBeginPtr = XLogCtl->InitializedUpTo;
2473 NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2475 Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
2477 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
2480 * Be sure to re-zero the buffer so that bytes beyond what we've
2481 * written will look like zeroes and not valid XLOG records...
2483 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
2486 * Fill the new page's header
2488 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
2490 /* NewPage->xlp_info = 0; */ /* done by memset */
2491 NewPage ->xlp_tli = ThisTimeLineID;
2492 NewPage ->xlp_pageaddr = NewPageBeginPtr;
2493 /* NewPage->xlp_rem_len = 0; */ /* done by memset */
2496 * If online backup is not in progress, mark the header to indicate
2497 * that* WAL records beginning in this page have removable backup
2498 * blocks. This allows the WAL archiver to know whether it is safe to
2499 * compress archived WAL data by transforming full-block records into
2500 * the non-full-block format. It is sufficient to record this at the
2501 * page level because we force a page switch (in fact a segment switch)
2502 * when starting a backup, so the flag will be off before any records
2503 * can be written during the backup. At the end of a backup, the last
2504 * page will be marked as all unsafe when perhaps only part is unsafe,
2505 * but at worst the archiver would miss the opportunity to compress a
2508 if (!Insert->forcePageWrites)
2509 NewPage ->xlp_info |= XLP_BKP_REMOVABLE;
2512 * If first page of an XLOG segment file, make it a long header.
2514 if ((NewPage->xlp_pageaddr % XLogSegSize) == 0)
2516 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
2518 NewLongPage->xlp_sysid = ControlFile->system_identifier;
2519 NewLongPage->xlp_seg_size = XLogSegSize;
2520 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
2521 NewPage ->xlp_info |= XLP_LONG_HEADER;
2525 * Make sure the initialization of the page becomes visible to others
2526 * before the xlblocks update. GetXLogBuffer() reads xlblocks without
2531 *((volatile XLogRecPtr *) &XLogCtl->xlblocks[nextidx]) = NewPageEndPtr;
2533 XLogCtl->InitializedUpTo = NewPageEndPtr;
2537 LWLockRelease(WALBufMappingLock);
2542 elog(DEBUG1, "initialized %d pages, upto %X/%X",
2543 npages, (uint32) (NewPageEndPtr >> 32), (uint32) NewPageEndPtr);
2549 * Check whether we've consumed enough xlog space that a checkpoint is needed.
2551 * new_segno indicates a log file that has just been filled up (or read
2552 * during recovery). We measure the distance from RedoRecPtr to new_segno
2553 * and see if that exceeds CheckPointSegments.
2555 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
2558 XLogCheckpointNeeded(XLogSegNo new_segno)
2560 XLogSegNo old_segno;
2562 XLByteToSeg(RedoRecPtr, old_segno);
2564 if (new_segno >= old_segno + (uint64) (CheckPointSegments - 1))
2570 * Write and/or fsync the log at least as far as WriteRqst indicates.
2572 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
2573 * may stop at any convenient boundary (such as a cache or logfile boundary).
2574 * This option allows us to avoid uselessly issuing multiple writes when a
2575 * single one would do.
2577 * Must be called with WALWriteLock held. WaitXLogInsertionsToFinish(WriteRqst)
2578 * must be called before grabbing the lock, to make sure the data is ready to
2582 XLogWrite(XLogwrtRqst WriteRqst, bool flexible)
2585 bool last_iteration;
2593 /* We should always be inside a critical section here */
2594 Assert(CritSectionCount > 0);
2597 * Update local LogwrtResult (caller probably did this already, but...)
2599 LogwrtResult = XLogCtl->LogwrtResult;
2602 * Since successive pages in the xlog cache are consecutively allocated,
2603 * we can usually gather multiple pages together and issue just one
2604 * write() call. npages is the number of pages we have determined can be
2605 * written together; startidx is the cache block index of the first one,
2606 * and startoffset is the file offset at which it should go. The latter
2607 * two variables are only valid when npages > 0, but we must initialize
2608 * all of them to keep the compiler quiet.
2615 * Within the loop, curridx is the cache block index of the page to
2616 * consider writing. Begin at the buffer containing the next unwritten
2617 * page, or last partially written page.
2619 curridx = XLogRecPtrToBufIdx(LogwrtResult.Write);
2621 while (LogwrtResult.Write < WriteRqst.Write)
2624 * Make sure we're not ahead of the insert process. This could happen
2625 * if we're passed a bogus WriteRqst.Write that is past the end of the
2626 * last page that's been initialized by AdvanceXLInsertBuffer.
2628 XLogRecPtr EndPtr = XLogCtl->xlblocks[curridx];
2629 if (LogwrtResult.Write >= EndPtr)
2630 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
2631 (uint32) (LogwrtResult.Write >> 32),
2632 (uint32) LogwrtResult.Write,
2633 (uint32) (EndPtr >> 32), (uint32) EndPtr);
2635 /* Advance LogwrtResult.Write to end of current buffer page */
2636 LogwrtResult.Write = EndPtr;
2637 ispartialpage = WriteRqst.Write < LogwrtResult.Write;
2639 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo))
2642 * Switch to new logfile segment. We cannot have any pending
2643 * pages here (since we dump what we have at segment end).
2645 Assert(npages == 0);
2646 if (openLogFile >= 0)
2648 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo);
2650 /* create/use new log file */
2651 use_existent = true;
2652 openLogFile = XLogFileInit(openLogSegNo, &use_existent, true);
2656 /* Make sure we have the current logfile open */
2657 if (openLogFile < 0)
2659 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo);
2660 openLogFile = XLogFileOpen(openLogSegNo);
2664 /* Add current page to the set of pending pages-to-dump */
2667 /* first of group */
2669 startoffset = (LogwrtResult.Write - XLOG_BLCKSZ) % XLogSegSize;
2674 * Dump the set if this will be the last loop iteration, or if we are
2675 * at the last page of the cache area (since the next page won't be
2676 * contiguous in memory), or if we are at the end of the logfile
2679 last_iteration = WriteRqst.Write <= LogwrtResult.Write;
2681 finishing_seg = !ispartialpage &&
2682 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
2684 if (last_iteration ||
2685 curridx == XLogCtl->XLogCacheBlck ||
2693 /* Need to seek in the file? */
2694 if (openLogOff != startoffset)
2696 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
2698 (errcode_for_file_access(),
2699 errmsg("could not seek in log file %s to offset %u: %m",
2700 XLogFileNameP(ThisTimeLineID, openLogSegNo),
2702 openLogOff = startoffset;
2705 /* OK to write the page(s) */
2706 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
2707 nbytes = npages * (Size) XLOG_BLCKSZ;
2712 written = write(openLogFile, from, nleft);
2718 (errcode_for_file_access(),
2719 errmsg("could not write to log file %s "
2720 "at offset %u, length %lu: %m",
2721 XLogFileNameP(ThisTimeLineID, openLogSegNo),
2722 openLogOff, (unsigned long) nbytes)));
2726 } while (nleft > 0);
2728 /* Update state for write */
2729 openLogOff += nbytes;
2733 * If we just wrote the whole last page of a logfile segment,
2734 * fsync the segment immediately. This avoids having to go back
2735 * and re-open prior segments when an fsync request comes along
2736 * later. Doing it here ensures that one and only one backend will
2737 * perform this fsync.
2739 * This is also the right place to notify the Archiver that the
2740 * segment is ready to copy to archival storage, and to update the
2741 * timer for archive_timeout, and to signal for a checkpoint if
2742 * too many logfile segments have been used since the last
2747 issue_xlog_fsync(openLogFile, openLogSegNo);
2749 /* signal that we need to wakeup walsenders later */
2750 WalSndWakeupRequest();
2752 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
2754 if (XLogArchivingActive())
2755 XLogArchiveNotifySeg(openLogSegNo);
2757 XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
2760 * Request a checkpoint if we've consumed too much xlog since
2761 * the last one. For speed, we first check using the local
2762 * copy of RedoRecPtr, which might be out of date; if it looks
2763 * like a checkpoint is needed, forcibly update RedoRecPtr and
2766 if (IsUnderPostmaster && XLogCheckpointNeeded(openLogSegNo))
2768 (void) GetRedoRecPtr();
2769 if (XLogCheckpointNeeded(openLogSegNo))
2770 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
2777 /* Only asked to write a partial page */
2778 LogwrtResult.Write = WriteRqst.Write;
2781 curridx = NextBufIdx(curridx);
2783 /* If flexible, break out of loop as soon as we wrote something */
2784 if (flexible && npages == 0)
2788 Assert(npages == 0);
2791 * If asked to flush, do so
2793 if (LogwrtResult.Flush < WriteRqst.Flush &&
2794 LogwrtResult.Flush < LogwrtResult.Write)
2798 * Could get here without iterating above loop, in which case we might
2799 * have no open file or the wrong one. However, we do not need to
2800 * fsync more than one file.
2802 if (sync_method != SYNC_METHOD_OPEN &&
2803 sync_method != SYNC_METHOD_OPEN_DSYNC)
2805 if (openLogFile >= 0 &&
2806 !XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo))
2808 if (openLogFile < 0)
2810 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo);
2811 openLogFile = XLogFileOpen(openLogSegNo);
2815 issue_xlog_fsync(openLogFile, openLogSegNo);
2818 /* signal that we need to wakeup walsenders later */
2819 WalSndWakeupRequest();
2821 LogwrtResult.Flush = LogwrtResult.Write;
2825 * Update shared-memory status
2827 * We make sure that the shared 'request' values do not fall behind the
2828 * 'result' values. This is not absolutely essential, but it saves some
2829 * code in a couple of places.
2832 /* use volatile pointer to prevent code rearrangement */
2833 volatile XLogCtlData *xlogctl = XLogCtl;
2835 SpinLockAcquire(&xlogctl->info_lck);
2836 xlogctl->LogwrtResult = LogwrtResult;
2837 if (xlogctl->LogwrtRqst.Write < LogwrtResult.Write)
2838 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
2839 if (xlogctl->LogwrtRqst.Flush < LogwrtResult.Flush)
2840 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
2841 SpinLockRelease(&xlogctl->info_lck);
2846 * Record the LSN for an asynchronous transaction commit/abort
2847 * and nudge the WALWriter if there is work for it to do.
2848 * (This should not be called for synchronous commits.)
2851 XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
2853 XLogRecPtr WriteRqstPtr = asyncXactLSN;
2856 /* use volatile pointer to prevent code rearrangement */
2857 volatile XLogCtlData *xlogctl = XLogCtl;
2859 SpinLockAcquire(&xlogctl->info_lck);
2860 LogwrtResult = xlogctl->LogwrtResult;
2861 sleeping = xlogctl->WalWriterSleeping;
2862 if (xlogctl->asyncXactLSN < asyncXactLSN)
2863 xlogctl->asyncXactLSN = asyncXactLSN;
2864 SpinLockRelease(&xlogctl->info_lck);
2867 * If the WALWriter is sleeping, we should kick it to make it come out of
2868 * low-power mode. Otherwise, determine whether there's a full page of
2869 * WAL available to write.
2873 /* back off to last completed page boundary */
2874 WriteRqstPtr -= WriteRqstPtr % XLOG_BLCKSZ;
2876 /* if we have already flushed that far, we're done */
2877 if (WriteRqstPtr <= LogwrtResult.Flush)
2882 * Nudge the WALWriter: it has a full page of WAL to write, or we want it
2883 * to come out of low-power mode so that this async commit will reach disk
2884 * within the expected amount of time.
2886 if (ProcGlobal->walwriterLatch)
2887 SetLatch(ProcGlobal->walwriterLatch);
2891 * Advance minRecoveryPoint in control file.
2893 * If we crash during recovery, we must reach this point again before the
2894 * database is consistent.
2896 * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
2897 * is only updated if it's not already greater than or equal to 'lsn'.
2900 UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
2902 /* Quick check using our local copy of the variable */
2903 if (!updateMinRecoveryPoint || (!force && lsn <= minRecoveryPoint))
2906 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2908 /* update local copy */
2909 minRecoveryPoint = ControlFile->minRecoveryPoint;
2910 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
2913 * An invalid minRecoveryPoint means that we need to recover all the WAL,
2914 * i.e., we're doing crash recovery. We never modify the control file's
2915 * value in that case, so we can short-circuit future checks here too.
2917 if (minRecoveryPoint == 0)
2918 updateMinRecoveryPoint = false;
2919 else if (force || minRecoveryPoint < lsn)
2921 /* use volatile pointer to prevent code rearrangement */
2922 volatile XLogCtlData *xlogctl = XLogCtl;
2923 XLogRecPtr newMinRecoveryPoint;
2924 TimeLineID newMinRecoveryPointTLI;
2927 * To avoid having to update the control file too often, we update it
2928 * all the way to the last record being replayed, even though 'lsn'
2929 * would suffice for correctness. This also allows the 'force' case
2930 * to not need a valid 'lsn' value.
2932 * Another important reason for doing it this way is that the passed
2933 * 'lsn' value could be bogus, i.e., past the end of available WAL, if
2934 * the caller got it from a corrupted heap page. Accepting such a
2935 * value as the min recovery point would prevent us from coming up at
2936 * all. Instead, we just log a warning and continue with recovery.
2937 * (See also the comments about corrupt LSNs in XLogFlush.)
2939 SpinLockAcquire(&xlogctl->info_lck);
2940 newMinRecoveryPoint = xlogctl->replayEndRecPtr;
2941 newMinRecoveryPointTLI = xlogctl->replayEndTLI;
2942 SpinLockRelease(&xlogctl->info_lck);
2944 if (!force && newMinRecoveryPoint < lsn)
2946 "xlog min recovery request %X/%X is past current point %X/%X",
2947 (uint32) (lsn >> 32), (uint32) lsn,
2948 (uint32) (newMinRecoveryPoint >> 32),
2949 (uint32) newMinRecoveryPoint);
2951 /* update control file */
2952 if (ControlFile->minRecoveryPoint < newMinRecoveryPoint)
2954 ControlFile->minRecoveryPoint = newMinRecoveryPoint;
2955 ControlFile->minRecoveryPointTLI = newMinRecoveryPointTLI;
2956 UpdateControlFile();
2957 minRecoveryPoint = newMinRecoveryPoint;
2958 minRecoveryPointTLI = newMinRecoveryPointTLI;
2961 (errmsg("updated min recovery point to %X/%X on timeline %u",
2962 (uint32) (minRecoveryPoint >> 32),
2963 (uint32) minRecoveryPoint,
2964 newMinRecoveryPointTLI)));
2967 LWLockRelease(ControlFileLock);
2971 * Ensure that all XLOG data through the given position is flushed to disk.
2973 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
2974 * already held, and we try to avoid acquiring it if possible.
2977 XLogFlush(XLogRecPtr record)
2979 XLogRecPtr WriteRqstPtr;
2980 XLogwrtRqst WriteRqst;
2983 * During REDO, we are reading not writing WAL. Therefore, instead of
2984 * trying to flush the WAL, we should update minRecoveryPoint instead. We
2985 * test XLogInsertAllowed(), not InRecovery, because we need checkpointer
2986 * to act this way too, and because when it tries to write the
2987 * end-of-recovery checkpoint, it should indeed flush.
2989 if (!XLogInsertAllowed())
2991 UpdateMinRecoveryPoint(record, false);
2995 /* Quick exit if already known flushed */
2996 if (record <= LogwrtResult.Flush)
3001 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
3002 (uint32) (record >> 32), (uint32) record,
3003 (uint32) (LogwrtResult.Write >> 32), (uint32) LogwrtResult.Write,
3004 (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
3007 START_CRIT_SECTION();
3010 * Since fsync is usually a horribly expensive operation, we try to
3011 * piggyback as much data as we can on each fsync: if we see any more data
3012 * entered into the xlog buffer, we'll write and fsync that too, so that
3013 * the final value of LogwrtResult.Flush is as large as possible. This
3014 * gives us some chance of avoiding another fsync immediately after.
3017 /* initialize to given target; may increase below */
3018 WriteRqstPtr = record;
3021 * Now wait until we get the write lock, or someone else does the flush
3026 /* use volatile pointer to prevent code rearrangement */
3027 volatile XLogCtlData *xlogctl = XLogCtl;
3028 XLogRecPtr insertpos;
3030 /* read LogwrtResult and update local state */
3031 SpinLockAcquire(&xlogctl->info_lck);
3032 if (WriteRqstPtr < xlogctl->LogwrtRqst.Write)
3033 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
3034 LogwrtResult = xlogctl->LogwrtResult;
3035 SpinLockRelease(&xlogctl->info_lck);
3038 if (record <= LogwrtResult.Flush)
3042 * Before actually performing the write, wait for all in-flight
3043 * insertions to the pages we're about to write to finish.
3045 insertpos = WaitXLogInsertionsToFinish(WriteRqstPtr);
3048 * Try to get the write lock. If we can't get it immediately, wait
3049 * until it's released, and recheck if we still need to do the flush
3050 * or if the backend that held the lock did it for us already. This
3051 * helps to maintain a good rate of group committing when the system
3052 * is bottlenecked by the speed of fsyncing.
3054 if (!LWLockAcquireOrWait(WALWriteLock, LW_EXCLUSIVE))
3057 * The lock is now free, but we didn't acquire it yet. Before we
3058 * do, loop back to check if someone else flushed the record for
3064 /* Got the lock; recheck whether request is satisfied */
3065 LogwrtResult = XLogCtl->LogwrtResult;
3066 if (record <= LogwrtResult.Flush)
3068 LWLockRelease(WALWriteLock);
3073 * Sleep before flush! By adding a delay here, we may give further
3074 * backends the opportunity to join the backlog of group commit
3075 * followers; this can significantly improve transaction throughput,
3076 * at the risk of increasing transaction latency.
3078 * We do not sleep if enableFsync is not turned on, nor if there are
3079 * fewer than CommitSiblings other backends with active transactions.
3081 if (CommitDelay > 0 && enableFsync &&
3082 MinimumActiveBackends(CommitSiblings))
3084 pg_usleep(CommitDelay);
3087 * Re-check how far we can now flush the WAL. It's generally not
3088 * safe to call WaitXLogInsetionsToFinish while holding
3089 * WALWriteLock, because an in-progress insertion might need to
3090 * also grab WALWriteLock to make progress. But we know that all
3091 * the insertions up to insertpos have already finished, because
3092 * that's what the earlier WaitXLogInsertionsToFinish() returned.
3093 * We're only calling it again to allow insertpos to be moved
3094 * further forward, not to actually wait for anyone.
3096 insertpos = WaitXLogInsertionsToFinish(insertpos);
3099 /* try to write/flush later additions to XLOG as well */
3100 WriteRqst.Write = insertpos;
3101 WriteRqst.Flush = insertpos;
3103 XLogWrite(WriteRqst, false);
3105 LWLockRelease(WALWriteLock);
3112 /* wake up walsenders now that we've released heavily contended locks */
3113 WalSndWakeupProcessRequests();
3116 * If we still haven't flushed to the request point then we have a
3117 * problem; most likely, the requested flush point is past end of XLOG.
3118 * This has been seen to occur when a disk page has a corrupted LSN.
3120 * Formerly we treated this as a PANIC condition, but that hurts the
3121 * system's robustness rather than helping it: we do not want to take down
3122 * the whole system due to corruption on one data page. In particular, if
3123 * the bad page is encountered again during recovery then we would be
3124 * unable to restart the database at all! (This scenario actually
3125 * happened in the field several times with 7.1 releases.) As of 8.4, bad
3126 * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
3127 * the only time we can reach here during recovery is while flushing the
3128 * end-of-recovery checkpoint record, and we don't expect that to have a
3131 * Note that for calls from xact.c, the ERROR will be promoted to PANIC
3132 * since xact.c calls this routine inside a critical section. However,
3133 * calls from bufmgr.c are not within critical sections and so we will not
3134 * force a restart for a bad LSN on a data page.
3136 if (LogwrtResult.Flush < record)
3138 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
3139 (uint32) (record >> 32), (uint32) record,
3140 (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
3144 * Flush xlog, but without specifying exactly where to flush to.
3146 * We normally flush only completed blocks; but if there is nothing to do on
3147 * that basis, we check for unflushed async commits in the current incomplete
3148 * block, and flush through the latest one of those. Thus, if async commits
3149 * are not being used, we will flush complete blocks only. We can guarantee
3150 * that async commits reach disk after at most three cycles; normally only
3151 * one or two. (When flushing complete blocks, we allow XLogWrite to write
3152 * "flexibly", meaning it can stop at the end of the buffer ring; this makes a
3153 * difference only with very high load or long wal_writer_delay, but imposes
3154 * one extra cycle for the worst case for async commits.)
3156 * This routine is invoked periodically by the background walwriter process.
3158 * Returns TRUE if we flushed anything.
3161 XLogBackgroundFlush(void)
3163 XLogRecPtr WriteRqstPtr;
3164 bool flexible = true;
3165 bool wrote_something = false;
3167 /* XLOG doesn't need flushing during recovery */
3168 if (RecoveryInProgress())
3171 /* read LogwrtResult and update local state */
3173 /* use volatile pointer to prevent code rearrangement */
3174 volatile XLogCtlData *xlogctl = XLogCtl;
3176 SpinLockAcquire(&xlogctl->info_lck);
3177 LogwrtResult = xlogctl->LogwrtResult;
3178 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
3179 SpinLockRelease(&xlogctl->info_lck);
3182 /* back off to last completed page boundary */
3183 WriteRqstPtr -= WriteRqstPtr % XLOG_BLCKSZ;
3185 /* if we have already flushed that far, consider async commit records */
3186 if (WriteRqstPtr <= LogwrtResult.Flush)
3188 /* use volatile pointer to prevent code rearrangement */
3189 volatile XLogCtlData *xlogctl = XLogCtl;
3191 SpinLockAcquire(&xlogctl->info_lck);
3192 WriteRqstPtr = xlogctl->asyncXactLSN;
3193 SpinLockRelease(&xlogctl->info_lck);
3194 flexible = false; /* ensure it all gets written */
3198 * If already known flushed, we're done. Just need to check if we are
3199 * holding an open file handle to a logfile that's no longer in use,
3200 * preventing the file from being deleted.
3202 if (WriteRqstPtr <= LogwrtResult.Flush)
3204 if (openLogFile >= 0)
3206 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo))
3216 elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
3217 (uint32) (WriteRqstPtr >> 32), (uint32) WriteRqstPtr,
3218 (uint32) (LogwrtResult.Write >> 32), (uint32) LogwrtResult.Write,
3219 (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
3222 START_CRIT_SECTION();
3224 /* now wait for any in-progress insertions to finish and get write lock */
3225 WaitXLogInsertionsToFinish(WriteRqstPtr);
3226 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
3227 LogwrtResult = XLogCtl->LogwrtResult;
3228 if (WriteRqstPtr > LogwrtResult.Flush)
3230 XLogwrtRqst WriteRqst;
3232 WriteRqst.Write = WriteRqstPtr;
3233 WriteRqst.Flush = WriteRqstPtr;
3234 XLogWrite(WriteRqst, flexible);
3235 wrote_something = true;
3237 LWLockRelease(WALWriteLock);
3241 /* wake up walsenders now that we've released heavily contended locks */
3242 WalSndWakeupProcessRequests();
3245 * Great, done. To take some work off the critical path, try to initialize
3246 * as many of the no-longer-needed WAL buffers for future use as we can.
3248 AdvanceXLInsertBuffer(InvalidXLogRecPtr, true);
3250 return wrote_something;
3254 * Test whether XLOG data has been flushed up to (at least) the given position.
3256 * Returns true if a flush is still needed. (It may be that someone else
3257 * is already in process of flushing that far, however.)
3260 XLogNeedsFlush(XLogRecPtr record)
3263 * During recovery, we don't flush WAL but update minRecoveryPoint
3264 * instead. So "needs flush" is taken to mean whether minRecoveryPoint
3265 * would need to be updated.
3267 if (RecoveryInProgress())
3269 /* Quick exit if already known updated */
3270 if (record <= minRecoveryPoint || !updateMinRecoveryPoint)
3274 * Update local copy of minRecoveryPoint. But if the lock is busy,
3275 * just return a conservative guess.
3277 if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
3279 minRecoveryPoint = ControlFile->minRecoveryPoint;
3280 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
3281 LWLockRelease(ControlFileLock);
3284 * An invalid minRecoveryPoint means that we need to recover all the
3285 * WAL, i.e., we're doing crash recovery. We never modify the control
3286 * file's value in that case, so we can short-circuit future checks
3289 if (minRecoveryPoint == 0)
3290 updateMinRecoveryPoint = false;
3293 if (record <= minRecoveryPoint || !updateMinRecoveryPoint)
3299 /* Quick exit if already known flushed */
3300 if (record <= LogwrtResult.Flush)
3303 /* read LogwrtResult and update local state */
3305 /* use volatile pointer to prevent code rearrangement */
3306 volatile XLogCtlData *xlogctl = XLogCtl;
3308 SpinLockAcquire(&xlogctl->info_lck);
3309 LogwrtResult = xlogctl->LogwrtResult;
3310 SpinLockRelease(&xlogctl->info_lck);
3314 if (record <= LogwrtResult.Flush)
3321 * Create a new XLOG file segment, or open a pre-existing one.
3323 * log, seg: identify segment to be created/opened.
3325 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
3326 * pre-existing file will be deleted). On return, TRUE if a pre-existing
3329 * use_lock: if TRUE, acquire ControlFileLock while moving file into
3330 * place. This should be TRUE except during bootstrap log creation. The
3331 * caller must *not* hold the lock at call.
3333 * Returns FD of opened file.
3335 * Note: errors here are ERROR not PANIC because we might or might not be
3336 * inside a critical section (eg, during checkpoint there is no reason to
3337 * take down the system on failure). They will promote to PANIC if we are
3338 * in a critical section.
3341 XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
3343 char path[MAXPGPATH];
3344 char tmppath[MAXPGPATH];
3345 XLogSegNo installed_segno;
3348 bool zero_fill = true;
3350 XLogFilePath(path, ThisTimeLineID, logsegno);
3353 * Try to use existent file (checkpoint maker may have created it already)
3357 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
3361 if (errno != ENOENT)
3363 (errcode_for_file_access(),
3364 errmsg("could not open file \"%s\": %m", path)));
3371 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
3372 * another process is doing the same thing. If so, we will end up
3373 * pre-creating an extra log segment. That seems OK, and better than
3374 * holding the lock throughout this lengthy process.
3376 elog(DEBUG2, "creating and filling new WAL file");
3378 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3382 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3383 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3387 (errcode_for_file_access(),
3388 errmsg("could not create file \"%s\": %m", tmppath)));
3390 #ifdef HAVE_POSIX_FALLOCATE
3392 * If posix_fallocate() is available and succeeds, then the file is
3393 * properly allocated and we don't need to zero-fill it (which is less
3394 * efficient). In case of an error, fall back to writing zeros, because on
3395 * some platforms posix_fallocate() is available but will not always
3396 * succeed in cases where zero-filling will.
3398 if (posix_fallocate(fd, 0, XLogSegSize) == 0)
3400 #endif /* HAVE_POSIX_FALLOCATE */
3405 * Allocate a buffer full of zeros. This is done before opening the
3406 * file so that we don't leak the file descriptor if palloc fails.
3408 * Note: palloc zbuffer, instead of just using a local char array, to
3409 * ensure it is reasonably well-aligned; this may save a few cycles
3410 * transferring data to the kernel.
3413 char *zbuffer = (char *) palloc0(XLOG_BLCKSZ);
3417 * Zero-fill the file. We have to do this the hard way to ensure that
3418 * all the file space has really been allocated --- on platforms that
3419 * allow "holes" in files, just seeking to the end doesn't allocate
3420 * intermediate space. This way, we know that we have all the space
3421 * and (after the fsync below) that all the indirect blocks are down on
3422 * disk. Therefore, fdatasync(2) or O_DSYNC will be sufficient to sync
3423 * future writes to the log file.
3425 for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
3428 if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
3430 int save_errno = errno;
3433 * If we fail to make the file, delete it to release disk space
3439 /* if write didn't set errno, assume no disk space */
3440 errno = save_errno ? save_errno : ENOSPC;
3443 (errcode_for_file_access(),
3444 errmsg("could not write to file \"%s\": %m",
3451 if (pg_fsync(fd) != 0)
3455 (errcode_for_file_access(),
3456 errmsg("could not fsync file \"%s\": %m", tmppath)));
3461 (errcode_for_file_access(),
3462 errmsg("could not close file \"%s\": %m", tmppath)));
3465 * Now move the segment into place with its final name.
3467 * If caller didn't want to use a pre-existing file, get rid of any
3468 * pre-existing file. Otherwise, cope with possibility that someone else
3469 * has created the file while we were filling ours: if so, use ours to
3470 * pre-create a future log segment.
3472 installed_segno = logsegno;
3473 max_advance = XLOGfileslop;
3474 if (!InstallXLogFileSegment(&installed_segno, tmppath,
3475 *use_existent, &max_advance,
3479 * No need for any more future segments, or InstallXLogFileSegment()
3480 * failed to rename the file into place. If the rename failed, opening
3481 * the file below will fail.
3486 /* Set flag to tell caller there was no existent file */
3487 *use_existent = false;
3489 /* Now open original target segment (might not be file I just made) */
3490 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
3494 (errcode_for_file_access(),
3495 errmsg("could not open file \"%s\": %m", path)));
3497 elog(DEBUG2, "done creating and filling new WAL file");
3503 * Create a new XLOG file segment by copying a pre-existing one.
3505 * destsegno: identify segment to be created.
3507 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
3508 * a different timeline)
3510 * Currently this is only used during recovery, and so there are no locking
3511 * considerations. But we should be just as tense as XLogFileInit to avoid
3512 * emplacing a bogus file.
3515 XLogFileCopy(XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno)
3517 char path[MAXPGPATH];
3518 char tmppath[MAXPGPATH];
3519 char buffer[XLOG_BLCKSZ];
3525 * Open the source file
3527 XLogFilePath(path, srcTLI, srcsegno);
3528 srcfd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
3531 (errcode_for_file_access(),
3532 errmsg("could not open file \"%s\": %m", path)));
3535 * Copy into a temp file name.
3537 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3541 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3542 fd = OpenTransientFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3546 (errcode_for_file_access(),
3547 errmsg("could not create file \"%s\": %m", tmppath)));
3550 * Do the data copying.
3552 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
3555 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
3559 (errcode_for_file_access(),
3560 errmsg("could not read file \"%s\": %m", path)));
3563 (errmsg("not enough data in file \"%s\"", path)));
3566 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
3568 int save_errno = errno;
3571 * If we fail to make the file, delete it to release disk space
3574 /* if write didn't set errno, assume problem is no disk space */
3575 errno = save_errno ? save_errno : ENOSPC;
3578 (errcode_for_file_access(),
3579 errmsg("could not write to file \"%s\": %m", tmppath)));
3583 if (pg_fsync(fd) != 0)
3585 (errcode_for_file_access(),
3586 errmsg("could not fsync file \"%s\": %m", tmppath)));
3588 if (CloseTransientFile(fd))
3590 (errcode_for_file_access(),
3591 errmsg("could not close file \"%s\": %m", tmppath)));
3593 CloseTransientFile(srcfd);
3596 * Now move the segment into place with its final name.
3598 if (!InstallXLogFileSegment(&destsegno, tmppath, false, NULL, false))
3599 elog(ERROR, "InstallXLogFileSegment should not have failed");
3603 * Install a new XLOG segment file as a current or future log segment.
3605 * This is used both to install a newly-created segment (which has a temp
3606 * filename while it's being created) and to recycle an old segment.
3608 * *segno: identify segment to install as (or first possible target).
3609 * When find_free is TRUE, this is modified on return to indicate the
3610 * actual installation location or last segment searched.
3612 * tmppath: initial name of file to install. It will be renamed into place.
3614 * find_free: if TRUE, install the new segment at the first empty segno
3615 * number at or after the passed numbers. If FALSE, install the new segment
3616 * exactly where specified, deleting any existing segment file there.
3618 * *max_advance: maximum number of segno slots to advance past the starting
3619 * point. Fail if no free slot is found in this range. On return, reduced
3620 * by the number of slots skipped over. (Irrelevant, and may be NULL,
3621 * when find_free is FALSE.)
3623 * use_lock: if TRUE, acquire ControlFileLock while moving file into
3624 * place. This should be TRUE except during bootstrap log creation. The
3625 * caller must *not* hold the lock at call.
3627 * Returns TRUE if the file was installed successfully. FALSE indicates that
3628 * max_advance limit was exceeded, or an error occurred while renaming the
3632 InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
3633 bool find_free, int *max_advance,
3636 char path[MAXPGPATH];
3637 struct stat stat_buf;
3639 XLogFilePath(path, ThisTimeLineID, *segno);
3642 * We want to be sure that only one process does this at a time.
3645 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3649 /* Force installation: get rid of any pre-existing segment file */
3654 /* Find a free slot to put it in */
3655 while (stat(path, &stat_buf) == 0)
3657 if (*max_advance <= 0)
3659 /* Failed to find a free slot within specified range */
3661 LWLockRelease(ControlFileLock);
3666 XLogFilePath(path, ThisTimeLineID, *segno);
3671 * Prefer link() to rename() here just to be really sure that we don't
3672 * overwrite an existing logfile. However, there shouldn't be one, so
3673 * rename() is an acceptable substitute except for the truly paranoid.
3675 #if HAVE_WORKING_LINK
3676 if (link(tmppath, path) < 0)
3679 LWLockRelease(ControlFileLock);
3681 (errcode_for_file_access(),
3682 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file): %m",
3688 if (rename(tmppath, path) < 0)
3691 LWLockRelease(ControlFileLock);
3693 (errcode_for_file_access(),
3694 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file): %m",
3701 LWLockRelease(ControlFileLock);
3707 * Open a pre-existing logfile segment for writing.
3710 XLogFileOpen(XLogSegNo segno)
3712 char path[MAXPGPATH];
3715 XLogFilePath(path, ThisTimeLineID, segno);
3717 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
3721 (errcode_for_file_access(),
3722 errmsg("could not open xlog file \"%s\": %m", path)));
3728 * Open a logfile segment for reading (during recovery).
3730 * If source == XLOG_FROM_ARCHIVE, the segment is retrieved from archive.
3731 * Otherwise, it's assumed to be already available in pg_xlog.
3734 XLogFileRead(XLogSegNo segno, int emode, TimeLineID tli,
3735 int source, bool notfoundOk)
3737 char xlogfname[MAXFNAMELEN];
3738 char activitymsg[MAXFNAMELEN + 16];
3739 char path[MAXPGPATH];
3742 XLogFileName(xlogfname, tli, segno);
3746 case XLOG_FROM_ARCHIVE:
3747 /* Report recovery progress in PS display */
3748 snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
3750 set_ps_display(activitymsg, false);
3752 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
3756 if (!restoredFromArchive)
3760 case XLOG_FROM_PG_XLOG:
3761 case XLOG_FROM_STREAM:
3762 XLogFilePath(path, tli, segno);
3763 restoredFromArchive = false;
3767 elog(ERROR, "invalid XLogFileRead source %d", source);
3771 * If the segment was fetched from archival storage, replace the existing
3772 * xlog segment (if any) with the archival version.
3774 if (source == XLOG_FROM_ARCHIVE)
3776 KeepFileRestoredFromArchive(path, xlogfname);
3779 * Set path to point at the new file in pg_xlog.
3781 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
3784 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
3790 /* Report recovery progress in PS display */
3791 snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
3793 set_ps_display(activitymsg, false);
3795 /* Track source of data in assorted state variables */
3796 readSource = source;
3797 XLogReceiptSource = source;
3798 /* In FROM_STREAM case, caller tracks receipt time, not me */
3799 if (source != XLOG_FROM_STREAM)
3800 XLogReceiptTime = GetCurrentTimestamp();
3804 if (errno != ENOENT || !notfoundOk) /* unexpected failure? */
3806 (errcode_for_file_access(),
3807 errmsg("could not open file \"%s\": %m", path)));
3812 * Open a logfile segment for reading (during recovery).
3814 * This version searches for the segment with any TLI listed in expectedTLEs.
3817 XLogFileReadAnyTLI(XLogSegNo segno, int emode, int source)
3819 char path[MAXPGPATH];
3825 * Loop looking for a suitable timeline ID: we might need to read any of
3826 * the timelines listed in expectedTLEs.
3828 * We expect curFileTLI on entry to be the TLI of the preceding file in
3829 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
3830 * to go backwards; this prevents us from picking up the wrong file when a
3831 * parent timeline extends to higher segment numbers than the child we
3834 * If we haven't read the timeline history file yet, read it now, so that
3835 * we know which TLIs to scan. We don't save the list in expectedTLEs,
3836 * however, unless we actually find a valid segment. That way if there is
3837 * neither a timeline history file nor a WAL segment in the archive, and
3838 * streaming replication is set up, we'll read the timeline history file
3839 * streamed from the master when we start streaming, instead of recovering
3840 * with a dummy history generated here.
3843 tles = expectedTLEs;
3845 tles = readTimeLineHistory(recoveryTargetTLI);
3849 TimeLineID tli = ((TimeLineHistoryEntry *) lfirst(cell))->tli;
3851 if (tli < curFileTLI)
3852 break; /* don't bother looking at too-old TLIs */
3854 if (source == XLOG_FROM_ANY || source == XLOG_FROM_ARCHIVE)
3856 fd = XLogFileRead(segno, emode, tli,
3857 XLOG_FROM_ARCHIVE, true);
3860 elog(DEBUG1, "got WAL segment from archive");
3862 expectedTLEs = tles;
3867 if (source == XLOG_FROM_ANY || source == XLOG_FROM_PG_XLOG)
3869 fd = XLogFileRead(segno, emode, tli,
3870 XLOG_FROM_PG_XLOG, true);
3874 expectedTLEs = tles;
3880 /* Couldn't find it. For simplicity, complain about front timeline */
3881 XLogFilePath(path, recoveryTargetTLI, segno);
3884 (errcode_for_file_access(),
3885 errmsg("could not open file \"%s\": %m", path)));
3890 * Close the current logfile segment for writing.
3895 Assert(openLogFile >= 0);
3898 * WAL segment files will not be re-read in normal operation, so we advise
3899 * the OS to release any cached pages. But do not do so if WAL archiving
3900 * or streaming is active, because archiver and walsender process could
3901 * use the cache to read the WAL segment.
3903 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3904 if (!XLogIsNeeded())
3905 (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3908 if (close(openLogFile))
3910 (errcode_for_file_access(),
3911 errmsg("could not close log file %s: %m",
3912 XLogFileNameP(ThisTimeLineID, openLogSegNo))));
3917 * Preallocate log files beyond the specified log endpoint.
3919 * XXX this is currently extremely conservative, since it forces only one
3920 * future log segment to exist, and even that only if we are 75% done with
3921 * the current one. This is only appropriate for very low-WAL-volume systems.
3922 * High-volume systems will be OK once they've built up a sufficient set of
3923 * recycled log segments, but the startup transient is likely to include
3924 * a lot of segment creations by foreground processes, which is not so good.
3927 PreallocXlogFiles(XLogRecPtr endptr)
3929 XLogSegNo _logSegNo;
3933 XLByteToPrevSeg(endptr, _logSegNo);
3934 if ((endptr - 1) % XLogSegSize >= (uint32) (0.75 * XLogSegSize))
3937 use_existent = true;
3938 lf = XLogFileInit(_logSegNo, &use_existent, true);
3941 CheckpointStats.ckpt_segs_added++;
3946 * Throws an error if the given log segment has already been removed or
3947 * recycled. The caller should only pass a segment that it knows to have
3948 * existed while the server has been running, as this function always
3949 * succeeds if no WAL segments have been removed since startup.
3950 * 'tli' is only used in the error message.
3953 CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
3955 /* use volatile pointer to prevent code rearrangement */
3956 volatile XLogCtlData *xlogctl = XLogCtl;
3957 XLogSegNo lastRemovedSegNo;
3959 SpinLockAcquire(&xlogctl->info_lck);
3960 lastRemovedSegNo = xlogctl->lastRemovedSegNo;
3961 SpinLockRelease(&xlogctl->info_lck);
3963 if (segno <= lastRemovedSegNo)
3965 char filename[MAXFNAMELEN];
3967 XLogFileName(filename, tli, segno);
3969 (errcode_for_file_access(),
3970 errmsg("requested WAL segment %s has already been removed",
3976 * Update the last removed segno pointer in shared memory, to reflect
3977 * that the given XLOG file has been removed.
3980 UpdateLastRemovedPtr(char *filename)
3982 /* use volatile pointer to prevent code rearrangement */
3983 volatile XLogCtlData *xlogctl = XLogCtl;
3987 XLogFromFileName(filename, &tli, &segno);
3989 SpinLockAcquire(&xlogctl->info_lck);
3990 if (segno > xlogctl->lastRemovedSegNo)
3991 xlogctl->lastRemovedSegNo = segno;
3992 SpinLockRelease(&xlogctl->info_lck);
3996 * Recycle or remove all log files older or equal to passed segno
3998 * endptr is current (or recent) end of xlog; this is used to determine
3999 * whether we want to recycle rather than delete no-longer-wanted log files.
4002 RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr endptr)
4004 XLogSegNo endlogSegNo;
4007 struct dirent *xlde;
4008 char lastoff[MAXFNAMELEN];
4009 char path[MAXPGPATH];
4012 char newpath[MAXPGPATH];
4014 struct stat statbuf;
4017 * Initialize info about where to try to recycle to. We allow recycling
4018 * segments up to XLOGfileslop segments beyond the current XLOG location.
4020 XLByteToPrevSeg(endptr, endlogSegNo);
4021 max_advance = XLOGfileslop;
4023 xldir = AllocateDir(XLOGDIR);
4026 (errcode_for_file_access(),
4027 errmsg("could not open transaction log directory \"%s\": %m",
4031 * Construct a filename of the last segment to be kept. The timeline ID
4032 * doesn't matter, we ignore that in the comparison. (During recovery,
4033 * ThisTimeLineID isn't set, so we can't use that.)
4035 XLogFileName(lastoff, 0, segno);
4037 elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
4040 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4043 * We ignore the timeline part of the XLOG segment identifiers in
4044 * deciding whether a segment is still needed. This ensures that we
4045 * won't prematurely remove a segment from a parent timeline. We could
4046 * probably be a little more proactive about removing segments of
4047 * non-parent timelines, but that would be a whole lot more
4050 * We use the alphanumeric sorting property of the filenames to decide
4051 * which ones are earlier than the lastoff segment.
4053 if (strlen(xlde->d_name) == 24 &&
4054 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
4055 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
4057 if (XLogArchiveCheckDone(xlde->d_name))
4059 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
4061 /* Update the last removed location in shared memory first */
4062 UpdateLastRemovedPtr(xlde->d_name);
4065 * Before deleting the file, see if it can be recycled as a
4066 * future log segment. Only recycle normal files, pg_standby
4067 * for example can create symbolic links pointing to a
4068 * separate archive directory.
4070 if (lstat(path, &statbuf) == 0 && S_ISREG(statbuf.st_mode) &&
4071 InstallXLogFileSegment(&endlogSegNo, path,
4072 true, &max_advance, true))
4075 (errmsg("recycled transaction log file \"%s\"",
4077 CheckpointStats.ckpt_segs_recycled++;
4078 /* Needn't recheck that slot on future iterations */
4079 if (max_advance > 0)
4087 /* No need for any more future segments... */
4091 (errmsg("removing transaction log file \"%s\"",
4097 * On Windows, if another process (e.g another backend)
4098 * holds the file open in FILE_SHARE_DELETE mode, unlink
4099 * will succeed, but the file will still show up in
4100 * directory listing until the last handle is closed. To
4101 * avoid confusing the lingering deleted file for a live
4102 * WAL file that needs to be archived, rename it before
4105 * If another process holds the file open without
4106 * FILE_SHARE_DELETE flag, rename will fail. We'll try
4107 * again at the next checkpoint.
4109 snprintf(newpath, MAXPGPATH, "%s.deleted", path);
4110 if (rename(path, newpath) != 0)
4113 (errcode_for_file_access(),
4114 errmsg("could not rename old transaction log file \"%s\": %m",
4118 rc = unlink(newpath);
4125 (errcode_for_file_access(),
4126 errmsg("could not remove old transaction log file \"%s\": %m",
4130 CheckpointStats.ckpt_segs_removed++;
4133 XLogArchiveCleanup(xlde->d_name);
4142 * Verify whether pg_xlog and pg_xlog/archive_status exist.
4143 * If the latter does not exist, recreate it.
4145 * It is not the goal of this function to verify the contents of these
4146 * directories, but to help in cases where someone has performed a cluster
4147 * copy for PITR purposes but omitted pg_xlog from the copy.
4149 * We could also recreate pg_xlog if it doesn't exist, but a deliberate
4150 * policy decision was made not to. It is fairly common for pg_xlog to be
4151 * a symlink, and if that was the DBA's intent then automatically making a
4152 * plain directory would result in degraded performance with no notice.
4155 ValidateXLOGDirectoryStructure(void)
4157 char path[MAXPGPATH];
4158 struct stat stat_buf;
4160 /* Check for pg_xlog; if it doesn't exist, error out */
4161 if (stat(XLOGDIR, &stat_buf) != 0 ||
4162 !S_ISDIR(stat_buf.st_mode))
4164 (errmsg("required WAL directory \"%s\" does not exist",
4167 /* Check for archive_status */
4168 snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
4169 if (stat(path, &stat_buf) == 0)
4171 /* Check for weird cases where it exists but isn't a directory */
4172 if (!S_ISDIR(stat_buf.st_mode))
4174 (errmsg("required WAL directory \"%s\" does not exist",
4180 (errmsg("creating missing WAL directory \"%s\"", path)));
4181 if (mkdir(path, S_IRWXU) < 0)
4183 (errmsg("could not create missing directory \"%s\": %m",
4189 * Remove previous backup history files. This also retries creation of
4190 * .ready files for any backup history files for which XLogArchiveNotify
4194 CleanupBackupHistory(void)
4197 struct dirent *xlde;
4198 char path[MAXPGPATH];
4200 xldir = AllocateDir(XLOGDIR);
4203 (errcode_for_file_access(),
4204 errmsg("could not open transaction log directory \"%s\": %m",
4207 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4209 if (strlen(xlde->d_name) > 24 &&
4210 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
4211 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
4214 if (XLogArchiveCheckDone(xlde->d_name))
4217 (errmsg("removing transaction log backup history file \"%s\"",
4219 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
4221 XLogArchiveCleanup(xlde->d_name);
4230 * Restore a full-page image from a backup block attached to an XLOG record.
4232 * lsn: LSN of the XLOG record being replayed
4233 * record: the complete XLOG record
4234 * block_index: which backup block to restore (0 .. XLR_MAX_BKP_BLOCKS - 1)
4235 * get_cleanup_lock: TRUE to get a cleanup rather than plain exclusive lock
4236 * keep_buffer: TRUE to return the buffer still locked and pinned
4238 * Returns the buffer number containing the page. Note this is not terribly
4239 * useful unless keep_buffer is specified as TRUE.
4241 * Note: when a backup block is available in XLOG, we restore it
4242 * unconditionally, even if the page in the database appears newer.
4243 * This is to protect ourselves against database pages that were partially
4244 * or incorrectly written during a crash. We assume that the XLOG data
4245 * must be good because it has passed a CRC check, while the database
4246 * page might not be. This will force us to replay all subsequent
4247 * modifications of the page that appear in XLOG, rather than possibly
4248 * ignoring them as already applied, but that's not a huge drawback.
4250 * If 'get_cleanup_lock' is true, a cleanup lock is obtained on the buffer,
4251 * else a normal exclusive lock is used. During crash recovery, that's just
4252 * pro forma because there can't be any regular backends in the system, but
4253 * in hot standby mode the distinction is important.
4255 * If 'keep_buffer' is true, return without releasing the buffer lock and pin;
4256 * then caller is responsible for doing UnlockReleaseBuffer() later. This
4257 * is needed in some cases when replaying XLOG records that touch multiple
4258 * pages, to prevent inconsistent states from being visible to other backends.
4259 * (Again, that's only important in hot standby mode.)
4262 RestoreBackupBlock(XLogRecPtr lsn, XLogRecord *record, int block_index,
4263 bool get_cleanup_lock, bool keep_buffer)
4269 /* Locate requested BkpBlock in the record */
4270 blk = (char *) XLogRecGetData(record) + record->xl_len;
4271 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
4273 if (!(record->xl_info & XLR_BKP_BLOCK(i)))
4276 memcpy(&bkpb, blk, sizeof(BkpBlock));
4277 blk += sizeof(BkpBlock);
4279 if (i == block_index)
4281 /* Found it, apply the update */
4282 return RestoreBackupBlockContents(lsn, bkpb, blk, get_cleanup_lock,
4286 blk += BLCKSZ - bkpb.hole_length;
4289 /* Caller specified a bogus block_index */
4290 elog(ERROR, "failed to restore block_index %d", block_index);
4291 return InvalidBuffer; /* keep compiler quiet */
4295 * Workhorse for RestoreBackupBlock usable without an xlog record
4297 * Restores a full-page image from BkpBlock and a data pointer.
4300 RestoreBackupBlockContents(XLogRecPtr lsn, BkpBlock bkpb, char *blk,
4301 bool get_cleanup_lock, bool keep_buffer)
4306 buffer = XLogReadBufferExtended(bkpb.node, bkpb.fork, bkpb.block,
4308 Assert(BufferIsValid(buffer));
4309 if (get_cleanup_lock)
4310 LockBufferForCleanup(buffer);
4312 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
4314 page = (Page) BufferGetPage(buffer);
4316 if (bkpb.hole_length == 0)
4318 memcpy((char *) page, blk, BLCKSZ);
4322 memcpy((char *) page, blk, bkpb.hole_offset);
4323 /* must zero-fill the hole */
4324 MemSet((char *) page + bkpb.hole_offset, 0, bkpb.hole_length);
4325 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
4326 blk + bkpb.hole_offset,
4327 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
4331 * The checksum value on this page is currently invalid. We don't need to
4332 * reset it here since it will be set before being written.
4335 PageSetLSN(page, lsn);
4336 MarkBufferDirty(buffer);
4339 UnlockReleaseBuffer(buffer);
4345 * Attempt to read an XLOG record.
4347 * If RecPtr is not NULL, try to read a record at that position. Otherwise
4348 * try to read a record just after the last one previously read.
4350 * If no valid record is available, returns NULL, or fails if emode is PANIC.
4351 * (emode must be either PANIC, LOG). In standby mode, retries until a valid
4352 * record is available.
4354 * The record is copied into readRecordBuf, so that on successful return,
4355 * the returned record pointer always points there.
4358 ReadRecord(XLogReaderState *xlogreader, XLogRecPtr RecPtr, int emode,
4362 XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
4364 /* Pass through parameters to XLogPageRead */
4365 private->fetching_ckpt = fetching_ckpt;
4366 private->emode = emode;
4367 private->randAccess = (RecPtr != InvalidXLogRecPtr);
4369 /* This is the first attempt to read this page. */
4370 lastSourceFailed = false;
4376 record = XLogReadRecord(xlogreader, RecPtr, &errormsg);
4377 ReadRecPtr = xlogreader->ReadRecPtr;
4378 EndRecPtr = xlogreader->EndRecPtr;
4388 * We only end up here without a message when XLogPageRead()
4389 * failed - in that case we already logged something. In
4390 * StandbyMode that only happens if we have been triggered, so we
4391 * shouldn't loop anymore in that case.
4394 ereport(emode_for_corrupt_record(emode,
4395 RecPtr ? RecPtr : EndRecPtr),
4396 (errmsg_internal("%s", errormsg) /* already translated */ ));
4400 * Check page TLI is one of the expected values.
4402 else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
4404 char fname[MAXFNAMELEN];
4408 XLByteToSeg(xlogreader->latestPagePtr, segno);
4409 offset = xlogreader->latestPagePtr % XLogSegSize;
4410 XLogFileName(fname, xlogreader->readPageTLI, segno);
4411 ereport(emode_for_corrupt_record(emode,
4412 RecPtr ? RecPtr : EndRecPtr),
4413 (errmsg("unexpected timeline ID %u in log segment %s, offset %u",
4414 xlogreader->latestPageTLI,
4422 /* Great, got a record */
4427 /* No valid record available from this source */
4428 lastSourceFailed = true;
4431 * If archive recovery was requested, but we were still doing
4432 * crash recovery, switch to archive recovery and retry using the
4433 * offline archive. We have now replayed all the valid WAL in
4434 * pg_xlog, so we are presumably now consistent.
4436 * We require that there's at least some valid WAL present in
4437 * pg_xlog, however (!fetch_ckpt). We could recover using the WAL
4438 * from the archive, even if pg_xlog is completely empty, but we'd
4439 * have no idea how far we'd have to replay to reach consistency.
4440 * So err on the safe side and give up.
4442 if (!InArchiveRecovery && ArchiveRecoveryRequested &&
4446 (errmsg_internal("reached end of WAL in pg_xlog, entering archive recovery")));
4447 InArchiveRecovery = true;
4448 if (StandbyModeRequested)
4451 /* initialize minRecoveryPoint to this record */
4452 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
4453 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4454 if (ControlFile->minRecoveryPoint < EndRecPtr)
4456 ControlFile->minRecoveryPoint = EndRecPtr;
4457 ControlFile->minRecoveryPointTLI = ThisTimeLineID;
4459 /* update local copy */
4460 minRecoveryPoint = ControlFile->minRecoveryPoint;
4461 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
4463 UpdateControlFile();
4464 LWLockRelease(ControlFileLock);
4466 CheckRecoveryConsistency();
4469 * Before we retry, reset lastSourceFailed and currentSource
4470 * so that we will check the archive next.
4472 lastSourceFailed = false;
4478 /* In standby mode, loop back to retry. Otherwise, give up. */
4479 if (StandbyMode && !CheckForStandbyTrigger())
4488 * Scan for new timelines that might have appeared in the archive since we
4491 * If there are any, the function changes recovery target TLI to the latest
4492 * one and returns 'true'.
4495 rescanLatestTimeLine(void)
4497 List *newExpectedTLEs;
4500 TimeLineID newtarget;
4501 TimeLineID oldtarget = recoveryTargetTLI;
4502 TimeLineHistoryEntry *currentTle = NULL;
4504 newtarget = findNewestTimeLine(recoveryTargetTLI);
4505 if (newtarget == recoveryTargetTLI)
4507 /* No new timelines found */
4512 * Determine the list of expected TLIs for the new TLI
4515 newExpectedTLEs = readTimeLineHistory(newtarget);
4518 * If the current timeline is not part of the history of the new timeline,
4519 * we cannot proceed to it.
4522 foreach(cell, newExpectedTLEs)
4524 currentTle = (TimeLineHistoryEntry *) lfirst(cell);
4526 if (currentTle->tli == recoveryTargetTLI)
4535 (errmsg("new timeline %u is not a child of database system timeline %u",
4542 * The current timeline was found in the history file, but check that the
4543 * next timeline was forked off from it *after* the current recovery
4546 if (currentTle->end < EndRecPtr)
4549 (errmsg("new timeline %u forked off current database system timeline %u before current recovery point %X/%X",
4552 (uint32) (EndRecPtr >> 32), (uint32) EndRecPtr)));
4556 /* The new timeline history seems valid. Switch target */
4557 recoveryTargetTLI = newtarget;
4558 list_free_deep(expectedTLEs);
4559 expectedTLEs = newExpectedTLEs;
4562 * As in StartupXLOG(), try to ensure we have all the history files
4563 * between the old target and new target in pg_xlog.
4565 restoreTimeLineHistoryFiles(oldtarget + 1, newtarget);
4568 (errmsg("new target timeline is %u",
4569 recoveryTargetTLI)));
4575 * I/O routines for pg_control
4577 * *ControlFile is a buffer in shared memory that holds an image of the
4578 * contents of pg_control. WriteControlFile() initializes pg_control
4579 * given a preloaded buffer, ReadControlFile() loads the buffer from
4580 * the pg_control file (during postmaster or standalone-backend startup),
4581 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
4583 * For simplicity, WriteControlFile() initializes the fields of pg_control
4584 * that are related to checking backend/database compatibility, and
4585 * ReadControlFile() verifies they are correct. We could split out the
4586 * I/O and compatibility-check functions, but there seems no need currently.
4589 WriteControlFile(void)
4592 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
4595 * Initialize version and compatibility-check fields
4597 ControlFile->pg_control_version = PG_CONTROL_VERSION;
4598 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
4600 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
4601 ControlFile->floatFormat = FLOATFORMAT_VALUE;
4603 ControlFile->blcksz = BLCKSZ;
4604 ControlFile->relseg_size = RELSEG_SIZE;
4605 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4606 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
4608 ControlFile->nameDataLen = NAMEDATALEN;
4609 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
4611 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
4613 #ifdef HAVE_INT64_TIMESTAMP
4614 ControlFile->enableIntTimes = true;
4616 ControlFile->enableIntTimes = false;
4618 ControlFile->float4ByVal = FLOAT4PASSBYVAL;
4619 ControlFile->float8ByVal = FLOAT8PASSBYVAL;
4621 /* Contents are protected with a CRC */
4622 INIT_CRC32(ControlFile->crc);
4623 COMP_CRC32(ControlFile->crc,
4624 (char *) ControlFile,
4625 offsetof(ControlFileData, crc));
4626 FIN_CRC32(ControlFile->crc);
4629 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
4630 * excess over sizeof(ControlFileData). This reduces the odds of
4631 * premature-EOF errors when reading pg_control. We'll still fail when we
4632 * check the contents of the file, but hopefully with a more specific
4633 * error than "couldn't read pg_control".
4635 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
4636 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
4638 memset(buffer, 0, PG_CONTROL_SIZE);
4639 memcpy(buffer, ControlFile, sizeof(ControlFileData));
4641 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4642 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
4646 (errcode_for_file_access(),
4647 errmsg("could not create control file \"%s\": %m",
4648 XLOG_CONTROL_FILE)));
4651 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
4653 /* if write didn't set errno, assume problem is no disk space */
4657 (errcode_for_file_access(),
4658 errmsg("could not write to control file: %m")));
4661 if (pg_fsync(fd) != 0)
4663 (errcode_for_file_access(),
4664 errmsg("could not fsync control file: %m")));
4668 (errcode_for_file_access(),
4669 errmsg("could not close control file: %m")));
4673 ReadControlFile(void)
4681 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4686 (errcode_for_file_access(),
4687 errmsg("could not open control file \"%s\": %m",
4688 XLOG_CONTROL_FILE)));
4690 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4692 (errcode_for_file_access(),
4693 errmsg("could not read from control file: %m")));
4698 * Check for expected pg_control format version. If this is wrong, the
4699 * CRC check will likely fail because we'll be checking the wrong number
4700 * of bytes. Complaining about wrong version will probably be more
4701 * enlightening than complaining about wrong CRC.
4704 if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
4706 (errmsg("database files are incompatible with server"),
4707 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4708 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4709 ControlFile->pg_control_version, ControlFile->pg_control_version,
4710 PG_CONTROL_VERSION, PG_CONTROL_VERSION),
4711 errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4713 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
4715 (errmsg("database files are incompatible with server"),
4716 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4717 " but the server was compiled with PG_CONTROL_VERSION %d.",
4718 ControlFile->pg_control_version, PG_CONTROL_VERSION),
4719 errhint("It looks like you need to initdb.")));
4721 /* Now check the CRC. */
4724 (char *) ControlFile,
4725 offsetof(ControlFileData, crc));
4728 if (!EQ_CRC32(crc, ControlFile->crc))
4730 (errmsg("incorrect checksum in control file")));
4733 * Do compatibility checking immediately. If the database isn't
4734 * compatible with the backend executable, we want to abort before we can
4735 * possibly do any damage.
4737 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
4739 (errmsg("database files are incompatible with server"),
4740 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
4741 " but the server was compiled with CATALOG_VERSION_NO %d.",
4742 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
4743 errhint("It looks like you need to initdb.")));
4744 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4746 (errmsg("database files are incompatible with server"),
4747 errdetail("The database cluster was initialized with MAXALIGN %d,"
4748 " but the server was compiled with MAXALIGN %d.",
4749 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
4750 errhint("It looks like you need to initdb.")));
4751 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
4753 (errmsg("database files are incompatible with server"),
4754 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4755 errhint("It looks like you need to initdb.")));
4756 if (ControlFile->blcksz != BLCKSZ)
4758 (errmsg("database files are incompatible with server"),
4759 errdetail("The database cluster was initialized with BLCKSZ %d,"
4760 " but the server was compiled with BLCKSZ %d.",
4761 ControlFile->blcksz, BLCKSZ),
4762 errhint("It looks like you need to recompile or initdb.")));
4763 if (ControlFile->relseg_size != RELSEG_SIZE)
4765 (errmsg("database files are incompatible with server"),
4766 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
4767 " but the server was compiled with RELSEG_SIZE %d.",
4768 ControlFile->relseg_size, RELSEG_SIZE),
4769 errhint("It looks like you need to recompile or initdb.")));
4770 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4772 (errmsg("database files are incompatible with server"),
4773 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
4774 " but the server was compiled with XLOG_BLCKSZ %d.",
4775 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4776 errhint("It looks like you need to recompile or initdb.")));
4777 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
4779 (errmsg("database files are incompatible with server"),
4780 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
4781 " but the server was compiled with XLOG_SEG_SIZE %d.",
4782 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
4783 errhint("It looks like you need to recompile or initdb.")));
4784 if (ControlFile->nameDataLen != NAMEDATALEN)
4786 (errmsg("database files are incompatible with server"),
4787 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
4788 " but the server was compiled with NAMEDATALEN %d.",
4789 ControlFile->nameDataLen, NAMEDATALEN),
4790 errhint("It looks like you need to recompile or initdb.")));
4791 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4793 (errmsg("database files are incompatible with server"),
4794 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
4795 " but the server was compiled with INDEX_MAX_KEYS %d.",
4796 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
4797 errhint("It looks like you need to recompile or initdb.")));
4798 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
4800 (errmsg("database files are incompatible with server"),
4801 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
4802 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
4803 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4804 errhint("It looks like you need to recompile or initdb.")));
4806 #ifdef HAVE_INT64_TIMESTAMP
4807 if (ControlFile->enableIntTimes != true)
4809 (errmsg("database files are incompatible with server"),
4810 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
4811 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
4812 errhint("It looks like you need to recompile or initdb.")));
4814 if (ControlFile->enableIntTimes != false)
4816 (errmsg("database files are incompatible with server"),
4817 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
4818 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
4819 errhint("It looks like you need to recompile or initdb.")));
4822 #ifdef USE_FLOAT4_BYVAL
4823 if (ControlFile->float4ByVal != true)
4825 (errmsg("database files are incompatible with server"),
4826 errdetail("The database cluster was initialized without USE_FLOAT4_BYVAL"
4827 " but the server was compiled with USE_FLOAT4_BYVAL."),
4828 errhint("It looks like you need to recompile or initdb.")));
4830 if (ControlFile->float4ByVal != false)
4832 (errmsg("database files are incompatible with server"),
4833 errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
4834 " but the server was compiled without USE_FLOAT4_BYVAL."),
4835 errhint("It looks like you need to recompile or initdb.")));
4838 #ifdef USE_FLOAT8_BYVAL
4839 if (ControlFile->float8ByVal != true)
4841 (errmsg("database files are incompatible with server"),
4842 errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4843 " but the server was compiled with USE_FLOAT8_BYVAL."),
4844 errhint("It looks like you need to recompile or initdb.")));
4846 if (ControlFile->float8ByVal != false)
4848 (errmsg("database files are incompatible with server"),
4849 errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4850 " but the server was compiled without USE_FLOAT8_BYVAL."),
4851 errhint("It looks like you need to recompile or initdb.")));
4856 UpdateControlFile(void)
4860 INIT_CRC32(ControlFile->crc);
4861 COMP_CRC32(ControlFile->crc,
4862 (char *) ControlFile,
4863 offsetof(ControlFileData, crc));
4864 FIN_CRC32(ControlFile->crc);
4866 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4871 (errcode_for_file_access(),
4872 errmsg("could not open control file \"%s\": %m",
4873 XLOG_CONTROL_FILE)));
4876 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4878 /* if write didn't set errno, assume problem is no disk space */
4882 (errcode_for_file_access(),
4883 errmsg("could not write to control file: %m")));
4886 if (pg_fsync(fd) != 0)
4888 (errcode_for_file_access(),
4889 errmsg("could not fsync control file: %m")));
4893 (errcode_for_file_access(),
4894 errmsg("could not close control file: %m")));
4898 * Returns the unique system identifier from control file.
4901 GetSystemIdentifier(void)
4903 Assert(ControlFile != NULL);
4904 return ControlFile->system_identifier;
4908 * Are checksums enabled for data pages?
4911 DataChecksumsEnabled(void)
4913 Assert(ControlFile != NULL);
4914 return (ControlFile->data_checksum_version > 0);
4918 * Returns a fake LSN for unlogged relations.
4920 * Each call generates an LSN that is greater than any previous value
4921 * returned. The current counter value is saved and restored across clean
4922 * shutdowns, but like unlogged relations, does not survive a crash. This can
4923 * be used in lieu of real LSN values returned by XLogInsert, if you need an
4924 * LSN-like increasing sequence of numbers without writing any WAL.
4927 GetFakeLSNForUnloggedRel(void)
4929 XLogRecPtr nextUnloggedLSN;
4931 /* use volatile pointer to prevent code rearrangement */
4932 volatile XLogCtlData *xlogctl = XLogCtl;
4934 /* increment the unloggedLSN counter, need SpinLock */
4935 SpinLockAcquire(&xlogctl->ulsn_lck);
4936 nextUnloggedLSN = xlogctl->unloggedLSN++;
4937 SpinLockRelease(&xlogctl->ulsn_lck);
4939 return nextUnloggedLSN;
4943 * Auto-tune the number of XLOG buffers.
4945 * The preferred setting for wal_buffers is about 3% of shared_buffers, with
4946 * a maximum of one XLOG segment (there is little reason to think that more
4947 * is helpful, at least so long as we force an fsync when switching log files)
4948 * and a minimum of 8 blocks (which was the default value prior to PostgreSQL
4949 * 9.1, when auto-tuning was added).
4951 * This should not be called until NBuffers has received its final value.
4954 XLOGChooseNumBuffers(void)
4958 xbuffers = NBuffers / 32;
4959 if (xbuffers > XLOG_SEG_SIZE / XLOG_BLCKSZ)
4960 xbuffers = XLOG_SEG_SIZE / XLOG_BLCKSZ;
4967 * GUC check_hook for wal_buffers
4970 check_wal_buffers(int *newval, void **extra, GucSource source)
4973 * -1 indicates a request for auto-tune.
4978 * If we haven't yet changed the boot_val default of -1, just let it
4979 * be. We'll fix it when XLOGShmemSize is called.
4981 if (XLOGbuffers == -1)
4984 /* Otherwise, substitute the auto-tune value */
4985 *newval = XLOGChooseNumBuffers();
4989 * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
4990 * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
4991 * the case, we just silently treat such values as a request for the
4992 * minimum. (We could throw an error instead, but that doesn't seem very
5002 * Initialization of shared memory for XLOG
5010 * If the value of wal_buffers is -1, use the preferred auto-tune value.
5011 * This isn't an amazingly clean place to do this, but we must wait till
5012 * NBuffers has received its final value, and must do it before using the
5013 * value of XLOGbuffers to do anything important.
5015 if (XLOGbuffers == -1)
5019 snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
5020 SetConfigOption("wal_buffers", buf, PGC_POSTMASTER, PGC_S_OVERRIDE);
5022 Assert(XLOGbuffers > 0);
5025 size = sizeof(XLogCtlData);
5027 /* xlog insertion slots, plus alignment */
5028 size = add_size(size, mul_size(sizeof(XLogInsertSlotPadded), num_xloginsert_slots + 1));
5029 /* xlblocks array */
5030 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
5031 /* extra alignment padding for XLOG I/O buffers */
5032 size = add_size(size, XLOG_BLCKSZ);
5033 /* and the buffers themselves */
5034 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
5037 * Note: we don't count ControlFileData, it comes out of the "slop factor"
5038 * added by CreateSharedMemoryAndSemaphores. This lets us use this
5039 * routine again below to compute the actual allocation size.
5053 ControlFile = (ControlFileData *)
5054 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
5055 XLogCtl = (XLogCtlData *)
5056 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
5058 if (foundCFile || foundXLog)
5060 /* both should be present or neither */
5061 Assert(foundCFile && foundXLog);
5064 memset(XLogCtl, 0, sizeof(XLogCtlData));
5067 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
5068 * multiple of the alignment for same, so no extra alignment padding is
5071 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
5072 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
5073 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
5074 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
5076 /* Xlog insertion slots. Ensure they're aligned to the full padded size */
5077 allocptr += sizeof(XLogInsertSlotPadded) -
5078 ((uintptr_t) allocptr) % sizeof(XLogInsertSlotPadded);
5079 XLogCtl->Insert.insertSlots = (XLogInsertSlotPadded *) allocptr;
5080 allocptr += sizeof(XLogInsertSlotPadded) * num_xloginsert_slots;
5083 * Align the start of the page buffers to a full xlog block size boundary.
5084 * This simplifies some calculations in XLOG insertion. It is also required
5087 allocptr = (char *) TYPEALIGN(XLOG_BLCKSZ, allocptr);
5088 XLogCtl->pages = allocptr;
5089 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
5092 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
5093 * in additional info.)
5095 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
5096 XLogCtl->SharedRecoveryInProgress = true;
5097 XLogCtl->SharedHotStandbyActive = false;
5098 XLogCtl->WalWriterSleeping = false;
5100 for (i = 0; i < num_xloginsert_slots; i++)
5102 XLogInsertSlot *slot = &XLogCtl->Insert.insertSlots[i].slot;
5103 SpinLockInit(&slot->mutex);
5104 slot->xlogInsertingAt = InvalidXLogRecPtr;
5107 slot->releaseOK = true;
5108 slot->exclusive = 0;
5113 SpinLockInit(&XLogCtl->Insert.insertpos_lck);
5114 SpinLockInit(&XLogCtl->info_lck);
5115 SpinLockInit(&XLogCtl->ulsn_lck);
5116 InitSharedLatch(&XLogCtl->recoveryWakeupLatch);
5119 * If we are not in bootstrap mode, pg_control should already exist. Read
5120 * and validate it immediately (see comments in ReadControlFile() for the
5123 if (!IsBootstrapProcessingMode())
5128 * This func must be called ONCE on system install. It creates pg_control
5129 * and the initial XLOG segment.
5134 CheckPoint checkPoint;
5136 XLogPageHeader page;
5137 XLogLongPageHeader longpage;
5140 uint64 sysidentifier;
5145 * Select a hopefully-unique system identifier code for this installation.
5146 * We use the result of gettimeofday(), including the fractional seconds
5147 * field, as being about as unique as we can easily get. (Think not to
5148 * use random(), since it hasn't been seeded and there's no portable way
5149 * to seed it other than the system clock value...) The upper half of the
5150 * uint64 value is just the tv_sec part, while the lower half is the XOR
5151 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
5152 * unnecessarily if "uint64" is really only 32 bits wide. A person
5153 * knowing this encoding can determine the initialization time of the
5154 * installation, which could perhaps be useful sometimes.
5156 gettimeofday(&tv, NULL);
5157 sysidentifier = ((uint64) tv.tv_sec) << 32;
5158 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
5160 /* First timeline ID is always 1 */
5163 /* page buffer must be aligned suitably for O_DIRECT */
5164 buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5165 page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5166 memset(page, 0, XLOG_BLCKSZ);
5169 * Set up information for the initial checkpoint record
5171 * The initial checkpoint record is written to the beginning of the WAL
5172 * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5173 * used, so that we can use 0/0 to mean "before any valid WAL segment".
5175 checkPoint.redo = XLogSegSize + SizeOfXLogLongPHD;
5176 checkPoint.ThisTimeLineID = ThisTimeLineID;
5177 checkPoint.PrevTimeLineID = ThisTimeLineID;
5178 checkPoint.fullPageWrites = fullPageWrites;
5179 checkPoint.nextXidEpoch = 0;
5180 checkPoint.nextXid = FirstNormalTransactionId;
5181 checkPoint.nextOid = FirstBootstrapObjectId;
5182 checkPoint.nextMulti = FirstMultiXactId;
5183 checkPoint.nextMultiOffset = 0;
5184 checkPoint.oldestXid = FirstNormalTransactionId;
5185 checkPoint.oldestXidDB = TemplateDbOid;
5186 checkPoint.oldestMulti = FirstMultiXactId;
5187 checkPoint.oldestMultiDB = TemplateDbOid;
5188 checkPoint.time = (pg_time_t) time(NULL);
5189 checkPoint.oldestActiveXid = InvalidTransactionId;
5191 ShmemVariableCache->nextXid = checkPoint.nextXid;
5192 ShmemVariableCache->nextOid = checkPoint.nextOid;
5193 ShmemVariableCache->oidCount = 0;
5194 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5195 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5196 SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
5198 /* Set up the XLOG page header */
5199 page->xlp_magic = XLOG_PAGE_MAGIC;
5200 page->xlp_info = XLP_LONG_HEADER;
5201 page->xlp_tli = ThisTimeLineID;
5202 page->xlp_pageaddr = XLogSegSize;
5203 longpage = (XLogLongPageHeader) page;
5204 longpage->xlp_sysid = sysidentifier;
5205 longpage->xlp_seg_size = XLogSegSize;
5206 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5208 /* Insert the initial checkpoint record */
5209 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
5210 record->xl_prev = 0;
5211 record->xl_xid = InvalidTransactionId;
5212 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
5213 record->xl_len = sizeof(checkPoint);
5214 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
5215 record->xl_rmid = RM_XLOG_ID;
5216 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
5219 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
5220 COMP_CRC32(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5222 record->xl_crc = crc;
5224 /* Create first XLOG segment file */
5225 use_existent = false;
5226 openLogFile = XLogFileInit(1, &use_existent, false);
5228 /* Write the first page with the initial record */
5230 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5232 /* if write didn't set errno, assume problem is no disk space */
5236 (errcode_for_file_access(),
5237 errmsg("could not write bootstrap transaction log file: %m")));
5240 if (pg_fsync(openLogFile) != 0)
5242 (errcode_for_file_access(),
5243 errmsg("could not fsync bootstrap transaction log file: %m")));
5245 if (close(openLogFile))
5247 (errcode_for_file_access(),
5248 errmsg("could not close bootstrap transaction log file: %m")));
5252 /* Now create pg_control */
5254 memset(ControlFile, 0, sizeof(ControlFileData));
5255 /* Initialize pg_control status fields */
5256 ControlFile->system_identifier = sysidentifier;
5257 ControlFile->state = DB_SHUTDOWNED;
5258 ControlFile->time = checkPoint.time;
5259 ControlFile->checkPoint = checkPoint.redo;
5260 ControlFile->checkPointCopy = checkPoint;
5261 ControlFile->unloggedLSN = 1;
5263 /* Set important parameter values for use when replaying WAL */
5264 ControlFile->MaxConnections = MaxConnections;
5265 ControlFile->max_worker_processes = max_worker_processes;
5266 ControlFile->max_prepared_xacts = max_prepared_xacts;
5267 ControlFile->max_locks_per_xact = max_locks_per_xact;
5268 ControlFile->wal_level = wal_level;
5269 ControlFile->data_checksum_version = bootstrap_data_checksum_version;
5271 /* some additional ControlFile fields are set in WriteControlFile() */
5275 /* Bootstrap the commit log, too */
5277 BootStrapSUBTRANS();
5278 BootStrapMultiXact();
5284 str_time(pg_time_t tnow)
5286 static char buf[128];
5288 pg_strftime(buf, sizeof(buf),
5289 "%Y-%m-%d %H:%M:%S %Z",
5290 pg_localtime(&tnow, log_timezone));
5296 * See if there is a recovery command file (recovery.conf), and if so
5297 * read in parameters for archive recovery and XLOG streaming.
5299 * The file is parsed using the main configuration parser.
5302 readRecoveryCommandFile(void)
5305 TimeLineID rtli = 0;
5306 bool rtliGiven = false;
5307 ConfigVariable *item,
5311 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
5314 if (errno == ENOENT)
5315 return; /* not there, so no archive recovery */
5317 (errcode_for_file_access(),
5318 errmsg("could not open recovery command file \"%s\": %m",
5319 RECOVERY_COMMAND_FILE)));
5323 * Since we're asking ParseConfigFp() to report errors as FATAL, there's
5324 * no need to check the return value.
5326 (void) ParseConfigFp(fd, RECOVERY_COMMAND_FILE, 0, FATAL, &head, &tail);
5330 for (item = head; item; item = item->next)
5332 if (strcmp(item->name, "restore_command") == 0)
5334 recoveryRestoreCommand = pstrdup(item->value);
5336 (errmsg_internal("restore_command = '%s'",
5337 recoveryRestoreCommand)));
5339 else if (strcmp(item->name, "recovery_end_command") == 0)
5341 recoveryEndCommand = pstrdup(item->value);
5343 (errmsg_internal("recovery_end_command = '%s'",
5344 recoveryEndCommand)));
5346 else if (strcmp(item->name, "archive_cleanup_command") == 0)
5348 archiveCleanupCommand = pstrdup(item->value);
5350 (errmsg_internal("archive_cleanup_command = '%s'",
5351 archiveCleanupCommand)));
5353 else if (strcmp(item->name, "pause_at_recovery_target") == 0)
5355 if (!parse_bool(item->value, &recoveryPauseAtTarget))
5357 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5358 errmsg("parameter \"%s\" requires a Boolean value", "pause_at_recovery_target")));
5360 (errmsg_internal("pause_at_recovery_target = '%s'",
5363 else if (strcmp(item->name, "recovery_target_timeline") == 0)
5366 if (strcmp(item->value, "latest") == 0)
5371 rtli = (TimeLineID) strtoul(item->value, NULL, 0);
5372 if (errno == EINVAL || errno == ERANGE)
5374 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
5379 (errmsg_internal("recovery_target_timeline = %u", rtli)));
5382 (errmsg_internal("recovery_target_timeline = latest")));
5384 else if (strcmp(item->name, "recovery_target_xid") == 0)
5387 recoveryTargetXid = (TransactionId) strtoul(item->value, NULL, 0);
5388 if (errno == EINVAL || errno == ERANGE)
5390 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
5393 (errmsg_internal("recovery_target_xid = %u",
5394 recoveryTargetXid)));
5395 recoveryTarget = RECOVERY_TARGET_XID;
5397 else if (strcmp(item->name, "recovery_target_time") == 0)
5400 * if recovery_target_xid or recovery_target_name specified, then
5401 * this overrides recovery_target_time
5403 if (recoveryTarget == RECOVERY_TARGET_XID ||
5404 recoveryTarget == RECOVERY_TARGET_NAME)
5406 recoveryTarget = RECOVERY_TARGET_TIME;
5409 * Convert the time string given by the user to TimestampTz form.
5411 recoveryTargetTime =
5412 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
5413 CStringGetDatum(item->value),
5414 ObjectIdGetDatum(InvalidOid),
5415 Int32GetDatum(-1)));
5417 (errmsg_internal("recovery_target_time = '%s'",
5418 timestamptz_to_str(recoveryTargetTime))));
5420 else if (strcmp(item->name, "recovery_target_name") == 0)
5423 * if recovery_target_xid specified, then this overrides
5424 * recovery_target_name
5426 if (recoveryTarget == RECOVERY_TARGET_XID)
5428 recoveryTarget = RECOVERY_TARGET_NAME;
5430 recoveryTargetName = pstrdup(item->value);
5431 if (strlen(recoveryTargetName) >= MAXFNAMELEN)
5433 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5434 errmsg("recovery_target_name is too long (maximum %d characters)",
5438 (errmsg_internal("recovery_target_name = '%s'",
5439 recoveryTargetName)));
5441 else if (strcmp(item->name, "recovery_target_inclusive") == 0)
5444 * does nothing if a recovery_target is not also set
5446 if (!parse_bool(item->value, &recoveryTargetInclusive))
5448 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5449 errmsg("parameter \"%s\" requires a Boolean value",
5450 "recovery_target_inclusive")));
5452 (errmsg_internal("recovery_target_inclusive = %s",
5455 else if (strcmp(item->name, "standby_mode") == 0)
5457 if (!parse_bool(item->value, &StandbyModeRequested))
5459 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5460 errmsg("parameter \"%s\" requires a Boolean value",
5463 (errmsg_internal("standby_mode = '%s'", item->value)));
5465 else if (strcmp(item->name, "primary_conninfo") == 0)
5467 PrimaryConnInfo = pstrdup(item->value);
5469 (errmsg_internal("primary_conninfo = '%s'",
5472 else if (strcmp(item->name, "trigger_file") == 0)
5474 TriggerFile = pstrdup(item->value);
5476 (errmsg_internal("trigger_file = '%s'",
5481 (errmsg("unrecognized recovery parameter \"%s\"",
5486 * Check for compulsory parameters
5488 if (StandbyModeRequested)
5490 if (PrimaryConnInfo == NULL && recoveryRestoreCommand == NULL)
5492 (errmsg("recovery command file \"%s\" specified neither primary_conninfo nor restore_command",
5493 RECOVERY_COMMAND_FILE),
5494 errhint("The database server will regularly poll the pg_xlog subdirectory to check for files placed there.")));
5498 if (recoveryRestoreCommand == NULL)
5500 (errmsg("recovery command file \"%s\" must specify restore_command when standby mode is not enabled",
5501 RECOVERY_COMMAND_FILE)));
5504 /* Enable fetching from archive recovery area */
5505 ArchiveRecoveryRequested = true;
5508 * If user specified recovery_target_timeline, validate it or compute the
5509 * "latest" value. We can't do this until after we've gotten the restore
5510 * command and set InArchiveRecovery, because we need to fetch timeline
5511 * history files from the archive.
5517 /* Timeline 1 does not have a history file, all else should */
5518 if (rtli != 1 && !existsTimeLineHistory(rtli))
5520 (errmsg("recovery target timeline %u does not exist",
5522 recoveryTargetTLI = rtli;
5523 recoveryTargetIsLatest = false;
5527 /* We start the "latest" search from pg_control's timeline */
5528 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
5529 recoveryTargetIsLatest = true;
5533 FreeConfigVariables(head);
5537 * Exit archive-recovery state
5540 exitArchiveRecovery(TimeLineID endTLI, XLogSegNo endLogSegNo)
5542 char recoveryPath[MAXPGPATH];
5543 char xlogpath[MAXPGPATH];
5546 * We are no longer in archive recovery state.
5548 InArchiveRecovery = false;
5551 * Update min recovery point one last time.
5553 UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
5556 * If the ending log segment is still open, close it (to avoid problems on
5557 * Windows with trying to rename or delete an open file).
5566 * If we are establishing a new timeline, we have to copy data from the
5567 * last WAL segment of the old timeline to create a starting WAL segment
5568 * for the new timeline.
5570 * Notify the archiver that the last WAL segment of the old timeline is
5571 * ready to copy to archival storage. Otherwise, it is not archived for a
5574 if (endTLI != ThisTimeLineID)
5576 XLogFileCopy(endLogSegNo, endTLI, endLogSegNo);
5578 if (XLogArchivingActive())
5580 XLogFileName(xlogpath, endTLI, endLogSegNo);
5581 XLogArchiveNotify(xlogpath);
5586 * Let's just make real sure there are not .ready or .done flags posted
5587 * for the new segment.
5589 XLogFileName(xlogpath, ThisTimeLineID, endLogSegNo);
5590 XLogArchiveCleanup(xlogpath);
5593 * Since there might be a partial WAL segment named RECOVERYXLOG, get rid
5596 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
5597 unlink(recoveryPath); /* ignore any error */
5599 /* Get rid of any remaining recovered timeline-history file, too */
5600 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
5601 unlink(recoveryPath); /* ignore any error */
5604 * Rename the config file out of the way, so that we don't accidentally
5605 * re-enter archive recovery mode in a subsequent crash.
5607 unlink(RECOVERY_COMMAND_DONE);
5608 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
5610 (errcode_for_file_access(),
5611 errmsg("could not rename file \"%s\" to \"%s\": %m",
5612 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
5615 (errmsg("archive recovery complete")));
5619 * For point-in-time recovery, this function decides whether we want to
5620 * stop applying the XLOG at or after the current record.
5622 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
5623 * *includeThis is set TRUE if we should apply this record before stopping.
5625 * We also track the timestamp of the latest applied COMMIT/ABORT
5626 * record in XLogCtl->recoveryLastXTime, for logging purposes.
5627 * Also, some information is saved in recoveryStopXid et al for use in
5628 * annotating the new timeline's history file.
5631 recoveryStopsHere(XLogRecord *record, bool *includeThis)
5635 TimestampTz recordXtime;
5636 char recordRPName[MAXFNAMELEN];
5638 /* We only consider stopping at COMMIT, ABORT or RESTORE POINT records */
5639 if (record->xl_rmid != RM_XACT_ID && record->xl_rmid != RM_XLOG_ID)
5641 record_info = record->xl_info & ~XLR_INFO_MASK;
5642 if (record->xl_rmid == RM_XACT_ID && record_info == XLOG_XACT_COMMIT_COMPACT)
5644 xl_xact_commit_compact *recordXactCommitData;
5646 recordXactCommitData = (xl_xact_commit_compact *) XLogRecGetData(record);
5647 recordXtime = recordXactCommitData->xact_time;
5649 else if (record->xl_rmid == RM_XACT_ID && record_info == XLOG_XACT_COMMIT)
5651 xl_xact_commit *recordXactCommitData;
5653 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
5654 recordXtime = recordXactCommitData->xact_time;
5656 else if (record->xl_rmid == RM_XACT_ID && record_info == XLOG_XACT_ABORT)
5658 xl_xact_abort *recordXactAbortData;
5660 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
5661 recordXtime = recordXactAbortData->xact_time;
5663 else if (record->xl_rmid == RM_XLOG_ID && record_info == XLOG_RESTORE_POINT)
5665 xl_restore_point *recordRestorePointData;
5667 recordRestorePointData = (xl_restore_point *) XLogRecGetData(record);
5668 recordXtime = recordRestorePointData->rp_time;
5669 strncpy(recordRPName, recordRestorePointData->rp_name, MAXFNAMELEN);
5674 /* Do we have a PITR target at all? */
5675 if (recoveryTarget == RECOVERY_TARGET_UNSET)
5678 * Save timestamp of latest transaction commit/abort if this is a
5679 * transaction record
5681 if (record->xl_rmid == RM_XACT_ID)
5682 SetLatestXTime(recordXtime);
5686 if (recoveryTarget == RECOVERY_TARGET_XID)
5689 * There can be only one transaction end record with this exact
5692 * when testing for an xid, we MUST test for equality only, since
5693 * transactions are numbered in the order they start, not the order
5694 * they complete. A higher numbered xid will complete before you about
5695 * 50% of the time...
5697 stopsHere = (record->xl_xid == recoveryTargetXid);
5699 *includeThis = recoveryTargetInclusive;
5701 else if (recoveryTarget == RECOVERY_TARGET_NAME)
5704 * There can be many restore points that share the same name, so we
5705 * stop at the first one
5707 stopsHere = (strcmp(recordRPName, recoveryTargetName) == 0);
5710 * Ignore recoveryTargetInclusive because this is not a transaction
5713 *includeThis = false;
5718 * There can be many transactions that share the same commit time, so
5719 * we stop after the last one, if we are inclusive, or stop at the
5720 * first one if we are exclusive
5722 if (recoveryTargetInclusive)
5723 stopsHere = (recordXtime > recoveryTargetTime);
5725 stopsHere = (recordXtime >= recoveryTargetTime);
5727 *includeThis = false;
5732 recoveryStopXid = record->xl_xid;
5733 recoveryStopTime = recordXtime;
5734 recoveryStopAfter = *includeThis;
5736 if (record_info == XLOG_XACT_COMMIT_COMPACT || record_info == XLOG_XACT_COMMIT)
5738 if (recoveryStopAfter)
5740 (errmsg("recovery stopping after commit of transaction %u, time %s",
5742 timestamptz_to_str(recoveryStopTime))));
5745 (errmsg("recovery stopping before commit of transaction %u, time %s",
5747 timestamptz_to_str(recoveryStopTime))));
5749 else if (record_info == XLOG_XACT_ABORT)
5751 if (recoveryStopAfter)
5753 (errmsg("recovery stopping after abort of transaction %u, time %s",
5755 timestamptz_to_str(recoveryStopTime))));
5758 (errmsg("recovery stopping before abort of transaction %u, time %s",
5760 timestamptz_to_str(recoveryStopTime))));
5764 strncpy(recoveryStopName, recordRPName, MAXFNAMELEN);
5767 (errmsg("recovery stopping at restore point \"%s\", time %s",
5769 timestamptz_to_str(recoveryStopTime))));
5773 * Note that if we use a RECOVERY_TARGET_TIME then we can stop at a
5774 * restore point since they are timestamped, though the latest
5775 * transaction time is not updated.
5777 if (record->xl_rmid == RM_XACT_ID && recoveryStopAfter)
5778 SetLatestXTime(recordXtime);
5780 else if (record->xl_rmid == RM_XACT_ID)
5781 SetLatestXTime(recordXtime);
5787 * Wait until shared recoveryPause flag is cleared.
5789 * XXX Could also be done with shared latch, avoiding the pg_usleep loop.
5790 * Probably not worth the trouble though. This state shouldn't be one that
5791 * anyone cares about server power consumption in.
5794 recoveryPausesHere(void)
5796 /* Don't pause unless users can connect! */
5797 if (!LocalHotStandbyActive)
5801 (errmsg("recovery has paused"),
5802 errhint("Execute pg_xlog_replay_resume() to continue.")));
5804 while (RecoveryIsPaused())
5806 pg_usleep(1000000L); /* 1000 ms */
5807 HandleStartupProcInterrupts();
5812 RecoveryIsPaused(void)
5814 /* use volatile pointer to prevent code rearrangement */
5815 volatile XLogCtlData *xlogctl = XLogCtl;
5818 SpinLockAcquire(&xlogctl->info_lck);
5819 recoveryPause = xlogctl->recoveryPause;
5820 SpinLockRelease(&xlogctl->info_lck);
5822 return recoveryPause;
5826 SetRecoveryPause(bool recoveryPause)
5828 /* use volatile pointer to prevent code rearrangement */
5829 volatile XLogCtlData *xlogctl = XLogCtl;
5831 SpinLockAcquire(&xlogctl->info_lck);
5832 xlogctl->recoveryPause = recoveryPause;
5833 SpinLockRelease(&xlogctl->info_lck);
5837 * Save timestamp of latest processed commit/abort record.
5839 * We keep this in XLogCtl, not a simple static variable, so that it can be
5840 * seen by processes other than the startup process. Note in particular
5841 * that CreateRestartPoint is executed in the checkpointer.
5844 SetLatestXTime(TimestampTz xtime)
5846 /* use volatile pointer to prevent code rearrangement */
5847 volatile XLogCtlData *xlogctl = XLogCtl;
5849 SpinLockAcquire(&xlogctl->info_lck);
5850 xlogctl->recoveryLastXTime = xtime;
5851 SpinLockRelease(&xlogctl->info_lck);
5855 * Fetch timestamp of latest processed commit/abort record.
5858 GetLatestXTime(void)
5860 /* use volatile pointer to prevent code rearrangement */
5861 volatile XLogCtlData *xlogctl = XLogCtl;
5864 SpinLockAcquire(&xlogctl->info_lck);
5865 xtime = xlogctl->recoveryLastXTime;
5866 SpinLockRelease(&xlogctl->info_lck);
5872 * Save timestamp of the next chunk of WAL records to apply.
5874 * We keep this in XLogCtl, not a simple static variable, so that it can be
5875 * seen by all backends.
5878 SetCurrentChunkStartTime(TimestampTz xtime)
5880 /* use volatile pointer to prevent code rearrangement */
5881 volatile XLogCtlData *xlogctl = XLogCtl;
5883 SpinLockAcquire(&xlogctl->info_lck);
5884 xlogctl->currentChunkStartTime = xtime;
5885 SpinLockRelease(&xlogctl->info_lck);
5889 * Fetch timestamp of latest processed commit/abort record.
5890 * Startup process maintains an accurate local copy in XLogReceiptTime
5893 GetCurrentChunkReplayStartTime(void)
5895 /* use volatile pointer to prevent code rearrangement */
5896 volatile XLogCtlData *xlogctl = XLogCtl;
5899 SpinLockAcquire(&xlogctl->info_lck);
5900 xtime = xlogctl->currentChunkStartTime;
5901 SpinLockRelease(&xlogctl->info_lck);
5907 * Returns time of receipt of current chunk of XLOG data, as well as
5908 * whether it was received from streaming replication or from archives.
5911 GetXLogReceiptTime(TimestampTz *rtime, bool *fromStream)
5914 * This must be executed in the startup process, since we don't export the
5915 * relevant state to shared memory.
5919 *rtime = XLogReceiptTime;
5920 *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
5924 * Note that text field supplied is a parameter name and does not require
5927 #define RecoveryRequiresIntParameter(param_name, currValue, minValue) \
5929 if ((currValue) < (minValue)) \
5931 (errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
5932 errmsg("hot standby is not possible because " \
5933 "%s = %d is a lower setting than on the master server " \
5934 "(its value was %d)", \
5941 * Check to see if required parameters are set high enough on this server
5942 * for various aspects of recovery operation.
5945 CheckRequiredParameterValues(void)
5948 * For archive recovery, the WAL must be generated with at least 'archive'
5951 if (InArchiveRecovery && ControlFile->wal_level == WAL_LEVEL_MINIMAL)
5954 (errmsg("WAL was generated with wal_level=minimal, data may be missing"),
5955 errhint("This happens if you temporarily set wal_level=minimal without taking a new base backup.")));
5959 * For Hot Standby, the WAL must be generated with 'hot_standby' mode, and
5960 * we must have at least as many backend slots as the primary.
5962 if (InArchiveRecovery && EnableHotStandby)
5964 if (ControlFile->wal_level < WAL_LEVEL_HOT_STANDBY)
5966 (errmsg("hot standby is not possible because wal_level was not set to \"hot_standby\" on the master server"),
5967 errhint("Either set wal_level to \"hot_standby\" on the master, or turn off hot_standby here.")));
5969 /* We ignore autovacuum_max_workers when we make this test. */
5970 RecoveryRequiresIntParameter("max_connections",
5972 ControlFile->MaxConnections);
5973 RecoveryRequiresIntParameter("max_worker_processes",
5974 max_worker_processes,
5975 ControlFile->max_worker_processes);
5976 RecoveryRequiresIntParameter("max_prepared_transactions",
5978 ControlFile->max_prepared_xacts);
5979 RecoveryRequiresIntParameter("max_locks_per_transaction",
5981 ControlFile->max_locks_per_xact);
5986 * This must be called ONCE during postmaster or standalone-backend startup
5991 XLogCtlInsert *Insert;
5992 CheckPoint checkPoint;
5994 bool reachedStopPoint = false;
5995 bool haveBackupLabel = false;
5999 XLogSegNo endLogSegNo;
6000 TimeLineID PrevTimeLineID;
6002 TransactionId oldestActiveXID;
6003 bool backupEndRequired = false;
6004 bool backupFromStandby = false;
6005 DBState dbstate_at_startup;
6006 XLogReaderState *xlogreader;
6007 XLogPageReadPrivate private;
6008 bool fast_promoted = false;
6011 * Read control file and check XLOG status looks valid.
6013 * Note: in most control paths, *ControlFile is already valid and we need
6014 * not do ReadControlFile() here, but might as well do it to be sure.
6018 if (ControlFile->state < DB_SHUTDOWNED ||
6019 ControlFile->state > DB_IN_PRODUCTION ||
6020 !XRecOffIsValid(ControlFile->checkPoint))
6022 (errmsg("control file contains invalid data")));
6024 if (ControlFile->state == DB_SHUTDOWNED)
6026 /* This is the expected case, so don't be chatty in standalone mode */
6027 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
6028 (errmsg("database system was shut down at %s",
6029 str_time(ControlFile->time))));
6031 else if (ControlFile->state == DB_SHUTDOWNED_IN_RECOVERY)
6033 (errmsg("database system was shut down in recovery at %s",
6034 str_time(ControlFile->time))));
6035 else if (ControlFile->state == DB_SHUTDOWNING)
6037 (errmsg("database system shutdown was interrupted; last known up at %s",
6038 str_time(ControlFile->time))));
6039 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
6041 (errmsg("database system was interrupted while in recovery at %s",
6042 str_time(ControlFile->time)),
6043 errhint("This probably means that some data is corrupted and"
6044 " you will have to use the last backup for recovery.")));
6045 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
6047 (errmsg("database system was interrupted while in recovery at log time %s",
6048 str_time(ControlFile->checkPointCopy.time)),
6049 errhint("If this has occurred more than once some data might be corrupted"
6050 " and you might need to choose an earlier recovery target.")));
6051 else if (ControlFile->state == DB_IN_PRODUCTION)
6053 (errmsg("database system was interrupted; last known up at %s",
6054 str_time(ControlFile->time))));
6056 /* This is just to allow attaching to startup process with a debugger */
6057 #ifdef XLOG_REPLAY_DELAY
6058 if (ControlFile->state != DB_SHUTDOWNED)
6059 pg_usleep(60000000L);
6063 * Verify that pg_xlog and pg_xlog/archive_status exist. In cases where
6064 * someone has performed a copy for PITR, these directories may have been
6065 * excluded and need to be re-created.
6067 ValidateXLOGDirectoryStructure();
6070 * Clear out any old relcache cache files. This is *necessary* if we do
6071 * any WAL replay, since that would probably result in the cache files
6072 * being out of sync with database reality. In theory we could leave them
6073 * in place if the database had been cleanly shut down, but it seems
6074 * safest to just remove them always and let them be rebuilt during the
6075 * first backend startup.
6077 RelationCacheInitFileRemove();
6080 * Initialize on the assumption we want to recover to the latest timeline
6081 * that's active according to pg_control.
6083 if (ControlFile->minRecoveryPointTLI >
6084 ControlFile->checkPointCopy.ThisTimeLineID)
6085 recoveryTargetTLI = ControlFile->minRecoveryPointTLI;
6087 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
6090 * Check for recovery control file, and if so set up state for offline
6093 readRecoveryCommandFile();
6096 * Save archive_cleanup_command in shared memory so that other processes
6099 strncpy(XLogCtl->archiveCleanupCommand,
6100 archiveCleanupCommand ? archiveCleanupCommand : "",
6101 sizeof(XLogCtl->archiveCleanupCommand));
6103 if (ArchiveRecoveryRequested)
6105 if (StandbyModeRequested)
6107 (errmsg("entering standby mode")));
6108 else if (recoveryTarget == RECOVERY_TARGET_XID)
6110 (errmsg("starting point-in-time recovery to XID %u",
6111 recoveryTargetXid)));
6112 else if (recoveryTarget == RECOVERY_TARGET_TIME)
6114 (errmsg("starting point-in-time recovery to %s",
6115 timestamptz_to_str(recoveryTargetTime))));
6116 else if (recoveryTarget == RECOVERY_TARGET_NAME)
6118 (errmsg("starting point-in-time recovery to \"%s\"",
6119 recoveryTargetName)));
6122 (errmsg("starting archive recovery")));
6126 * Take ownership of the wakeup latch if we're going to sleep during
6129 if (StandbyModeRequested)
6130 OwnLatch(&XLogCtl->recoveryWakeupLatch);
6132 /* Set up XLOG reader facility */
6133 MemSet(&private, 0, sizeof(XLogPageReadPrivate));
6134 xlogreader = XLogReaderAllocate(&XLogPageRead, &private);
6137 (errcode(ERRCODE_OUT_OF_MEMORY),
6138 errmsg("out of memory"),
6139 errdetail("Failed while allocating an XLog reading processor")));
6140 xlogreader->system_identifier = ControlFile->system_identifier;
6142 if (read_backup_label(&checkPointLoc, &backupEndRequired,
6143 &backupFromStandby))
6146 * Archive recovery was requested, and thanks to the backup label
6147 * file, we know how far we need to replay to reach consistency. Enter
6148 * archive recovery directly.
6150 InArchiveRecovery = true;
6151 if (StandbyModeRequested)
6155 * When a backup_label file is present, we want to roll forward from
6156 * the checkpoint it identifies, rather than using pg_control.
6158 record = ReadCheckpointRecord(xlogreader, checkPointLoc, 0, true);
6161 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6162 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
6164 (errmsg("checkpoint record is at %X/%X",
6165 (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6166 InRecovery = true; /* force recovery even if SHUTDOWNED */
6169 * Make sure that REDO location exists. This may not be the case
6170 * if there was a crash during an online backup, which left a
6171 * backup_label around that references a WAL segment that's
6172 * already been archived.
6174 if (checkPoint.redo < checkPointLoc)
6176 if (!ReadRecord(xlogreader, checkPoint.redo, LOG, false))
6178 (errmsg("could not find redo location referenced by checkpoint record"),
6179 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6185 (errmsg("could not locate required checkpoint record"),
6186 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6187 wasShutdown = false; /* keep compiler quiet */
6189 /* set flag to delete it later */
6190 haveBackupLabel = true;
6195 * It's possible that archive recovery was requested, but we don't
6196 * know how far we need to replay the WAL before we reach consistency.
6197 * This can happen for example if a base backup is taken from a
6198 * running server using an atomic filesystem snapshot, without calling
6199 * pg_start/stop_backup. Or if you just kill a running master server
6200 * and put it into archive recovery by creating a recovery.conf file.
6202 * Our strategy in that case is to perform crash recovery first,
6203 * replaying all the WAL present in pg_xlog, and only enter archive
6204 * recovery after that.
6206 * But usually we already know how far we need to replay the WAL (up
6207 * to minRecoveryPoint, up to backupEndPoint, or until we see an
6208 * end-of-backup record), and we can enter archive recovery directly.
6210 if (ArchiveRecoveryRequested &&
6211 (ControlFile->minRecoveryPoint != InvalidXLogRecPtr ||
6212 ControlFile->backupEndRequired ||
6213 ControlFile->backupEndPoint != InvalidXLogRecPtr ||
6214 ControlFile->state == DB_SHUTDOWNED))
6216 InArchiveRecovery = true;
6217 if (StandbyModeRequested)
6222 * Get the last valid checkpoint record. If the latest one according
6223 * to pg_control is broken, try the next-to-last one.
6225 checkPointLoc = ControlFile->checkPoint;
6226 RedoStartLSN = ControlFile->checkPointCopy.redo;
6227 record = ReadCheckpointRecord(xlogreader, checkPointLoc, 1, true);
6231 (errmsg("checkpoint record is at %X/%X",
6232 (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6234 else if (StandbyMode)
6237 * The last valid checkpoint record required for a streaming
6238 * recovery exists in neither standby nor the primary.
6241 (errmsg("could not locate a valid checkpoint record")));
6245 checkPointLoc = ControlFile->prevCheckPoint;
6246 record = ReadCheckpointRecord(xlogreader, checkPointLoc, 2, true);
6250 (errmsg("using previous checkpoint record at %X/%X",
6251 (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6252 InRecovery = true; /* force recovery even if SHUTDOWNED */
6256 (errmsg("could not locate a valid checkpoint record")));
6258 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6259 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
6263 * If the location of the checkpoint record is not on the expected
6264 * timeline in the history of the requested timeline, we cannot proceed:
6265 * the backup is not part of the history of the requested timeline.
6267 Assert(expectedTLEs); /* was initialized by reading checkpoint
6269 if (tliOfPointInHistory(checkPointLoc, expectedTLEs) !=
6270 checkPoint.ThisTimeLineID)
6272 XLogRecPtr switchpoint;
6275 * tliSwitchPoint will throw an error if the checkpoint's timeline is
6276 * not in expectedTLEs at all.
6278 switchpoint = tliSwitchPoint(ControlFile->checkPointCopy.ThisTimeLineID, expectedTLEs, NULL);
6280 (errmsg("requested timeline %u is not a child of this server's history",
6282 errdetail("Latest checkpoint is at %X/%X on timeline %u, but in the history of the requested timeline, the server forked off from that timeline at %X/%X",
6283 (uint32) (ControlFile->checkPoint >> 32),
6284 (uint32) ControlFile->checkPoint,
6285 ControlFile->checkPointCopy.ThisTimeLineID,
6286 (uint32) (switchpoint >> 32),
6287 (uint32) switchpoint)));
6291 * The min recovery point should be part of the requested timeline's
6294 if (!XLogRecPtrIsInvalid(ControlFile->minRecoveryPoint) &&
6295 tliOfPointInHistory(ControlFile->minRecoveryPoint - 1, expectedTLEs) !=
6296 ControlFile->minRecoveryPointTLI)
6298 (errmsg("requested timeline %u does not contain minimum recovery point %X/%X on timeline %u",
6300 (uint32) (ControlFile->minRecoveryPoint >> 32),
6301 (uint32) ControlFile->minRecoveryPoint,
6302 ControlFile->minRecoveryPointTLI)));
6304 LastRec = RecPtr = checkPointLoc;
6307 (errmsg("redo record is at %X/%X; shutdown %s",
6308 (uint32) (checkPoint.redo >> 32), (uint32) checkPoint.redo,
6309 wasShutdown ? "TRUE" : "FALSE")));
6311 (errmsg("next transaction ID: %u/%u; next OID: %u",
6312 checkPoint.nextXidEpoch, checkPoint.nextXid,
6313 checkPoint.nextOid)));
6315 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
6316 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
6318 (errmsg("oldest unfrozen transaction ID: %u, in database %u",
6319 checkPoint.oldestXid, checkPoint.oldestXidDB)));
6321 (errmsg("oldest MultiXactId: %u, in database %u",
6322 checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
6323 if (!TransactionIdIsNormal(checkPoint.nextXid))
6325 (errmsg("invalid next transaction ID")));
6327 /* initialize shared memory variables from the checkpoint record */
6328 ShmemVariableCache->nextXid = checkPoint.nextXid;
6329 ShmemVariableCache->nextOid = checkPoint.nextOid;
6330 ShmemVariableCache->oidCount = 0;
6331 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
6332 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
6333 SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
6334 XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
6335 XLogCtl->ckptXid = checkPoint.nextXid;
6338 * Initialize unlogged LSN. On a clean shutdown, it's restored from the
6339 * control file. On recovery, all unlogged relations are blown away, so
6340 * the unlogged LSN counter can be reset too.
6342 if (ControlFile->state == DB_SHUTDOWNED)
6343 XLogCtl->unloggedLSN = ControlFile->unloggedLSN;
6345 XLogCtl->unloggedLSN = 1;
6348 * We must replay WAL entries using the same TimeLineID they were created
6349 * under, so temporarily adopt the TLI indicated by the checkpoint (see
6350 * also xlog_redo()).
6352 ThisTimeLineID = checkPoint.ThisTimeLineID;
6355 * Copy any missing timeline history files between 'now' and the recovery
6356 * target timeline from archive to pg_xlog. While we don't need those
6357 * files ourselves - the history file of the recovery target timeline
6358 * covers all the previous timelines in the history too - a cascading
6359 * standby server might be interested in them. Or, if you archive the WAL
6360 * from this server to a different archive than the master, it'd be good
6361 * for all the history files to get archived there after failover, so that
6362 * you can use one of the old timelines as a PITR target. Timeline history
6363 * files are small, so it's better to copy them unnecessarily than not
6364 * copy them and regret later.
6366 restoreTimeLineHistoryFiles(ThisTimeLineID, recoveryTargetTLI);
6368 lastFullPageWrites = checkPoint.fullPageWrites;
6370 RedoRecPtr = XLogCtl->RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
6372 if (RecPtr < checkPoint.redo)
6374 (errmsg("invalid redo in checkpoint record")));
6377 * Check whether we need to force recovery from WAL. If it appears to
6378 * have been a clean shutdown and we did not have a recovery.conf file,
6379 * then assume no recovery needed.
6381 if (checkPoint.redo < RecPtr)
6385 (errmsg("invalid redo record in shutdown checkpoint")));
6388 else if (ControlFile->state != DB_SHUTDOWNED)
6390 else if (ArchiveRecoveryRequested)
6392 /* force recovery due to presence of recovery.conf */
6401 /* use volatile pointer to prevent code rearrangement */
6402 volatile XLogCtlData *xlogctl = XLogCtl;
6405 * Update pg_control to show that we are recovering and to show the
6406 * selected checkpoint as the place we are starting from. We also mark
6407 * pg_control with any minimum recovery stop point obtained from a
6408 * backup history file.
6410 dbstate_at_startup = ControlFile->state;
6411 if (InArchiveRecovery)
6412 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
6416 (errmsg("database system was not properly shut down; "
6417 "automatic recovery in progress")));
6418 if (recoveryTargetTLI > ControlFile->checkPointCopy.ThisTimeLineID)
6420 (errmsg("crash recovery starts in timeline %u "
6421 "and has target timeline %u",
6422 ControlFile->checkPointCopy.ThisTimeLineID,
6423 recoveryTargetTLI)));
6424 ControlFile->state = DB_IN_CRASH_RECOVERY;
6426 ControlFile->prevCheckPoint = ControlFile->checkPoint;
6427 ControlFile->checkPoint = checkPointLoc;
6428 ControlFile->checkPointCopy = checkPoint;
6429 if (InArchiveRecovery)
6431 /* initialize minRecoveryPoint if not set yet */
6432 if (ControlFile->minRecoveryPoint < checkPoint.redo)
6434 ControlFile->minRecoveryPoint = checkPoint.redo;
6435 ControlFile->minRecoveryPointTLI = checkPoint.ThisTimeLineID;
6440 * Set backupStartPoint if we're starting recovery from a base backup.
6442 * Set backupEndPoint and use minRecoveryPoint as the backup end
6443 * location if we're starting recovery from a base backup which was
6444 * taken from the standby. In this case, the database system status in
6445 * pg_control must indicate DB_IN_ARCHIVE_RECOVERY. If not, which
6446 * means that backup is corrupted, so we cancel recovery.
6448 if (haveBackupLabel)
6450 ControlFile->backupStartPoint = checkPoint.redo;
6451 ControlFile->backupEndRequired = backupEndRequired;
6453 if (backupFromStandby)
6455 if (dbstate_at_startup != DB_IN_ARCHIVE_RECOVERY)
6457 (errmsg("backup_label contains data inconsistent with control file"),
6458 errhint("This means that the backup is corrupted and you will "
6459 "have to use another backup for recovery.")));
6460 ControlFile->backupEndPoint = ControlFile->minRecoveryPoint;
6463 ControlFile->time = (pg_time_t) time(NULL);
6464 /* No need to hold ControlFileLock yet, we aren't up far enough */
6465 UpdateControlFile();
6467 /* initialize our local copy of minRecoveryPoint */
6468 minRecoveryPoint = ControlFile->minRecoveryPoint;
6469 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
6472 * Reset pgstat data, because it may be invalid after recovery.
6477 * If there was a backup label file, it's done its job and the info
6478 * has now been propagated into pg_control. We must get rid of the
6479 * label file so that if we crash during recovery, we'll pick up at
6480 * the latest recovery restartpoint instead of going all the way back
6481 * to the backup start point. It seems prudent though to just rename
6482 * the file out of the way rather than delete it completely.
6484 if (haveBackupLabel)
6486 unlink(BACKUP_LABEL_OLD);
6487 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
6489 (errcode_for_file_access(),
6490 errmsg("could not rename file \"%s\" to \"%s\": %m",
6491 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
6494 /* Check that the GUCs used to generate the WAL allow recovery */
6495 CheckRequiredParameterValues();
6498 * We're in recovery, so unlogged relations may be trashed and must be
6499 * reset. This should be done BEFORE allowing Hot Standby
6500 * connections, so that read-only backends don't try to read whatever
6501 * garbage is left over from before.
6503 ResetUnloggedRelations(UNLOGGED_RELATION_CLEANUP);
6506 * Likewise, delete any saved transaction snapshot files that got left
6507 * behind by crashed backends.
6509 DeleteAllExportedSnapshotFiles();
6512 * Initialize for Hot Standby, if enabled. We won't let backends in
6513 * yet, not until we've reached the min recovery point specified in
6514 * control file and we've established a recovery snapshot from a
6515 * running-xacts WAL record.
6517 if (ArchiveRecoveryRequested && EnableHotStandby)
6519 TransactionId *xids;
6523 (errmsg("initializing for hot standby")));
6525 InitRecoveryTransactionEnvironment();
6528 oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
6530 oldestActiveXID = checkPoint.oldestActiveXid;
6531 Assert(TransactionIdIsValid(oldestActiveXID));
6533 /* Tell procarray about the range of xids it has to deal with */
6534 ProcArrayInitRecovery(ShmemVariableCache->nextXid);
6537 * Startup commit log and subtrans only. Other SLRUs are not
6538 * maintained during recovery and need not be started yet.
6541 StartupSUBTRANS(oldestActiveXID);
6544 * If we're beginning at a shutdown checkpoint, we know that
6545 * nothing was running on the master at this point. So fake-up an
6546 * empty running-xacts record and use that here and now. Recover
6547 * additional standby state for prepared transactions.
6551 RunningTransactionsData running;
6552 TransactionId latestCompletedXid;
6555 * Construct a RunningTransactions snapshot representing a
6556 * shut down server, with only prepared transactions still
6557 * alive. We're never overflowed at this point because all
6558 * subxids are listed with their parent prepared transactions.
6560 running.xcnt = nxids;
6561 running.subxcnt = 0;
6562 running.subxid_overflow = false;
6563 running.nextXid = checkPoint.nextXid;
6564 running.oldestRunningXid = oldestActiveXID;
6565 latestCompletedXid = checkPoint.nextXid;
6566 TransactionIdRetreat(latestCompletedXid);
6567 Assert(TransactionIdIsNormal(latestCompletedXid));
6568 running.latestCompletedXid = latestCompletedXid;
6569 running.xids = xids;
6571 ProcArrayApplyRecoveryInfo(&running);
6573 StandbyRecoverPreparedTransactions(false);
6577 /* Initialize resource managers */
6578 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
6580 if (RmgrTable[rmid].rm_startup != NULL)
6581 RmgrTable[rmid].rm_startup();
6585 * Initialize shared replayEndRecPtr, lastReplayedEndRecPtr, and
6586 * recoveryLastXTime.
6588 * This is slightly confusing if we're starting from an online
6589 * checkpoint; we've just read and replayed the checkpoint record, but
6590 * we're going to start replay from its redo pointer, which precedes
6591 * the location of the checkpoint record itself. So even though the
6592 * last record we've replayed is indeed ReadRecPtr, we haven't
6593 * replayed all the preceding records yet. That's OK for the current
6594 * use of these variables.
6596 SpinLockAcquire(&xlogctl->info_lck);
6597 xlogctl->replayEndRecPtr = ReadRecPtr;
6598 xlogctl->replayEndTLI = ThisTimeLineID;
6599 xlogctl->lastReplayedEndRecPtr = EndRecPtr;
6600 xlogctl->lastReplayedTLI = ThisTimeLineID;
6601 xlogctl->recoveryLastXTime = 0;
6602 xlogctl->currentChunkStartTime = 0;
6603 xlogctl->recoveryPause = false;
6604 SpinLockRelease(&xlogctl->info_lck);
6606 /* Also ensure XLogReceiptTime has a sane value */
6607 XLogReceiptTime = GetCurrentTimestamp();
6610 * Let postmaster know we've started redo now, so that it can launch
6611 * checkpointer to perform restartpoints. We don't bother during
6612 * crash recovery as restartpoints can only be performed during
6613 * archive recovery. And we'd like to keep crash recovery simple, to
6614 * avoid introducing bugs that could affect you when recovering after
6617 * After this point, we can no longer assume that we're the only
6618 * process in addition to postmaster! Also, fsync requests are
6619 * subsequently to be handled by the checkpointer, not locally.
6621 if (ArchiveRecoveryRequested && IsUnderPostmaster)
6623 PublishStartupProcessInformation();
6624 SetForwardFsyncRequests();
6625 SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED);
6626 bgwriterLaunched = true;
6630 * Allow read-only connections immediately if we're consistent
6633 CheckRecoveryConsistency();
6636 * Find the first record that logically follows the checkpoint --- it
6637 * might physically precede it, though.
6639 if (checkPoint.redo < RecPtr)
6641 /* back up to find the record */
6642 record = ReadRecord(xlogreader, checkPoint.redo, PANIC, false);
6646 /* just have to read next record after CheckPoint */
6647 record = ReadRecord(xlogreader, InvalidXLogRecPtr, LOG, false);
6652 bool recoveryContinue = true;
6653 bool recoveryApply = true;
6654 ErrorContextCallback errcallback;
6660 (errmsg("redo starts at %X/%X",
6661 (uint32) (ReadRecPtr >> 32), (uint32) ReadRecPtr)));
6664 * main redo apply loop
6668 bool switchedTLI = false;
6672 (rmid == RM_XACT_ID && trace_recovery_messages <= DEBUG2) ||
6673 (rmid != RM_XACT_ID && trace_recovery_messages <= DEBUG3))
6677 initStringInfo(&buf);
6678 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
6679 (uint32) (ReadRecPtr >> 32), (uint32) ReadRecPtr,
6680 (uint32) (EndRecPtr >> 32), (uint32) EndRecPtr);
6681 xlog_outrec(&buf, record);
6682 appendStringInfo(&buf, " - ");
6683 RmgrTable[record->xl_rmid].rm_desc(&buf,
6685 XLogRecGetData(record));
6686 elog(LOG, "%s", buf.data);
6691 /* Handle interrupt signals of startup process */
6692 HandleStartupProcInterrupts();
6695 * Pause WAL replay, if requested by a hot-standby session via
6696 * SetRecoveryPause().
6698 * Note that we intentionally don't take the info_lck spinlock
6699 * here. We might therefore read a slightly stale value of
6700 * the recoveryPause flag, but it can't be very stale (no
6701 * worse than the last spinlock we did acquire). Since a
6702 * pause request is a pretty asynchronous thing anyway,
6703 * possibly responding to it one WAL record later than we
6704 * otherwise would is a minor issue, so it doesn't seem worth
6705 * adding another spinlock cycle to prevent that.
6707 if (xlogctl->recoveryPause)
6708 recoveryPausesHere();
6711 * Have we reached our recovery target?
6713 if (recoveryStopsHere(record, &recoveryApply))
6715 if (recoveryPauseAtTarget)
6717 SetRecoveryPause(true);
6718 recoveryPausesHere();
6720 reachedStopPoint = true; /* see below */
6721 recoveryContinue = false;
6723 /* Exit loop if we reached non-inclusive recovery target */
6728 /* Setup error traceback support for ereport() */
6729 errcallback.callback = rm_redo_error_callback;
6730 errcallback.arg = (void *) record;
6731 errcallback.previous = error_context_stack;
6732 error_context_stack = &errcallback;
6735 * ShmemVariableCache->nextXid must be beyond record's xid.
6737 * We don't expect anyone else to modify nextXid, hence we
6738 * don't need to hold a lock while examining it. We still
6739 * acquire the lock to modify it, though.
6741 if (TransactionIdFollowsOrEquals(record->xl_xid,
6742 ShmemVariableCache->nextXid))
6744 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
6745 ShmemVariableCache->nextXid = record->xl_xid;
6746 TransactionIdAdvance(ShmemVariableCache->nextXid);
6747 LWLockRelease(XidGenLock);
6751 * Before replaying this record, check if this record causes
6752 * the current timeline to change. The record is already
6753 * considered to be part of the new timeline, so we update
6754 * ThisTimeLineID before replaying it. That's important so
6755 * that replayEndTLI, which is recorded as the minimum
6756 * recovery point's TLI if recovery stops after this record,
6759 if (record->xl_rmid == RM_XLOG_ID)
6761 TimeLineID newTLI = ThisTimeLineID;
6762 TimeLineID prevTLI = ThisTimeLineID;
6763 uint8 info = record->xl_info & ~XLR_INFO_MASK;
6765 if (info == XLOG_CHECKPOINT_SHUTDOWN)
6767 CheckPoint checkPoint;
6769 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6770 newTLI = checkPoint.ThisTimeLineID;
6771 prevTLI = checkPoint.PrevTimeLineID;
6773 else if (info == XLOG_END_OF_RECOVERY)
6775 xl_end_of_recovery xlrec;
6777 memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_end_of_recovery));
6778 newTLI = xlrec.ThisTimeLineID;
6779 prevTLI = xlrec.PrevTimeLineID;
6782 if (newTLI != ThisTimeLineID)
6784 /* Check that it's OK to switch to this TLI */
6785 checkTimeLineSwitch(EndRecPtr, newTLI, prevTLI);
6787 /* Following WAL records should be run with new TLI */
6788 ThisTimeLineID = newTLI;
6794 * Update shared replayEndRecPtr before replaying this record,
6795 * so that XLogFlush will update minRecoveryPoint correctly.
6797 SpinLockAcquire(&xlogctl->info_lck);
6798 xlogctl->replayEndRecPtr = EndRecPtr;
6799 xlogctl->replayEndTLI = ThisTimeLineID;
6800 SpinLockRelease(&xlogctl->info_lck);
6803 * If we are attempting to enter Hot Standby mode, process
6806 if (standbyState >= STANDBY_INITIALIZED &&
6807 TransactionIdIsValid(record->xl_xid))
6808 RecordKnownAssignedTransactionIds(record->xl_xid);
6810 /* Now apply the WAL record itself */
6811 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
6813 /* Pop the error context stack */
6814 error_context_stack = errcallback.previous;
6817 * Update lastReplayedEndRecPtr after this record has been
6818 * successfully replayed.
6820 SpinLockAcquire(&xlogctl->info_lck);
6821 xlogctl->lastReplayedEndRecPtr = EndRecPtr;
6822 xlogctl->lastReplayedTLI = ThisTimeLineID;
6823 SpinLockRelease(&xlogctl->info_lck);
6825 /* Remember this record as the last-applied one */
6826 LastRec = ReadRecPtr;
6828 /* Allow read-only connections if we're consistent now */
6829 CheckRecoveryConsistency();
6832 * If this record was a timeline switch, wake up any
6833 * walsenders to notice that we are on a new timeline.
6835 if (switchedTLI && AllowCascadeReplication())
6838 /* Exit loop if we reached inclusive recovery target */
6839 if (!recoveryContinue)
6842 /* Else, try to fetch the next WAL record */
6843 record = ReadRecord(xlogreader, InvalidXLogRecPtr, LOG, false);
6844 } while (record != NULL);
6847 * end of main redo apply loop
6851 (errmsg("redo done at %X/%X",
6852 (uint32) (ReadRecPtr >> 32), (uint32) ReadRecPtr)));
6853 xtime = GetLatestXTime();
6856 (errmsg("last completed transaction was at log time %s",
6857 timestamptz_to_str(xtime))));
6862 /* there are no WAL records following the checkpoint */
6864 (errmsg("redo is not required")));
6869 * Kill WAL receiver, if it's still running, before we continue to write
6870 * the startup checkpoint record. It will trump over the checkpoint and
6871 * subsequent records if it's still alive when we start writing WAL.
6876 * We don't need the latch anymore. It's not strictly necessary to disown
6877 * it, but let's do it for the sake of tidiness.
6879 if (StandbyModeRequested)
6880 DisownLatch(&XLogCtl->recoveryWakeupLatch);
6883 * We are now done reading the xlog from stream. Turn off streaming
6884 * recovery to force fetching the files (which would be required at end of
6885 * recovery, e.g., timeline history file) from archive or pg_xlog.
6887 StandbyMode = false;
6890 * Re-fetch the last valid or last applied record, so we can identify the
6891 * exact endpoint of what we consider the valid portion of WAL.
6893 record = ReadRecord(xlogreader, LastRec, PANIC, false);
6894 EndOfLog = EndRecPtr;
6895 XLByteToPrevSeg(EndOfLog, endLogSegNo);
6898 * Complain if we did not roll forward far enough to render the backup
6899 * dump consistent. Note: it is indeed okay to look at the local variable
6900 * minRecoveryPoint here, even though ControlFile->minRecoveryPoint might
6901 * be further ahead --- ControlFile->minRecoveryPoint cannot have been
6902 * advanced beyond the WAL we processed.
6905 (EndOfLog < minRecoveryPoint ||
6906 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint)))
6908 if (reachedStopPoint)
6910 /* stopped because of stop request */
6912 (errmsg("requested recovery stop point is before consistent recovery point")));
6916 * Ran off end of WAL before reaching end-of-backup WAL record, or
6917 * minRecoveryPoint. That's usually a bad sign, indicating that you
6918 * tried to recover from an online backup but never called
6919 * pg_stop_backup(), or you didn't archive all the WAL up to that
6920 * point. However, this also happens in crash recovery, if the system
6921 * crashes while an online backup is in progress. We must not treat
6922 * that as an error, or the database will refuse to start up.
6924 if (ArchiveRecoveryRequested || ControlFile->backupEndRequired)
6926 if (ControlFile->backupEndRequired)
6928 (errmsg("WAL ends before end of online backup"),
6929 errhint("All WAL generated while online backup was taken must be available at recovery.")));
6930 else if (!XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
6932 (errmsg("WAL ends before end of online backup"),
6933 errhint("Online backup started with pg_start_backup() must be ended with pg_stop_backup(), and all WAL up to that point must be available at recovery.")));
6936 (errmsg("WAL ends before consistent recovery point")));
6941 * Consider whether we need to assign a new timeline ID.
6943 * If we are doing an archive recovery, we always assign a new ID. This
6944 * handles a couple of issues. If we stopped short of the end of WAL
6945 * during recovery, then we are clearly generating a new timeline and must
6946 * assign it a unique new ID. Even if we ran to the end, modifying the
6947 * current last segment is problematic because it may result in trying to
6948 * overwrite an already-archived copy of that segment, and we encourage
6949 * DBAs to make their archive_commands reject that. We can dodge the
6950 * problem by making the new active segment have a new timeline ID.
6952 * In a normal crash recovery, we can just extend the timeline we were in.
6954 PrevTimeLineID = ThisTimeLineID;
6955 if (ArchiveRecoveryRequested)
6959 Assert(InArchiveRecovery);
6961 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
6963 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
6966 * Create a comment for the history file to explain why and where
6969 if (recoveryTarget == RECOVERY_TARGET_XID)
6970 snprintf(reason, sizeof(reason),
6971 "%s transaction %u",
6972 recoveryStopAfter ? "after" : "before",
6974 else if (recoveryTarget == RECOVERY_TARGET_TIME)
6975 snprintf(reason, sizeof(reason),
6977 recoveryStopAfter ? "after" : "before",
6978 timestamptz_to_str(recoveryStopTime));
6979 else if (recoveryTarget == RECOVERY_TARGET_NAME)
6980 snprintf(reason, sizeof(reason),
6981 "at restore point \"%s\"",
6984 snprintf(reason, sizeof(reason), "no recovery target specified");
6986 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
6990 /* Save the selected TimeLineID in shared memory, too */
6991 XLogCtl->ThisTimeLineID = ThisTimeLineID;
6992 XLogCtl->PrevTimeLineID = PrevTimeLineID;
6995 * We are now done reading the old WAL. Turn off archive fetching if it
6996 * was active, and make a writable copy of the last WAL segment. (Note
6997 * that we also have a copy of the last block of the old WAL in readBuf;
6998 * we will use that below.)
7000 if (ArchiveRecoveryRequested)
7001 exitArchiveRecovery(xlogreader->readPageTLI, endLogSegNo);
7004 * Prepare to write WAL starting at EndOfLog position, and init xlog
7005 * buffer cache using the block containing the last record from the
7006 * previous incarnation.
7008 openLogSegNo = endLogSegNo;
7009 openLogFile = XLogFileOpen(openLogSegNo);
7011 Insert = &XLogCtl->Insert;
7012 Insert->PrevBytePos = XLogRecPtrToBytePos(LastRec);
7013 Insert->CurrBytePos = XLogRecPtrToBytePos(EndOfLog);
7016 * Tricky point here: readBuf contains the *last* block that the LastRec
7017 * record spans, not the one it starts in. The last block is indeed the
7018 * one we want to use.
7020 if (EndOfLog % XLOG_BLCKSZ != 0)
7025 XLogRecPtr pageBeginPtr;
7027 pageBeginPtr = EndOfLog - (EndOfLog % XLOG_BLCKSZ);
7028 Assert(readOff == pageBeginPtr % XLogSegSize);
7030 firstIdx = XLogRecPtrToBufIdx(EndOfLog);
7032 /* Copy the valid part of the last block, and zero the rest */
7033 page = &XLogCtl->pages[firstIdx * XLOG_BLCKSZ];
7034 len = EndOfLog % XLOG_BLCKSZ;
7035 memcpy(page, xlogreader->readBuf, len);
7036 memset(page + len, 0, XLOG_BLCKSZ - len);
7038 XLogCtl->xlblocks[firstIdx] = pageBeginPtr + XLOG_BLCKSZ;
7039 XLogCtl->InitializedUpTo = pageBeginPtr + XLOG_BLCKSZ;
7044 * There is no partial block to copy. Just set InitializedUpTo,
7045 * and let the first attempt to insert a log record to initialize
7048 XLogCtl->InitializedUpTo = EndOfLog;
7051 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
7053 XLogCtl->LogwrtResult = LogwrtResult;
7055 XLogCtl->LogwrtRqst.Write = EndOfLog;
7056 XLogCtl->LogwrtRqst.Flush = EndOfLog;
7058 /* Pre-scan prepared transactions to find out the range of XIDs present */
7059 oldestActiveXID = PrescanPreparedTransactions(NULL, NULL);
7062 * Update full_page_writes in shared memory and write an XLOG_FPW_CHANGE
7063 * record before resource manager writes cleanup WAL records or checkpoint
7064 * record is written.
7066 Insert->fullPageWrites = lastFullPageWrites;
7067 LocalSetXLogInsertAllowed();
7068 UpdateFullPageWrites();
7069 LocalXLogInsertAllowed = -1;
7076 * Resource managers might need to write WAL records, eg, to record
7077 * index cleanup actions. So temporarily enable XLogInsertAllowed in
7078 * this process only.
7080 LocalSetXLogInsertAllowed();
7083 * Allow resource managers to do any required cleanup.
7085 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
7087 if (RmgrTable[rmid].rm_cleanup != NULL)
7088 RmgrTable[rmid].rm_cleanup();
7091 /* Disallow XLogInsert again */
7092 LocalXLogInsertAllowed = -1;
7095 * Perform a checkpoint to update all our recovery activity to disk.
7097 * Note that we write a shutdown checkpoint rather than an on-line
7098 * one. This is not particularly critical, but since we may be
7099 * assigning a new TLI, using a shutdown checkpoint allows us to have
7100 * the rule that TLI only changes in shutdown checkpoints, which
7101 * allows some extra error checking in xlog_redo.
7103 * In fast promotion, only create a lightweight end-of-recovery record
7104 * instead of a full checkpoint. A checkpoint is requested later,
7105 * after we're fully out of recovery mode and already accepting
7108 if (bgwriterLaunched)
7112 checkPointLoc = ControlFile->prevCheckPoint;
7115 * Confirm the last checkpoint is available for us to recover
7116 * from if we fail. Note that we don't check for the secondary
7117 * checkpoint since that isn't available in most base backups.
7119 record = ReadCheckpointRecord(xlogreader, checkPointLoc, 1, false);
7122 fast_promoted = true;
7125 * Insert a special WAL record to mark the end of
7126 * recovery, since we aren't doing a checkpoint. That
7127 * means that the checkpointer process may likely be in
7128 * the middle of a time-smoothed restartpoint and could
7129 * continue to be for minutes after this. That sounds
7130 * strange, but the effect is roughly the same and it
7131 * would be stranger to try to come out of the
7132 * restartpoint and then checkpoint. We request a
7133 * checkpoint later anyway, just for safety.
7135 CreateEndOfRecoveryRecord();
7140 RequestCheckpoint(CHECKPOINT_END_OF_RECOVERY |
7141 CHECKPOINT_IMMEDIATE |
7145 CreateCheckPoint(CHECKPOINT_END_OF_RECOVERY | CHECKPOINT_IMMEDIATE);
7148 * And finally, execute the recovery_end_command, if any.
7150 if (recoveryEndCommand)
7151 ExecuteRecoveryCommand(recoveryEndCommand,
7152 "recovery_end_command",
7157 * Preallocate additional log files, if wanted.
7159 PreallocXlogFiles(EndOfLog);
7162 * Reset initial contents of unlogged relations. This has to be done
7163 * AFTER recovery is complete so that any unlogged relations created
7164 * during recovery also get picked up.
7167 ResetUnloggedRelations(UNLOGGED_RELATION_INIT);
7170 * Okay, we're officially UP.
7174 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7175 ControlFile->state = DB_IN_PRODUCTION;
7176 ControlFile->time = (pg_time_t) time(NULL);
7177 UpdateControlFile();
7178 LWLockRelease(ControlFileLock);
7180 /* start the archive_timeout timer running */
7181 XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
7183 /* also initialize latestCompletedXid, to nextXid - 1 */
7184 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
7185 ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
7186 TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);
7187 LWLockRelease(ProcArrayLock);
7190 * Start up the commit log and subtrans, if not already done for hot
7193 if (standbyState == STANDBY_DISABLED)
7196 StartupSUBTRANS(oldestActiveXID);
7200 * Perform end of recovery actions for any SLRUs that need it.
7205 /* Reload shared-memory state for prepared transactions */
7206 RecoverPreparedTransactions();
7209 * Shutdown the recovery environment. This must occur after
7210 * RecoverPreparedTransactions(), see notes for lock_twophase_recover()
7212 if (standbyState != STANDBY_DISABLED)
7213 ShutdownRecoveryTransactionEnvironment();
7215 /* Shut down xlogreader */
7221 XLogReaderFree(xlogreader);
7224 * If any of the critical GUCs have changed, log them before we allow
7225 * backends to write WAL.
7227 LocalSetXLogInsertAllowed();
7228 XLogReportParameters();
7231 * All done. Allow backends to write WAL. (Although the bool flag is
7232 * probably atomic in itself, we use the info_lck here to ensure that
7233 * there are no race conditions concerning visibility of other recent
7234 * updates to shared memory.)
7237 /* use volatile pointer to prevent code rearrangement */
7238 volatile XLogCtlData *xlogctl = XLogCtl;
7240 SpinLockAcquire(&xlogctl->info_lck);
7241 xlogctl->SharedRecoveryInProgress = false;
7242 SpinLockRelease(&xlogctl->info_lck);
7246 * If there were cascading standby servers connected to us, nudge any wal
7247 * sender processes to notice that we've been promoted.
7252 * If this was a fast promotion, request an (online) checkpoint now. This
7253 * isn't required for consistency, but the last restartpoint might be far
7254 * back, and in case of a crash, recovering from it might take a longer
7255 * than is appropriate now that we're not in standby mode anymore.
7258 RequestCheckpoint(CHECKPOINT_FORCE);
7262 * Checks if recovery has reached a consistent state. When consistency is
7263 * reached and we have a valid starting standby snapshot, tell postmaster
7264 * that it can start accepting read-only connections.
7267 CheckRecoveryConsistency(void)
7270 * During crash recovery, we don't reach a consistent state until we've
7271 * replayed all the WAL.
7273 if (XLogRecPtrIsInvalid(minRecoveryPoint))
7277 * Have we reached the point where our base backup was completed?
7279 if (!XLogRecPtrIsInvalid(ControlFile->backupEndPoint) &&
7280 ControlFile->backupEndPoint <= EndRecPtr)
7283 * We have reached the end of base backup, as indicated by pg_control.
7284 * The data on disk is now consistent. Reset backupStartPoint and
7285 * backupEndPoint, and update minRecoveryPoint to make sure we don't
7286 * allow starting up at an earlier point even if recovery is stopped
7287 * and restarted soon after this.
7289 elog(DEBUG1, "end of backup reached");
7291 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7293 if (ControlFile->minRecoveryPoint < EndRecPtr)
7294 ControlFile->minRecoveryPoint = EndRecPtr;
7296 ControlFile->backupStartPoint = InvalidXLogRecPtr;
7297 ControlFile->backupEndPoint = InvalidXLogRecPtr;
7298 ControlFile->backupEndRequired = false;
7299 UpdateControlFile();
7301 LWLockRelease(ControlFileLock);
7305 * Have we passed our safe starting point? Note that minRecoveryPoint is
7306 * known to be incorrectly set if ControlFile->backupEndRequired, until
7307 * the XLOG_BACKUP_RECORD arrives to advise us of the correct
7308 * minRecoveryPoint. All we know prior to that is that we're not
7311 if (!reachedConsistency && !ControlFile->backupEndRequired &&
7312 minRecoveryPoint <= XLogCtl->lastReplayedEndRecPtr &&
7313 XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
7316 * Check to see if the XLOG sequence contained any unresolved
7317 * references to uninitialized pages.
7319 XLogCheckInvalidPages();
7321 reachedConsistency = true;
7323 (errmsg("consistent recovery state reached at %X/%X",
7324 (uint32) (XLogCtl->lastReplayedEndRecPtr >> 32),
7325 (uint32) XLogCtl->lastReplayedEndRecPtr)));
7329 * Have we got a valid starting snapshot that will allow queries to be
7330 * run? If so, we can tell postmaster that the database is consistent now,
7331 * enabling connections.
7333 if (standbyState == STANDBY_SNAPSHOT_READY &&
7334 !LocalHotStandbyActive &&
7335 reachedConsistency &&
7338 /* use volatile pointer to prevent code rearrangement */
7339 volatile XLogCtlData *xlogctl = XLogCtl;
7341 SpinLockAcquire(&xlogctl->info_lck);
7342 xlogctl->SharedHotStandbyActive = true;
7343 SpinLockRelease(&xlogctl->info_lck);
7345 LocalHotStandbyActive = true;
7347 SendPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY);
7352 * Is the system still in recovery?
7354 * Unlike testing InRecovery, this works in any process that's connected to
7357 * As a side-effect, we initialize the local TimeLineID and RedoRecPtr
7358 * variables the first time we see that recovery is finished.
7361 RecoveryInProgress(void)
7364 * We check shared state each time only until we leave recovery mode. We
7365 * can't re-enter recovery, so there's no need to keep checking after the
7366 * shared variable has once been seen false.
7368 if (!LocalRecoveryInProgress)
7372 /* use volatile pointer to prevent code rearrangement */
7373 volatile XLogCtlData *xlogctl = XLogCtl;
7375 /* spinlock is essential on machines with weak memory ordering! */
7376 SpinLockAcquire(&xlogctl->info_lck);
7377 LocalRecoveryInProgress = xlogctl->SharedRecoveryInProgress;
7378 SpinLockRelease(&xlogctl->info_lck);
7381 * Initialize TimeLineID and RedoRecPtr when we discover that recovery
7382 * is finished. InitPostgres() relies upon this behaviour to ensure
7383 * that InitXLOGAccess() is called at backend startup. (If you change
7384 * this, see also LocalSetXLogInsertAllowed.)
7386 if (!LocalRecoveryInProgress)
7389 return LocalRecoveryInProgress;
7394 * Is HotStandby active yet? This is only important in special backends
7395 * since normal backends won't ever be able to connect until this returns
7396 * true. Postmaster knows this by way of signal, not via shared memory.
7398 * Unlike testing standbyState, this works in any process that's connected to
7402 HotStandbyActive(void)
7405 * We check shared state each time only until Hot Standby is active. We
7406 * can't de-activate Hot Standby, so there's no need to keep checking
7407 * after the shared variable has once been seen true.
7409 if (LocalHotStandbyActive)
7413 /* use volatile pointer to prevent code rearrangement */
7414 volatile XLogCtlData *xlogctl = XLogCtl;
7416 /* spinlock is essential on machines with weak memory ordering! */
7417 SpinLockAcquire(&xlogctl->info_lck);
7418 LocalHotStandbyActive = xlogctl->SharedHotStandbyActive;
7419 SpinLockRelease(&xlogctl->info_lck);
7421 return LocalHotStandbyActive;
7426 * Is this process allowed to insert new WAL records?
7428 * Ordinarily this is essentially equivalent to !RecoveryInProgress().
7429 * But we also have provisions for forcing the result "true" or "false"
7430 * within specific processes regardless of the global state.
7433 XLogInsertAllowed(void)
7436 * If value is "unconditionally true" or "unconditionally false", just
7437 * return it. This provides the normal fast path once recovery is known
7440 if (LocalXLogInsertAllowed >= 0)
7441 return (bool) LocalXLogInsertAllowed;
7444 * Else, must check to see if we're still in recovery.
7446 if (RecoveryInProgress())
7450 * On exit from recovery, reset to "unconditionally true", since there is
7451 * no need to keep checking.
7453 LocalXLogInsertAllowed = 1;
7458 * Make XLogInsertAllowed() return true in the current process only.
7460 * Note: it is allowed to switch LocalXLogInsertAllowed back to -1 later,
7461 * and even call LocalSetXLogInsertAllowed() again after that.
7464 LocalSetXLogInsertAllowed(void)
7466 Assert(LocalXLogInsertAllowed == -1);
7467 LocalXLogInsertAllowed = 1;
7469 /* Initialize as RecoveryInProgress() would do when switching state */
7474 * Subroutine to try to fetch and validate a prior checkpoint record.
7476 * whichChkpt identifies the checkpoint (merely for reporting purposes).
7477 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
7480 ReadCheckpointRecord(XLogReaderState *xlogreader, XLogRecPtr RecPtr,
7481 int whichChkpt, bool report)
7485 if (!XRecOffIsValid(RecPtr))
7494 (errmsg("invalid primary checkpoint link in control file")));
7498 (errmsg("invalid secondary checkpoint link in control file")));
7502 (errmsg("invalid checkpoint link in backup_label file")));
7508 record = ReadRecord(xlogreader, RecPtr, LOG, true);
7519 (errmsg("invalid primary checkpoint record")));
7523 (errmsg("invalid secondary checkpoint record")));
7527 (errmsg("invalid checkpoint record")));
7532 if (record->xl_rmid != RM_XLOG_ID)
7538 (errmsg("invalid resource manager ID in primary checkpoint record")));
7542 (errmsg("invalid resource manager ID in secondary checkpoint record")));
7546 (errmsg("invalid resource manager ID in checkpoint record")));
7551 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
7552 record->xl_info != XLOG_CHECKPOINT_ONLINE)
7558 (errmsg("invalid xl_info in primary checkpoint record")));
7562 (errmsg("invalid xl_info in secondary checkpoint record")));
7566 (errmsg("invalid xl_info in checkpoint record")));
7571 if (record->xl_len != sizeof(CheckPoint) ||
7572 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
7578 (errmsg("invalid length of primary checkpoint record")));
7582 (errmsg("invalid length of secondary checkpoint record")));
7586 (errmsg("invalid length of checkpoint record")));
7595 * This must be called during startup of a backend process, except that
7596 * it need not be called in a standalone backend (which does StartupXLOG
7597 * instead). We need to initialize the local copies of ThisTimeLineID and
7600 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
7601 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
7602 * unnecessary however, since the postmaster itself never touches XLOG anyway.
7605 InitXLOGAccess(void)
7607 /* ThisTimeLineID doesn't change so we need no lock to copy it */
7608 ThisTimeLineID = XLogCtl->ThisTimeLineID;
7609 Assert(ThisTimeLineID != 0 || IsBootstrapProcessingMode());
7611 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
7612 (void) GetRedoRecPtr();
7616 * Return the current Redo pointer from shared memory.
7618 * As a side-effect, the local RedoRecPtr copy is updated.
7623 /* use volatile pointer to prevent code rearrangement */
7624 volatile XLogCtlData *xlogctl = XLogCtl;
7628 * The possibly not up-to-date copy in XlogCtl is enough. Even if we
7629 * grabbed a WAL insertion slot to read the master copy, someone might
7630 * update it just after we've released the lock.
7632 SpinLockAcquire(&xlogctl->info_lck);
7633 ptr = xlogctl->RedoRecPtr;
7634 SpinLockRelease(&xlogctl->info_lck);
7636 if (RedoRecPtr < ptr)
7643 * GetInsertRecPtr -- Returns the current insert position.
7645 * NOTE: The value *actually* returned is the position of the last full
7646 * xlog page. It lags behind the real insert position by at most 1 page.
7647 * For that, we don't need to scan through WAL insertion slots, and an
7648 * approximation is enough for the current usage of this function.
7651 GetInsertRecPtr(void)
7653 /* use volatile pointer to prevent code rearrangement */
7654 volatile XLogCtlData *xlogctl = XLogCtl;
7657 SpinLockAcquire(&xlogctl->info_lck);
7658 recptr = xlogctl->LogwrtRqst.Write;
7659 SpinLockRelease(&xlogctl->info_lck);
7665 * GetFlushRecPtr -- Returns the current flush position, ie, the last WAL
7666 * position known to be fsync'd to disk.
7669 GetFlushRecPtr(void)
7671 /* use volatile pointer to prevent code rearrangement */
7672 volatile XLogCtlData *xlogctl = XLogCtl;
7675 SpinLockAcquire(&xlogctl->info_lck);
7676 recptr = xlogctl->LogwrtResult.Flush;
7677 SpinLockRelease(&xlogctl->info_lck);
7683 * Get the time of the last xlog segment switch
7686 GetLastSegSwitchTime(void)
7690 /* Need WALWriteLock, but shared lock is sufficient */
7691 LWLockAcquire(WALWriteLock, LW_SHARED);
7692 result = XLogCtl->lastSegSwitchTime;
7693 LWLockRelease(WALWriteLock);
7699 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
7701 * This is exported for use by code that would like to have 64-bit XIDs.
7702 * We don't really support such things, but all XIDs within the system
7703 * can be presumed "close to" the result, and thus the epoch associated
7704 * with them can be determined.
7707 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
7709 uint32 ckptXidEpoch;
7710 TransactionId ckptXid;
7711 TransactionId nextXid;
7713 /* Must read checkpoint info first, else have race condition */
7715 /* use volatile pointer to prevent code rearrangement */
7716 volatile XLogCtlData *xlogctl = XLogCtl;
7718 SpinLockAcquire(&xlogctl->info_lck);
7719 ckptXidEpoch = xlogctl->ckptXidEpoch;
7720 ckptXid = xlogctl->ckptXid;
7721 SpinLockRelease(&xlogctl->info_lck);
7724 /* Now fetch current nextXid */
7725 nextXid = ReadNewTransactionId();
7728 * nextXid is certainly logically later than ckptXid. So if it's
7729 * numerically less, it must have wrapped into the next epoch.
7731 if (nextXid < ckptXid)
7735 *epoch = ckptXidEpoch;
7739 * This must be called ONCE during postmaster or standalone-backend shutdown
7742 ShutdownXLOG(int code, Datum arg)
7744 /* Don't be chatty in standalone mode */
7745 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
7746 (errmsg("shutting down")));
7748 if (RecoveryInProgress())
7749 CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
7753 * If archiving is enabled, rotate the last XLOG file so that all the
7754 * remaining records are archived (postmaster wakes up the archiver
7755 * process one more time at the end of shutdown). The checkpoint
7756 * record will go to the next XLOG file and won't be archived (yet).
7758 if (XLogArchivingActive() && XLogArchiveCommandSet())
7759 RequestXLogSwitch();
7761 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
7765 ShutdownMultiXact();
7767 /* Don't be chatty in standalone mode */
7768 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
7769 (errmsg("database system is shut down")));
7773 * Log start of a checkpoint.
7776 LogCheckpointStart(int flags, bool restartpoint)
7781 * XXX: This is hopelessly untranslatable. We could call gettext_noop for
7782 * the main message, but what about all the flags?
7785 msg = "restartpoint starting:%s%s%s%s%s%s%s";
7787 msg = "checkpoint starting:%s%s%s%s%s%s%s";
7790 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
7791 (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
7792 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
7793 (flags & CHECKPOINT_FORCE) ? " force" : "",
7794 (flags & CHECKPOINT_WAIT) ? " wait" : "",
7795 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
7796 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
7800 * Log end of a checkpoint.
7803 LogCheckpointEnd(bool restartpoint)
7815 uint64 average_sync_time;
7817 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
7819 TimestampDifference(CheckpointStats.ckpt_write_t,
7820 CheckpointStats.ckpt_sync_t,
7821 &write_secs, &write_usecs);
7823 TimestampDifference(CheckpointStats.ckpt_sync_t,
7824 CheckpointStats.ckpt_sync_end_t,
7825 &sync_secs, &sync_usecs);
7827 /* Accumulate checkpoint timing summary data, in milliseconds. */
7828 BgWriterStats.m_checkpoint_write_time +=
7829 write_secs * 1000 + write_usecs / 1000;
7830 BgWriterStats.m_checkpoint_sync_time +=
7831 sync_secs * 1000 + sync_usecs / 1000;
7834 * All of the published timing statistics are accounted for. Only
7835 * continue if a log message is to be written.
7837 if (!log_checkpoints)
7840 TimestampDifference(CheckpointStats.ckpt_start_t,
7841 CheckpointStats.ckpt_end_t,
7842 &total_secs, &total_usecs);
7845 * Timing values returned from CheckpointStats are in microseconds.
7846 * Convert to the second plus microsecond form that TimestampDifference
7847 * returns for homogeneous printing.
7849 longest_secs = (long) (CheckpointStats.ckpt_longest_sync / 1000000);
7850 longest_usecs = CheckpointStats.ckpt_longest_sync -
7851 (uint64) longest_secs *1000000;
7853 average_sync_time = 0;
7854 if (CheckpointStats.ckpt_sync_rels > 0)
7855 average_sync_time = CheckpointStats.ckpt_agg_sync_time /
7856 CheckpointStats.ckpt_sync_rels;
7857 average_secs = (long) (average_sync_time / 1000000);
7858 average_usecs = average_sync_time - (uint64) average_secs *1000000;
7861 elog(LOG, "restartpoint complete: wrote %d buffers (%.1f%%); "
7862 "%d transaction log file(s) added, %d removed, %d recycled; "
7863 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s; "
7864 "sync files=%d, longest=%ld.%03d s, average=%ld.%03d s",
7865 CheckpointStats.ckpt_bufs_written,
7866 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
7867 CheckpointStats.ckpt_segs_added,
7868 CheckpointStats.ckpt_segs_removed,
7869 CheckpointStats.ckpt_segs_recycled,
7870 write_secs, write_usecs / 1000,
7871 sync_secs, sync_usecs / 1000,
7872 total_secs, total_usecs / 1000,
7873 CheckpointStats.ckpt_sync_rels,
7874 longest_secs, longest_usecs / 1000,
7875 average_secs, average_usecs / 1000);
7877 elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
7878 "%d transaction log file(s) added, %d removed, %d recycled; "
7879 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s; "
7880 "sync files=%d, longest=%ld.%03d s, average=%ld.%03d s",
7881 CheckpointStats.ckpt_bufs_written,
7882 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
7883 CheckpointStats.ckpt_segs_added,
7884 CheckpointStats.ckpt_segs_removed,
7885 CheckpointStats.ckpt_segs_recycled,
7886 write_secs, write_usecs / 1000,
7887 sync_secs, sync_usecs / 1000,
7888 total_secs, total_usecs / 1000,
7889 CheckpointStats.ckpt_sync_rels,
7890 longest_secs, longest_usecs / 1000,
7891 average_secs, average_usecs / 1000);
7895 * Perform a checkpoint --- either during shutdown, or on-the-fly
7897 * flags is a bitwise OR of the following:
7898 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
7899 * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
7900 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
7901 * ignoring checkpoint_completion_target parameter.
7902 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
7903 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
7904 * CHECKPOINT_END_OF_RECOVERY).
7906 * Note: flags contains other bits, of interest here only for logging purposes.
7907 * In particular note that this routine is synchronous and does not pay
7908 * attention to CHECKPOINT_WAIT.
7910 * If !shutdown then we are writing an online checkpoint. This is a very special
7911 * kind of operation and WAL record because the checkpoint action occurs over
7912 * a period of time yet logically occurs at just a single LSN. The logical
7913 * position of the WAL record (redo ptr) is the same or earlier than the
7914 * physical position. When we replay WAL we locate the checkpoint via its
7915 * physical position then read the redo ptr and actually start replay at the
7916 * earlier logical position. Note that we don't write *anything* to WAL at
7917 * the logical position, so that location could be any other kind of WAL record.
7918 * All of this mechanism allows us to continue working while we checkpoint.
7919 * As a result, timing of actions is critical here and be careful to note that
7920 * this function will likely take minutes to execute on a busy system.
7923 CreateCheckPoint(int flags)
7925 /* use volatile pointer to prevent code rearrangement */
7926 volatile XLogCtlData *xlogctl = XLogCtl;
7928 CheckPoint checkPoint;
7930 XLogCtlInsert *Insert = &XLogCtl->Insert;
7933 XLogSegNo _logSegNo;
7934 XLogRecPtr curInsert;
7935 VirtualTransactionId *vxids;
7939 * An end-of-recovery checkpoint is really a shutdown checkpoint, just
7940 * issued at a different time.
7942 if (flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY))
7948 if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
7949 elog(ERROR, "can't create a checkpoint during recovery");
7952 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
7953 * (This is just pro forma, since in the present system structure there is
7954 * only one process that is allowed to issue checkpoints at any given
7957 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
7960 * Prepare to accumulate statistics.
7962 * Note: because it is possible for log_checkpoints to change while a
7963 * checkpoint proceeds, we always accumulate stats, even if
7964 * log_checkpoints is currently off.
7966 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
7967 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
7970 * Use a critical section to force system panic if we have trouble.
7972 START_CRIT_SECTION();
7976 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7977 ControlFile->state = DB_SHUTDOWNING;
7978 ControlFile->time = (pg_time_t) time(NULL);
7979 UpdateControlFile();
7980 LWLockRelease(ControlFileLock);
7984 * Let smgr prepare for checkpoint; this has to happen before we determine
7985 * the REDO pointer. Note that smgr must not do anything that'd have to
7986 * be undone if we decide no checkpoint is needed.
7990 /* Begin filling in the checkpoint WAL record */
7991 MemSet(&checkPoint, 0, sizeof(checkPoint));
7992 checkPoint.time = (pg_time_t) time(NULL);
7995 * For Hot Standby, derive the oldestActiveXid before we fix the redo
7996 * pointer. This allows us to begin accumulating changes to assemble our
7997 * starting snapshot of locks and transactions.
7999 if (!shutdown && XLogStandbyInfoActive())
8000 checkPoint.oldestActiveXid = GetOldestActiveTransactionId();
8002 checkPoint.oldestActiveXid = InvalidTransactionId;
8005 * We must block concurrent insertions while examining insert state to
8006 * determine the checkpoint REDO pointer.
8008 WALInsertSlotAcquire(true);
8009 curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
8012 * If this isn't a shutdown or forced checkpoint, and we have not inserted
8013 * any XLOG records since the start of the last checkpoint, skip the
8014 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
8015 * when the system is idle. That wastes log space, and more importantly it
8016 * exposes us to possible loss of both current and previous checkpoint
8017 * records if the machine crashes just as we're writing the update.
8018 * (Perhaps it'd make even more sense to checkpoint only when the previous
8019 * checkpoint record is in a different xlog page?)
8021 * We have to make two tests to determine that nothing has happened since
8022 * the start of the last checkpoint: current insertion point must match
8023 * the end of the last checkpoint record, and its redo pointer must point
8026 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
8027 CHECKPOINT_FORCE)) == 0)
8029 if (curInsert == ControlFile->checkPoint +
8030 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
8031 ControlFile->checkPoint == ControlFile->checkPointCopy.redo)
8033 WALInsertSlotRelease();
8034 LWLockRelease(CheckpointLock);
8041 * An end-of-recovery checkpoint is created before anyone is allowed to
8042 * write WAL. To allow us to write the checkpoint record, temporarily
8043 * enable XLogInsertAllowed. (This also ensures ThisTimeLineID is
8044 * initialized, which we need here and in AdvanceXLInsertBuffer.)
8046 if (flags & CHECKPOINT_END_OF_RECOVERY)
8047 LocalSetXLogInsertAllowed();
8049 checkPoint.ThisTimeLineID = ThisTimeLineID;
8050 if (flags & CHECKPOINT_END_OF_RECOVERY)
8051 checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8053 checkPoint.PrevTimeLineID = ThisTimeLineID;
8055 checkPoint.fullPageWrites = Insert->fullPageWrites;
8058 * Compute new REDO record ptr = location of next XLOG record.
8060 * NB: this is NOT necessarily where the checkpoint record itself will be,
8061 * since other backends may insert more XLOG records while we're off doing
8062 * the buffer flush work. Those XLOG records are logically after the
8063 * checkpoint, even though physically before it. Got that?
8065 freespace = INSERT_FREESPACE(curInsert);
8068 if (curInsert % XLogSegSize == 0)
8069 curInsert += SizeOfXLogLongPHD;
8071 curInsert += SizeOfXLogShortPHD;
8073 checkPoint.redo = curInsert;
8076 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
8077 * must be done while holding the insertion slots.
8079 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
8080 * pointing past where it really needs to point. This is okay; the only
8081 * consequence is that XLogInsert might back up whole buffers that it
8082 * didn't really need to. We can't postpone advancing RedoRecPtr because
8083 * XLogInserts that happen while we are dumping buffers must assume that
8084 * their buffer changes are not included in the checkpoint.
8086 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
8089 * Now we can release the WAL insertion slots, allowing other xacts to
8090 * proceed while we are flushing disk buffers.
8092 WALInsertSlotRelease();
8094 /* Update the info_lck-protected copy of RedoRecPtr as well */
8095 SpinLockAcquire(&xlogctl->info_lck);
8096 xlogctl->RedoRecPtr = checkPoint.redo;
8097 SpinLockRelease(&xlogctl->info_lck);
8100 * If enabled, log checkpoint start. We postpone this until now so as not
8101 * to log anything if we decided to skip the checkpoint.
8103 if (log_checkpoints)
8104 LogCheckpointStart(flags, false);
8106 TRACE_POSTGRESQL_CHECKPOINT_START(flags);
8109 * In some cases there are groups of actions that must all occur on one
8110 * side or the other of a checkpoint record. Before flushing the
8111 * checkpoint record we must explicitly wait for any backend currently
8112 * performing those groups of actions.
8114 * One example is end of transaction, so we must wait for any transactions
8115 * that are currently in commit critical sections. If an xact inserted
8116 * its commit record into XLOG just before the REDO point, then a crash
8117 * restart from the REDO point would not replay that record, which means
8118 * that our flushing had better include the xact's update of pg_clog. So
8119 * we wait till he's out of his commit critical section before proceeding.
8120 * See notes in RecordTransactionCommit().
8122 * Because we've already released the insertion slots, this test is a bit
8123 * fuzzy: it is possible that we will wait for xacts we didn't really need
8124 * to wait for. But the delay should be short and it seems better to make
8125 * checkpoint take a bit longer than to hold off insertions longer than
8127 * (In fact, the whole reason we have this issue is that xact.c does
8128 * commit record XLOG insertion and clog update as two separate steps
8129 * protected by different locks, but again that seems best on grounds of
8130 * minimizing lock contention.)
8132 * A transaction that has not yet set delayChkpt when we look cannot be at
8133 * risk, since he's not inserted his commit record yet; and one that's
8134 * already cleared it is not at risk either, since he's done fixing clog
8135 * and we will correctly flush the update below. So we cannot miss any
8136 * xacts we need to wait for.
8138 vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
8143 pg_usleep(10000L); /* wait for 10 msec */
8144 } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
8149 * Get the other info we need for the checkpoint record.
8151 LWLockAcquire(XidGenLock, LW_SHARED);
8152 checkPoint.nextXid = ShmemVariableCache->nextXid;
8153 checkPoint.oldestXid = ShmemVariableCache->oldestXid;
8154 checkPoint.oldestXidDB = ShmemVariableCache->oldestXidDB;
8155 LWLockRelease(XidGenLock);
8157 /* Increase XID epoch if we've wrapped around since last checkpoint */
8158 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
8159 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
8160 checkPoint.nextXidEpoch++;
8162 LWLockAcquire(OidGenLock, LW_SHARED);
8163 checkPoint.nextOid = ShmemVariableCache->nextOid;
8165 checkPoint.nextOid += ShmemVariableCache->oidCount;
8166 LWLockRelease(OidGenLock);
8168 MultiXactGetCheckptMulti(shutdown,
8169 &checkPoint.nextMulti,
8170 &checkPoint.nextMultiOffset,
8171 &checkPoint.oldestMulti,
8172 &checkPoint.oldestMultiDB);
8175 * Having constructed the checkpoint record, ensure all shmem disk buffers
8176 * and commit-log buffers are flushed to disk.
8178 * This I/O could fail for various reasons. If so, we will fail to
8179 * complete the checkpoint, but there is no reason to force a system
8180 * panic. Accordingly, exit critical section while doing it.
8184 CheckPointGuts(checkPoint.redo, flags);
8187 * Take a snapshot of running transactions and write this to WAL. This
8188 * allows us to reconstruct the state of running transactions during
8189 * archive recovery, if required. Skip, if this info disabled.
8191 * If we are shutting down, or Startup process is completing crash
8192 * recovery we don't need to write running xact data.
8194 if (!shutdown && XLogStandbyInfoActive())
8195 LogStandbySnapshot();
8197 START_CRIT_SECTION();
8200 * Now insert the checkpoint record into XLOG.
8202 rdata.data = (char *) (&checkPoint);
8203 rdata.len = sizeof(checkPoint);
8204 rdata.buffer = InvalidBuffer;
8207 recptr = XLogInsert(RM_XLOG_ID,
8208 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
8209 XLOG_CHECKPOINT_ONLINE,
8215 * We mustn't write any new WAL after a shutdown checkpoint, or it will be
8216 * overwritten at next startup. No-one should even try, this just allows
8217 * sanity-checking. In the case of an end-of-recovery checkpoint, we want
8218 * to just temporarily disable writing until the system has exited
8223 if (flags & CHECKPOINT_END_OF_RECOVERY)
8224 LocalXLogInsertAllowed = -1; /* return to "check" state */
8226 LocalXLogInsertAllowed = 0; /* never again write WAL */
8230 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
8231 * = end of actual checkpoint record.
8233 if (shutdown && checkPoint.redo != ProcLastRecPtr)
8235 (errmsg("concurrent transaction log activity while database system is shutting down")));
8238 * Select point at which we can truncate the log, which we base on the
8239 * prior checkpoint's earliest info.
8241 XLByteToSeg(ControlFile->checkPointCopy.redo, _logSegNo);
8244 * Update the control file.
8246 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8248 ControlFile->state = DB_SHUTDOWNED;
8249 ControlFile->prevCheckPoint = ControlFile->checkPoint;
8250 ControlFile->checkPoint = ProcLastRecPtr;
8251 ControlFile->checkPointCopy = checkPoint;
8252 ControlFile->time = (pg_time_t) time(NULL);
8253 /* crash recovery should always recover to the end of WAL */
8254 ControlFile->minRecoveryPoint = InvalidXLogRecPtr;
8255 ControlFile->minRecoveryPointTLI = 0;
8258 * Persist unloggedLSN value. It's reset on crash recovery, so this goes
8259 * unused on non-shutdown checkpoints, but seems useful to store it always
8260 * for debugging purposes.
8262 SpinLockAcquire(&XLogCtl->ulsn_lck);
8263 ControlFile->unloggedLSN = XLogCtl->unloggedLSN;
8264 SpinLockRelease(&XLogCtl->ulsn_lck);
8266 UpdateControlFile();
8267 LWLockRelease(ControlFileLock);
8269 /* Update shared-memory copy of checkpoint XID/epoch */
8271 /* use volatile pointer to prevent code rearrangement */
8272 volatile XLogCtlData *xlogctl = XLogCtl;
8274 SpinLockAcquire(&xlogctl->info_lck);
8275 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
8276 xlogctl->ckptXid = checkPoint.nextXid;
8277 SpinLockRelease(&xlogctl->info_lck);
8281 * We are now done with critical updates; no need for system panic if we
8282 * have trouble while fooling with old log segments.
8287 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
8292 * Delete old log files (those no longer needed even for previous
8293 * checkpoint or the standbys in XLOG streaming).
8297 KeepLogSeg(recptr, &_logSegNo);
8299 RemoveOldXlogFiles(_logSegNo, recptr);
8303 * Make more log segments if needed. (Do this after recycling old log
8304 * segments, since that may supply some of the needed files.)
8307 PreallocXlogFiles(recptr);
8310 * Truncate pg_subtrans if possible. We can throw away all data before
8311 * the oldest XMIN of any running transaction. No future transaction will
8312 * attempt to reference any pg_subtrans entry older than that (see Asserts
8313 * in subtrans.c). During recovery, though, we mustn't do this because
8314 * StartupSUBTRANS hasn't been called yet.
8316 if (!RecoveryInProgress())
8317 TruncateSUBTRANS(GetOldestXmin(true, false));
8319 /* Real work is done, but log and update stats before releasing lock. */
8320 LogCheckpointEnd(false);
8322 TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
8324 CheckpointStats.ckpt_segs_added,
8325 CheckpointStats.ckpt_segs_removed,
8326 CheckpointStats.ckpt_segs_recycled);
8328 LWLockRelease(CheckpointLock);
8332 * Mark the end of recovery in WAL though without running a full checkpoint.
8333 * We can expect that a restartpoint is likely to be in progress as we
8334 * do this, though we are unwilling to wait for it to complete. So be
8335 * careful to avoid taking the CheckpointLock anywhere here.
8337 * CreateRestartPoint() allows for the case where recovery may end before
8338 * the restartpoint completes so there is no concern of concurrent behaviour.
8341 CreateEndOfRecoveryRecord(void)
8343 xl_end_of_recovery xlrec;
8348 if (!RecoveryInProgress())
8349 elog(ERROR, "can only be used to end recovery");
8351 xlrec.end_time = time(NULL);
8353 WALInsertSlotAcquire(true);
8354 xlrec.ThisTimeLineID = ThisTimeLineID;
8355 xlrec.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8356 WALInsertSlotRelease();
8358 LocalSetXLogInsertAllowed();
8360 START_CRIT_SECTION();
8362 rdata.data = (char *) &xlrec;
8363 rdata.len = sizeof(xl_end_of_recovery);
8364 rdata.buffer = InvalidBuffer;
8367 recptr = XLogInsert(RM_XLOG_ID, XLOG_END_OF_RECOVERY, &rdata);
8372 * Update the control file so that crash recovery can follow the timeline
8373 * changes to this point.
8375 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8376 ControlFile->time = (pg_time_t) xlrec.end_time;
8377 ControlFile->minRecoveryPoint = recptr;
8378 ControlFile->minRecoveryPointTLI = ThisTimeLineID;
8379 UpdateControlFile();
8380 LWLockRelease(ControlFileLock);
8384 LocalXLogInsertAllowed = -1; /* return to "check" state */
8388 * Flush all data in shared memory to disk, and fsync
8390 * This is the common code shared between regular checkpoints and
8391 * recovery restartpoints.
8394 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
8397 CheckPointSUBTRANS();
8398 CheckPointMultiXact();
8399 CheckPointPredicate();
8400 CheckPointRelationMap();
8401 CheckPointBuffers(flags); /* performs all required fsyncs */
8402 /* We deliberately delay 2PC checkpointing as long as possible */
8403 CheckPointTwoPhase(checkPointRedo);
8407 * Save a checkpoint for recovery restart if appropriate
8409 * This function is called each time a checkpoint record is read from XLOG.
8410 * It must determine whether the checkpoint represents a safe restartpoint or
8411 * not. If so, the checkpoint record is stashed in shared memory so that
8412 * CreateRestartPoint can consult it. (Note that the latter function is
8413 * executed by the checkpointer, while this one will be executed by the
8417 RecoveryRestartPoint(const CheckPoint *checkPoint)
8421 /* use volatile pointer to prevent code rearrangement */
8422 volatile XLogCtlData *xlogctl = XLogCtl;
8425 * Is it safe to restartpoint? We must ask each of the resource managers
8426 * whether they have any partial state information that might prevent a
8427 * correct restart from this point. If so, we skip this opportunity, but
8428 * return at the next checkpoint record for another try.
8430 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
8432 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
8433 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
8435 elog(trace_recovery(DEBUG2),
8436 "RM %d not safe to record restart point at %X/%X",
8438 (uint32) (checkPoint->redo >> 32),
8439 (uint32) checkPoint->redo);
8445 * Also refrain from creating a restartpoint if we have seen any
8446 * references to non-existent pages. Restarting recovery from the
8447 * restartpoint would not see the references, so we would lose the
8448 * cross-check that the pages belonged to a relation that was dropped
8451 if (XLogHaveInvalidPages())
8453 elog(trace_recovery(DEBUG2),
8454 "could not record restart point at %X/%X because there "
8455 "are unresolved references to invalid pages",
8456 (uint32) (checkPoint->redo >> 32),
8457 (uint32) checkPoint->redo);
8462 * Copy the checkpoint record to shared memory, so that checkpointer can
8463 * work out the next time it wants to perform a restartpoint.
8465 SpinLockAcquire(&xlogctl->info_lck);
8466 xlogctl->lastCheckPointRecPtr = ReadRecPtr;
8467 xlogctl->lastCheckPoint = *checkPoint;
8468 SpinLockRelease(&xlogctl->info_lck);
8472 * Establish a restartpoint if possible.
8474 * This is similar to CreateCheckPoint, but is used during WAL recovery
8475 * to establish a point from which recovery can roll forward without
8476 * replaying the entire recovery log.
8478 * Returns true if a new restartpoint was established. We can only establish
8479 * a restartpoint if we have replayed a safe checkpoint record since last
8483 CreateRestartPoint(int flags)
8485 XLogRecPtr lastCheckPointRecPtr;
8486 CheckPoint lastCheckPoint;
8487 XLogSegNo _logSegNo;
8490 /* use volatile pointer to prevent code rearrangement */
8491 volatile XLogCtlData *xlogctl = XLogCtl;
8494 * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
8495 * happens at a time.
8497 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
8499 /* Get a local copy of the last safe checkpoint record. */
8500 SpinLockAcquire(&xlogctl->info_lck);
8501 lastCheckPointRecPtr = xlogctl->lastCheckPointRecPtr;
8502 lastCheckPoint = xlogctl->lastCheckPoint;
8503 SpinLockRelease(&xlogctl->info_lck);
8506 * Check that we're still in recovery mode. It's ok if we exit recovery
8507 * mode after this check, the restart point is valid anyway.
8509 if (!RecoveryInProgress())
8512 (errmsg("skipping restartpoint, recovery has already ended")));
8513 LWLockRelease(CheckpointLock);
8518 * If the last checkpoint record we've replayed is already our last
8519 * restartpoint, we can't perform a new restart point. We still update
8520 * minRecoveryPoint in that case, so that if this is a shutdown restart
8521 * point, we won't start up earlier than before. That's not strictly
8522 * necessary, but when hot standby is enabled, it would be rather weird if
8523 * the database opened up for read-only connections at a point-in-time
8524 * before the last shutdown. Such time travel is still possible in case of
8525 * immediate shutdown, though.
8527 * We don't explicitly advance minRecoveryPoint when we do create a
8528 * restartpoint. It's assumed that flushing the buffers will do that as a
8531 if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
8532 lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
8535 (errmsg("skipping restartpoint, already performed at %X/%X",
8536 (uint32) (lastCheckPoint.redo >> 32),
8537 (uint32) lastCheckPoint.redo)));
8539 UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
8540 if (flags & CHECKPOINT_IS_SHUTDOWN)
8542 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8543 ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
8544 ControlFile->time = (pg_time_t) time(NULL);
8545 UpdateControlFile();
8546 LWLockRelease(ControlFileLock);
8548 LWLockRelease(CheckpointLock);
8553 * Update the shared RedoRecPtr so that the startup process can calculate
8554 * the number of segments replayed since last restartpoint, and request a
8555 * restartpoint if it exceeds checkpoint_segments.
8557 * Like in CreateCheckPoint(), hold off insertions to update it, although
8558 * during recovery this is just pro forma, because no WAL insertions are
8561 WALInsertSlotAcquire(true);
8562 xlogctl->Insert.RedoRecPtr = lastCheckPoint.redo;
8563 WALInsertSlotRelease();
8565 /* Also update the info_lck-protected copy */
8566 SpinLockAcquire(&xlogctl->info_lck);
8567 xlogctl->RedoRecPtr = lastCheckPoint.redo;
8568 SpinLockRelease(&xlogctl->info_lck);
8571 * Prepare to accumulate statistics.
8573 * Note: because it is possible for log_checkpoints to change while a
8574 * checkpoint proceeds, we always accumulate stats, even if
8575 * log_checkpoints is currently off.
8577 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
8578 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
8580 if (log_checkpoints)
8581 LogCheckpointStart(flags, true);
8583 CheckPointGuts(lastCheckPoint.redo, flags);
8586 * Select point at which we can truncate the xlog, which we base on the
8587 * prior checkpoint's earliest info.
8589 XLByteToSeg(ControlFile->checkPointCopy.redo, _logSegNo);
8592 * Update pg_control, using current time. Check that it still shows
8593 * IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
8594 * this is a quick hack to make sure nothing really bad happens if somehow
8595 * we get here after the end-of-recovery checkpoint.
8597 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8598 if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY &&
8599 ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
8601 ControlFile->prevCheckPoint = ControlFile->checkPoint;
8602 ControlFile->checkPoint = lastCheckPointRecPtr;
8603 ControlFile->checkPointCopy = lastCheckPoint;
8604 ControlFile->time = (pg_time_t) time(NULL);
8605 if (flags & CHECKPOINT_IS_SHUTDOWN)
8606 ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
8607 UpdateControlFile();
8609 LWLockRelease(ControlFileLock);
8612 * Delete old log files (those no longer needed even for previous
8613 * checkpoint/restartpoint) to prevent the disk holding the xlog from
8618 XLogRecPtr receivePtr;
8619 XLogRecPtr replayPtr;
8620 TimeLineID replayTLI;
8624 * Get the current end of xlog replayed or received, whichever is
8627 receivePtr = GetWalRcvWriteRecPtr(NULL, NULL);
8628 replayPtr = GetXLogReplayRecPtr(&replayTLI);
8629 endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
8631 KeepLogSeg(endptr, &_logSegNo);
8635 * Try to recycle segments on a useful timeline. If we've been promoted
8636 * since the beginning of this restartpoint, use the new timeline
8637 * chosen at end of recovery (RecoveryInProgress() sets ThisTimeLineID
8638 * in that case). If we're still in recovery, use the timeline we're
8639 * currently replaying.
8641 * There is no guarantee that the WAL segments will be useful on the
8642 * current timeline; if recovery proceeds to a new timeline right
8643 * after this, the pre-allocated WAL segments on this timeline will
8644 * not be used, and will go wasted until recycled on the next
8645 * restartpoint. We'll live with that.
8647 if (RecoveryInProgress())
8648 ThisTimeLineID = replayTLI;
8650 RemoveOldXlogFiles(_logSegNo, endptr);
8653 * Make more log segments if needed. (Do this after recycling old log
8654 * segments, since that may supply some of the needed files.)
8656 PreallocXlogFiles(endptr);
8659 * ThisTimeLineID is normally not set when we're still in recovery.
8660 * However, recycling/preallocating segments above needed
8661 * ThisTimeLineID to determine which timeline to install the segments
8662 * on. Reset it now, to restore the normal state of affairs for
8663 * debugging purposes.
8665 if (RecoveryInProgress())
8670 * Truncate pg_subtrans if possible. We can throw away all data before
8671 * the oldest XMIN of any running transaction. No future transaction will
8672 * attempt to reference any pg_subtrans entry older than that (see Asserts
8673 * in subtrans.c). When hot standby is disabled, though, we mustn't do
8674 * this because StartupSUBTRANS hasn't been called yet.
8676 if (EnableHotStandby)
8677 TruncateSUBTRANS(GetOldestXmin(true, false));
8679 /* Real work is done, but log and update before releasing lock. */
8680 LogCheckpointEnd(true);
8682 xtime = GetLatestXTime();
8683 ereport((log_checkpoints ? LOG : DEBUG2),
8684 (errmsg("recovery restart point at %X/%X",
8685 (uint32) (lastCheckPoint.redo >> 32), (uint32) lastCheckPoint.redo),
8686 xtime ? errdetail("last completed transaction was at log time %s",
8687 timestamptz_to_str(xtime)) : 0));
8689 LWLockRelease(CheckpointLock);
8692 * Finally, execute archive_cleanup_command, if any.
8694 if (XLogCtl->archiveCleanupCommand[0])
8695 ExecuteRecoveryCommand(XLogCtl->archiveCleanupCommand,
8696 "archive_cleanup_command",
8703 * Retreat *logSegNo to the last segment that we need to retain because of
8704 * wal_keep_segments. This is calculated by subtracting wal_keep_segments
8705 * from the given xlog location, recptr.
8708 KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
8712 if (wal_keep_segments == 0)
8715 XLByteToSeg(recptr, segno);
8717 /* avoid underflow, don't go below 1 */
8718 if (segno <= wal_keep_segments)
8721 segno = segno - wal_keep_segments;
8723 /* don't delete WAL segments newer than the calculated segment */
8724 if (segno < *logSegNo)
8729 * Write a NEXTOID log record
8732 XLogPutNextOid(Oid nextOid)
8736 rdata.data = (char *) (&nextOid);
8737 rdata.len = sizeof(Oid);
8738 rdata.buffer = InvalidBuffer;
8740 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
8743 * We need not flush the NEXTOID record immediately, because any of the
8744 * just-allocated OIDs could only reach disk as part of a tuple insert or
8745 * update that would have its own XLOG record that must follow the NEXTOID
8746 * record. Therefore, the standard buffer LSN interlock applied to those
8747 * records will ensure no such OID reaches disk before the NEXTOID record
8750 * Note, however, that the above statement only covers state "within" the
8751 * database. When we use a generated OID as a file or directory name, we
8752 * are in a sense violating the basic WAL rule, because that filesystem
8753 * change may reach disk before the NEXTOID WAL record does. The impact
8754 * of this is that if a database crash occurs immediately afterward, we
8755 * might after restart re-generate the same OID and find that it conflicts
8756 * with the leftover file or directory. But since for safety's sake we
8757 * always loop until finding a nonconflicting filename, this poses no real
8758 * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
8763 * Write an XLOG SWITCH record.
8765 * Here we just blindly issue an XLogInsert request for the record.
8766 * All the magic happens inside XLogInsert.
8768 * The return value is either the end+1 address of the switch record,
8769 * or the end+1 address of the prior segment if we did not need to
8770 * write a switch record because we are already at segment start.
8773 RequestXLogSwitch(void)
8778 /* XLOG SWITCH, alone among xlog record types, has no data */
8779 rdata.buffer = InvalidBuffer;
8784 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
8790 * Write a RESTORE POINT record
8793 XLogRestorePoint(const char *rpName)
8797 xl_restore_point xlrec;
8799 xlrec.rp_time = GetCurrentTimestamp();
8800 strncpy(xlrec.rp_name, rpName, MAXFNAMELEN);
8802 rdata.buffer = InvalidBuffer;
8803 rdata.data = (char *) &xlrec;
8804 rdata.len = sizeof(xl_restore_point);
8807 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_RESTORE_POINT, &rdata);
8810 (errmsg("restore point \"%s\" created at %X/%X",
8811 rpName, (uint32) (RecPtr >> 32), (uint32) RecPtr)));
8817 * Write a backup block if needed when we are setting a hint. Note that
8818 * this may be called for a variety of page types, not just heaps.
8820 * Callable while holding just share lock on the buffer content.
8822 * We can't use the plain backup block mechanism since that relies on the
8823 * Buffer being exclusively locked. Since some modifications (setting LSN, hint
8824 * bits) are allowed in a sharelocked buffer that can lead to wal checksum
8825 * failures. So instead we copy the page and insert the copied data as normal
8828 * We only need to do something if page has not yet been full page written in
8829 * this checkpoint round. The LSN of the inserted wal record is returned if we
8830 * had to write, InvalidXLogRecPtr otherwise.
8832 * It is possible that multiple concurrent backends could attempt to write WAL
8833 * records. In that case, multiple copies of the same block would be recorded
8834 * in separate WAL records by different backends, though that is still OK from
8835 * a correctness perspective.
8838 XLogSaveBufferForHint(Buffer buffer, bool buffer_std)
8840 XLogRecPtr recptr = InvalidXLogRecPtr;
8842 XLogRecData rdata[2];
8846 * Ensure no checkpoint can change our view of RedoRecPtr.
8848 Assert(MyPgXact->delayChkpt);
8851 * Update RedoRecPtr so XLogCheckBuffer can make the right decision
8856 * Setup phony rdata element for use within XLogCheckBuffer only. We reuse
8857 * and reset rdata for any actual WAL record insert.
8859 rdata[0].buffer = buffer;
8860 rdata[0].buffer_std = buffer_std;
8863 * Check buffer while not holding an exclusive lock.
8865 if (XLogCheckBuffer(rdata, false, &lsn, &bkpb))
8867 char copied_buffer[BLCKSZ];
8868 char *origdata = (char *) BufferGetBlock(buffer);
8871 * Copy buffer so we don't have to worry about concurrent hint bit or
8872 * lsn updates. We assume pd_lower/upper cannot be changed without an
8873 * exclusive lock, so the contents bkp are not racy.
8875 * With buffer_std set to false, XLogCheckBuffer() sets hole_length and
8876 * hole_offset to 0; so the following code is safe for either case.
8878 memcpy(copied_buffer, origdata, bkpb.hole_offset);
8879 memcpy(copied_buffer + bkpb.hole_offset,
8880 origdata + bkpb.hole_offset + bkpb.hole_length,
8881 BLCKSZ - bkpb.hole_offset - bkpb.hole_length);
8884 * Header for backup block.
8886 rdata[0].data = (char *) &bkpb;
8887 rdata[0].len = sizeof(BkpBlock);
8888 rdata[0].buffer = InvalidBuffer;
8889 rdata[0].next = &(rdata[1]);
8892 * Save copy of the buffer.
8894 rdata[1].data = copied_buffer;
8895 rdata[1].len = BLCKSZ - bkpb.hole_length;
8896 rdata[1].buffer = InvalidBuffer;
8897 rdata[1].next = NULL;
8899 recptr = XLogInsert(RM_XLOG_ID, XLOG_FPI, rdata);
8906 * Check if any of the GUC parameters that are critical for hot standby
8907 * have changed, and update the value in pg_control file if necessary.
8910 XLogReportParameters(void)
8912 if (wal_level != ControlFile->wal_level ||
8913 MaxConnections != ControlFile->MaxConnections ||
8914 max_worker_processes != ControlFile->max_worker_processes ||
8915 max_prepared_xacts != ControlFile->max_prepared_xacts ||
8916 max_locks_per_xact != ControlFile->max_locks_per_xact)
8919 * The change in number of backend slots doesn't need to be WAL-logged
8920 * if archiving is not enabled, as you can't start archive recovery
8921 * with wal_level=minimal anyway. We don't really care about the
8922 * values in pg_control either if wal_level=minimal, but seems better
8923 * to keep them up-to-date to avoid confusion.
8925 if (wal_level != ControlFile->wal_level || XLogIsNeeded())
8928 xl_parameter_change xlrec;
8930 xlrec.MaxConnections = MaxConnections;
8931 xlrec.max_worker_processes = max_worker_processes;
8932 xlrec.max_prepared_xacts = max_prepared_xacts;
8933 xlrec.max_locks_per_xact = max_locks_per_xact;
8934 xlrec.wal_level = wal_level;
8936 rdata.buffer = InvalidBuffer;
8937 rdata.data = (char *) &xlrec;
8938 rdata.len = sizeof(xlrec);
8941 XLogInsert(RM_XLOG_ID, XLOG_PARAMETER_CHANGE, &rdata);
8944 ControlFile->MaxConnections = MaxConnections;
8945 ControlFile->max_worker_processes = max_worker_processes;
8946 ControlFile->max_prepared_xacts = max_prepared_xacts;
8947 ControlFile->max_locks_per_xact = max_locks_per_xact;
8948 ControlFile->wal_level = wal_level;
8949 UpdateControlFile();
8954 * Update full_page_writes in shared memory, and write an
8955 * XLOG_FPW_CHANGE record if necessary.
8957 * Note: this function assumes there is no other process running
8958 * concurrently that could update it.
8961 UpdateFullPageWrites(void)
8963 XLogCtlInsert *Insert = &XLogCtl->Insert;
8966 * Do nothing if full_page_writes has not been changed.
8968 * It's safe to check the shared full_page_writes without the lock,
8969 * because we assume that there is no concurrently running process which
8972 if (fullPageWrites == Insert->fullPageWrites)
8975 START_CRIT_SECTION();
8978 * It's always safe to take full page images, even when not strictly
8979 * required, but not the other round. So if we're setting full_page_writes
8980 * to true, first set it true and then write the WAL record. If we're
8981 * setting it to false, first write the WAL record and then set the global
8986 WALInsertSlotAcquire(true);
8987 Insert->fullPageWrites = true;
8988 WALInsertSlotRelease();
8992 * Write an XLOG_FPW_CHANGE record. This allows us to keep track of
8993 * full_page_writes during archive recovery, if required.
8995 if (XLogStandbyInfoActive() && !RecoveryInProgress())
8999 rdata.data = (char *) (&fullPageWrites);
9000 rdata.len = sizeof(bool);
9001 rdata.buffer = InvalidBuffer;
9004 XLogInsert(RM_XLOG_ID, XLOG_FPW_CHANGE, &rdata);
9007 if (!fullPageWrites)
9009 WALInsertSlotAcquire(true);
9010 Insert->fullPageWrites = false;
9011 WALInsertSlotRelease();
9017 * Check that it's OK to switch to new timeline during recovery.
9019 * 'lsn' is the address of the shutdown checkpoint record we're about to
9020 * replay. (Currently, timeline can only change at a shutdown checkpoint).
9023 checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI, TimeLineID prevTLI)
9025 /* Check that the record agrees on what the current (old) timeline is */
9026 if (prevTLI != ThisTimeLineID)
9028 (errmsg("unexpected prev timeline ID %u (current timeline ID %u) in checkpoint record",
9029 prevTLI, ThisTimeLineID)));
9032 * The new timeline better be in the list of timelines we expect to see,
9033 * according to the timeline history. It should also not decrease.
9035 if (newTLI < ThisTimeLineID || !tliInHistory(newTLI, expectedTLEs))
9037 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
9038 newTLI, ThisTimeLineID)));
9041 * If we have not yet reached min recovery point, and we're about to
9042 * switch to a timeline greater than the timeline of the min recovery
9043 * point: trouble. After switching to the new timeline, we could not
9044 * possibly visit the min recovery point on the correct timeline anymore.
9045 * This can happen if there is a newer timeline in the archive that
9046 * branched before the timeline the min recovery point is on, and you
9047 * attempt to do PITR to the new timeline.
9049 if (!XLogRecPtrIsInvalid(minRecoveryPoint) &&
9050 lsn < minRecoveryPoint &&
9051 newTLI > minRecoveryPointTLI)
9053 (errmsg("unexpected timeline ID %u in checkpoint record, before reaching minimum recovery point %X/%X on timeline %u",
9055 (uint32) (minRecoveryPoint >> 32),
9056 (uint32) minRecoveryPoint,
9057 minRecoveryPointTLI)));
9063 * XLOG resource manager's routines
9065 * Definitions of info values are in include/catalog/pg_control.h, though
9066 * not all record types are related to control file updates.
9069 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
9071 uint8 info = record->xl_info & ~XLR_INFO_MASK;
9073 /* Backup blocks are not used by XLOG rmgr */
9074 Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
9076 if (info == XLOG_NEXTOID)
9081 * We used to try to take the maximum of ShmemVariableCache->nextOid
9082 * and the recorded nextOid, but that fails if the OID counter wraps
9083 * around. Since no OID allocation should be happening during replay
9084 * anyway, better to just believe the record exactly. We still take
9085 * OidGenLock while setting the variable, just in case.
9087 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
9088 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9089 ShmemVariableCache->nextOid = nextOid;
9090 ShmemVariableCache->oidCount = 0;
9091 LWLockRelease(OidGenLock);
9093 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
9095 CheckPoint checkPoint;
9097 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9098 /* In a SHUTDOWN checkpoint, believe the counters exactly */
9099 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
9100 ShmemVariableCache->nextXid = checkPoint.nextXid;
9101 LWLockRelease(XidGenLock);
9102 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9103 ShmemVariableCache->nextOid = checkPoint.nextOid;
9104 ShmemVariableCache->oidCount = 0;
9105 LWLockRelease(OidGenLock);
9106 MultiXactSetNextMXact(checkPoint.nextMulti,
9107 checkPoint.nextMultiOffset);
9108 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
9109 SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
9112 * If we see a shutdown checkpoint while waiting for an end-of-backup
9113 * record, the backup was canceled and the end-of-backup record will
9116 if (ArchiveRecoveryRequested &&
9117 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint) &&
9118 XLogRecPtrIsInvalid(ControlFile->backupEndPoint))
9120 (errmsg("online backup was canceled, recovery cannot continue")));
9123 * If we see a shutdown checkpoint, we know that nothing was running
9124 * on the master at this point. So fake-up an empty running-xacts
9125 * record and use that here and now. Recover additional standby state
9126 * for prepared transactions.
9128 if (standbyState >= STANDBY_INITIALIZED)
9130 TransactionId *xids;
9132 TransactionId oldestActiveXID;
9133 TransactionId latestCompletedXid;
9134 RunningTransactionsData running;
9136 oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
9139 * Construct a RunningTransactions snapshot representing a shut
9140 * down server, with only prepared transactions still alive. We're
9141 * never overflowed at this point because all subxids are listed
9142 * with their parent prepared transactions.
9144 running.xcnt = nxids;
9145 running.subxcnt = 0;
9146 running.subxid_overflow = false;
9147 running.nextXid = checkPoint.nextXid;
9148 running.oldestRunningXid = oldestActiveXID;
9149 latestCompletedXid = checkPoint.nextXid;
9150 TransactionIdRetreat(latestCompletedXid);
9151 Assert(TransactionIdIsNormal(latestCompletedXid));
9152 running.latestCompletedXid = latestCompletedXid;
9153 running.xids = xids;
9155 ProcArrayApplyRecoveryInfo(&running);
9157 StandbyRecoverPreparedTransactions(true);
9160 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
9161 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
9162 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
9164 /* Update shared-memory copy of checkpoint XID/epoch */
9166 /* use volatile pointer to prevent code rearrangement */
9167 volatile XLogCtlData *xlogctl = XLogCtl;
9169 SpinLockAcquire(&xlogctl->info_lck);
9170 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
9171 xlogctl->ckptXid = checkPoint.nextXid;
9172 SpinLockRelease(&xlogctl->info_lck);
9176 * We should've already switched to the new TLI before replaying this
9179 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
9181 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
9182 checkPoint.ThisTimeLineID, ThisTimeLineID)));
9184 RecoveryRestartPoint(&checkPoint);
9186 else if (info == XLOG_CHECKPOINT_ONLINE)
9188 CheckPoint checkPoint;
9190 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9191 /* In an ONLINE checkpoint, treat the XID counter as a minimum */
9192 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
9193 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
9194 checkPoint.nextXid))
9195 ShmemVariableCache->nextXid = checkPoint.nextXid;
9196 LWLockRelease(XidGenLock);
9197 /* ... but still treat OID counter as exact */
9198 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9199 ShmemVariableCache->nextOid = checkPoint.nextOid;
9200 ShmemVariableCache->oidCount = 0;
9201 LWLockRelease(OidGenLock);
9202 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
9203 checkPoint.nextMultiOffset);
9204 if (TransactionIdPrecedes(ShmemVariableCache->oldestXid,
9205 checkPoint.oldestXid))
9206 SetTransactionIdLimit(checkPoint.oldestXid,
9207 checkPoint.oldestXidDB);
9208 MultiXactAdvanceOldest(checkPoint.oldestMulti,
9209 checkPoint.oldestMultiDB);
9211 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
9212 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
9213 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
9215 /* Update shared-memory copy of checkpoint XID/epoch */
9217 /* use volatile pointer to prevent code rearrangement */
9218 volatile XLogCtlData *xlogctl = XLogCtl;
9220 SpinLockAcquire(&xlogctl->info_lck);
9221 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
9222 xlogctl->ckptXid = checkPoint.nextXid;
9223 SpinLockRelease(&xlogctl->info_lck);
9226 /* TLI should not change in an on-line checkpoint */
9227 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
9229 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
9230 checkPoint.ThisTimeLineID, ThisTimeLineID)));
9232 RecoveryRestartPoint(&checkPoint);
9234 else if (info == XLOG_END_OF_RECOVERY)
9236 xl_end_of_recovery xlrec;
9238 memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_end_of_recovery));
9241 * For Hot Standby, we could treat this like a Shutdown Checkpoint,
9242 * but this case is rarer and harder to test, so the benefit doesn't
9243 * outweigh the potential extra cost of maintenance.
9247 * We should've already switched to the new TLI before replaying this
9250 if (xlrec.ThisTimeLineID != ThisTimeLineID)
9252 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
9253 xlrec.ThisTimeLineID, ThisTimeLineID)));
9255 else if (info == XLOG_NOOP)
9257 /* nothing to do here */
9259 else if (info == XLOG_SWITCH)
9261 /* nothing to do here */
9263 else if (info == XLOG_RESTORE_POINT)
9265 /* nothing to do here */
9267 else if (info == XLOG_FPI)
9273 * Full-page image (FPI) records contain a backup block stored "inline"
9274 * in the normal data since the locking when writing hint records isn't
9275 * sufficient to use the normal backup block mechanism, which assumes
9276 * exclusive lock on the buffer supplied.
9278 * Since the only change in these backup block are hint bits, there
9279 * are no recovery conflicts generated.
9281 * This also means there is no corresponding API call for this, so an
9282 * smgr implementation has no need to implement anything. Which means
9283 * nothing is needed in md.c etc
9285 data = XLogRecGetData(record);
9286 memcpy(&bkpb, data, sizeof(BkpBlock));
9287 data += sizeof(BkpBlock);
9289 RestoreBackupBlockContents(lsn, bkpb, data, false, false);
9291 else if (info == XLOG_BACKUP_END)
9293 XLogRecPtr startpoint;
9295 memcpy(&startpoint, XLogRecGetData(record), sizeof(startpoint));
9297 if (ControlFile->backupStartPoint == startpoint)
9300 * We have reached the end of base backup, the point where
9301 * pg_stop_backup() was done. The data on disk is now consistent.
9302 * Reset backupStartPoint, and update minRecoveryPoint to make
9303 * sure we don't allow starting up at an earlier point even if
9304 * recovery is stopped and restarted soon after this.
9306 elog(DEBUG1, "end of backup reached");
9308 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9310 if (ControlFile->minRecoveryPoint < lsn)
9312 ControlFile->minRecoveryPoint = lsn;
9313 ControlFile->minRecoveryPointTLI = ThisTimeLineID;
9315 ControlFile->backupStartPoint = InvalidXLogRecPtr;
9316 ControlFile->backupEndRequired = false;
9317 UpdateControlFile();
9319 LWLockRelease(ControlFileLock);
9322 else if (info == XLOG_PARAMETER_CHANGE)
9324 xl_parameter_change xlrec;
9326 /* Update our copy of the parameters in pg_control */
9327 memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_parameter_change));
9329 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9330 ControlFile->MaxConnections = xlrec.MaxConnections;
9331 ControlFile->max_worker_processes = xlrec.max_worker_processes;
9332 ControlFile->max_prepared_xacts = xlrec.max_prepared_xacts;
9333 ControlFile->max_locks_per_xact = xlrec.max_locks_per_xact;
9334 ControlFile->wal_level = xlrec.wal_level;
9337 * Update minRecoveryPoint to ensure that if recovery is aborted, we
9338 * recover back up to this point before allowing hot standby again.
9339 * This is particularly important if wal_level was set to 'archive'
9340 * before, and is now 'hot_standby', to ensure you don't run queries
9341 * against the WAL preceding the wal_level change. Same applies to
9342 * decreasing max_* settings.
9344 minRecoveryPoint = ControlFile->minRecoveryPoint;
9345 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
9346 if (minRecoveryPoint != 0 && minRecoveryPoint < lsn)
9348 ControlFile->minRecoveryPoint = lsn;
9349 ControlFile->minRecoveryPointTLI = ThisTimeLineID;
9352 UpdateControlFile();
9353 LWLockRelease(ControlFileLock);
9355 /* Check to see if any changes to max_connections give problems */
9356 CheckRequiredParameterValues();
9358 else if (info == XLOG_FPW_CHANGE)
9360 /* use volatile pointer to prevent code rearrangement */
9361 volatile XLogCtlData *xlogctl = XLogCtl;
9364 memcpy(&fpw, XLogRecGetData(record), sizeof(bool));
9367 * Update the LSN of the last replayed XLOG_FPW_CHANGE record so that
9368 * do_pg_start_backup() and do_pg_stop_backup() can check whether
9369 * full_page_writes has been disabled during online backup.
9373 SpinLockAcquire(&xlogctl->info_lck);
9374 if (xlogctl->lastFpwDisableRecPtr < ReadRecPtr)
9375 xlogctl->lastFpwDisableRecPtr = ReadRecPtr;
9376 SpinLockRelease(&xlogctl->info_lck);
9379 /* Keep track of full_page_writes */
9380 lastFullPageWrites = fpw;
9387 xlog_outrec(StringInfo buf, XLogRecord *record)
9391 appendStringInfo(buf, "prev %X/%X; xid %u",
9392 (uint32) (record->xl_prev >> 32),
9393 (uint32) record->xl_prev,
9396 appendStringInfo(buf, "; len %u",
9399 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
9401 if (record->xl_info & XLR_BKP_BLOCK(i))
9402 appendStringInfo(buf, "; bkpb%d", i);
9405 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
9407 #endif /* WAL_DEBUG */
9411 * Return the (possible) sync flag used for opening a file, depending on the
9412 * value of the GUC wal_sync_method.
9415 get_sync_bit(int method)
9417 int o_direct_flag = 0;
9419 /* If fsync is disabled, never open in sync mode */
9424 * Optimize writes by bypassing kernel cache with O_DIRECT when using
9425 * O_SYNC/O_FSYNC and O_DSYNC. But only if archiving and streaming are
9426 * disabled, otherwise the archive command or walsender process will read
9427 * the WAL soon after writing it, which is guaranteed to cause a physical
9428 * read if we bypassed the kernel cache. We also skip the
9429 * posix_fadvise(POSIX_FADV_DONTNEED) call in XLogFileClose() for the same
9432 * Never use O_DIRECT in walreceiver process for similar reasons; the WAL
9433 * written by walreceiver is normally read by the startup process soon
9434 * after its written. Also, walreceiver performs unaligned writes, which
9435 * don't work with O_DIRECT, so it is required for correctness too.
9437 if (!XLogIsNeeded() && !AmWalReceiverProcess())
9438 o_direct_flag = PG_O_DIRECT;
9443 * enum values for all sync options are defined even if they are
9444 * not supported on the current platform. But if not, they are
9445 * not included in the enum option array, and therefore will never
9448 case SYNC_METHOD_FSYNC:
9449 case SYNC_METHOD_FSYNC_WRITETHROUGH:
9450 case SYNC_METHOD_FDATASYNC:
9452 #ifdef OPEN_SYNC_FLAG
9453 case SYNC_METHOD_OPEN:
9454 return OPEN_SYNC_FLAG | o_direct_flag;
9456 #ifdef OPEN_DATASYNC_FLAG
9457 case SYNC_METHOD_OPEN_DSYNC:
9458 return OPEN_DATASYNC_FLAG | o_direct_flag;
9461 /* can't happen (unless we are out of sync with option array) */
9462 elog(ERROR, "unrecognized wal_sync_method: %d", method);
9463 return 0; /* silence warning */
9471 assign_xlog_sync_method(int new_sync_method, void *extra)
9473 if (sync_method != new_sync_method)
9476 * To ensure that no blocks escape unsynced, force an fsync on the
9477 * currently open log segment (if any). Also, if the open flag is
9478 * changing, close the log file so it will be reopened (with new flag
9481 if (openLogFile >= 0)
9483 if (pg_fsync(openLogFile) != 0)
9485 (errcode_for_file_access(),
9486 errmsg("could not fsync log segment %s: %m",
9487 XLogFileNameP(ThisTimeLineID, openLogSegNo))));
9488 if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
9496 * Issue appropriate kind of fsync (if any) for an XLOG output file.
9498 * 'fd' is a file descriptor for the XLOG file to be fsync'd.
9499 * 'log' and 'seg' are for error reporting purposes.
9502 issue_xlog_fsync(int fd, XLogSegNo segno)
9504 switch (sync_method)
9506 case SYNC_METHOD_FSYNC:
9507 if (pg_fsync_no_writethrough(fd) != 0)
9509 (errcode_for_file_access(),
9510 errmsg("could not fsync log file %s: %m",
9511 XLogFileNameP(ThisTimeLineID, segno))));
9513 #ifdef HAVE_FSYNC_WRITETHROUGH
9514 case SYNC_METHOD_FSYNC_WRITETHROUGH:
9515 if (pg_fsync_writethrough(fd) != 0)
9517 (errcode_for_file_access(),
9518 errmsg("could not fsync write-through log file %s: %m",
9519 XLogFileNameP(ThisTimeLineID, segno))));
9522 #ifdef HAVE_FDATASYNC
9523 case SYNC_METHOD_FDATASYNC:
9524 if (pg_fdatasync(fd) != 0)
9526 (errcode_for_file_access(),
9527 errmsg("could not fdatasync log file %s: %m",
9528 XLogFileNameP(ThisTimeLineID, segno))));
9531 case SYNC_METHOD_OPEN:
9532 case SYNC_METHOD_OPEN_DSYNC:
9533 /* write synced it already */
9536 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
9542 * Return the filename of given log segment, as a palloc'd string.
9545 XLogFileNameP(TimeLineID tli, XLogSegNo segno)
9547 char *result = palloc(MAXFNAMELEN);
9549 XLogFileName(result, tli, segno);
9554 * do_pg_start_backup is the workhorse of the user-visible pg_start_backup()
9555 * function. It creates the necessary starting checkpoint and constructs the
9556 * backup label file.
9558 * There are two kind of backups: exclusive and non-exclusive. An exclusive
9559 * backup is started with pg_start_backup(), and there can be only one active
9560 * at a time. The backup label file of an exclusive backup is written to
9561 * $PGDATA/backup_label, and it is removed by pg_stop_backup().
9563 * A non-exclusive backup is used for the streaming base backups (see
9564 * src/backend/replication/basebackup.c). The difference to exclusive backups
9565 * is that the backup label file is not written to disk. Instead, its would-be
9566 * contents are returned in *labelfile, and the caller is responsible for
9567 * including it in the backup archive as 'backup_label'. There can be many
9568 * non-exclusive backups active at the same time, and they don't conflict
9569 * with an exclusive backup either.
9571 * Returns the minimum WAL position that must be present to restore from this
9572 * backup, and the corresponding timeline ID in *starttli_p.
9574 * Every successfully started non-exclusive backup must be stopped by calling
9575 * do_pg_stop_backup() or do_pg_abort_backup().
9578 do_pg_start_backup(const char *backupidstr, bool fast, TimeLineID *starttli_p,
9581 bool exclusive = (labelfile == NULL);
9582 bool backup_started_in_recovery = false;
9583 XLogRecPtr checkpointloc;
9584 XLogRecPtr startpoint;
9585 TimeLineID starttli;
9586 pg_time_t stamp_time;
9588 char xlogfilename[MAXFNAMELEN];
9589 XLogSegNo _logSegNo;
9590 struct stat stat_buf;
9592 StringInfoData labelfbuf;
9594 backup_started_in_recovery = RecoveryInProgress();
9596 if (!superuser() && !has_rolreplication(GetUserId()))
9598 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
9599 errmsg("must be superuser or replication role to run a backup")));
9602 * Currently only non-exclusive backup can be taken during recovery.
9604 if (backup_started_in_recovery && exclusive)
9606 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9607 errmsg("recovery is in progress"),
9608 errhint("WAL control functions cannot be executed during recovery.")));
9611 * During recovery, we don't need to check WAL level. Because, if WAL
9612 * level is not sufficient, it's impossible to get here during recovery.
9614 if (!backup_started_in_recovery && !XLogIsNeeded())
9616 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9617 errmsg("WAL level not sufficient for making an online backup"),
9618 errhint("wal_level must be set to \"archive\" or \"hot_standby\" at server start.")));
9620 if (strlen(backupidstr) > MAXPGPATH)
9622 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9623 errmsg("backup label too long (max %d bytes)",
9627 * Mark backup active in shared memory. We must do full-page WAL writes
9628 * during an on-line backup even if not doing so at other times, because
9629 * it's quite possible for the backup dump to obtain a "torn" (partially
9630 * written) copy of a database page if it reads the page concurrently with
9631 * our write to the same page. This can be fixed as long as the first
9632 * write to the page in the WAL sequence is a full-page write. Hence, we
9633 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
9634 * are no dirty pages in shared memory that might get dumped while the
9635 * backup is in progress without having a corresponding WAL record. (Once
9636 * the backup is complete, we need not force full-page writes anymore,
9637 * since we expect that any pages not modified during the backup interval
9638 * must have been correctly captured by the backup.)
9640 * Note that forcePageWrites has no effect during an online backup from
9643 * We must hold all the insertion slots to change the value of
9644 * forcePageWrites, to ensure adequate interlocking against XLogInsert().
9646 WALInsertSlotAcquire(true);
9649 if (XLogCtl->Insert.exclusiveBackup)
9651 WALInsertSlotRelease();
9653 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9654 errmsg("a backup is already in progress"),
9655 errhint("Run pg_stop_backup() and try again.")));
9657 XLogCtl->Insert.exclusiveBackup = true;
9660 XLogCtl->Insert.nonExclusiveBackups++;
9661 XLogCtl->Insert.forcePageWrites = true;
9662 WALInsertSlotRelease();
9664 /* Ensure we release forcePageWrites if fail below */
9665 PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) BoolGetDatum(exclusive));
9667 bool gotUniqueStartpoint = false;
9670 * Force an XLOG file switch before the checkpoint, to ensure that the
9671 * WAL segment the checkpoint is written to doesn't contain pages with
9672 * old timeline IDs. That would otherwise happen if you called
9673 * pg_start_backup() right after restoring from a PITR archive: the
9674 * first WAL segment containing the startup checkpoint has pages in
9675 * the beginning with the old timeline ID. That can cause trouble at
9676 * recovery: we won't have a history file covering the old timeline if
9677 * pg_xlog directory was not included in the base backup and the WAL
9678 * archive was cleared too before starting the backup.
9680 * This also ensures that we have emitted a WAL page header that has
9681 * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
9682 * Therefore, if a WAL archiver (such as pglesslog) is trying to
9683 * compress out removable backup blocks, it won't remove any that
9684 * occur after this point.
9686 * During recovery, we skip forcing XLOG file switch, which means that
9687 * the backup taken during recovery is not available for the special
9688 * recovery case described above.
9690 if (!backup_started_in_recovery)
9691 RequestXLogSwitch();
9698 * Force a CHECKPOINT. Aside from being necessary to prevent torn
9699 * page problems, this guarantees that two successive backup runs
9700 * will have different checkpoint positions and hence different
9701 * history file names, even if nothing happened in between.
9703 * During recovery, establish a restartpoint if possible. We use
9704 * the last restartpoint as the backup starting checkpoint. This
9705 * means that two successive backup runs can have same checkpoint
9708 * Since the fact that we are executing do_pg_start_backup()
9709 * during recovery means that checkpointer is running, we can use
9710 * RequestCheckpoint() to establish a restartpoint.
9712 * We use CHECKPOINT_IMMEDIATE only if requested by user (via
9713 * passing fast = true). Otherwise this can take awhile.
9715 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT |
9716 (fast ? CHECKPOINT_IMMEDIATE : 0));
9719 * Now we need to fetch the checkpoint record location, and also
9720 * its REDO pointer. The oldest point in WAL that would be needed
9721 * to restore starting from the checkpoint is precisely the REDO
9724 LWLockAcquire(ControlFileLock, LW_SHARED);
9725 checkpointloc = ControlFile->checkPoint;
9726 startpoint = ControlFile->checkPointCopy.redo;
9727 starttli = ControlFile->checkPointCopy.ThisTimeLineID;
9728 checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
9729 LWLockRelease(ControlFileLock);
9731 if (backup_started_in_recovery)
9733 /* use volatile pointer to prevent code rearrangement */
9734 volatile XLogCtlData *xlogctl = XLogCtl;
9738 * Check to see if all WAL replayed during online backup
9739 * (i.e., since last restartpoint used as backup starting
9740 * checkpoint) contain full-page writes.
9742 SpinLockAcquire(&xlogctl->info_lck);
9743 recptr = xlogctl->lastFpwDisableRecPtr;
9744 SpinLockRelease(&xlogctl->info_lck);
9746 if (!checkpointfpw || startpoint <= recptr)
9748 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9749 errmsg("WAL generated with full_page_writes=off was replayed "
9750 "since last restartpoint"),
9751 errhint("This means that the backup being taken on the standby "
9752 "is corrupt and should not be used. "
9753 "Enable full_page_writes and run CHECKPOINT on the master, "
9754 "and then try an online backup again.")));
9757 * During recovery, since we don't use the end-of-backup WAL
9758 * record and don't write the backup history file, the
9759 * starting WAL location doesn't need to be unique. This means
9760 * that two base backups started at the same time might use
9761 * the same checkpoint as starting locations.
9763 gotUniqueStartpoint = true;
9767 * If two base backups are started at the same time (in WAL sender
9768 * processes), we need to make sure that they use different
9769 * checkpoints as starting locations, because we use the starting
9770 * WAL location as a unique identifier for the base backup in the
9771 * end-of-backup WAL record and when we write the backup history
9772 * file. Perhaps it would be better generate a separate unique ID
9773 * for each backup instead of forcing another checkpoint, but
9774 * taking a checkpoint right after another is not that expensive
9775 * either because only few buffers have been dirtied yet.
9777 WALInsertSlotAcquire(true);
9778 if (XLogCtl->Insert.lastBackupStart < startpoint)
9780 XLogCtl->Insert.lastBackupStart = startpoint;
9781 gotUniqueStartpoint = true;
9783 WALInsertSlotRelease();
9784 } while (!gotUniqueStartpoint);
9786 XLByteToSeg(startpoint, _logSegNo);
9787 XLogFileName(xlogfilename, ThisTimeLineID, _logSegNo);
9790 * Construct backup label file
9792 initStringInfo(&labelfbuf);
9794 /* Use the log timezone here, not the session timezone */
9795 stamp_time = (pg_time_t) time(NULL);
9796 pg_strftime(strfbuf, sizeof(strfbuf),
9797 "%Y-%m-%d %H:%M:%S %Z",
9798 pg_localtime(&stamp_time, log_timezone));
9799 appendStringInfo(&labelfbuf, "START WAL LOCATION: %X/%X (file %s)\n",
9800 (uint32) (startpoint >> 32), (uint32) startpoint, xlogfilename);
9801 appendStringInfo(&labelfbuf, "CHECKPOINT LOCATION: %X/%X\n",
9802 (uint32) (checkpointloc >> 32), (uint32) checkpointloc);
9803 appendStringInfo(&labelfbuf, "BACKUP METHOD: %s\n",
9804 exclusive ? "pg_start_backup" : "streamed");
9805 appendStringInfo(&labelfbuf, "BACKUP FROM: %s\n",
9806 backup_started_in_recovery ? "standby" : "master");
9807 appendStringInfo(&labelfbuf, "START TIME: %s\n", strfbuf);
9808 appendStringInfo(&labelfbuf, "LABEL: %s\n", backupidstr);
9811 * Okay, write the file, or return its contents to caller.
9816 * Check for existing backup label --- implies a backup is already
9817 * running. (XXX given that we checked exclusiveBackup above,
9818 * maybe it would be OK to just unlink any such label file?)
9820 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
9822 if (errno != ENOENT)
9824 (errcode_for_file_access(),
9825 errmsg("could not stat file \"%s\": %m",
9826 BACKUP_LABEL_FILE)));
9830 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9831 errmsg("a backup is already in progress"),
9832 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
9833 BACKUP_LABEL_FILE)));
9835 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
9839 (errcode_for_file_access(),
9840 errmsg("could not create file \"%s\": %m",
9841 BACKUP_LABEL_FILE)));
9842 if (fwrite(labelfbuf.data, labelfbuf.len, 1, fp) != 1 ||
9844 pg_fsync(fileno(fp)) != 0 ||
9848 (errcode_for_file_access(),
9849 errmsg("could not write file \"%s\": %m",
9850 BACKUP_LABEL_FILE)));
9851 pfree(labelfbuf.data);
9854 *labelfile = labelfbuf.data;
9856 PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) BoolGetDatum(exclusive));
9859 * We're done. As a convenience, return the starting WAL location.
9862 *starttli_p = starttli;
9866 /* Error cleanup callback for pg_start_backup */
9868 pg_start_backup_callback(int code, Datum arg)
9870 bool exclusive = DatumGetBool(arg);
9872 /* Update backup counters and forcePageWrites on failure */
9873 WALInsertSlotAcquire(true);
9876 Assert(XLogCtl->Insert.exclusiveBackup);
9877 XLogCtl->Insert.exclusiveBackup = false;
9881 Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
9882 XLogCtl->Insert.nonExclusiveBackups--;
9885 if (!XLogCtl->Insert.exclusiveBackup &&
9886 XLogCtl->Insert.nonExclusiveBackups == 0)
9888 XLogCtl->Insert.forcePageWrites = false;
9890 WALInsertSlotRelease();
9894 * do_pg_stop_backup is the workhorse of the user-visible pg_stop_backup()
9897 * If labelfile is NULL, this stops an exclusive backup. Otherwise this stops
9898 * the non-exclusive backup specified by 'labelfile'.
9900 * Returns the last WAL position that must be present to restore from this
9901 * backup, and the corresponding timeline ID in *stoptli_p.
9904 do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
9906 bool exclusive = (labelfile == NULL);
9907 bool backup_started_in_recovery = false;
9908 XLogRecPtr startpoint;
9909 XLogRecPtr stoppoint;
9912 pg_time_t stamp_time;
9914 char histfilepath[MAXPGPATH];
9915 char startxlogfilename[MAXFNAMELEN];
9916 char stopxlogfilename[MAXFNAMELEN];
9917 char lastxlogfilename[MAXFNAMELEN];
9918 char histfilename[MAXFNAMELEN];
9919 char backupfrom[20];
9920 XLogSegNo _logSegNo;
9924 int seconds_before_warning;
9926 bool reported_waiting = false;
9932 backup_started_in_recovery = RecoveryInProgress();
9934 if (!superuser() && !has_rolreplication(GetUserId()))
9936 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
9937 (errmsg("must be superuser or replication role to run a backup"))));
9940 * Currently only non-exclusive backup can be taken during recovery.
9942 if (backup_started_in_recovery && exclusive)
9944 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9945 errmsg("recovery is in progress"),
9946 errhint("WAL control functions cannot be executed during recovery.")));
9949 * During recovery, we don't need to check WAL level. Because, if WAL
9950 * level is not sufficient, it's impossible to get here during recovery.
9952 if (!backup_started_in_recovery && !XLogIsNeeded())
9954 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9955 errmsg("WAL level not sufficient for making an online backup"),
9956 errhint("wal_level must be set to \"archive\" or \"hot_standby\" at server start.")));
9959 * OK to update backup counters and forcePageWrites
9961 WALInsertSlotAcquire(true);
9963 XLogCtl->Insert.exclusiveBackup = false;
9967 * The user-visible pg_start/stop_backup() functions that operate on
9968 * exclusive backups can be called at any time, but for non-exclusive
9969 * backups, it is expected that each do_pg_start_backup() call is
9970 * matched by exactly one do_pg_stop_backup() call.
9972 Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
9973 XLogCtl->Insert.nonExclusiveBackups--;
9976 if (!XLogCtl->Insert.exclusiveBackup &&
9977 XLogCtl->Insert.nonExclusiveBackups == 0)
9979 XLogCtl->Insert.forcePageWrites = false;
9981 WALInsertSlotRelease();
9986 * Read the existing label file into memory.
9988 struct stat statbuf;
9991 if (stat(BACKUP_LABEL_FILE, &statbuf))
9993 if (errno != ENOENT)
9995 (errcode_for_file_access(),
9996 errmsg("could not stat file \"%s\": %m",
9997 BACKUP_LABEL_FILE)));
9999 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10000 errmsg("a backup is not in progress")));
10003 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
10007 (errcode_for_file_access(),
10008 errmsg("could not read file \"%s\": %m",
10009 BACKUP_LABEL_FILE)));
10011 labelfile = palloc(statbuf.st_size + 1);
10012 r = fread(labelfile, statbuf.st_size, 1, lfp);
10013 labelfile[statbuf.st_size] = '\0';
10016 * Close and remove the backup label file
10018 if (r != 1 || ferror(lfp) || FreeFile(lfp))
10020 (errcode_for_file_access(),
10021 errmsg("could not read file \"%s\": %m",
10022 BACKUP_LABEL_FILE)));
10023 if (unlink(BACKUP_LABEL_FILE) != 0)
10025 (errcode_for_file_access(),
10026 errmsg("could not remove file \"%s\": %m",
10027 BACKUP_LABEL_FILE)));
10031 * Read and parse the START WAL LOCATION line (this code is pretty crude,
10032 * but we are not expecting any variability in the file format).
10034 if (sscanf(labelfile, "START WAL LOCATION: %X/%X (file %24s)%c",
10035 &hi, &lo, startxlogfilename,
10036 &ch) != 4 || ch != '\n')
10038 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10039 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10040 startpoint = ((uint64) hi) << 32 | lo;
10041 remaining = strchr(labelfile, '\n') + 1; /* %n is not portable enough */
10044 * Parse the BACKUP FROM line. If we are taking an online backup from the
10045 * standby, we confirm that the standby has not been promoted during the
10048 ptr = strstr(remaining, "BACKUP FROM:");
10049 if (!ptr || sscanf(ptr, "BACKUP FROM: %19s\n", backupfrom) != 1)
10051 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10052 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10053 if (strcmp(backupfrom, "standby") == 0 && !backup_started_in_recovery)
10055 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10056 errmsg("the standby was promoted during online backup"),
10057 errhint("This means that the backup being taken is corrupt "
10058 "and should not be used. "
10059 "Try taking another online backup.")));
10062 * During recovery, we don't write an end-of-backup record. We assume that
10063 * pg_control was backed up last and its minimum recovery point can be
10064 * available as the backup end location. Since we don't have an
10065 * end-of-backup record, we use the pg_control value to check whether
10066 * we've reached the end of backup when starting recovery from this
10067 * backup. We have no way of checking if pg_control wasn't backed up last
10070 * We don't force a switch to new WAL file and wait for all the required
10071 * files to be archived. This is okay if we use the backup to start the
10072 * standby. But, if it's for an archive recovery, to ensure all the
10073 * required files are available, a user should wait for them to be
10074 * archived, or include them into the backup.
10076 * We return the current minimum recovery point as the backup end
10077 * location. Note that it can be greater than the exact backup end
10078 * location if the minimum recovery point is updated after the backup of
10079 * pg_control. This is harmless for current uses.
10081 * XXX currently a backup history file is for informational and debug
10082 * purposes only. It's not essential for an online backup. Furthermore,
10083 * even if it's created, it will not be archived during recovery because
10084 * an archiver is not invoked. So it doesn't seem worthwhile to write a
10085 * backup history file during recovery.
10087 if (backup_started_in_recovery)
10089 /* use volatile pointer to prevent code rearrangement */
10090 volatile XLogCtlData *xlogctl = XLogCtl;
10094 * Check to see if all WAL replayed during online backup contain
10095 * full-page writes.
10097 SpinLockAcquire(&xlogctl->info_lck);
10098 recptr = xlogctl->lastFpwDisableRecPtr;
10099 SpinLockRelease(&xlogctl->info_lck);
10101 if (startpoint <= recptr)
10103 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10104 errmsg("WAL generated with full_page_writes=off was replayed "
10105 "during online backup"),
10106 errhint("This means that the backup being taken on the standby "
10107 "is corrupt and should not be used. "
10108 "Enable full_page_writes and run CHECKPOINT on the master, "
10109 "and then try an online backup again.")));
10112 LWLockAcquire(ControlFileLock, LW_SHARED);
10113 stoppoint = ControlFile->minRecoveryPoint;
10114 stoptli = ControlFile->minRecoveryPointTLI;
10115 LWLockRelease(ControlFileLock);
10118 *stoptli_p = stoptli;
10123 * Write the backup-end xlog record
10125 rdata.data = (char *) (&startpoint);
10126 rdata.len = sizeof(startpoint);
10127 rdata.buffer = InvalidBuffer;
10129 stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END, &rdata);
10130 stoptli = ThisTimeLineID;
10133 * Force a switch to a new xlog segment file, so that the backup is valid
10134 * as soon as archiver moves out the current segment file.
10136 RequestXLogSwitch();
10138 XLByteToPrevSeg(stoppoint, _logSegNo);
10139 XLogFileName(stopxlogfilename, ThisTimeLineID, _logSegNo);
10141 /* Use the log timezone here, not the session timezone */
10142 stamp_time = (pg_time_t) time(NULL);
10143 pg_strftime(strfbuf, sizeof(strfbuf),
10144 "%Y-%m-%d %H:%M:%S %Z",
10145 pg_localtime(&stamp_time, log_timezone));
10148 * Write the backup history file
10150 XLByteToSeg(startpoint, _logSegNo);
10151 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logSegNo,
10152 (uint32) (startpoint % XLogSegSize));
10153 fp = AllocateFile(histfilepath, "w");
10156 (errcode_for_file_access(),
10157 errmsg("could not create file \"%s\": %m",
10159 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
10160 (uint32) (startpoint >> 32), (uint32) startpoint, startxlogfilename);
10161 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
10162 (uint32) (stoppoint >> 32), (uint32) stoppoint, stopxlogfilename);
10163 /* transfer remaining lines from label to history file */
10164 fprintf(fp, "%s", remaining);
10165 fprintf(fp, "STOP TIME: %s\n", strfbuf);
10166 if (fflush(fp) || ferror(fp) || FreeFile(fp))
10168 (errcode_for_file_access(),
10169 errmsg("could not write file \"%s\": %m",
10173 * Clean out any no-longer-needed history files. As a side effect, this
10174 * will post a .ready file for the newly created history file, notifying
10175 * the archiver that history file may be archived immediately.
10177 CleanupBackupHistory();
10180 * If archiving is enabled, wait for all the required WAL files to be
10181 * archived before returning. If archiving isn't enabled, the required WAL
10182 * needs to be transported via streaming replication (hopefully with
10183 * wal_keep_segments set high enough), or some more exotic mechanism like
10184 * polling and copying files from pg_xlog with script. We have no
10185 * knowledge of those mechanisms, so it's up to the user to ensure that he
10186 * gets all the required WAL.
10188 * We wait until both the last WAL file filled during backup and the
10189 * history file have been archived, and assume that the alphabetic sorting
10190 * property of the WAL files ensures any earlier WAL files are safely
10191 * archived as well.
10193 * We wait forever, since archive_command is supposed to work and we
10194 * assume the admin wanted his backup to work completely. If you don't
10195 * wish to wait, you can set statement_timeout. Also, some notices are
10196 * issued to clue in anyone who might be doing this interactively.
10198 if (waitforarchive && XLogArchivingActive())
10200 XLByteToPrevSeg(stoppoint, _logSegNo);
10201 XLogFileName(lastxlogfilename, ThisTimeLineID, _logSegNo);
10203 XLByteToSeg(startpoint, _logSegNo);
10204 BackupHistoryFileName(histfilename, ThisTimeLineID, _logSegNo,
10205 (uint32) (startpoint % XLogSegSize));
10207 seconds_before_warning = 60;
10210 while (XLogArchiveIsBusy(lastxlogfilename) ||
10211 XLogArchiveIsBusy(histfilename))
10213 CHECK_FOR_INTERRUPTS();
10215 if (!reported_waiting && waits > 5)
10218 (errmsg("pg_stop_backup cleanup done, waiting for required WAL segments to be archived")));
10219 reported_waiting = true;
10222 pg_usleep(1000000L);
10224 if (++waits >= seconds_before_warning)
10226 seconds_before_warning *= 2; /* This wraps in >10 years... */
10228 (errmsg("pg_stop_backup still waiting for all required WAL segments to be archived (%d seconds elapsed)",
10230 errhint("Check that your archive_command is executing properly. "
10231 "pg_stop_backup can be canceled safely, "
10232 "but the database backup will not be usable without all the WAL segments.")));
10237 (errmsg("pg_stop_backup complete, all required WAL segments have been archived")));
10239 else if (waitforarchive)
10241 (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
10244 * We're done. As a convenience, return the ending WAL location.
10247 *stoptli_p = stoptli;
10253 * do_pg_abort_backup: abort a running backup
10255 * This does just the most basic steps of do_pg_stop_backup(), by taking the
10256 * system out of backup mode, thus making it a lot more safe to call from
10257 * an error handler.
10259 * NB: This is only for aborting a non-exclusive backup that doesn't write
10260 * backup_label. A backup started with pg_stop_backup() needs to be finished
10261 * with pg_stop_backup().
10264 do_pg_abort_backup(void)
10266 WALInsertSlotAcquire(true);
10267 Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
10268 XLogCtl->Insert.nonExclusiveBackups--;
10270 if (!XLogCtl->Insert.exclusiveBackup &&
10271 XLogCtl->Insert.nonExclusiveBackups == 0)
10273 XLogCtl->Insert.forcePageWrites = false;
10275 WALInsertSlotRelease();
10279 * Get latest redo apply position.
10281 * Exported to allow WALReceiver to read the pointer directly.
10284 GetXLogReplayRecPtr(TimeLineID *replayTLI)
10286 /* use volatile pointer to prevent code rearrangement */
10287 volatile XLogCtlData *xlogctl = XLogCtl;
10291 SpinLockAcquire(&xlogctl->info_lck);
10292 recptr = xlogctl->lastReplayedEndRecPtr;
10293 tli = xlogctl->lastReplayedTLI;
10294 SpinLockRelease(&xlogctl->info_lck);
10302 * Get latest WAL insert pointer
10305 GetXLogInsertRecPtr(void)
10307 volatile XLogCtlInsert *Insert = &XLogCtl->Insert;
10308 uint64 current_bytepos;
10310 SpinLockAcquire(&Insert->insertpos_lck);
10311 current_bytepos = Insert->CurrBytePos;
10312 SpinLockRelease(&Insert->insertpos_lck);
10314 return XLogBytePosToRecPtr(current_bytepos);
10318 * Get latest WAL write pointer
10321 GetXLogWriteRecPtr(void)
10324 /* use volatile pointer to prevent code rearrangement */
10325 volatile XLogCtlData *xlogctl = XLogCtl;
10327 SpinLockAcquire(&xlogctl->info_lck);
10328 LogwrtResult = xlogctl->LogwrtResult;
10329 SpinLockRelease(&xlogctl->info_lck);
10332 return LogwrtResult.Write;
10336 * Returns the redo pointer of the last checkpoint or restartpoint. This is
10337 * the oldest point in WAL that we still need, if we have to restart recovery.
10340 GetOldestRestartPoint(XLogRecPtr *oldrecptr, TimeLineID *oldtli)
10342 LWLockAcquire(ControlFileLock, LW_SHARED);
10343 *oldrecptr = ControlFile->checkPointCopy.redo;
10344 *oldtli = ControlFile->checkPointCopy.ThisTimeLineID;
10345 LWLockRelease(ControlFileLock);
10349 * read_backup_label: check to see if a backup_label file is present
10351 * If we see a backup_label during recovery, we assume that we are recovering
10352 * from a backup dump file, and we therefore roll forward from the checkpoint
10353 * identified by the label file, NOT what pg_control says. This avoids the
10354 * problem that pg_control might have been archived one or more checkpoints
10355 * later than the start of the dump, and so if we rely on it as the start
10356 * point, we will fail to restore a consistent database state.
10358 * Returns TRUE if a backup_label was found (and fills the checkpoint
10359 * location and its REDO location into *checkPointLoc and RedoStartLSN,
10360 * respectively); returns FALSE if not. If this backup_label came from a
10361 * streamed backup, *backupEndRequired is set to TRUE. If this backup_label
10362 * was created during recovery, *backupFromStandby is set to TRUE.
10365 read_backup_label(XLogRecPtr *checkPointLoc, bool *backupEndRequired,
10366 bool *backupFromStandby)
10368 char startxlogfilename[MAXFNAMELEN];
10372 char backuptype[20];
10373 char backupfrom[20];
10377 *backupEndRequired = false;
10378 *backupFromStandby = false;
10381 * See if label file is present
10383 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
10386 if (errno != ENOENT)
10388 (errcode_for_file_access(),
10389 errmsg("could not read file \"%s\": %m",
10390 BACKUP_LABEL_FILE)));
10391 return false; /* it's not there, all is fine */
10395 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
10396 * is pretty crude, but we are not expecting any variability in the file
10399 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
10400 &hi, &lo, &tli, startxlogfilename, &ch) != 5 || ch != '\n')
10402 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10403 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10404 RedoStartLSN = ((uint64) hi) << 32 | lo;
10405 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
10406 &hi, &lo, &ch) != 3 || ch != '\n')
10408 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10409 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10410 *checkPointLoc = ((uint64) hi) << 32 | lo;
10413 * BACKUP METHOD and BACKUP FROM lines are new in 9.2. We can't restore
10414 * from an older backup anyway, but since the information on it is not
10415 * strictly required, don't error out if it's missing for some reason.
10417 if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
10419 if (strcmp(backuptype, "streamed") == 0)
10420 *backupEndRequired = true;
10423 if (fscanf(lfp, "BACKUP FROM: %19s\n", backupfrom) == 1)
10425 if (strcmp(backupfrom, "standby") == 0)
10426 *backupFromStandby = true;
10429 if (ferror(lfp) || FreeFile(lfp))
10431 (errcode_for_file_access(),
10432 errmsg("could not read file \"%s\": %m",
10433 BACKUP_LABEL_FILE)));
10439 * Error context callback for errors occurring during rm_redo().
10442 rm_redo_error_callback(void *arg)
10444 XLogRecord *record = (XLogRecord *) arg;
10445 StringInfoData buf;
10447 initStringInfo(&buf);
10448 RmgrTable[record->xl_rmid].rm_desc(&buf,
10450 XLogRecGetData(record));
10452 /* don't bother emitting empty description */
10454 errcontext("xlog redo %s", buf.data);
10460 * BackupInProgress: check if online backup mode is active
10462 * This is done by checking for existence of the "backup_label" file.
10465 BackupInProgress(void)
10467 struct stat stat_buf;
10469 return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
10473 * CancelBackup: rename the "backup_label" file to cancel backup mode
10475 * If the "backup_label" file exists, it will be renamed to "backup_label.old".
10476 * Note that this will render an online backup in progress useless.
10477 * To correctly finish an online backup, pg_stop_backup must be called.
10482 struct stat stat_buf;
10484 /* if the file is not there, return */
10485 if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
10488 /* remove leftover file from previously canceled backup if it exists */
10489 unlink(BACKUP_LABEL_OLD);
10491 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) == 0)
10494 (errmsg("online backup mode canceled"),
10495 errdetail("\"%s\" was renamed to \"%s\".",
10496 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
10501 (errcode_for_file_access(),
10502 errmsg("online backup mode was not canceled"),
10503 errdetail("Could not rename \"%s\" to \"%s\": %m.",
10504 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
10509 * Read the XLOG page containing RecPtr into readBuf (if not read already).
10510 * Returns number of bytes read, if the page is read successfully, or -1
10511 * in case of errors. When errors occur, they are ereport'ed, but only
10512 * if they have not been previously reported.
10514 * This is responsible for restoring files from archive as needed, as well
10515 * as for waiting for the requested WAL record to arrive in standby mode.
10517 * 'emode' specifies the log level used for reporting "file not found" or
10518 * "end of WAL" situations in archive recovery, or in standby mode when a
10519 * trigger file is found. If set to WARNING or below, XLogPageRead() returns
10520 * false in those situations, on higher log levels the ereport() won't
10523 * In standby mode, if after a successful return of XLogPageRead() the
10524 * caller finds the record it's interested in to be broken, it should
10525 * ereport the error with the level determined by
10526 * emode_for_corrupt_record(), and then set lastSourceFailed
10527 * and call XLogPageRead() again with the same arguments. This lets
10528 * XLogPageRead() to try fetching the record from another source, or to
10532 XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
10533 XLogRecPtr targetRecPtr, char *readBuf, TimeLineID *readTLI)
10535 XLogPageReadPrivate *private =
10536 (XLogPageReadPrivate *) xlogreader->private_data;
10537 int emode = private->emode;
10538 uint32 targetPageOff;
10539 XLogSegNo targetSegNo PG_USED_FOR_ASSERTS_ONLY;
10541 XLByteToSeg(targetPagePtr, targetSegNo);
10542 targetPageOff = targetPagePtr % XLogSegSize;
10545 * See if we need to switch to a new segment because the requested record
10546 * is not in the currently open one.
10548 if (readFile >= 0 && !XLByteInSeg(targetPagePtr, readSegNo))
10551 * Request a restartpoint if we've replayed too much xlog since the
10554 if (StandbyModeRequested && bgwriterLaunched)
10556 if (XLogCheckpointNeeded(readSegNo))
10558 (void) GetRedoRecPtr();
10559 if (XLogCheckpointNeeded(readSegNo))
10560 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
10569 XLByteToSeg(targetPagePtr, readSegNo);
10572 /* See if we need to retrieve more data */
10573 if (readFile < 0 ||
10574 (readSource == XLOG_FROM_STREAM &&
10575 receivedUpto < targetPagePtr + reqLen))
10577 if (!WaitForWALToBecomeAvailable(targetPagePtr + reqLen,
10578 private->randAccess,
10579 private->fetching_ckpt,
10593 * At this point, we have the right segment open and if we're streaming we
10594 * know the requested record is in it.
10596 Assert(readFile != -1);
10599 * If the current segment is being streamed from master, calculate how
10600 * much of the current page we have received already. We know the
10601 * requested record has been received, but this is for the benefit of
10602 * future calls, to allow quick exit at the top of this function.
10604 if (readSource == XLOG_FROM_STREAM)
10606 if (((targetPagePtr) / XLOG_BLCKSZ) != (receivedUpto / XLOG_BLCKSZ))
10607 readLen = XLOG_BLCKSZ;
10609 readLen = receivedUpto % XLogSegSize - targetPageOff;
10612 readLen = XLOG_BLCKSZ;
10614 /* Read the requested page */
10615 readOff = targetPageOff;
10616 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
10618 char fname[MAXFNAMELEN];
10620 XLogFileName(fname, curFileTLI, readSegNo);
10621 ereport(emode_for_corrupt_record(emode, targetPagePtr + reqLen),
10622 (errcode_for_file_access(),
10623 errmsg("could not seek in log segment %s to offset %u: %m",
10625 goto next_record_is_invalid;
10628 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
10630 char fname[MAXFNAMELEN];
10632 XLogFileName(fname, curFileTLI, readSegNo);
10633 ereport(emode_for_corrupt_record(emode, targetPagePtr + reqLen),
10634 (errcode_for_file_access(),
10635 errmsg("could not read from log segment %s, offset %u: %m",
10637 goto next_record_is_invalid;
10640 Assert(targetSegNo == readSegNo);
10641 Assert(targetPageOff == readOff);
10642 Assert(reqLen <= readLen);
10644 *readTLI = curFileTLI;
10647 next_record_is_invalid:
10648 lastSourceFailed = true;
10656 /* In standby-mode, keep trying */
10664 * Open the WAL segment containing WAL position 'RecPtr'.
10666 * The segment can be fetched via restore_command, or via walreceiver having
10667 * streamed the record, or it can already be present in pg_xlog. Checking
10668 * pg_xlog is mainly for crash recovery, but it will be polled in standby mode
10669 * too, in case someone copies a new segment directly to pg_xlog. That is not
10670 * documented or recommended, though.
10672 * If 'fetching_ckpt' is true, we're fetching a checkpoint record, and should
10673 * prepare to read WAL starting from RedoStartLSN after this.
10675 * 'RecPtr' might not point to the beginning of the record we're interested
10676 * in, it might also point to the page or segment header. In that case,
10677 * 'tliRecPtr' is the position of the WAL record we're interested in. It is
10678 * used to decide which timeline to stream the requested WAL from.
10680 * If the the record is not immediately available, the function returns false
10681 * if we're not in standby mode. In standby mode, waits for it to become
10684 * When the requested record becomes available, the function opens the file
10685 * containing it (if not open already), and returns true. When end of standby
10686 * mode is triggered by the user, and there is no more WAL available, returns
10690 WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
10691 bool fetching_ckpt, XLogRecPtr tliRecPtr)
10693 static pg_time_t last_fail_time = 0;
10697 * Standby mode is implemented by a state machine:
10699 * 1. Read from archive (XLOG_FROM_ARCHIVE)
10700 * 2. Read from pg_xlog (XLOG_FROM_PG_XLOG)
10701 * 3. Check trigger file
10702 * 4. Read from primary server via walreceiver (XLOG_FROM_STREAM)
10703 * 5. Rescan timelines
10704 * 6. Sleep 5 seconds, and loop back to 1.
10706 * Failure to read from the current source advances the state machine to
10707 * the next state. In addition, successfully reading a file from pg_xlog
10708 * moves the state machine from state 2 back to state 1 (we always prefer
10709 * files in the archive over files in pg_xlog).
10711 * 'currentSource' indicates the current state. There are no currentSource
10712 * values for "check trigger", "rescan timelines", and "sleep" states,
10713 * those actions are taken when reading from the previous source fails, as
10714 * part of advancing to the next state.
10717 if (!InArchiveRecovery)
10718 currentSource = XLOG_FROM_PG_XLOG;
10719 else if (currentSource == 0)
10720 currentSource = XLOG_FROM_ARCHIVE;
10724 int oldSource = currentSource;
10727 * First check if we failed to read from the current source, and
10728 * advance the state machine if so. The failure to read might've
10729 * happened outside this function, e.g when a CRC check fails on a
10730 * record, or within this loop.
10732 if (lastSourceFailed)
10734 switch (currentSource)
10736 case XLOG_FROM_ARCHIVE:
10737 currentSource = XLOG_FROM_PG_XLOG;
10740 case XLOG_FROM_PG_XLOG:
10743 * Check to see if the trigger file exists. Note that we
10744 * do this only after failure, so when you create the
10745 * trigger file, we still finish replaying as much as we
10746 * can from archive and pg_xlog before failover.
10748 if (StandbyMode && CheckForStandbyTrigger())
10755 * Not in standby mode, and we've now tried the archive
10762 * If primary_conninfo is set, launch walreceiver to try
10763 * to stream the missing WAL.
10765 * If fetching_ckpt is TRUE, RecPtr points to the initial
10766 * checkpoint location. In that case, we use RedoStartLSN
10767 * as the streaming start position instead of RecPtr, so
10768 * that when we later jump backwards to start redo at
10769 * RedoStartLSN, we will have the logs streamed already.
10771 if (PrimaryConnInfo)
10778 ptr = RedoStartLSN;
10779 tli = ControlFile->checkPointCopy.ThisTimeLineID;
10784 tli = tliOfPointInHistory(tliRecPtr, expectedTLEs);
10786 if (curFileTLI > 0 && tli < curFileTLI)
10787 elog(ERROR, "according to history file, WAL location %X/%X belongs to timeline %u, but previous recovered WAL file came from timeline %u",
10788 (uint32) (ptr >> 32), (uint32) ptr,
10792 RequestXLogStreaming(tli, ptr, PrimaryConnInfo);
10797 * Move to XLOG_FROM_STREAM state in either case. We'll
10798 * get immediate failure if we didn't launch walreceiver,
10799 * and move on to the next state.
10801 currentSource = XLOG_FROM_STREAM;
10804 case XLOG_FROM_STREAM:
10807 * Failure while streaming. Most likely, we got here
10808 * because streaming replication was terminated, or
10809 * promotion was triggered. But we also get here if we
10810 * find an invalid record in the WAL streamed from master,
10811 * in which case something is seriously wrong. There's
10812 * little chance that the problem will just go away, but
10813 * PANIC is not good for availability either, especially
10814 * in hot standby mode. So, we treat that the same as
10815 * disconnection, and retry from archive/pg_xlog again.
10816 * The WAL in the archive should be identical to what was
10817 * streamed, so it's unlikely that it helps, but one can
10822 * Before we leave XLOG_FROM_STREAM state, make sure that
10823 * walreceiver is not active, so that it won't overwrite
10824 * WAL that we restore from archive.
10826 if (WalRcvStreaming())
10830 * Before we sleep, re-scan for possible new timelines if
10831 * we were requested to recover to the latest timeline.
10833 if (recoveryTargetIsLatest)
10835 if (rescanLatestTimeLine())
10837 currentSource = XLOG_FROM_ARCHIVE;
10843 * XLOG_FROM_STREAM is the last state in our state
10844 * machine, so we've exhausted all the options for
10845 * obtaining the requested WAL. We're going to loop back
10846 * and retry from the archive, but if it hasn't been long
10847 * since last attempt, sleep 5 seconds to avoid
10850 now = (pg_time_t) time(NULL);
10851 if ((now - last_fail_time) < 5)
10853 pg_usleep(1000000L * (5 - (now - last_fail_time)));
10854 now = (pg_time_t) time(NULL);
10856 last_fail_time = now;
10857 currentSource = XLOG_FROM_ARCHIVE;
10861 elog(ERROR, "unexpected WAL source %d", currentSource);
10864 else if (currentSource == XLOG_FROM_PG_XLOG)
10867 * We just successfully read a file in pg_xlog. We prefer files in
10868 * the archive over ones in pg_xlog, so try the next file again
10869 * from the archive first.
10871 if (InArchiveRecovery)
10872 currentSource = XLOG_FROM_ARCHIVE;
10875 if (currentSource != oldSource)
10876 elog(DEBUG2, "switched WAL source from %s to %s after %s",
10877 xlogSourceNames[oldSource], xlogSourceNames[currentSource],
10878 lastSourceFailed ? "failure" : "success");
10881 * We've now handled possible failure. Try to read from the chosen
10884 lastSourceFailed = false;
10886 switch (currentSource)
10888 case XLOG_FROM_ARCHIVE:
10889 case XLOG_FROM_PG_XLOG:
10890 /* Close any old file we might have open. */
10896 /* Reset curFileTLI if random fetch. */
10901 * Try to restore the file from archive, or read an existing
10902 * file from pg_xlog.
10904 readFile = XLogFileReadAnyTLI(readSegNo, DEBUG2, currentSource);
10906 return true; /* success! */
10909 * Nope, not found in archive or pg_xlog.
10911 lastSourceFailed = true;
10914 case XLOG_FROM_STREAM:
10919 * Check if WAL receiver is still active.
10921 if (!WalRcvStreaming())
10923 lastSourceFailed = true;
10928 * Walreceiver is active, so see if new data has arrived.
10930 * We only advance XLogReceiptTime when we obtain fresh
10931 * WAL from walreceiver and observe that we had already
10932 * processed everything before the most recent "chunk"
10933 * that it flushed to disk. In steady state where we are
10934 * keeping up with the incoming data, XLogReceiptTime will
10935 * be updated on each cycle. When we are behind,
10936 * XLogReceiptTime will not advance, so the grace time
10937 * allotted to conflicting queries will decrease.
10939 if (RecPtr < receivedUpto)
10943 XLogRecPtr latestChunkStart;
10945 receivedUpto = GetWalRcvWriteRecPtr(&latestChunkStart, &receiveTLI);
10946 if (RecPtr < receivedUpto && receiveTLI == curFileTLI)
10949 if (latestChunkStart <= RecPtr)
10951 XLogReceiptTime = GetCurrentTimestamp();
10952 SetCurrentChunkStartTime(XLogReceiptTime);
10961 * Great, streamed far enough. Open the file if it's
10962 * not open already. Also read the timeline history
10963 * file if we haven't initialized timeline history
10964 * yet; it should be streamed over and present in
10965 * pg_xlog by now. Use XLOG_FROM_STREAM so that
10966 * source info is set correctly and XLogReceiptTime
10972 expectedTLEs = readTimeLineHistory(receiveTLI);
10973 readFile = XLogFileRead(readSegNo, PANIC,
10975 XLOG_FROM_STREAM, false);
10976 Assert(readFile >= 0);
10980 /* just make sure source info is correct... */
10981 readSource = XLOG_FROM_STREAM;
10982 XLogReceiptSource = XLOG_FROM_STREAM;
10989 * Data not here yet. Check for trigger, then wait for
10990 * walreceiver to wake us up when new WAL arrives.
10992 if (CheckForStandbyTrigger())
10995 * Note that we don't "return false" immediately here.
10996 * After being triggered, we still want to replay all
10997 * the WAL that was already streamed. It's in pg_xlog
10998 * now, so we just treat this as a failure, and the
10999 * state machine will move on to replay the streamed
11000 * WAL from pg_xlog, and then recheck the trigger and
11003 lastSourceFailed = true;
11008 * Wait for more WAL to arrive. Time out after 5 seconds,
11009 * like when polling the archive, to react to a trigger
11012 WaitLatch(&XLogCtl->recoveryWakeupLatch,
11013 WL_LATCH_SET | WL_TIMEOUT,
11015 ResetLatch(&XLogCtl->recoveryWakeupLatch);
11020 elog(ERROR, "unexpected WAL source %d", currentSource);
11024 * This possibly-long loop needs to handle interrupts of startup
11027 HandleStartupProcInterrupts();
11028 } while (StandbyMode);
11034 * Determine what log level should be used to report a corrupt WAL record
11035 * in the current WAL page, previously read by XLogPageRead().
11037 * 'emode' is the error mode that would be used to report a file-not-found
11038 * or legitimate end-of-WAL situation. Generally, we use it as-is, but if
11039 * we're retrying the exact same record that we've tried previously, only
11040 * complain the first time to keep the noise down. However, we only do when
11041 * reading from pg_xlog, because we don't expect any invalid records in archive
11042 * or in records streamed from master. Files in the archive should be complete,
11043 * and we should never hit the end of WAL because we stop and wait for more WAL
11044 * to arrive before replaying it.
11046 * NOTE: This function remembers the RecPtr value it was last called with,
11047 * to suppress repeated messages about the same record. Only call this when
11048 * you are about to ereport(), or you might cause a later message to be
11049 * erroneously suppressed.
11052 emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
11054 static XLogRecPtr lastComplaint = 0;
11056 if (readSource == XLOG_FROM_PG_XLOG && emode == LOG)
11058 if (RecPtr == lastComplaint)
11061 lastComplaint = RecPtr;
11067 * Check to see whether the user-specified trigger file exists and whether a
11068 * promote request has arrived. If either condition holds, return true.
11071 CheckForStandbyTrigger(void)
11073 struct stat stat_buf;
11074 static bool triggered = false;
11079 if (IsPromoteTriggered())
11082 * In 9.1 and 9.2 the postmaster unlinked the promote file inside the
11083 * signal handler. We now leave the file in place and let the Startup
11084 * process do the unlink. This allows Startup to know whether we're
11085 * doing fast or normal promotion. Fast promotion takes precedence.
11087 if (stat(FAST_PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
11089 unlink(FAST_PROMOTE_SIGNAL_FILE);
11090 unlink(PROMOTE_SIGNAL_FILE);
11091 fast_promote = true;
11093 else if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
11095 unlink(PROMOTE_SIGNAL_FILE);
11096 fast_promote = false;
11099 ereport(LOG, (errmsg("received promote request")));
11101 ResetPromoteTriggered();
11106 if (TriggerFile == NULL)
11109 if (stat(TriggerFile, &stat_buf) == 0)
11112 (errmsg("trigger file found: %s", TriggerFile)));
11113 unlink(TriggerFile);
11115 fast_promote = true;
11122 * Check to see if a promote request has arrived. Should be
11123 * called by postmaster after receiving SIGUSR1.
11126 CheckPromoteSignal(void)
11128 struct stat stat_buf;
11130 if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0 ||
11131 stat(FAST_PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
11138 * Wake up startup process to replay newly arrived WAL, or to notice that
11139 * failover has been requested.
11142 WakeupRecovery(void)
11144 SetLatch(&XLogCtl->recoveryWakeupLatch);
11148 * Update the WalWriterSleeping flag.
11151 SetWalWriterSleeping(bool sleeping)
11153 /* use volatile pointer to prevent code rearrangement */
11154 volatile XLogCtlData *xlogctl = XLogCtl;
11156 SpinLockAcquire(&xlogctl->info_lck);
11157 xlogctl->WalWriterSleeping = sleeping;
11158 SpinLockRelease(&xlogctl->info_lck);