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 FALLBACK_PROMOTE_SIGNAL_FILE "fallback_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 value. However, if we are already at the beginning of the current
1326 * segment, *StartPos and *EndPos 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. There is no cleanup
1579 * mechanism to release the slot if the backend dies while holding one,
1580 * so make this a critical section.
1582 START_CRIT_SECTION();
1585 * Loop here to try to acquire slot after each time we are signaled by
1586 * WALInsertSlotRelease.
1592 slot = &XLogCtl->Insert.insertSlots[MySlotNo].slot;
1594 /* Acquire mutex. Time spent holding mutex should be short! */
1595 SpinLockAcquire(&slot->mutex);
1597 /* If retrying, allow WALInsertSlotRelease to release waiters again */
1599 slot->releaseOK = true;
1601 /* If I can get the slot, do so quickly. */
1602 if (slot->exclusive == 0)
1611 break; /* got the lock */
1613 Assert(slot->owner != MyProc);
1616 * Add myself to wait queue.
1618 proc->lwWaiting = true;
1619 proc->lwWaitMode = LW_EXCLUSIVE;
1620 proc->lwWaitLink = NULL;
1621 if (slot->head == NULL)
1624 slot->tail->lwWaitLink = proc;
1627 /* Can release the mutex now */
1628 SpinLockRelease(&slot->mutex);
1631 * Wait until awakened.
1633 * Since we share the process wait semaphore with the regular lock
1634 * manager and ProcWaitForSignal, and we may need to acquire a slot
1635 * while one of those is pending, it is possible that we get awakened
1636 * for a reason other than being signaled by WALInsertSlotRelease. If
1637 * so, loop back and wait again. Once we've gotten the slot,
1638 * re-increment the sema by the number of additional signals received,
1639 * so that the lock manager or signal manager will see the received
1640 * signal when it next waits.
1644 /* "false" means cannot accept cancel/die interrupt here. */
1645 PGSemaphoreLock(&proc->sem, false);
1646 if (!proc->lwWaiting)
1651 /* Now loop back and try to acquire lock again. */
1658 * Normally, we initialize the xlogInsertingAt value of the slot to 1,
1659 * because we don't yet know where in the WAL we're going to insert. It's
1660 * not critical what it points to right now - leaving it to a too small
1661 * value just means that WaitXlogInsertionsToFinish() might wait on us
1662 * unnecessarily, until we update the value (when we finish the insert or
1663 * move to next page).
1665 * If we're grabbing all the slots, however, stamp all but the last one
1666 * with InvalidXLogRecPtr, meaning there is no insert in progress. The last
1667 * slot is the one that we will update as we proceed with the insert, the
1668 * rest are held just to keep off other inserters.
1670 if (slotno != -1 && slotno != num_xloginsert_slots - 1)
1671 slot->xlogInsertingAt = InvalidXLogRecPtr;
1673 slot->xlogInsertingAt = 1;
1675 /* We are done updating shared state of the slot itself. */
1676 SpinLockRelease(&slot->mutex);
1679 * Fix the process wait semaphore's count for any absorbed wakeups.
1681 while (extraWaits-- > 0)
1682 PGSemaphoreUnlock(&proc->sem);
1685 * If we couldn't get the slot immediately, try another slot next time.
1686 * On a system with more insertion slots than concurrent inserters, this
1687 * causes all the inserters to eventually migrate to a slot that no-one
1688 * else is using. On a system with more inserters than slots, it still
1689 * causes the inserters to be distributed quite evenly across the slots.
1691 if (slotno != -1 && retry)
1692 slotToTry = (slotToTry + 1) % num_xloginsert_slots;
1696 * Wait for the given slot to become free, or for its xlogInsertingAt location
1697 * to change to something else than 'waitptr'. In other words, wait for the
1698 * inserter using the given slot to finish its insertion, or to at least make
1702 WaitOnSlot(volatile XLogInsertSlot *slot, XLogRecPtr waitptr)
1704 PGPROC *proc = MyProc;
1708 * Lock out cancel/die interrupts while we sleep on the slot. There is
1709 * no cleanup mechanism to remove us from the wait queue if we got
1715 * Loop here to try to acquire lock after each time we are signaled.
1721 /* Acquire mutex. Time spent holding mutex should be short! */
1722 SpinLockAcquire(&slot->mutex);
1724 /* If I can get the lock, do so quickly. */
1725 if (slot->exclusive == 0 || slot->xlogInsertingAt != waitptr)
1731 break; /* the lock was free */
1733 Assert(slot->owner != MyProc);
1736 * Add myself to wait queue.
1738 proc->lwWaiting = true;
1739 proc->lwWaitMode = LW_WAIT_UNTIL_FREE;
1740 proc->lwWaitLink = NULL;
1742 /* waiters are added to the front of the queue */
1743 proc->lwWaitLink = slot->head;
1744 if (slot->head == NULL)
1748 /* Can release the mutex now */
1749 SpinLockRelease(&slot->mutex);
1752 * Wait until awakened.
1754 * Since we share the process wait semaphore with other things, like
1755 * the regular lock manager and ProcWaitForSignal, and we may need to
1756 * acquire an LWLock while one of those is pending, it is possible that
1757 * we get awakened for a reason other than being signaled by
1758 * LWLockRelease. If so, loop back and wait again. Once we've gotten
1759 * the LWLock, re-increment the sema by the number of additional
1760 * signals received, so that the lock manager or signal manager will
1761 * see the received signal when it next waits.
1765 /* "false" means cannot accept cancel/die interrupt here. */
1766 PGSemaphoreLock(&proc->sem, false);
1767 if (!proc->lwWaiting)
1772 /* Now loop back and try to acquire lock again. */
1775 /* We are done updating shared state of the lock itself. */
1776 SpinLockRelease(&slot->mutex);
1779 * Fix the process wait semaphore's count for any absorbed wakeups.
1781 while (extraWaits-- > 0)
1782 PGSemaphoreUnlock(&proc->sem);
1785 * Now okay to allow cancel/die interrupts.
1787 RESUME_INTERRUPTS();
1791 * Wake up all processes waiting for us with WaitOnSlot(). Sets our
1792 * xlogInsertingAt value to EndPos, without releasing the slot.
1795 WakeupWaiters(XLogRecPtr EndPos)
1797 volatile XLogInsertSlot *slot = &XLogCtl->Insert.insertSlots[MySlotNo].slot;
1803 * If we have already reported progress up to the same point, do nothing.
1804 * No other process can modify xlogInsertingAt, so we can check this before
1805 * grabbing the spinlock.
1807 if (slot->xlogInsertingAt == EndPos)
1809 /* xlogInsertingAt should not go backwards */
1810 Assert(slot->xlogInsertingAt < EndPos);
1812 /* Acquire mutex. Time spent holding mutex should be short! */
1813 SpinLockAcquire(&slot->mutex);
1815 /* we should own the slot */
1816 Assert(slot->exclusive == 1 && slot->owner == MyProc);
1818 slot->xlogInsertingAt = EndPos;
1821 * See if there are any waiters that need to be woken up.
1829 /* LW_WAIT_UNTIL_FREE waiters are always in the front of the queue */
1830 next = proc->lwWaitLink;
1831 while (next && next->lwWaitMode == LW_WAIT_UNTIL_FREE)
1834 next = next->lwWaitLink;
1837 /* proc is now the last PGPROC to be released */
1839 proc->lwWaitLink = NULL;
1842 /* We are done updating shared state of the lock itself. */
1843 SpinLockRelease(&slot->mutex);
1846 * Awaken any waiters I removed from the queue.
1848 while (head != NULL)
1851 head = proc->lwWaitLink;
1852 proc->lwWaitLink = NULL;
1853 proc->lwWaiting = false;
1854 PGSemaphoreUnlock(&proc->sem);
1859 * Release our insertion slot (or slots, if we're holding them all).
1862 WALInsertSlotRelease(void)
1866 if (holdingAllSlots)
1868 for (i = 0; i < num_xloginsert_slots; i++)
1869 WALInsertSlotReleaseOne(i);
1870 holdingAllSlots = false;
1873 WALInsertSlotReleaseOne(MySlotNo);
1877 WALInsertSlotReleaseOne(int slotno)
1879 volatile XLogInsertSlot *slot = &XLogCtl->Insert.insertSlots[slotno].slot;
1883 /* Acquire mutex. Time spent holding mutex should be short! */
1884 SpinLockAcquire(&slot->mutex);
1886 /* we must be holding it */
1887 Assert(slot->exclusive == 1 && slot->owner == MyProc);
1889 slot->xlogInsertingAt = InvalidXLogRecPtr;
1891 /* Release my hold on the slot */
1892 slot->exclusive = 0;
1896 * See if I need to awaken any waiters..
1901 if (slot->releaseOK)
1904 * Remove the to-be-awakened PGPROCs from the queue.
1906 bool releaseOK = true;
1911 * First wake up any backends that want to be woken up without
1912 * acquiring the lock. These are always in the front of the queue.
1914 while (proc->lwWaitMode == LW_WAIT_UNTIL_FREE && proc->lwWaitLink)
1915 proc = proc->lwWaitLink;
1918 * Awaken the first exclusive-waiter, if any.
1920 if (proc->lwWaitLink)
1922 Assert(proc->lwWaitLink->lwWaitMode == LW_EXCLUSIVE);
1923 proc = proc->lwWaitLink;
1926 /* proc is now the last PGPROC to be released */
1927 slot->head = proc->lwWaitLink;
1928 proc->lwWaitLink = NULL;
1930 slot->releaseOK = releaseOK;
1936 /* We are done updating shared state of the slot itself. */
1937 SpinLockRelease(&slot->mutex);
1940 * Awaken any waiters I removed from the queue.
1942 while (head != NULL)
1945 head = proc->lwWaitLink;
1946 proc->lwWaitLink = NULL;
1947 proc->lwWaiting = false;
1948 PGSemaphoreUnlock(&proc->sem);
1952 * Now okay to allow cancel/die interrupts.
1959 * Wait for any WAL insertions < upto to finish.
1961 * Returns the location of the oldest insertion that is still in-progress.
1962 * Any WAL prior to that point has been fully copied into WAL buffers, and
1963 * can be flushed out to disk. Because this waits for any insertions older
1964 * than 'upto' to finish, the return value is always >= 'upto'.
1966 * Note: When you are about to write out WAL, you must call this function
1967 * *before* acquiring WALWriteLock, to avoid deadlocks. This function might
1968 * need to wait for an insertion to finish (or at least advance to next
1969 * uninitialized page), and the inserter might need to evict an old WAL buffer
1970 * to make room for a new one, which in turn requires WALWriteLock.
1973 WaitXLogInsertionsToFinish(XLogRecPtr upto)
1976 XLogRecPtr reservedUpto;
1977 XLogRecPtr finishedUpto;
1978 volatile XLogCtlInsert *Insert = &XLogCtl->Insert;
1982 elog(PANIC, "cannot wait without a PGPROC structure");
1984 /* Read the current insert position */
1985 SpinLockAcquire(&Insert->insertpos_lck);
1986 bytepos = Insert->CurrBytePos;
1987 SpinLockRelease(&Insert->insertpos_lck);
1988 reservedUpto = XLogBytePosToEndRecPtr(bytepos);
1991 * No-one should request to flush a piece of WAL that hasn't even been
1992 * reserved yet. However, it can happen if there is a block with a bogus
1993 * LSN on disk, for example. XLogFlush checks for that situation and
1994 * complains, but only after the flush. Here we just assume that to mean
1995 * that all WAL that has been reserved needs to be finished. In this
1996 * corner-case, the return value can be smaller than 'upto' argument.
1998 if (upto > reservedUpto)
2000 elog(LOG, "request to flush past end of generated WAL; request %X/%X, currpos %X/%X",
2001 (uint32) (upto >> 32), (uint32) upto,
2002 (uint32) (reservedUpto >> 32), (uint32) reservedUpto);
2003 upto = reservedUpto;
2007 * finishedUpto is our return value, indicating the point upto which
2008 * all the WAL insertions have been finished. Initialize it to the head
2009 * of reserved WAL, and as we iterate through the insertion slots, back it
2010 * out for any insertion that's still in progress.
2012 finishedUpto = reservedUpto;
2015 * Loop through all the slots, sleeping on any in-progress insert older
2018 for (i = 0; i < num_xloginsert_slots; i++)
2020 volatile XLogInsertSlot *slot = &XLogCtl->Insert.insertSlots[i].slot;
2021 XLogRecPtr insertingat;
2025 * We can check if the slot is in use without grabbing the spinlock.
2026 * The spinlock acquisition of insertpos_lck before this loop acts
2027 * as a memory barrier. If someone acquires the slot after that, it
2028 * can't possibly be inserting to anything < reservedUpto. If it was
2029 * acquired before that, an unlocked test will return true.
2031 if (!slot->exclusive)
2034 SpinLockAcquire(&slot->mutex);
2035 /* re-check now that we have the lock */
2036 if (!slot->exclusive)
2038 SpinLockRelease(&slot->mutex);
2041 insertingat = slot->xlogInsertingAt;
2042 SpinLockRelease(&slot->mutex);
2044 if (insertingat == InvalidXLogRecPtr)
2047 * slot is reserved just to hold off other inserters, there is no
2048 * actual insert in progress.
2054 * This insertion is still in progress. Do we need to wait for it?
2056 * When an inserter acquires a slot, it doesn't reset 'insertingat', so
2057 * it will initially point to the old value of some already-finished
2058 * insertion. The inserter will update the value as soon as it finishes
2059 * the insertion, moves to the next page, or has to do I/O to flush an
2060 * old dirty buffer. That means that when we see a slot with
2061 * insertingat value < upto, we don't know if that insertion is still
2062 * truly in progress, or if the slot is reused by a new inserter that
2063 * hasn't updated the insertingat value yet. We have to assume it's the
2066 if (insertingat < upto)
2068 WaitOnSlot(slot, insertingat);
2074 * We don't need to wait for this insertion, but update the
2077 if (insertingat < finishedUpto)
2078 finishedUpto = insertingat;
2081 return finishedUpto;
2085 * Get a pointer to the right location in the WAL buffer containing the
2088 * If the page is not initialized yet, it is initialized. That might require
2089 * evicting an old dirty buffer from the buffer cache, which means I/O.
2091 * The caller must ensure that the page containing the requested location
2092 * isn't evicted yet, and won't be evicted. The way to ensure that is to
2093 * hold onto an XLogInsertSlot with the xlogInsertingAt position set to
2094 * something <= ptr. GetXLogBuffer() will update xlogInsertingAt if it needs
2095 * to evict an old page from the buffer. (This means that once you call
2096 * GetXLogBuffer() with a given 'ptr', you must not access anything before
2097 * that point anymore, and must not call GetXLogBuffer() with an older 'ptr'
2098 * later, because older buffers might be recycled already)
2101 GetXLogBuffer(XLogRecPtr ptr)
2105 static uint64 cachedPage = 0;
2106 static char *cachedPos = NULL;
2107 XLogRecPtr expectedEndPtr;
2110 * Fast path for the common case that we need to access again the same
2111 * page as last time.
2113 if (ptr / XLOG_BLCKSZ == cachedPage)
2115 Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
2116 Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
2117 return cachedPos + ptr % XLOG_BLCKSZ;
2121 * The XLog buffer cache is organized so that a page is always loaded
2122 * to a particular buffer. That way we can easily calculate the buffer
2123 * a given page must be loaded into, from the XLogRecPtr alone.
2125 idx = XLogRecPtrToBufIdx(ptr);
2128 * See what page is loaded in the buffer at the moment. It could be the
2129 * page we're looking for, or something older. It can't be anything newer
2130 * - that would imply the page we're looking for has already been written
2131 * out to disk and evicted, and the caller is responsible for making sure
2132 * that doesn't happen.
2134 * However, we don't hold a lock while we read the value. If someone has
2135 * just initialized the page, it's possible that we get a "torn read" of
2136 * the XLogRecPtr if 64-bit fetches are not atomic on this platform. In
2137 * that case we will see a bogus value. That's ok, we'll grab the mapping
2138 * lock (in AdvanceXLInsertBuffer) and retry if we see anything else than
2139 * the page we're looking for. But it means that when we do this unlocked
2140 * read, we might see a value that appears to be ahead of the page we're
2141 * looking for. Don't PANIC on that, until we've verified the value while
2144 expectedEndPtr = ptr;
2145 expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
2147 endptr = XLogCtl->xlblocks[idx];
2148 if (expectedEndPtr != endptr)
2151 * Let others know that we're finished inserting the record up
2152 * to the page boundary.
2154 WakeupWaiters(expectedEndPtr - XLOG_BLCKSZ);
2156 AdvanceXLInsertBuffer(ptr, false);
2157 endptr = XLogCtl->xlblocks[idx];
2159 if (expectedEndPtr != endptr)
2160 elog(PANIC, "could not find WAL buffer for %X/%X",
2161 (uint32) (ptr >> 32) , (uint32) ptr);
2166 * Make sure the initialization of the page is visible to us, and
2167 * won't arrive later to overwrite the WAL data we write on the page.
2169 pg_memory_barrier();
2173 * Found the buffer holding this page. Return a pointer to the right
2174 * offset within the page.
2176 cachedPage = ptr / XLOG_BLCKSZ;
2177 cachedPos = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
2179 Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
2180 Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
2182 return cachedPos + ptr % XLOG_BLCKSZ;
2186 * Converts a "usable byte position" to XLogRecPtr. A usable byte position
2187 * is the position starting from the beginning of WAL, excluding all WAL
2191 XLogBytePosToRecPtr(uint64 bytepos)
2199 fullsegs = bytepos / UsableBytesInSegment;
2200 bytesleft = bytepos % UsableBytesInSegment;
2202 if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
2204 /* fits on first page of segment */
2205 seg_offset = bytesleft + SizeOfXLogLongPHD;
2209 /* account for the first page on segment with long header */
2210 seg_offset = XLOG_BLCKSZ;
2211 bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2213 fullpages = bytesleft / UsableBytesInPage;
2214 bytesleft = bytesleft % UsableBytesInPage;
2216 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2219 XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, result);
2225 * Like XLogBytePosToRecPtr, but if the position is at a page boundary,
2226 * returns a pointer to the beginning of the page (ie. before page header),
2227 * not to where the first xlog record on that page would go to. This is used
2228 * when converting a pointer to the end of a record.
2231 XLogBytePosToEndRecPtr(uint64 bytepos)
2239 fullsegs = bytepos / UsableBytesInSegment;
2240 bytesleft = bytepos % UsableBytesInSegment;
2242 if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
2244 /* fits on first page of segment */
2248 seg_offset = bytesleft + SizeOfXLogLongPHD;
2252 /* account for the first page on segment with long header */
2253 seg_offset = XLOG_BLCKSZ;
2254 bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2256 fullpages = bytesleft / UsableBytesInPage;
2257 bytesleft = bytesleft % UsableBytesInPage;
2260 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
2262 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2265 XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, result);
2271 * Convert an XLogRecPtr to a "usable byte position".
2274 XLogRecPtrToBytePos(XLogRecPtr ptr)
2281 XLByteToSeg(ptr, fullsegs);
2283 fullpages = (ptr % XLOG_SEG_SIZE) / XLOG_BLCKSZ;
2284 offset = ptr % XLOG_BLCKSZ;
2288 result = fullsegs * UsableBytesInSegment;
2291 Assert(offset >= SizeOfXLogLongPHD);
2292 result += offset - SizeOfXLogLongPHD;
2297 result = fullsegs * UsableBytesInSegment +
2298 (XLOG_BLCKSZ - SizeOfXLogLongPHD) + /* account for first page */
2299 (fullpages - 1) * UsableBytesInPage; /* full pages */
2302 Assert(offset >= SizeOfXLogShortPHD);
2303 result += offset - SizeOfXLogShortPHD;
2311 * Determine whether the buffer referenced by an XLogRecData item has to
2312 * be backed up, and if so fill a BkpBlock struct for it. In any case
2313 * save the buffer's LSN at *lsn.
2316 XLogCheckBuffer(XLogRecData *rdata, bool holdsExclusiveLock,
2317 XLogRecPtr *lsn, BkpBlock *bkpb)
2321 page = BufferGetPage(rdata->buffer);
2324 * We assume page LSN is first data on *every* page that can be passed to
2325 * XLogInsert, whether it has the standard page layout or not. We don't
2326 * need to take the buffer header lock for PageGetLSN if we hold an
2327 * exclusive lock on the page and/or the relation.
2329 if (holdsExclusiveLock)
2330 *lsn = PageGetLSN(page);
2332 *lsn = BufferGetLSNAtomic(rdata->buffer);
2334 if (*lsn <= RedoRecPtr)
2337 * The page needs to be backed up, so set up *bkpb
2339 BufferGetTag(rdata->buffer, &bkpb->node, &bkpb->fork, &bkpb->block);
2341 if (rdata->buffer_std)
2343 /* Assume we can omit data between pd_lower and pd_upper */
2344 uint16 lower = ((PageHeader) page)->pd_lower;
2345 uint16 upper = ((PageHeader) page)->pd_upper;
2347 if (lower >= SizeOfPageHeaderData &&
2351 bkpb->hole_offset = lower;
2352 bkpb->hole_length = upper - lower;
2356 /* No "hole" to compress out */
2357 bkpb->hole_offset = 0;
2358 bkpb->hole_length = 0;
2363 /* Not a standard page header, don't try to eliminate "hole" */
2364 bkpb->hole_offset = 0;
2365 bkpb->hole_length = 0;
2368 return true; /* buffer requires backup */
2371 return false; /* buffer does not need to be backed up */
2375 * Initialize XLOG buffers, writing out old buffers if they still contain
2376 * unwritten data, upto the page containing 'upto'. Or if 'opportunistic' is
2377 * true, initialize as many pages as we can without having to write out
2378 * unwritten data. Any new pages are initialized to zeros, with pages headers
2379 * initialized properly.
2382 AdvanceXLInsertBuffer(XLogRecPtr upto, bool opportunistic)
2384 XLogCtlInsert *Insert = &XLogCtl->Insert;
2386 XLogRecPtr OldPageRqstPtr;
2387 XLogwrtRqst WriteRqst;
2388 XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
2389 XLogRecPtr NewPageBeginPtr;
2390 XLogPageHeader NewPage;
2393 LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2396 * Now that we have the lock, check if someone initialized the page
2399 while (upto >= XLogCtl->InitializedUpTo || opportunistic)
2401 nextidx = XLogRecPtrToBufIdx(XLogCtl->InitializedUpTo);
2404 * Get ending-offset of the buffer page we need to replace (this may
2405 * be zero if the buffer hasn't been used yet). Fall through if it's
2406 * already written out.
2408 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
2409 if (LogwrtResult.Write < OldPageRqstPtr)
2412 * Nope, got work to do. If we just want to pre-initialize as much
2413 * as we can without flushing, give up now.
2418 /* Before waiting, get info_lck and update LogwrtResult */
2420 /* use volatile pointer to prevent code rearrangement */
2421 volatile XLogCtlData *xlogctl = XLogCtl;
2423 SpinLockAcquire(&xlogctl->info_lck);
2424 if (xlogctl->LogwrtRqst.Write < OldPageRqstPtr)
2425 xlogctl->LogwrtRqst.Write = OldPageRqstPtr;
2426 LogwrtResult = xlogctl->LogwrtResult;
2427 SpinLockRelease(&xlogctl->info_lck);
2431 * Now that we have an up-to-date LogwrtResult value, see if we
2432 * still need to write it or if someone else already did.
2434 if (LogwrtResult.Write < OldPageRqstPtr)
2437 * Must acquire write lock. Release WALBufMappingLock first,
2438 * to make sure that all insertions that we need to wait for
2439 * can finish (up to this same position). Otherwise we risk
2442 LWLockRelease(WALBufMappingLock);
2444 WaitXLogInsertionsToFinish(OldPageRqstPtr);
2446 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2448 LogwrtResult = XLogCtl->LogwrtResult;
2449 if (LogwrtResult.Write >= OldPageRqstPtr)
2451 /* OK, someone wrote it already */
2452 LWLockRelease(WALWriteLock);
2456 /* Have to write it ourselves */
2457 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2458 WriteRqst.Write = OldPageRqstPtr;
2459 WriteRqst.Flush = 0;
2460 XLogWrite(WriteRqst, false);
2461 LWLockRelease(WALWriteLock);
2462 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
2464 /* Re-acquire WALBufMappingLock and retry */
2465 LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2471 * Now the next buffer slot is free and we can set it up to be the next
2474 NewPageBeginPtr = XLogCtl->InitializedUpTo;
2475 NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2477 Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
2479 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
2482 * Be sure to re-zero the buffer so that bytes beyond what we've
2483 * written will look like zeroes and not valid XLOG records...
2485 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
2488 * Fill the new page's header
2490 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
2492 /* NewPage->xlp_info = 0; */ /* done by memset */
2493 NewPage ->xlp_tli = ThisTimeLineID;
2494 NewPage ->xlp_pageaddr = NewPageBeginPtr;
2495 /* NewPage->xlp_rem_len = 0; */ /* done by memset */
2498 * If online backup is not in progress, mark the header to indicate
2499 * that* WAL records beginning in this page have removable backup
2500 * blocks. This allows the WAL archiver to know whether it is safe to
2501 * compress archived WAL data by transforming full-block records into
2502 * the non-full-block format. It is sufficient to record this at the
2503 * page level because we force a page switch (in fact a segment switch)
2504 * when starting a backup, so the flag will be off before any records
2505 * can be written during the backup. At the end of a backup, the last
2506 * page will be marked as all unsafe when perhaps only part is unsafe,
2507 * but at worst the archiver would miss the opportunity to compress a
2510 if (!Insert->forcePageWrites)
2511 NewPage ->xlp_info |= XLP_BKP_REMOVABLE;
2514 * If first page of an XLOG segment file, make it a long header.
2516 if ((NewPage->xlp_pageaddr % XLogSegSize) == 0)
2518 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
2520 NewLongPage->xlp_sysid = ControlFile->system_identifier;
2521 NewLongPage->xlp_seg_size = XLogSegSize;
2522 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
2523 NewPage ->xlp_info |= XLP_LONG_HEADER;
2527 * Make sure the initialization of the page becomes visible to others
2528 * before the xlblocks update. GetXLogBuffer() reads xlblocks without
2533 *((volatile XLogRecPtr *) &XLogCtl->xlblocks[nextidx]) = NewPageEndPtr;
2535 XLogCtl->InitializedUpTo = NewPageEndPtr;
2539 LWLockRelease(WALBufMappingLock);
2544 elog(DEBUG1, "initialized %d pages, upto %X/%X",
2545 npages, (uint32) (NewPageEndPtr >> 32), (uint32) NewPageEndPtr);
2551 * Check whether we've consumed enough xlog space that a checkpoint is needed.
2553 * new_segno indicates a log file that has just been filled up (or read
2554 * during recovery). We measure the distance from RedoRecPtr to new_segno
2555 * and see if that exceeds CheckPointSegments.
2557 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
2560 XLogCheckpointNeeded(XLogSegNo new_segno)
2562 XLogSegNo old_segno;
2564 XLByteToSeg(RedoRecPtr, old_segno);
2566 if (new_segno >= old_segno + (uint64) (CheckPointSegments - 1))
2572 * Write and/or fsync the log at least as far as WriteRqst indicates.
2574 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
2575 * may stop at any convenient boundary (such as a cache or logfile boundary).
2576 * This option allows us to avoid uselessly issuing multiple writes when a
2577 * single one would do.
2579 * Must be called with WALWriteLock held. WaitXLogInsertionsToFinish(WriteRqst)
2580 * must be called before grabbing the lock, to make sure the data is ready to
2584 XLogWrite(XLogwrtRqst WriteRqst, bool flexible)
2587 bool last_iteration;
2595 /* We should always be inside a critical section here */
2596 Assert(CritSectionCount > 0);
2599 * Update local LogwrtResult (caller probably did this already, but...)
2601 LogwrtResult = XLogCtl->LogwrtResult;
2604 * Since successive pages in the xlog cache are consecutively allocated,
2605 * we can usually gather multiple pages together and issue just one
2606 * write() call. npages is the number of pages we have determined can be
2607 * written together; startidx is the cache block index of the first one,
2608 * and startoffset is the file offset at which it should go. The latter
2609 * two variables are only valid when npages > 0, but we must initialize
2610 * all of them to keep the compiler quiet.
2617 * Within the loop, curridx is the cache block index of the page to
2618 * consider writing. Begin at the buffer containing the next unwritten
2619 * page, or last partially written page.
2621 curridx = XLogRecPtrToBufIdx(LogwrtResult.Write);
2623 while (LogwrtResult.Write < WriteRqst.Write)
2626 * Make sure we're not ahead of the insert process. This could happen
2627 * if we're passed a bogus WriteRqst.Write that is past the end of the
2628 * last page that's been initialized by AdvanceXLInsertBuffer.
2630 XLogRecPtr EndPtr = XLogCtl->xlblocks[curridx];
2631 if (LogwrtResult.Write >= EndPtr)
2632 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
2633 (uint32) (LogwrtResult.Write >> 32),
2634 (uint32) LogwrtResult.Write,
2635 (uint32) (EndPtr >> 32), (uint32) EndPtr);
2637 /* Advance LogwrtResult.Write to end of current buffer page */
2638 LogwrtResult.Write = EndPtr;
2639 ispartialpage = WriteRqst.Write < LogwrtResult.Write;
2641 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo))
2644 * Switch to new logfile segment. We cannot have any pending
2645 * pages here (since we dump what we have at segment end).
2647 Assert(npages == 0);
2648 if (openLogFile >= 0)
2650 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo);
2652 /* create/use new log file */
2653 use_existent = true;
2654 openLogFile = XLogFileInit(openLogSegNo, &use_existent, true);
2658 /* Make sure we have the current logfile open */
2659 if (openLogFile < 0)
2661 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo);
2662 openLogFile = XLogFileOpen(openLogSegNo);
2666 /* Add current page to the set of pending pages-to-dump */
2669 /* first of group */
2671 startoffset = (LogwrtResult.Write - XLOG_BLCKSZ) % XLogSegSize;
2676 * Dump the set if this will be the last loop iteration, or if we are
2677 * at the last page of the cache area (since the next page won't be
2678 * contiguous in memory), or if we are at the end of the logfile
2681 last_iteration = WriteRqst.Write <= LogwrtResult.Write;
2683 finishing_seg = !ispartialpage &&
2684 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
2686 if (last_iteration ||
2687 curridx == XLogCtl->XLogCacheBlck ||
2695 /* Need to seek in the file? */
2696 if (openLogOff != startoffset)
2698 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
2700 (errcode_for_file_access(),
2701 errmsg("could not seek in log file %s to offset %u: %m",
2702 XLogFileNameP(ThisTimeLineID, openLogSegNo),
2704 openLogOff = startoffset;
2707 /* OK to write the page(s) */
2708 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
2709 nbytes = npages * (Size) XLOG_BLCKSZ;
2714 written = write(openLogFile, from, nleft);
2720 (errcode_for_file_access(),
2721 errmsg("could not write to log file %s "
2722 "at offset %u, length %lu: %m",
2723 XLogFileNameP(ThisTimeLineID, openLogSegNo),
2724 openLogOff, (unsigned long) nbytes)));
2728 } while (nleft > 0);
2730 /* Update state for write */
2731 openLogOff += nbytes;
2735 * If we just wrote the whole last page of a logfile segment,
2736 * fsync the segment immediately. This avoids having to go back
2737 * and re-open prior segments when an fsync request comes along
2738 * later. Doing it here ensures that one and only one backend will
2739 * perform this fsync.
2741 * This is also the right place to notify the Archiver that the
2742 * segment is ready to copy to archival storage, and to update the
2743 * timer for archive_timeout, and to signal for a checkpoint if
2744 * too many logfile segments have been used since the last
2749 issue_xlog_fsync(openLogFile, openLogSegNo);
2751 /* signal that we need to wakeup walsenders later */
2752 WalSndWakeupRequest();
2754 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
2756 if (XLogArchivingActive())
2757 XLogArchiveNotifySeg(openLogSegNo);
2759 XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
2762 * Request a checkpoint if we've consumed too much xlog since
2763 * the last one. For speed, we first check using the local
2764 * copy of RedoRecPtr, which might be out of date; if it looks
2765 * like a checkpoint is needed, forcibly update RedoRecPtr and
2768 if (IsUnderPostmaster && XLogCheckpointNeeded(openLogSegNo))
2770 (void) GetRedoRecPtr();
2771 if (XLogCheckpointNeeded(openLogSegNo))
2772 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
2779 /* Only asked to write a partial page */
2780 LogwrtResult.Write = WriteRqst.Write;
2783 curridx = NextBufIdx(curridx);
2785 /* If flexible, break out of loop as soon as we wrote something */
2786 if (flexible && npages == 0)
2790 Assert(npages == 0);
2793 * If asked to flush, do so
2795 if (LogwrtResult.Flush < WriteRqst.Flush &&
2796 LogwrtResult.Flush < LogwrtResult.Write)
2800 * Could get here without iterating above loop, in which case we might
2801 * have no open file or the wrong one. However, we do not need to
2802 * fsync more than one file.
2804 if (sync_method != SYNC_METHOD_OPEN &&
2805 sync_method != SYNC_METHOD_OPEN_DSYNC)
2807 if (openLogFile >= 0 &&
2808 !XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo))
2810 if (openLogFile < 0)
2812 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo);
2813 openLogFile = XLogFileOpen(openLogSegNo);
2817 issue_xlog_fsync(openLogFile, openLogSegNo);
2820 /* signal that we need to wakeup walsenders later */
2821 WalSndWakeupRequest();
2823 LogwrtResult.Flush = LogwrtResult.Write;
2827 * Update shared-memory status
2829 * We make sure that the shared 'request' values do not fall behind the
2830 * 'result' values. This is not absolutely essential, but it saves some
2831 * code in a couple of places.
2834 /* use volatile pointer to prevent code rearrangement */
2835 volatile XLogCtlData *xlogctl = XLogCtl;
2837 SpinLockAcquire(&xlogctl->info_lck);
2838 xlogctl->LogwrtResult = LogwrtResult;
2839 if (xlogctl->LogwrtRqst.Write < LogwrtResult.Write)
2840 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
2841 if (xlogctl->LogwrtRqst.Flush < LogwrtResult.Flush)
2842 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
2843 SpinLockRelease(&xlogctl->info_lck);
2848 * Record the LSN for an asynchronous transaction commit/abort
2849 * and nudge the WALWriter if there is work for it to do.
2850 * (This should not be called for synchronous commits.)
2853 XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
2855 XLogRecPtr WriteRqstPtr = asyncXactLSN;
2858 /* use volatile pointer to prevent code rearrangement */
2859 volatile XLogCtlData *xlogctl = XLogCtl;
2861 SpinLockAcquire(&xlogctl->info_lck);
2862 LogwrtResult = xlogctl->LogwrtResult;
2863 sleeping = xlogctl->WalWriterSleeping;
2864 if (xlogctl->asyncXactLSN < asyncXactLSN)
2865 xlogctl->asyncXactLSN = asyncXactLSN;
2866 SpinLockRelease(&xlogctl->info_lck);
2869 * If the WALWriter is sleeping, we should kick it to make it come out of
2870 * low-power mode. Otherwise, determine whether there's a full page of
2871 * WAL available to write.
2875 /* back off to last completed page boundary */
2876 WriteRqstPtr -= WriteRqstPtr % XLOG_BLCKSZ;
2878 /* if we have already flushed that far, we're done */
2879 if (WriteRqstPtr <= LogwrtResult.Flush)
2884 * Nudge the WALWriter: it has a full page of WAL to write, or we want it
2885 * to come out of low-power mode so that this async commit will reach disk
2886 * within the expected amount of time.
2888 if (ProcGlobal->walwriterLatch)
2889 SetLatch(ProcGlobal->walwriterLatch);
2893 * Advance minRecoveryPoint in control file.
2895 * If we crash during recovery, we must reach this point again before the
2896 * database is consistent.
2898 * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
2899 * is only updated if it's not already greater than or equal to 'lsn'.
2902 UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
2904 /* Quick check using our local copy of the variable */
2905 if (!updateMinRecoveryPoint || (!force && lsn <= minRecoveryPoint))
2908 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2910 /* update local copy */
2911 minRecoveryPoint = ControlFile->minRecoveryPoint;
2912 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
2915 * An invalid minRecoveryPoint means that we need to recover all the WAL,
2916 * i.e., we're doing crash recovery. We never modify the control file's
2917 * value in that case, so we can short-circuit future checks here too.
2919 if (minRecoveryPoint == 0)
2920 updateMinRecoveryPoint = false;
2921 else if (force || minRecoveryPoint < lsn)
2923 /* use volatile pointer to prevent code rearrangement */
2924 volatile XLogCtlData *xlogctl = XLogCtl;
2925 XLogRecPtr newMinRecoveryPoint;
2926 TimeLineID newMinRecoveryPointTLI;
2929 * To avoid having to update the control file too often, we update it
2930 * all the way to the last record being replayed, even though 'lsn'
2931 * would suffice for correctness. This also allows the 'force' case
2932 * to not need a valid 'lsn' value.
2934 * Another important reason for doing it this way is that the passed
2935 * 'lsn' value could be bogus, i.e., past the end of available WAL, if
2936 * the caller got it from a corrupted heap page. Accepting such a
2937 * value as the min recovery point would prevent us from coming up at
2938 * all. Instead, we just log a warning and continue with recovery.
2939 * (See also the comments about corrupt LSNs in XLogFlush.)
2941 SpinLockAcquire(&xlogctl->info_lck);
2942 newMinRecoveryPoint = xlogctl->replayEndRecPtr;
2943 newMinRecoveryPointTLI = xlogctl->replayEndTLI;
2944 SpinLockRelease(&xlogctl->info_lck);
2946 if (!force && newMinRecoveryPoint < lsn)
2948 "xlog min recovery request %X/%X is past current point %X/%X",
2949 (uint32) (lsn >> 32), (uint32) lsn,
2950 (uint32) (newMinRecoveryPoint >> 32),
2951 (uint32) newMinRecoveryPoint);
2953 /* update control file */
2954 if (ControlFile->minRecoveryPoint < newMinRecoveryPoint)
2956 ControlFile->minRecoveryPoint = newMinRecoveryPoint;
2957 ControlFile->minRecoveryPointTLI = newMinRecoveryPointTLI;
2958 UpdateControlFile();
2959 minRecoveryPoint = newMinRecoveryPoint;
2960 minRecoveryPointTLI = newMinRecoveryPointTLI;
2963 (errmsg("updated min recovery point to %X/%X on timeline %u",
2964 (uint32) (minRecoveryPoint >> 32),
2965 (uint32) minRecoveryPoint,
2966 newMinRecoveryPointTLI)));
2969 LWLockRelease(ControlFileLock);
2973 * Ensure that all XLOG data through the given position is flushed to disk.
2975 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
2976 * already held, and we try to avoid acquiring it if possible.
2979 XLogFlush(XLogRecPtr record)
2981 XLogRecPtr WriteRqstPtr;
2982 XLogwrtRqst WriteRqst;
2985 * During REDO, we are reading not writing WAL. Therefore, instead of
2986 * trying to flush the WAL, we should update minRecoveryPoint instead. We
2987 * test XLogInsertAllowed(), not InRecovery, because we need checkpointer
2988 * to act this way too, and because when it tries to write the
2989 * end-of-recovery checkpoint, it should indeed flush.
2991 if (!XLogInsertAllowed())
2993 UpdateMinRecoveryPoint(record, false);
2997 /* Quick exit if already known flushed */
2998 if (record <= LogwrtResult.Flush)
3003 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
3004 (uint32) (record >> 32), (uint32) record,
3005 (uint32) (LogwrtResult.Write >> 32), (uint32) LogwrtResult.Write,
3006 (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
3009 START_CRIT_SECTION();
3012 * Since fsync is usually a horribly expensive operation, we try to
3013 * piggyback as much data as we can on each fsync: if we see any more data
3014 * entered into the xlog buffer, we'll write and fsync that too, so that
3015 * the final value of LogwrtResult.Flush is as large as possible. This
3016 * gives us some chance of avoiding another fsync immediately after.
3019 /* initialize to given target; may increase below */
3020 WriteRqstPtr = record;
3023 * Now wait until we get the write lock, or someone else does the flush
3028 /* use volatile pointer to prevent code rearrangement */
3029 volatile XLogCtlData *xlogctl = XLogCtl;
3030 XLogRecPtr insertpos;
3032 /* read LogwrtResult and update local state */
3033 SpinLockAcquire(&xlogctl->info_lck);
3034 if (WriteRqstPtr < xlogctl->LogwrtRqst.Write)
3035 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
3036 LogwrtResult = xlogctl->LogwrtResult;
3037 SpinLockRelease(&xlogctl->info_lck);
3040 if (record <= LogwrtResult.Flush)
3044 * Before actually performing the write, wait for all in-flight
3045 * insertions to the pages we're about to write to finish.
3047 insertpos = WaitXLogInsertionsToFinish(WriteRqstPtr);
3050 * Try to get the write lock. If we can't get it immediately, wait
3051 * until it's released, and recheck if we still need to do the flush
3052 * or if the backend that held the lock did it for us already. This
3053 * helps to maintain a good rate of group committing when the system
3054 * is bottlenecked by the speed of fsyncing.
3056 if (!LWLockAcquireOrWait(WALWriteLock, LW_EXCLUSIVE))
3059 * The lock is now free, but we didn't acquire it yet. Before we
3060 * do, loop back to check if someone else flushed the record for
3066 /* Got the lock; recheck whether request is satisfied */
3067 LogwrtResult = XLogCtl->LogwrtResult;
3068 if (record <= LogwrtResult.Flush)
3070 LWLockRelease(WALWriteLock);
3075 * Sleep before flush! By adding a delay here, we may give further
3076 * backends the opportunity to join the backlog of group commit
3077 * followers; this can significantly improve transaction throughput,
3078 * at the risk of increasing transaction latency.
3080 * We do not sleep if enableFsync is not turned on, nor if there are
3081 * fewer than CommitSiblings other backends with active transactions.
3083 if (CommitDelay > 0 && enableFsync &&
3084 MinimumActiveBackends(CommitSiblings))
3086 pg_usleep(CommitDelay);
3089 * Re-check how far we can now flush the WAL. It's generally not
3090 * safe to call WaitXLogInsetionsToFinish while holding
3091 * WALWriteLock, because an in-progress insertion might need to
3092 * also grab WALWriteLock to make progress. But we know that all
3093 * the insertions up to insertpos have already finished, because
3094 * that's what the earlier WaitXLogInsertionsToFinish() returned.
3095 * We're only calling it again to allow insertpos to be moved
3096 * further forward, not to actually wait for anyone.
3098 insertpos = WaitXLogInsertionsToFinish(insertpos);
3101 /* try to write/flush later additions to XLOG as well */
3102 WriteRqst.Write = insertpos;
3103 WriteRqst.Flush = insertpos;
3105 XLogWrite(WriteRqst, false);
3107 LWLockRelease(WALWriteLock);
3114 /* wake up walsenders now that we've released heavily contended locks */
3115 WalSndWakeupProcessRequests();
3118 * If we still haven't flushed to the request point then we have a
3119 * problem; most likely, the requested flush point is past end of XLOG.
3120 * This has been seen to occur when a disk page has a corrupted LSN.
3122 * Formerly we treated this as a PANIC condition, but that hurts the
3123 * system's robustness rather than helping it: we do not want to take down
3124 * the whole system due to corruption on one data page. In particular, if
3125 * the bad page is encountered again during recovery then we would be
3126 * unable to restart the database at all! (This scenario actually
3127 * happened in the field several times with 7.1 releases.) As of 8.4, bad
3128 * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
3129 * the only time we can reach here during recovery is while flushing the
3130 * end-of-recovery checkpoint record, and we don't expect that to have a
3133 * Note that for calls from xact.c, the ERROR will be promoted to PANIC
3134 * since xact.c calls this routine inside a critical section. However,
3135 * calls from bufmgr.c are not within critical sections and so we will not
3136 * force a restart for a bad LSN on a data page.
3138 if (LogwrtResult.Flush < record)
3140 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
3141 (uint32) (record >> 32), (uint32) record,
3142 (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
3146 * Flush xlog, but without specifying exactly where to flush to.
3148 * We normally flush only completed blocks; but if there is nothing to do on
3149 * that basis, we check for unflushed async commits in the current incomplete
3150 * block, and flush through the latest one of those. Thus, if async commits
3151 * are not being used, we will flush complete blocks only. We can guarantee
3152 * that async commits reach disk after at most three cycles; normally only
3153 * one or two. (When flushing complete blocks, we allow XLogWrite to write
3154 * "flexibly", meaning it can stop at the end of the buffer ring; this makes a
3155 * difference only with very high load or long wal_writer_delay, but imposes
3156 * one extra cycle for the worst case for async commits.)
3158 * This routine is invoked periodically by the background walwriter process.
3160 * Returns TRUE if we flushed anything.
3163 XLogBackgroundFlush(void)
3165 XLogRecPtr WriteRqstPtr;
3166 bool flexible = true;
3167 bool wrote_something = false;
3169 /* XLOG doesn't need flushing during recovery */
3170 if (RecoveryInProgress())
3173 /* read LogwrtResult and update local state */
3175 /* use volatile pointer to prevent code rearrangement */
3176 volatile XLogCtlData *xlogctl = XLogCtl;
3178 SpinLockAcquire(&xlogctl->info_lck);
3179 LogwrtResult = xlogctl->LogwrtResult;
3180 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
3181 SpinLockRelease(&xlogctl->info_lck);
3184 /* back off to last completed page boundary */
3185 WriteRqstPtr -= WriteRqstPtr % XLOG_BLCKSZ;
3187 /* if we have already flushed that far, consider async commit records */
3188 if (WriteRqstPtr <= LogwrtResult.Flush)
3190 /* use volatile pointer to prevent code rearrangement */
3191 volatile XLogCtlData *xlogctl = XLogCtl;
3193 SpinLockAcquire(&xlogctl->info_lck);
3194 WriteRqstPtr = xlogctl->asyncXactLSN;
3195 SpinLockRelease(&xlogctl->info_lck);
3196 flexible = false; /* ensure it all gets written */
3200 * If already known flushed, we're done. Just need to check if we are
3201 * holding an open file handle to a logfile that's no longer in use,
3202 * preventing the file from being deleted.
3204 if (WriteRqstPtr <= LogwrtResult.Flush)
3206 if (openLogFile >= 0)
3208 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo))
3218 elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
3219 (uint32) (WriteRqstPtr >> 32), (uint32) WriteRqstPtr,
3220 (uint32) (LogwrtResult.Write >> 32), (uint32) LogwrtResult.Write,
3221 (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
3224 START_CRIT_SECTION();
3226 /* now wait for any in-progress insertions to finish and get write lock */
3227 WaitXLogInsertionsToFinish(WriteRqstPtr);
3228 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
3229 LogwrtResult = XLogCtl->LogwrtResult;
3230 if (WriteRqstPtr > LogwrtResult.Flush)
3232 XLogwrtRqst WriteRqst;
3234 WriteRqst.Write = WriteRqstPtr;
3235 WriteRqst.Flush = WriteRqstPtr;
3236 XLogWrite(WriteRqst, flexible);
3237 wrote_something = true;
3239 LWLockRelease(WALWriteLock);
3243 /* wake up walsenders now that we've released heavily contended locks */
3244 WalSndWakeupProcessRequests();
3247 * Great, done. To take some work off the critical path, try to initialize
3248 * as many of the no-longer-needed WAL buffers for future use as we can.
3250 AdvanceXLInsertBuffer(InvalidXLogRecPtr, true);
3252 return wrote_something;
3256 * Test whether XLOG data has been flushed up to (at least) the given position.
3258 * Returns true if a flush is still needed. (It may be that someone else
3259 * is already in process of flushing that far, however.)
3262 XLogNeedsFlush(XLogRecPtr record)
3265 * During recovery, we don't flush WAL but update minRecoveryPoint
3266 * instead. So "needs flush" is taken to mean whether minRecoveryPoint
3267 * would need to be updated.
3269 if (RecoveryInProgress())
3271 /* Quick exit if already known updated */
3272 if (record <= minRecoveryPoint || !updateMinRecoveryPoint)
3276 * Update local copy of minRecoveryPoint. But if the lock is busy,
3277 * just return a conservative guess.
3279 if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
3281 minRecoveryPoint = ControlFile->minRecoveryPoint;
3282 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
3283 LWLockRelease(ControlFileLock);
3286 * An invalid minRecoveryPoint means that we need to recover all the
3287 * WAL, i.e., we're doing crash recovery. We never modify the control
3288 * file's value in that case, so we can short-circuit future checks
3291 if (minRecoveryPoint == 0)
3292 updateMinRecoveryPoint = false;
3295 if (record <= minRecoveryPoint || !updateMinRecoveryPoint)
3301 /* Quick exit if already known flushed */
3302 if (record <= LogwrtResult.Flush)
3305 /* read LogwrtResult and update local state */
3307 /* use volatile pointer to prevent code rearrangement */
3308 volatile XLogCtlData *xlogctl = XLogCtl;
3310 SpinLockAcquire(&xlogctl->info_lck);
3311 LogwrtResult = xlogctl->LogwrtResult;
3312 SpinLockRelease(&xlogctl->info_lck);
3316 if (record <= LogwrtResult.Flush)
3323 * Create a new XLOG file segment, or open a pre-existing one.
3325 * log, seg: identify segment to be created/opened.
3327 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
3328 * pre-existing file will be deleted). On return, TRUE if a pre-existing
3331 * use_lock: if TRUE, acquire ControlFileLock while moving file into
3332 * place. This should be TRUE except during bootstrap log creation. The
3333 * caller must *not* hold the lock at call.
3335 * Returns FD of opened file.
3337 * Note: errors here are ERROR not PANIC because we might or might not be
3338 * inside a critical section (eg, during checkpoint there is no reason to
3339 * take down the system on failure). They will promote to PANIC if we are
3340 * in a critical section.
3343 XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
3345 char path[MAXPGPATH];
3346 char tmppath[MAXPGPATH];
3347 XLogSegNo installed_segno;
3350 bool zero_fill = true;
3352 XLogFilePath(path, ThisTimeLineID, logsegno);
3355 * Try to use existent file (checkpoint maker may have created it already)
3359 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
3363 if (errno != ENOENT)
3365 (errcode_for_file_access(),
3366 errmsg("could not open file \"%s\": %m", path)));
3373 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
3374 * another process is doing the same thing. If so, we will end up
3375 * pre-creating an extra log segment. That seems OK, and better than
3376 * holding the lock throughout this lengthy process.
3378 elog(DEBUG2, "creating and filling new WAL file");
3380 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3384 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3385 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3389 (errcode_for_file_access(),
3390 errmsg("could not create file \"%s\": %m", tmppath)));
3392 #ifdef HAVE_POSIX_FALLOCATE
3394 * If posix_fallocate() is available and succeeds, then the file is
3395 * properly allocated and we don't need to zero-fill it (which is less
3396 * efficient). In case of an error, fall back to writing zeros, because on
3397 * some platforms posix_fallocate() is available but will not always
3398 * succeed in cases where zero-filling will.
3400 if (posix_fallocate(fd, 0, XLogSegSize) == 0)
3402 #endif /* HAVE_POSIX_FALLOCATE */
3407 * Allocate a buffer full of zeros. This is done before opening the
3408 * file so that we don't leak the file descriptor if palloc fails.
3410 * Note: palloc zbuffer, instead of just using a local char array, to
3411 * ensure it is reasonably well-aligned; this may save a few cycles
3412 * transferring data to the kernel.
3415 char *zbuffer = (char *) palloc0(XLOG_BLCKSZ);
3419 * Zero-fill the file. We have to do this the hard way to ensure that
3420 * all the file space has really been allocated --- on platforms that
3421 * allow "holes" in files, just seeking to the end doesn't allocate
3422 * intermediate space. This way, we know that we have all the space
3423 * and (after the fsync below) that all the indirect blocks are down on
3424 * disk. Therefore, fdatasync(2) or O_DSYNC will be sufficient to sync
3425 * future writes to the log file.
3427 for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
3430 if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
3432 int save_errno = errno;
3435 * If we fail to make the file, delete it to release disk space
3441 /* if write didn't set errno, assume no disk space */
3442 errno = save_errno ? save_errno : ENOSPC;
3445 (errcode_for_file_access(),
3446 errmsg("could not write to file \"%s\": %m",
3453 if (pg_fsync(fd) != 0)
3457 (errcode_for_file_access(),
3458 errmsg("could not fsync file \"%s\": %m", tmppath)));
3463 (errcode_for_file_access(),
3464 errmsg("could not close file \"%s\": %m", tmppath)));
3467 * Now move the segment into place with its final name.
3469 * If caller didn't want to use a pre-existing file, get rid of any
3470 * pre-existing file. Otherwise, cope with possibility that someone else
3471 * has created the file while we were filling ours: if so, use ours to
3472 * pre-create a future log segment.
3474 installed_segno = logsegno;
3475 max_advance = XLOGfileslop;
3476 if (!InstallXLogFileSegment(&installed_segno, tmppath,
3477 *use_existent, &max_advance,
3481 * No need for any more future segments, or InstallXLogFileSegment()
3482 * failed to rename the file into place. If the rename failed, opening
3483 * the file below will fail.
3488 /* Set flag to tell caller there was no existent file */
3489 *use_existent = false;
3491 /* Now open original target segment (might not be file I just made) */
3492 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
3496 (errcode_for_file_access(),
3497 errmsg("could not open file \"%s\": %m", path)));
3499 elog(DEBUG2, "done creating and filling new WAL file");
3505 * Create a new XLOG file segment by copying a pre-existing one.
3507 * destsegno: identify segment to be created.
3509 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
3510 * a different timeline)
3512 * Currently this is only used during recovery, and so there are no locking
3513 * considerations. But we should be just as tense as XLogFileInit to avoid
3514 * emplacing a bogus file.
3517 XLogFileCopy(XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno)
3519 char path[MAXPGPATH];
3520 char tmppath[MAXPGPATH];
3521 char buffer[XLOG_BLCKSZ];
3527 * Open the source file
3529 XLogFilePath(path, srcTLI, srcsegno);
3530 srcfd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
3533 (errcode_for_file_access(),
3534 errmsg("could not open file \"%s\": %m", path)));
3537 * Copy into a temp file name.
3539 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3543 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3544 fd = OpenTransientFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3548 (errcode_for_file_access(),
3549 errmsg("could not create file \"%s\": %m", tmppath)));
3552 * Do the data copying.
3554 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
3557 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
3561 (errcode_for_file_access(),
3562 errmsg("could not read file \"%s\": %m", path)));
3565 (errmsg("not enough data in file \"%s\"", path)));
3568 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
3570 int save_errno = errno;
3573 * If we fail to make the file, delete it to release disk space
3576 /* if write didn't set errno, assume problem is no disk space */
3577 errno = save_errno ? save_errno : ENOSPC;
3580 (errcode_for_file_access(),
3581 errmsg("could not write to file \"%s\": %m", tmppath)));
3585 if (pg_fsync(fd) != 0)
3587 (errcode_for_file_access(),
3588 errmsg("could not fsync file \"%s\": %m", tmppath)));
3590 if (CloseTransientFile(fd))
3592 (errcode_for_file_access(),
3593 errmsg("could not close file \"%s\": %m", tmppath)));
3595 CloseTransientFile(srcfd);
3598 * Now move the segment into place with its final name.
3600 if (!InstallXLogFileSegment(&destsegno, tmppath, false, NULL, false))
3601 elog(ERROR, "InstallXLogFileSegment should not have failed");
3605 * Install a new XLOG segment file as a current or future log segment.
3607 * This is used both to install a newly-created segment (which has a temp
3608 * filename while it's being created) and to recycle an old segment.
3610 * *segno: identify segment to install as (or first possible target).
3611 * When find_free is TRUE, this is modified on return to indicate the
3612 * actual installation location or last segment searched.
3614 * tmppath: initial name of file to install. It will be renamed into place.
3616 * find_free: if TRUE, install the new segment at the first empty segno
3617 * number at or after the passed numbers. If FALSE, install the new segment
3618 * exactly where specified, deleting any existing segment file there.
3620 * *max_advance: maximum number of segno slots to advance past the starting
3621 * point. Fail if no free slot is found in this range. On return, reduced
3622 * by the number of slots skipped over. (Irrelevant, and may be NULL,
3623 * when find_free is FALSE.)
3625 * use_lock: if TRUE, acquire ControlFileLock while moving file into
3626 * place. This should be TRUE except during bootstrap log creation. The
3627 * caller must *not* hold the lock at call.
3629 * Returns TRUE if the file was installed successfully. FALSE indicates that
3630 * max_advance limit was exceeded, or an error occurred while renaming the
3634 InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
3635 bool find_free, int *max_advance,
3638 char path[MAXPGPATH];
3639 struct stat stat_buf;
3641 XLogFilePath(path, ThisTimeLineID, *segno);
3644 * We want to be sure that only one process does this at a time.
3647 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3651 /* Force installation: get rid of any pre-existing segment file */
3656 /* Find a free slot to put it in */
3657 while (stat(path, &stat_buf) == 0)
3659 if (*max_advance <= 0)
3661 /* Failed to find a free slot within specified range */
3663 LWLockRelease(ControlFileLock);
3668 XLogFilePath(path, ThisTimeLineID, *segno);
3673 * Prefer link() to rename() here just to be really sure that we don't
3674 * overwrite an existing logfile. However, there shouldn't be one, so
3675 * rename() is an acceptable substitute except for the truly paranoid.
3677 #if HAVE_WORKING_LINK
3678 if (link(tmppath, path) < 0)
3681 LWLockRelease(ControlFileLock);
3683 (errcode_for_file_access(),
3684 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file): %m",
3690 if (rename(tmppath, path) < 0)
3693 LWLockRelease(ControlFileLock);
3695 (errcode_for_file_access(),
3696 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file): %m",
3703 LWLockRelease(ControlFileLock);
3709 * Open a pre-existing logfile segment for writing.
3712 XLogFileOpen(XLogSegNo segno)
3714 char path[MAXPGPATH];
3717 XLogFilePath(path, ThisTimeLineID, segno);
3719 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
3723 (errcode_for_file_access(),
3724 errmsg("could not open transaction log file \"%s\": %m", path)));
3730 * Open a logfile segment for reading (during recovery).
3732 * If source == XLOG_FROM_ARCHIVE, the segment is retrieved from archive.
3733 * Otherwise, it's assumed to be already available in pg_xlog.
3736 XLogFileRead(XLogSegNo segno, int emode, TimeLineID tli,
3737 int source, bool notfoundOk)
3739 char xlogfname[MAXFNAMELEN];
3740 char activitymsg[MAXFNAMELEN + 16];
3741 char path[MAXPGPATH];
3744 XLogFileName(xlogfname, tli, segno);
3748 case XLOG_FROM_ARCHIVE:
3749 /* Report recovery progress in PS display */
3750 snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
3752 set_ps_display(activitymsg, false);
3754 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
3758 if (!restoredFromArchive)
3762 case XLOG_FROM_PG_XLOG:
3763 case XLOG_FROM_STREAM:
3764 XLogFilePath(path, tli, segno);
3765 restoredFromArchive = false;
3769 elog(ERROR, "invalid XLogFileRead source %d", source);
3773 * If the segment was fetched from archival storage, replace the existing
3774 * xlog segment (if any) with the archival version.
3776 if (source == XLOG_FROM_ARCHIVE)
3778 KeepFileRestoredFromArchive(path, xlogfname);
3781 * Set path to point at the new file in pg_xlog.
3783 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
3786 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
3792 /* Report recovery progress in PS display */
3793 snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
3795 set_ps_display(activitymsg, false);
3797 /* Track source of data in assorted state variables */
3798 readSource = source;
3799 XLogReceiptSource = source;
3800 /* In FROM_STREAM case, caller tracks receipt time, not me */
3801 if (source != XLOG_FROM_STREAM)
3802 XLogReceiptTime = GetCurrentTimestamp();
3806 if (errno != ENOENT || !notfoundOk) /* unexpected failure? */
3808 (errcode_for_file_access(),
3809 errmsg("could not open file \"%s\": %m", path)));
3814 * Open a logfile segment for reading (during recovery).
3816 * This version searches for the segment with any TLI listed in expectedTLEs.
3819 XLogFileReadAnyTLI(XLogSegNo segno, int emode, int source)
3821 char path[MAXPGPATH];
3827 * Loop looking for a suitable timeline ID: we might need to read any of
3828 * the timelines listed in expectedTLEs.
3830 * We expect curFileTLI on entry to be the TLI of the preceding file in
3831 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
3832 * to go backwards; this prevents us from picking up the wrong file when a
3833 * parent timeline extends to higher segment numbers than the child we
3836 * If we haven't read the timeline history file yet, read it now, so that
3837 * we know which TLIs to scan. We don't save the list in expectedTLEs,
3838 * however, unless we actually find a valid segment. That way if there is
3839 * neither a timeline history file nor a WAL segment in the archive, and
3840 * streaming replication is set up, we'll read the timeline history file
3841 * streamed from the master when we start streaming, instead of recovering
3842 * with a dummy history generated here.
3845 tles = expectedTLEs;
3847 tles = readTimeLineHistory(recoveryTargetTLI);
3851 TimeLineID tli = ((TimeLineHistoryEntry *) lfirst(cell))->tli;
3853 if (tli < curFileTLI)
3854 break; /* don't bother looking at too-old TLIs */
3856 if (source == XLOG_FROM_ANY || source == XLOG_FROM_ARCHIVE)
3858 fd = XLogFileRead(segno, emode, tli,
3859 XLOG_FROM_ARCHIVE, true);
3862 elog(DEBUG1, "got WAL segment from archive");
3864 expectedTLEs = tles;
3869 if (source == XLOG_FROM_ANY || source == XLOG_FROM_PG_XLOG)
3871 fd = XLogFileRead(segno, emode, tli,
3872 XLOG_FROM_PG_XLOG, true);
3876 expectedTLEs = tles;
3882 /* Couldn't find it. For simplicity, complain about front timeline */
3883 XLogFilePath(path, recoveryTargetTLI, segno);
3886 (errcode_for_file_access(),
3887 errmsg("could not open file \"%s\": %m", path)));
3892 * Close the current logfile segment for writing.
3897 Assert(openLogFile >= 0);
3900 * WAL segment files will not be re-read in normal operation, so we advise
3901 * the OS to release any cached pages. But do not do so if WAL archiving
3902 * or streaming is active, because archiver and walsender process could
3903 * use the cache to read the WAL segment.
3905 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3906 if (!XLogIsNeeded())
3907 (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3910 if (close(openLogFile))
3912 (errcode_for_file_access(),
3913 errmsg("could not close log file %s: %m",
3914 XLogFileNameP(ThisTimeLineID, openLogSegNo))));
3919 * Preallocate log files beyond the specified log endpoint.
3921 * XXX this is currently extremely conservative, since it forces only one
3922 * future log segment to exist, and even that only if we are 75% done with
3923 * the current one. This is only appropriate for very low-WAL-volume systems.
3924 * High-volume systems will be OK once they've built up a sufficient set of
3925 * recycled log segments, but the startup transient is likely to include
3926 * a lot of segment creations by foreground processes, which is not so good.
3929 PreallocXlogFiles(XLogRecPtr endptr)
3931 XLogSegNo _logSegNo;
3935 XLByteToPrevSeg(endptr, _logSegNo);
3936 if ((endptr - 1) % XLogSegSize >= (uint32) (0.75 * XLogSegSize))
3939 use_existent = true;
3940 lf = XLogFileInit(_logSegNo, &use_existent, true);
3943 CheckpointStats.ckpt_segs_added++;
3948 * Throws an error if the given log segment has already been removed or
3949 * recycled. The caller should only pass a segment that it knows to have
3950 * existed while the server has been running, as this function always
3951 * succeeds if no WAL segments have been removed since startup.
3952 * 'tli' is only used in the error message.
3955 CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
3957 /* use volatile pointer to prevent code rearrangement */
3958 volatile XLogCtlData *xlogctl = XLogCtl;
3959 XLogSegNo lastRemovedSegNo;
3961 SpinLockAcquire(&xlogctl->info_lck);
3962 lastRemovedSegNo = xlogctl->lastRemovedSegNo;
3963 SpinLockRelease(&xlogctl->info_lck);
3965 if (segno <= lastRemovedSegNo)
3967 char filename[MAXFNAMELEN];
3969 XLogFileName(filename, tli, segno);
3971 (errcode_for_file_access(),
3972 errmsg("requested WAL segment %s has already been removed",
3978 * Update the last removed segno pointer in shared memory, to reflect
3979 * that the given XLOG file has been removed.
3982 UpdateLastRemovedPtr(char *filename)
3984 /* use volatile pointer to prevent code rearrangement */
3985 volatile XLogCtlData *xlogctl = XLogCtl;
3989 XLogFromFileName(filename, &tli, &segno);
3991 SpinLockAcquire(&xlogctl->info_lck);
3992 if (segno > xlogctl->lastRemovedSegNo)
3993 xlogctl->lastRemovedSegNo = segno;
3994 SpinLockRelease(&xlogctl->info_lck);
3998 * Recycle or remove all log files older or equal to passed segno
4000 * endptr is current (or recent) end of xlog; this is used to determine
4001 * whether we want to recycle rather than delete no-longer-wanted log files.
4004 RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr endptr)
4006 XLogSegNo endlogSegNo;
4009 struct dirent *xlde;
4010 char lastoff[MAXFNAMELEN];
4011 char path[MAXPGPATH];
4014 char newpath[MAXPGPATH];
4016 struct stat statbuf;
4019 * Initialize info about where to try to recycle to. We allow recycling
4020 * segments up to XLOGfileslop segments beyond the current XLOG location.
4022 XLByteToPrevSeg(endptr, endlogSegNo);
4023 max_advance = XLOGfileslop;
4025 xldir = AllocateDir(XLOGDIR);
4028 (errcode_for_file_access(),
4029 errmsg("could not open transaction log directory \"%s\": %m",
4033 * Construct a filename of the last segment to be kept. The timeline ID
4034 * doesn't matter, we ignore that in the comparison. (During recovery,
4035 * ThisTimeLineID isn't set, so we can't use that.)
4037 XLogFileName(lastoff, 0, segno);
4039 elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
4042 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4045 * We ignore the timeline part of the XLOG segment identifiers in
4046 * deciding whether a segment is still needed. This ensures that we
4047 * won't prematurely remove a segment from a parent timeline. We could
4048 * probably be a little more proactive about removing segments of
4049 * non-parent timelines, but that would be a whole lot more
4052 * We use the alphanumeric sorting property of the filenames to decide
4053 * which ones are earlier than the lastoff segment.
4055 if (strlen(xlde->d_name) == 24 &&
4056 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
4057 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
4059 if (XLogArchiveCheckDone(xlde->d_name))
4061 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
4063 /* Update the last removed location in shared memory first */
4064 UpdateLastRemovedPtr(xlde->d_name);
4067 * Before deleting the file, see if it can be recycled as a
4068 * future log segment. Only recycle normal files, pg_standby
4069 * for example can create symbolic links pointing to a
4070 * separate archive directory.
4072 if (lstat(path, &statbuf) == 0 && S_ISREG(statbuf.st_mode) &&
4073 InstallXLogFileSegment(&endlogSegNo, path,
4074 true, &max_advance, true))
4077 (errmsg("recycled transaction log file \"%s\"",
4079 CheckpointStats.ckpt_segs_recycled++;
4080 /* Needn't recheck that slot on future iterations */
4081 if (max_advance > 0)
4089 /* No need for any more future segments... */
4093 (errmsg("removing transaction log file \"%s\"",
4099 * On Windows, if another process (e.g another backend)
4100 * holds the file open in FILE_SHARE_DELETE mode, unlink
4101 * will succeed, but the file will still show up in
4102 * directory listing until the last handle is closed. To
4103 * avoid confusing the lingering deleted file for a live
4104 * WAL file that needs to be archived, rename it before
4107 * If another process holds the file open without
4108 * FILE_SHARE_DELETE flag, rename will fail. We'll try
4109 * again at the next checkpoint.
4111 snprintf(newpath, MAXPGPATH, "%s.deleted", path);
4112 if (rename(path, newpath) != 0)
4115 (errcode_for_file_access(),
4116 errmsg("could not rename old transaction log file \"%s\": %m",
4120 rc = unlink(newpath);
4127 (errcode_for_file_access(),
4128 errmsg("could not remove old transaction log file \"%s\": %m",
4132 CheckpointStats.ckpt_segs_removed++;
4135 XLogArchiveCleanup(xlde->d_name);
4144 * Verify whether pg_xlog and pg_xlog/archive_status exist.
4145 * If the latter does not exist, recreate it.
4147 * It is not the goal of this function to verify the contents of these
4148 * directories, but to help in cases where someone has performed a cluster
4149 * copy for PITR purposes but omitted pg_xlog from the copy.
4151 * We could also recreate pg_xlog if it doesn't exist, but a deliberate
4152 * policy decision was made not to. It is fairly common for pg_xlog to be
4153 * a symlink, and if that was the DBA's intent then automatically making a
4154 * plain directory would result in degraded performance with no notice.
4157 ValidateXLOGDirectoryStructure(void)
4159 char path[MAXPGPATH];
4160 struct stat stat_buf;
4162 /* Check for pg_xlog; if it doesn't exist, error out */
4163 if (stat(XLOGDIR, &stat_buf) != 0 ||
4164 !S_ISDIR(stat_buf.st_mode))
4166 (errmsg("required WAL directory \"%s\" does not exist",
4169 /* Check for archive_status */
4170 snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
4171 if (stat(path, &stat_buf) == 0)
4173 /* Check for weird cases where it exists but isn't a directory */
4174 if (!S_ISDIR(stat_buf.st_mode))
4176 (errmsg("required WAL directory \"%s\" does not exist",
4182 (errmsg("creating missing WAL directory \"%s\"", path)));
4183 if (mkdir(path, S_IRWXU) < 0)
4185 (errmsg("could not create missing directory \"%s\": %m",
4191 * Remove previous backup history files. This also retries creation of
4192 * .ready files for any backup history files for which XLogArchiveNotify
4196 CleanupBackupHistory(void)
4199 struct dirent *xlde;
4200 char path[MAXPGPATH];
4202 xldir = AllocateDir(XLOGDIR);
4205 (errcode_for_file_access(),
4206 errmsg("could not open transaction log directory \"%s\": %m",
4209 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4211 if (strlen(xlde->d_name) > 24 &&
4212 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
4213 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
4216 if (XLogArchiveCheckDone(xlde->d_name))
4219 (errmsg("removing transaction log backup history file \"%s\"",
4221 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
4223 XLogArchiveCleanup(xlde->d_name);
4232 * Restore a full-page image from a backup block attached to an XLOG record.
4234 * lsn: LSN of the XLOG record being replayed
4235 * record: the complete XLOG record
4236 * block_index: which backup block to restore (0 .. XLR_MAX_BKP_BLOCKS - 1)
4237 * get_cleanup_lock: TRUE to get a cleanup rather than plain exclusive lock
4238 * keep_buffer: TRUE to return the buffer still locked and pinned
4240 * Returns the buffer number containing the page. Note this is not terribly
4241 * useful unless keep_buffer is specified as TRUE.
4243 * Note: when a backup block is available in XLOG, we restore it
4244 * unconditionally, even if the page in the database appears newer.
4245 * This is to protect ourselves against database pages that were partially
4246 * or incorrectly written during a crash. We assume that the XLOG data
4247 * must be good because it has passed a CRC check, while the database
4248 * page might not be. This will force us to replay all subsequent
4249 * modifications of the page that appear in XLOG, rather than possibly
4250 * ignoring them as already applied, but that's not a huge drawback.
4252 * If 'get_cleanup_lock' is true, a cleanup lock is obtained on the buffer,
4253 * else a normal exclusive lock is used. During crash recovery, that's just
4254 * pro forma because there can't be any regular backends in the system, but
4255 * in hot standby mode the distinction is important.
4257 * If 'keep_buffer' is true, return without releasing the buffer lock and pin;
4258 * then caller is responsible for doing UnlockReleaseBuffer() later. This
4259 * is needed in some cases when replaying XLOG records that touch multiple
4260 * pages, to prevent inconsistent states from being visible to other backends.
4261 * (Again, that's only important in hot standby mode.)
4264 RestoreBackupBlock(XLogRecPtr lsn, XLogRecord *record, int block_index,
4265 bool get_cleanup_lock, bool keep_buffer)
4271 /* Locate requested BkpBlock in the record */
4272 blk = (char *) XLogRecGetData(record) + record->xl_len;
4273 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
4275 if (!(record->xl_info & XLR_BKP_BLOCK(i)))
4278 memcpy(&bkpb, blk, sizeof(BkpBlock));
4279 blk += sizeof(BkpBlock);
4281 if (i == block_index)
4283 /* Found it, apply the update */
4284 return RestoreBackupBlockContents(lsn, bkpb, blk, get_cleanup_lock,
4288 blk += BLCKSZ - bkpb.hole_length;
4291 /* Caller specified a bogus block_index */
4292 elog(ERROR, "failed to restore block_index %d", block_index);
4293 return InvalidBuffer; /* keep compiler quiet */
4297 * Workhorse for RestoreBackupBlock usable without an xlog record
4299 * Restores a full-page image from BkpBlock and a data pointer.
4302 RestoreBackupBlockContents(XLogRecPtr lsn, BkpBlock bkpb, char *blk,
4303 bool get_cleanup_lock, bool keep_buffer)
4308 buffer = XLogReadBufferExtended(bkpb.node, bkpb.fork, bkpb.block,
4310 Assert(BufferIsValid(buffer));
4311 if (get_cleanup_lock)
4312 LockBufferForCleanup(buffer);
4314 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
4316 page = (Page) BufferGetPage(buffer);
4318 if (bkpb.hole_length == 0)
4320 memcpy((char *) page, blk, BLCKSZ);
4324 memcpy((char *) page, blk, bkpb.hole_offset);
4325 /* must zero-fill the hole */
4326 MemSet((char *) page + bkpb.hole_offset, 0, bkpb.hole_length);
4327 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
4328 blk + bkpb.hole_offset,
4329 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
4333 * The checksum value on this page is currently invalid. We don't need to
4334 * reset it here since it will be set before being written.
4337 PageSetLSN(page, lsn);
4338 MarkBufferDirty(buffer);
4341 UnlockReleaseBuffer(buffer);
4347 * Attempt to read an XLOG record.
4349 * If RecPtr is not NULL, try to read a record at that position. Otherwise
4350 * try to read a record just after the last one previously read.
4352 * If no valid record is available, returns NULL, or fails if emode is PANIC.
4353 * (emode must be either PANIC, LOG). In standby mode, retries until a valid
4354 * record is available.
4356 * The record is copied into readRecordBuf, so that on successful return,
4357 * the returned record pointer always points there.
4360 ReadRecord(XLogReaderState *xlogreader, XLogRecPtr RecPtr, int emode,
4364 XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
4366 /* Pass through parameters to XLogPageRead */
4367 private->fetching_ckpt = fetching_ckpt;
4368 private->emode = emode;
4369 private->randAccess = (RecPtr != InvalidXLogRecPtr);
4371 /* This is the first attempt to read this page. */
4372 lastSourceFailed = false;
4378 record = XLogReadRecord(xlogreader, RecPtr, &errormsg);
4379 ReadRecPtr = xlogreader->ReadRecPtr;
4380 EndRecPtr = xlogreader->EndRecPtr;
4390 * We only end up here without a message when XLogPageRead()
4391 * failed - in that case we already logged something. In
4392 * StandbyMode that only happens if we have been triggered, so we
4393 * shouldn't loop anymore in that case.
4396 ereport(emode_for_corrupt_record(emode,
4397 RecPtr ? RecPtr : EndRecPtr),
4398 (errmsg_internal("%s", errormsg) /* already translated */ ));
4402 * Check page TLI is one of the expected values.
4404 else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
4406 char fname[MAXFNAMELEN];
4410 XLByteToSeg(xlogreader->latestPagePtr, segno);
4411 offset = xlogreader->latestPagePtr % XLogSegSize;
4412 XLogFileName(fname, xlogreader->readPageTLI, segno);
4413 ereport(emode_for_corrupt_record(emode,
4414 RecPtr ? RecPtr : EndRecPtr),
4415 (errmsg("unexpected timeline ID %u in log segment %s, offset %u",
4416 xlogreader->latestPageTLI,
4424 /* Great, got a record */
4429 /* No valid record available from this source */
4430 lastSourceFailed = true;
4433 * If archive recovery was requested, but we were still doing
4434 * crash recovery, switch to archive recovery and retry using the
4435 * offline archive. We have now replayed all the valid WAL in
4436 * pg_xlog, so we are presumably now consistent.
4438 * We require that there's at least some valid WAL present in
4439 * pg_xlog, however (!fetch_ckpt). We could recover using the WAL
4440 * from the archive, even if pg_xlog is completely empty, but we'd
4441 * have no idea how far we'd have to replay to reach consistency.
4442 * So err on the safe side and give up.
4444 if (!InArchiveRecovery && ArchiveRecoveryRequested &&
4448 (errmsg_internal("reached end of WAL in pg_xlog, entering archive recovery")));
4449 InArchiveRecovery = true;
4450 if (StandbyModeRequested)
4453 /* initialize minRecoveryPoint to this record */
4454 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
4455 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4456 if (ControlFile->minRecoveryPoint < EndRecPtr)
4458 ControlFile->minRecoveryPoint = EndRecPtr;
4459 ControlFile->minRecoveryPointTLI = ThisTimeLineID;
4461 /* update local copy */
4462 minRecoveryPoint = ControlFile->minRecoveryPoint;
4463 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
4465 UpdateControlFile();
4466 LWLockRelease(ControlFileLock);
4468 CheckRecoveryConsistency();
4471 * Before we retry, reset lastSourceFailed and currentSource
4472 * so that we will check the archive next.
4474 lastSourceFailed = false;
4480 /* In standby mode, loop back to retry. Otherwise, give up. */
4481 if (StandbyMode && !CheckForStandbyTrigger())
4490 * Scan for new timelines that might have appeared in the archive since we
4493 * If there are any, the function changes recovery target TLI to the latest
4494 * one and returns 'true'.
4497 rescanLatestTimeLine(void)
4499 List *newExpectedTLEs;
4502 TimeLineID newtarget;
4503 TimeLineID oldtarget = recoveryTargetTLI;
4504 TimeLineHistoryEntry *currentTle = NULL;
4506 newtarget = findNewestTimeLine(recoveryTargetTLI);
4507 if (newtarget == recoveryTargetTLI)
4509 /* No new timelines found */
4514 * Determine the list of expected TLIs for the new TLI
4517 newExpectedTLEs = readTimeLineHistory(newtarget);
4520 * If the current timeline is not part of the history of the new timeline,
4521 * we cannot proceed to it.
4524 foreach(cell, newExpectedTLEs)
4526 currentTle = (TimeLineHistoryEntry *) lfirst(cell);
4528 if (currentTle->tli == recoveryTargetTLI)
4537 (errmsg("new timeline %u is not a child of database system timeline %u",
4544 * The current timeline was found in the history file, but check that the
4545 * next timeline was forked off from it *after* the current recovery
4548 if (currentTle->end < EndRecPtr)
4551 (errmsg("new timeline %u forked off current database system timeline %u before current recovery point %X/%X",
4554 (uint32) (EndRecPtr >> 32), (uint32) EndRecPtr)));
4558 /* The new timeline history seems valid. Switch target */
4559 recoveryTargetTLI = newtarget;
4560 list_free_deep(expectedTLEs);
4561 expectedTLEs = newExpectedTLEs;
4564 * As in StartupXLOG(), try to ensure we have all the history files
4565 * between the old target and new target in pg_xlog.
4567 restoreTimeLineHistoryFiles(oldtarget + 1, newtarget);
4570 (errmsg("new target timeline is %u",
4571 recoveryTargetTLI)));
4577 * I/O routines for pg_control
4579 * *ControlFile is a buffer in shared memory that holds an image of the
4580 * contents of pg_control. WriteControlFile() initializes pg_control
4581 * given a preloaded buffer, ReadControlFile() loads the buffer from
4582 * the pg_control file (during postmaster or standalone-backend startup),
4583 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
4585 * For simplicity, WriteControlFile() initializes the fields of pg_control
4586 * that are related to checking backend/database compatibility, and
4587 * ReadControlFile() verifies they are correct. We could split out the
4588 * I/O and compatibility-check functions, but there seems no need currently.
4591 WriteControlFile(void)
4594 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
4597 * Initialize version and compatibility-check fields
4599 ControlFile->pg_control_version = PG_CONTROL_VERSION;
4600 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
4602 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
4603 ControlFile->floatFormat = FLOATFORMAT_VALUE;
4605 ControlFile->blcksz = BLCKSZ;
4606 ControlFile->relseg_size = RELSEG_SIZE;
4607 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4608 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
4610 ControlFile->nameDataLen = NAMEDATALEN;
4611 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
4613 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
4615 #ifdef HAVE_INT64_TIMESTAMP
4616 ControlFile->enableIntTimes = true;
4618 ControlFile->enableIntTimes = false;
4620 ControlFile->float4ByVal = FLOAT4PASSBYVAL;
4621 ControlFile->float8ByVal = FLOAT8PASSBYVAL;
4623 /* Contents are protected with a CRC */
4624 INIT_CRC32(ControlFile->crc);
4625 COMP_CRC32(ControlFile->crc,
4626 (char *) ControlFile,
4627 offsetof(ControlFileData, crc));
4628 FIN_CRC32(ControlFile->crc);
4631 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
4632 * excess over sizeof(ControlFileData). This reduces the odds of
4633 * premature-EOF errors when reading pg_control. We'll still fail when we
4634 * check the contents of the file, but hopefully with a more specific
4635 * error than "couldn't read pg_control".
4637 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
4638 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
4640 memset(buffer, 0, PG_CONTROL_SIZE);
4641 memcpy(buffer, ControlFile, sizeof(ControlFileData));
4643 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4644 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
4648 (errcode_for_file_access(),
4649 errmsg("could not create control file \"%s\": %m",
4650 XLOG_CONTROL_FILE)));
4653 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
4655 /* if write didn't set errno, assume problem is no disk space */
4659 (errcode_for_file_access(),
4660 errmsg("could not write to control file: %m")));
4663 if (pg_fsync(fd) != 0)
4665 (errcode_for_file_access(),
4666 errmsg("could not fsync control file: %m")));
4670 (errcode_for_file_access(),
4671 errmsg("could not close control file: %m")));
4675 ReadControlFile(void)
4683 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4688 (errcode_for_file_access(),
4689 errmsg("could not open control file \"%s\": %m",
4690 XLOG_CONTROL_FILE)));
4692 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4694 (errcode_for_file_access(),
4695 errmsg("could not read from control file: %m")));
4700 * Check for expected pg_control format version. If this is wrong, the
4701 * CRC check will likely fail because we'll be checking the wrong number
4702 * of bytes. Complaining about wrong version will probably be more
4703 * enlightening than complaining about wrong CRC.
4706 if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
4708 (errmsg("database files are incompatible with server"),
4709 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4710 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4711 ControlFile->pg_control_version, ControlFile->pg_control_version,
4712 PG_CONTROL_VERSION, PG_CONTROL_VERSION),
4713 errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4715 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
4717 (errmsg("database files are incompatible with server"),
4718 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4719 " but the server was compiled with PG_CONTROL_VERSION %d.",
4720 ControlFile->pg_control_version, PG_CONTROL_VERSION),
4721 errhint("It looks like you need to initdb.")));
4723 /* Now check the CRC. */
4726 (char *) ControlFile,
4727 offsetof(ControlFileData, crc));
4730 if (!EQ_CRC32(crc, ControlFile->crc))
4732 (errmsg("incorrect checksum in control file")));
4735 * Do compatibility checking immediately. If the database isn't
4736 * compatible with the backend executable, we want to abort before we can
4737 * possibly do any damage.
4739 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
4741 (errmsg("database files are incompatible with server"),
4742 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
4743 " but the server was compiled with CATALOG_VERSION_NO %d.",
4744 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
4745 errhint("It looks like you need to initdb.")));
4746 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4748 (errmsg("database files are incompatible with server"),
4749 errdetail("The database cluster was initialized with MAXALIGN %d,"
4750 " but the server was compiled with MAXALIGN %d.",
4751 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
4752 errhint("It looks like you need to initdb.")));
4753 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
4755 (errmsg("database files are incompatible with server"),
4756 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4757 errhint("It looks like you need to initdb.")));
4758 if (ControlFile->blcksz != BLCKSZ)
4760 (errmsg("database files are incompatible with server"),
4761 errdetail("The database cluster was initialized with BLCKSZ %d,"
4762 " but the server was compiled with BLCKSZ %d.",
4763 ControlFile->blcksz, BLCKSZ),
4764 errhint("It looks like you need to recompile or initdb.")));
4765 if (ControlFile->relseg_size != RELSEG_SIZE)
4767 (errmsg("database files are incompatible with server"),
4768 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
4769 " but the server was compiled with RELSEG_SIZE %d.",
4770 ControlFile->relseg_size, RELSEG_SIZE),
4771 errhint("It looks like you need to recompile or initdb.")));
4772 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4774 (errmsg("database files are incompatible with server"),
4775 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
4776 " but the server was compiled with XLOG_BLCKSZ %d.",
4777 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4778 errhint("It looks like you need to recompile or initdb.")));
4779 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
4781 (errmsg("database files are incompatible with server"),
4782 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
4783 " but the server was compiled with XLOG_SEG_SIZE %d.",
4784 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
4785 errhint("It looks like you need to recompile or initdb.")));
4786 if (ControlFile->nameDataLen != NAMEDATALEN)
4788 (errmsg("database files are incompatible with server"),
4789 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
4790 " but the server was compiled with NAMEDATALEN %d.",
4791 ControlFile->nameDataLen, NAMEDATALEN),
4792 errhint("It looks like you need to recompile or initdb.")));
4793 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4795 (errmsg("database files are incompatible with server"),
4796 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
4797 " but the server was compiled with INDEX_MAX_KEYS %d.",
4798 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
4799 errhint("It looks like you need to recompile or initdb.")));
4800 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
4802 (errmsg("database files are incompatible with server"),
4803 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
4804 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
4805 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4806 errhint("It looks like you need to recompile or initdb.")));
4808 #ifdef HAVE_INT64_TIMESTAMP
4809 if (ControlFile->enableIntTimes != true)
4811 (errmsg("database files are incompatible with server"),
4812 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
4813 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
4814 errhint("It looks like you need to recompile or initdb.")));
4816 if (ControlFile->enableIntTimes != false)
4818 (errmsg("database files are incompatible with server"),
4819 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
4820 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
4821 errhint("It looks like you need to recompile or initdb.")));
4824 #ifdef USE_FLOAT4_BYVAL
4825 if (ControlFile->float4ByVal != true)
4827 (errmsg("database files are incompatible with server"),
4828 errdetail("The database cluster was initialized without USE_FLOAT4_BYVAL"
4829 " but the server was compiled with USE_FLOAT4_BYVAL."),
4830 errhint("It looks like you need to recompile or initdb.")));
4832 if (ControlFile->float4ByVal != false)
4834 (errmsg("database files are incompatible with server"),
4835 errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
4836 " but the server was compiled without USE_FLOAT4_BYVAL."),
4837 errhint("It looks like you need to recompile or initdb.")));
4840 #ifdef USE_FLOAT8_BYVAL
4841 if (ControlFile->float8ByVal != true)
4843 (errmsg("database files are incompatible with server"),
4844 errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4845 " but the server was compiled with USE_FLOAT8_BYVAL."),
4846 errhint("It looks like you need to recompile or initdb.")));
4848 if (ControlFile->float8ByVal != false)
4850 (errmsg("database files are incompatible with server"),
4851 errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4852 " but the server was compiled without USE_FLOAT8_BYVAL."),
4853 errhint("It looks like you need to recompile or initdb.")));
4858 UpdateControlFile(void)
4862 INIT_CRC32(ControlFile->crc);
4863 COMP_CRC32(ControlFile->crc,
4864 (char *) ControlFile,
4865 offsetof(ControlFileData, crc));
4866 FIN_CRC32(ControlFile->crc);
4868 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4873 (errcode_for_file_access(),
4874 errmsg("could not open control file \"%s\": %m",
4875 XLOG_CONTROL_FILE)));
4878 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4880 /* if write didn't set errno, assume problem is no disk space */
4884 (errcode_for_file_access(),
4885 errmsg("could not write to control file: %m")));
4888 if (pg_fsync(fd) != 0)
4890 (errcode_for_file_access(),
4891 errmsg("could not fsync control file: %m")));
4895 (errcode_for_file_access(),
4896 errmsg("could not close control file: %m")));
4900 * Returns the unique system identifier from control file.
4903 GetSystemIdentifier(void)
4905 Assert(ControlFile != NULL);
4906 return ControlFile->system_identifier;
4910 * Are checksums enabled for data pages?
4913 DataChecksumsEnabled(void)
4915 Assert(ControlFile != NULL);
4916 return (ControlFile->data_checksum_version > 0);
4920 * Returns a fake LSN for unlogged relations.
4922 * Each call generates an LSN that is greater than any previous value
4923 * returned. The current counter value is saved and restored across clean
4924 * shutdowns, but like unlogged relations, does not survive a crash. This can
4925 * be used in lieu of real LSN values returned by XLogInsert, if you need an
4926 * LSN-like increasing sequence of numbers without writing any WAL.
4929 GetFakeLSNForUnloggedRel(void)
4931 XLogRecPtr nextUnloggedLSN;
4933 /* use volatile pointer to prevent code rearrangement */
4934 volatile XLogCtlData *xlogctl = XLogCtl;
4936 /* increment the unloggedLSN counter, need SpinLock */
4937 SpinLockAcquire(&xlogctl->ulsn_lck);
4938 nextUnloggedLSN = xlogctl->unloggedLSN++;
4939 SpinLockRelease(&xlogctl->ulsn_lck);
4941 return nextUnloggedLSN;
4945 * Auto-tune the number of XLOG buffers.
4947 * The preferred setting for wal_buffers is about 3% of shared_buffers, with
4948 * a maximum of one XLOG segment (there is little reason to think that more
4949 * is helpful, at least so long as we force an fsync when switching log files)
4950 * and a minimum of 8 blocks (which was the default value prior to PostgreSQL
4951 * 9.1, when auto-tuning was added).
4953 * This should not be called until NBuffers has received its final value.
4956 XLOGChooseNumBuffers(void)
4960 xbuffers = NBuffers / 32;
4961 if (xbuffers > XLOG_SEG_SIZE / XLOG_BLCKSZ)
4962 xbuffers = XLOG_SEG_SIZE / XLOG_BLCKSZ;
4969 * GUC check_hook for wal_buffers
4972 check_wal_buffers(int *newval, void **extra, GucSource source)
4975 * -1 indicates a request for auto-tune.
4980 * If we haven't yet changed the boot_val default of -1, just let it
4981 * be. We'll fix it when XLOGShmemSize is called.
4983 if (XLOGbuffers == -1)
4986 /* Otherwise, substitute the auto-tune value */
4987 *newval = XLOGChooseNumBuffers();
4991 * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
4992 * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
4993 * the case, we just silently treat such values as a request for the
4994 * minimum. (We could throw an error instead, but that doesn't seem very
5004 * Initialization of shared memory for XLOG
5012 * If the value of wal_buffers is -1, use the preferred auto-tune value.
5013 * This isn't an amazingly clean place to do this, but we must wait till
5014 * NBuffers has received its final value, and must do it before using the
5015 * value of XLOGbuffers to do anything important.
5017 if (XLOGbuffers == -1)
5021 snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
5022 SetConfigOption("wal_buffers", buf, PGC_POSTMASTER, PGC_S_OVERRIDE);
5024 Assert(XLOGbuffers > 0);
5027 size = sizeof(XLogCtlData);
5029 /* xlog insertion slots, plus alignment */
5030 size = add_size(size, mul_size(sizeof(XLogInsertSlotPadded), num_xloginsert_slots + 1));
5031 /* xlblocks array */
5032 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
5033 /* extra alignment padding for XLOG I/O buffers */
5034 size = add_size(size, XLOG_BLCKSZ);
5035 /* and the buffers themselves */
5036 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
5039 * Note: we don't count ControlFileData, it comes out of the "slop factor"
5040 * added by CreateSharedMemoryAndSemaphores. This lets us use this
5041 * routine again below to compute the actual allocation size.
5055 ControlFile = (ControlFileData *)
5056 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
5057 XLogCtl = (XLogCtlData *)
5058 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
5060 if (foundCFile || foundXLog)
5062 /* both should be present or neither */
5063 Assert(foundCFile && foundXLog);
5066 memset(XLogCtl, 0, sizeof(XLogCtlData));
5069 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
5070 * multiple of the alignment for same, so no extra alignment padding is
5073 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
5074 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
5075 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
5076 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
5078 /* Xlog insertion slots. Ensure they're aligned to the full padded size */
5079 allocptr += sizeof(XLogInsertSlotPadded) -
5080 ((uintptr_t) allocptr) % sizeof(XLogInsertSlotPadded);
5081 XLogCtl->Insert.insertSlots = (XLogInsertSlotPadded *) allocptr;
5082 allocptr += sizeof(XLogInsertSlotPadded) * num_xloginsert_slots;
5085 * Align the start of the page buffers to a full xlog block size boundary.
5086 * This simplifies some calculations in XLOG insertion. It is also required
5089 allocptr = (char *) TYPEALIGN(XLOG_BLCKSZ, allocptr);
5090 XLogCtl->pages = allocptr;
5091 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
5094 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
5095 * in additional info.)
5097 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
5098 XLogCtl->SharedRecoveryInProgress = true;
5099 XLogCtl->SharedHotStandbyActive = false;
5100 XLogCtl->WalWriterSleeping = false;
5102 for (i = 0; i < num_xloginsert_slots; i++)
5104 XLogInsertSlot *slot = &XLogCtl->Insert.insertSlots[i].slot;
5105 SpinLockInit(&slot->mutex);
5106 slot->xlogInsertingAt = InvalidXLogRecPtr;
5109 slot->releaseOK = true;
5110 slot->exclusive = 0;
5115 SpinLockInit(&XLogCtl->Insert.insertpos_lck);
5116 SpinLockInit(&XLogCtl->info_lck);
5117 SpinLockInit(&XLogCtl->ulsn_lck);
5118 InitSharedLatch(&XLogCtl->recoveryWakeupLatch);
5121 * If we are not in bootstrap mode, pg_control should already exist. Read
5122 * and validate it immediately (see comments in ReadControlFile() for the
5125 if (!IsBootstrapProcessingMode())
5130 * This func must be called ONCE on system install. It creates pg_control
5131 * and the initial XLOG segment.
5136 CheckPoint checkPoint;
5138 XLogPageHeader page;
5139 XLogLongPageHeader longpage;
5142 uint64 sysidentifier;
5147 * Select a hopefully-unique system identifier code for this installation.
5148 * We use the result of gettimeofday(), including the fractional seconds
5149 * field, as being about as unique as we can easily get. (Think not to
5150 * use random(), since it hasn't been seeded and there's no portable way
5151 * to seed it other than the system clock value...) The upper half of the
5152 * uint64 value is just the tv_sec part, while the lower half is the XOR
5153 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
5154 * unnecessarily if "uint64" is really only 32 bits wide. A person
5155 * knowing this encoding can determine the initialization time of the
5156 * installation, which could perhaps be useful sometimes.
5158 gettimeofday(&tv, NULL);
5159 sysidentifier = ((uint64) tv.tv_sec) << 32;
5160 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
5162 /* First timeline ID is always 1 */
5165 /* page buffer must be aligned suitably for O_DIRECT */
5166 buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5167 page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5168 memset(page, 0, XLOG_BLCKSZ);
5171 * Set up information for the initial checkpoint record
5173 * The initial checkpoint record is written to the beginning of the WAL
5174 * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5175 * used, so that we can use 0/0 to mean "before any valid WAL segment".
5177 checkPoint.redo = XLogSegSize + SizeOfXLogLongPHD;
5178 checkPoint.ThisTimeLineID = ThisTimeLineID;
5179 checkPoint.PrevTimeLineID = ThisTimeLineID;
5180 checkPoint.fullPageWrites = fullPageWrites;
5181 checkPoint.nextXidEpoch = 0;
5182 checkPoint.nextXid = FirstNormalTransactionId;
5183 checkPoint.nextOid = FirstBootstrapObjectId;
5184 checkPoint.nextMulti = FirstMultiXactId;
5185 checkPoint.nextMultiOffset = 0;
5186 checkPoint.oldestXid = FirstNormalTransactionId;
5187 checkPoint.oldestXidDB = TemplateDbOid;
5188 checkPoint.oldestMulti = FirstMultiXactId;
5189 checkPoint.oldestMultiDB = TemplateDbOid;
5190 checkPoint.time = (pg_time_t) time(NULL);
5191 checkPoint.oldestActiveXid = InvalidTransactionId;
5193 ShmemVariableCache->nextXid = checkPoint.nextXid;
5194 ShmemVariableCache->nextOid = checkPoint.nextOid;
5195 ShmemVariableCache->oidCount = 0;
5196 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5197 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5198 SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
5200 /* Set up the XLOG page header */
5201 page->xlp_magic = XLOG_PAGE_MAGIC;
5202 page->xlp_info = XLP_LONG_HEADER;
5203 page->xlp_tli = ThisTimeLineID;
5204 page->xlp_pageaddr = XLogSegSize;
5205 longpage = (XLogLongPageHeader) page;
5206 longpage->xlp_sysid = sysidentifier;
5207 longpage->xlp_seg_size = XLogSegSize;
5208 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5210 /* Insert the initial checkpoint record */
5211 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
5212 record->xl_prev = 0;
5213 record->xl_xid = InvalidTransactionId;
5214 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
5215 record->xl_len = sizeof(checkPoint);
5216 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
5217 record->xl_rmid = RM_XLOG_ID;
5218 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
5221 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
5222 COMP_CRC32(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5224 record->xl_crc = crc;
5226 /* Create first XLOG segment file */
5227 use_existent = false;
5228 openLogFile = XLogFileInit(1, &use_existent, false);
5230 /* Write the first page with the initial record */
5232 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5234 /* if write didn't set errno, assume problem is no disk space */
5238 (errcode_for_file_access(),
5239 errmsg("could not write bootstrap transaction log file: %m")));
5242 if (pg_fsync(openLogFile) != 0)
5244 (errcode_for_file_access(),
5245 errmsg("could not fsync bootstrap transaction log file: %m")));
5247 if (close(openLogFile))
5249 (errcode_for_file_access(),
5250 errmsg("could not close bootstrap transaction log file: %m")));
5254 /* Now create pg_control */
5256 memset(ControlFile, 0, sizeof(ControlFileData));
5257 /* Initialize pg_control status fields */
5258 ControlFile->system_identifier = sysidentifier;
5259 ControlFile->state = DB_SHUTDOWNED;
5260 ControlFile->time = checkPoint.time;
5261 ControlFile->checkPoint = checkPoint.redo;
5262 ControlFile->checkPointCopy = checkPoint;
5263 ControlFile->unloggedLSN = 1;
5265 /* Set important parameter values for use when replaying WAL */
5266 ControlFile->MaxConnections = MaxConnections;
5267 ControlFile->max_worker_processes = max_worker_processes;
5268 ControlFile->max_prepared_xacts = max_prepared_xacts;
5269 ControlFile->max_locks_per_xact = max_locks_per_xact;
5270 ControlFile->wal_level = wal_level;
5271 ControlFile->data_checksum_version = bootstrap_data_checksum_version;
5273 /* some additional ControlFile fields are set in WriteControlFile() */
5277 /* Bootstrap the commit log, too */
5279 BootStrapSUBTRANS();
5280 BootStrapMultiXact();
5286 str_time(pg_time_t tnow)
5288 static char buf[128];
5290 pg_strftime(buf, sizeof(buf),
5291 "%Y-%m-%d %H:%M:%S %Z",
5292 pg_localtime(&tnow, log_timezone));
5298 * See if there is a recovery command file (recovery.conf), and if so
5299 * read in parameters for archive recovery and XLOG streaming.
5301 * The file is parsed using the main configuration parser.
5304 readRecoveryCommandFile(void)
5307 TimeLineID rtli = 0;
5308 bool rtliGiven = false;
5309 ConfigVariable *item,
5313 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
5316 if (errno == ENOENT)
5317 return; /* not there, so no archive recovery */
5319 (errcode_for_file_access(),
5320 errmsg("could not open recovery command file \"%s\": %m",
5321 RECOVERY_COMMAND_FILE)));
5325 * Since we're asking ParseConfigFp() to report errors as FATAL, there's
5326 * no need to check the return value.
5328 (void) ParseConfigFp(fd, RECOVERY_COMMAND_FILE, 0, FATAL, &head, &tail);
5332 for (item = head; item; item = item->next)
5334 if (strcmp(item->name, "restore_command") == 0)
5336 recoveryRestoreCommand = pstrdup(item->value);
5338 (errmsg_internal("restore_command = '%s'",
5339 recoveryRestoreCommand)));
5341 else if (strcmp(item->name, "recovery_end_command") == 0)
5343 recoveryEndCommand = pstrdup(item->value);
5345 (errmsg_internal("recovery_end_command = '%s'",
5346 recoveryEndCommand)));
5348 else if (strcmp(item->name, "archive_cleanup_command") == 0)
5350 archiveCleanupCommand = pstrdup(item->value);
5352 (errmsg_internal("archive_cleanup_command = '%s'",
5353 archiveCleanupCommand)));
5355 else if (strcmp(item->name, "pause_at_recovery_target") == 0)
5357 if (!parse_bool(item->value, &recoveryPauseAtTarget))
5359 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5360 errmsg("parameter \"%s\" requires a Boolean value", "pause_at_recovery_target")));
5362 (errmsg_internal("pause_at_recovery_target = '%s'",
5365 else if (strcmp(item->name, "recovery_target_timeline") == 0)
5368 if (strcmp(item->value, "latest") == 0)
5373 rtli = (TimeLineID) strtoul(item->value, NULL, 0);
5374 if (errno == EINVAL || errno == ERANGE)
5376 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
5381 (errmsg_internal("recovery_target_timeline = %u", rtli)));
5384 (errmsg_internal("recovery_target_timeline = latest")));
5386 else if (strcmp(item->name, "recovery_target_xid") == 0)
5389 recoveryTargetXid = (TransactionId) strtoul(item->value, NULL, 0);
5390 if (errno == EINVAL || errno == ERANGE)
5392 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
5395 (errmsg_internal("recovery_target_xid = %u",
5396 recoveryTargetXid)));
5397 recoveryTarget = RECOVERY_TARGET_XID;
5399 else if (strcmp(item->name, "recovery_target_time") == 0)
5402 * if recovery_target_xid or recovery_target_name specified, then
5403 * this overrides recovery_target_time
5405 if (recoveryTarget == RECOVERY_TARGET_XID ||
5406 recoveryTarget == RECOVERY_TARGET_NAME)
5408 recoveryTarget = RECOVERY_TARGET_TIME;
5411 * Convert the time string given by the user to TimestampTz form.
5413 recoveryTargetTime =
5414 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
5415 CStringGetDatum(item->value),
5416 ObjectIdGetDatum(InvalidOid),
5417 Int32GetDatum(-1)));
5419 (errmsg_internal("recovery_target_time = '%s'",
5420 timestamptz_to_str(recoveryTargetTime))));
5422 else if (strcmp(item->name, "recovery_target_name") == 0)
5425 * if recovery_target_xid specified, then this overrides
5426 * recovery_target_name
5428 if (recoveryTarget == RECOVERY_TARGET_XID)
5430 recoveryTarget = RECOVERY_TARGET_NAME;
5432 recoveryTargetName = pstrdup(item->value);
5433 if (strlen(recoveryTargetName) >= MAXFNAMELEN)
5435 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5436 errmsg("recovery_target_name is too long (maximum %d characters)",
5440 (errmsg_internal("recovery_target_name = '%s'",
5441 recoveryTargetName)));
5443 else if (strcmp(item->name, "recovery_target_inclusive") == 0)
5446 * does nothing if a recovery_target is not also set
5448 if (!parse_bool(item->value, &recoveryTargetInclusive))
5450 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5451 errmsg("parameter \"%s\" requires a Boolean value",
5452 "recovery_target_inclusive")));
5454 (errmsg_internal("recovery_target_inclusive = %s",
5457 else if (strcmp(item->name, "standby_mode") == 0)
5459 if (!parse_bool(item->value, &StandbyModeRequested))
5461 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5462 errmsg("parameter \"%s\" requires a Boolean value",
5465 (errmsg_internal("standby_mode = '%s'", item->value)));
5467 else if (strcmp(item->name, "primary_conninfo") == 0)
5469 PrimaryConnInfo = pstrdup(item->value);
5471 (errmsg_internal("primary_conninfo = '%s'",
5474 else if (strcmp(item->name, "trigger_file") == 0)
5476 TriggerFile = pstrdup(item->value);
5478 (errmsg_internal("trigger_file = '%s'",
5483 (errmsg("unrecognized recovery parameter \"%s\"",
5488 * Check for compulsory parameters
5490 if (StandbyModeRequested)
5492 if (PrimaryConnInfo == NULL && recoveryRestoreCommand == NULL)
5494 (errmsg("recovery command file \"%s\" specified neither primary_conninfo nor restore_command",
5495 RECOVERY_COMMAND_FILE),
5496 errhint("The database server will regularly poll the pg_xlog subdirectory to check for files placed there.")));
5500 if (recoveryRestoreCommand == NULL)
5502 (errmsg("recovery command file \"%s\" must specify restore_command when standby mode is not enabled",
5503 RECOVERY_COMMAND_FILE)));
5506 /* Enable fetching from archive recovery area */
5507 ArchiveRecoveryRequested = true;
5510 * If user specified recovery_target_timeline, validate it or compute the
5511 * "latest" value. We can't do this until after we've gotten the restore
5512 * command and set InArchiveRecovery, because we need to fetch timeline
5513 * history files from the archive.
5519 /* Timeline 1 does not have a history file, all else should */
5520 if (rtli != 1 && !existsTimeLineHistory(rtli))
5522 (errmsg("recovery target timeline %u does not exist",
5524 recoveryTargetTLI = rtli;
5525 recoveryTargetIsLatest = false;
5529 /* We start the "latest" search from pg_control's timeline */
5530 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
5531 recoveryTargetIsLatest = true;
5535 FreeConfigVariables(head);
5539 * Exit archive-recovery state
5542 exitArchiveRecovery(TimeLineID endTLI, XLogSegNo endLogSegNo)
5544 char recoveryPath[MAXPGPATH];
5545 char xlogpath[MAXPGPATH];
5548 * We are no longer in archive recovery state.
5550 InArchiveRecovery = false;
5553 * Update min recovery point one last time.
5555 UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
5558 * If the ending log segment is still open, close it (to avoid problems on
5559 * Windows with trying to rename or delete an open file).
5568 * If we are establishing a new timeline, we have to copy data from the
5569 * last WAL segment of the old timeline to create a starting WAL segment
5570 * for the new timeline.
5572 * Notify the archiver that the last WAL segment of the old timeline is
5573 * ready to copy to archival storage. Otherwise, it is not archived for a
5576 if (endTLI != ThisTimeLineID)
5578 XLogFileCopy(endLogSegNo, endTLI, endLogSegNo);
5580 if (XLogArchivingActive())
5582 XLogFileName(xlogpath, endTLI, endLogSegNo);
5583 XLogArchiveNotify(xlogpath);
5588 * Let's just make real sure there are not .ready or .done flags posted
5589 * for the new segment.
5591 XLogFileName(xlogpath, ThisTimeLineID, endLogSegNo);
5592 XLogArchiveCleanup(xlogpath);
5595 * Since there might be a partial WAL segment named RECOVERYXLOG, get rid
5598 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
5599 unlink(recoveryPath); /* ignore any error */
5601 /* Get rid of any remaining recovered timeline-history file, too */
5602 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
5603 unlink(recoveryPath); /* ignore any error */
5606 * Rename the config file out of the way, so that we don't accidentally
5607 * re-enter archive recovery mode in a subsequent crash.
5609 unlink(RECOVERY_COMMAND_DONE);
5610 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
5612 (errcode_for_file_access(),
5613 errmsg("could not rename file \"%s\" to \"%s\": %m",
5614 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
5617 (errmsg("archive recovery complete")));
5621 * For point-in-time recovery, this function decides whether we want to
5622 * stop applying the XLOG at or after the current record.
5624 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
5625 * *includeThis is set TRUE if we should apply this record before stopping.
5627 * We also track the timestamp of the latest applied COMMIT/ABORT
5628 * record in XLogCtl->recoveryLastXTime, for logging purposes.
5629 * Also, some information is saved in recoveryStopXid et al for use in
5630 * annotating the new timeline's history file.
5633 recoveryStopsHere(XLogRecord *record, bool *includeThis)
5637 TimestampTz recordXtime;
5638 char recordRPName[MAXFNAMELEN];
5640 /* We only consider stopping at COMMIT, ABORT or RESTORE POINT records */
5641 if (record->xl_rmid != RM_XACT_ID && record->xl_rmid != RM_XLOG_ID)
5643 record_info = record->xl_info & ~XLR_INFO_MASK;
5644 if (record->xl_rmid == RM_XACT_ID && record_info == XLOG_XACT_COMMIT_COMPACT)
5646 xl_xact_commit_compact *recordXactCommitData;
5648 recordXactCommitData = (xl_xact_commit_compact *) XLogRecGetData(record);
5649 recordXtime = recordXactCommitData->xact_time;
5651 else if (record->xl_rmid == RM_XACT_ID && record_info == XLOG_XACT_COMMIT)
5653 xl_xact_commit *recordXactCommitData;
5655 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
5656 recordXtime = recordXactCommitData->xact_time;
5658 else if (record->xl_rmid == RM_XACT_ID && record_info == XLOG_XACT_ABORT)
5660 xl_xact_abort *recordXactAbortData;
5662 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
5663 recordXtime = recordXactAbortData->xact_time;
5665 else if (record->xl_rmid == RM_XLOG_ID && record_info == XLOG_RESTORE_POINT)
5667 xl_restore_point *recordRestorePointData;
5669 recordRestorePointData = (xl_restore_point *) XLogRecGetData(record);
5670 recordXtime = recordRestorePointData->rp_time;
5671 strncpy(recordRPName, recordRestorePointData->rp_name, MAXFNAMELEN);
5676 /* Do we have a PITR target at all? */
5677 if (recoveryTarget == RECOVERY_TARGET_UNSET)
5680 * Save timestamp of latest transaction commit/abort if this is a
5681 * transaction record
5683 if (record->xl_rmid == RM_XACT_ID)
5684 SetLatestXTime(recordXtime);
5688 if (recoveryTarget == RECOVERY_TARGET_XID)
5691 * There can be only one transaction end record with this exact
5694 * when testing for an xid, we MUST test for equality only, since
5695 * transactions are numbered in the order they start, not the order
5696 * they complete. A higher numbered xid will complete before you about
5697 * 50% of the time...
5699 stopsHere = (record->xl_xid == recoveryTargetXid);
5701 *includeThis = recoveryTargetInclusive;
5703 else if (recoveryTarget == RECOVERY_TARGET_NAME)
5706 * There can be many restore points that share the same name, so we
5707 * stop at the first one
5709 stopsHere = (strcmp(recordRPName, recoveryTargetName) == 0);
5712 * Ignore recoveryTargetInclusive because this is not a transaction
5715 *includeThis = false;
5720 * There can be many transactions that share the same commit time, so
5721 * we stop after the last one, if we are inclusive, or stop at the
5722 * first one if we are exclusive
5724 if (recoveryTargetInclusive)
5725 stopsHere = (recordXtime > recoveryTargetTime);
5727 stopsHere = (recordXtime >= recoveryTargetTime);
5729 *includeThis = false;
5734 recoveryStopXid = record->xl_xid;
5735 recoveryStopTime = recordXtime;
5736 recoveryStopAfter = *includeThis;
5738 if (record_info == XLOG_XACT_COMMIT_COMPACT || record_info == XLOG_XACT_COMMIT)
5740 if (recoveryStopAfter)
5742 (errmsg("recovery stopping after commit of transaction %u, time %s",
5744 timestamptz_to_str(recoveryStopTime))));
5747 (errmsg("recovery stopping before commit of transaction %u, time %s",
5749 timestamptz_to_str(recoveryStopTime))));
5751 else if (record_info == XLOG_XACT_ABORT)
5753 if (recoveryStopAfter)
5755 (errmsg("recovery stopping after abort of transaction %u, time %s",
5757 timestamptz_to_str(recoveryStopTime))));
5760 (errmsg("recovery stopping before abort of transaction %u, time %s",
5762 timestamptz_to_str(recoveryStopTime))));
5766 strncpy(recoveryStopName, recordRPName, MAXFNAMELEN);
5769 (errmsg("recovery stopping at restore point \"%s\", time %s",
5771 timestamptz_to_str(recoveryStopTime))));
5775 * Note that if we use a RECOVERY_TARGET_TIME then we can stop at a
5776 * restore point since they are timestamped, though the latest
5777 * transaction time is not updated.
5779 if (record->xl_rmid == RM_XACT_ID && recoveryStopAfter)
5780 SetLatestXTime(recordXtime);
5782 else if (record->xl_rmid == RM_XACT_ID)
5783 SetLatestXTime(recordXtime);
5789 * Wait until shared recoveryPause flag is cleared.
5791 * XXX Could also be done with shared latch, avoiding the pg_usleep loop.
5792 * Probably not worth the trouble though. This state shouldn't be one that
5793 * anyone cares about server power consumption in.
5796 recoveryPausesHere(void)
5798 /* Don't pause unless users can connect! */
5799 if (!LocalHotStandbyActive)
5803 (errmsg("recovery has paused"),
5804 errhint("Execute pg_xlog_replay_resume() to continue.")));
5806 while (RecoveryIsPaused())
5808 pg_usleep(1000000L); /* 1000 ms */
5809 HandleStartupProcInterrupts();
5814 RecoveryIsPaused(void)
5816 /* use volatile pointer to prevent code rearrangement */
5817 volatile XLogCtlData *xlogctl = XLogCtl;
5820 SpinLockAcquire(&xlogctl->info_lck);
5821 recoveryPause = xlogctl->recoveryPause;
5822 SpinLockRelease(&xlogctl->info_lck);
5824 return recoveryPause;
5828 SetRecoveryPause(bool recoveryPause)
5830 /* use volatile pointer to prevent code rearrangement */
5831 volatile XLogCtlData *xlogctl = XLogCtl;
5833 SpinLockAcquire(&xlogctl->info_lck);
5834 xlogctl->recoveryPause = recoveryPause;
5835 SpinLockRelease(&xlogctl->info_lck);
5839 * Save timestamp of latest processed commit/abort record.
5841 * We keep this in XLogCtl, not a simple static variable, so that it can be
5842 * seen by processes other than the startup process. Note in particular
5843 * that CreateRestartPoint is executed in the checkpointer.
5846 SetLatestXTime(TimestampTz xtime)
5848 /* use volatile pointer to prevent code rearrangement */
5849 volatile XLogCtlData *xlogctl = XLogCtl;
5851 SpinLockAcquire(&xlogctl->info_lck);
5852 xlogctl->recoveryLastXTime = xtime;
5853 SpinLockRelease(&xlogctl->info_lck);
5857 * Fetch timestamp of latest processed commit/abort record.
5860 GetLatestXTime(void)
5862 /* use volatile pointer to prevent code rearrangement */
5863 volatile XLogCtlData *xlogctl = XLogCtl;
5866 SpinLockAcquire(&xlogctl->info_lck);
5867 xtime = xlogctl->recoveryLastXTime;
5868 SpinLockRelease(&xlogctl->info_lck);
5874 * Save timestamp of the next chunk of WAL records to apply.
5876 * We keep this in XLogCtl, not a simple static variable, so that it can be
5877 * seen by all backends.
5880 SetCurrentChunkStartTime(TimestampTz xtime)
5882 /* use volatile pointer to prevent code rearrangement */
5883 volatile XLogCtlData *xlogctl = XLogCtl;
5885 SpinLockAcquire(&xlogctl->info_lck);
5886 xlogctl->currentChunkStartTime = xtime;
5887 SpinLockRelease(&xlogctl->info_lck);
5891 * Fetch timestamp of latest processed commit/abort record.
5892 * Startup process maintains an accurate local copy in XLogReceiptTime
5895 GetCurrentChunkReplayStartTime(void)
5897 /* use volatile pointer to prevent code rearrangement */
5898 volatile XLogCtlData *xlogctl = XLogCtl;
5901 SpinLockAcquire(&xlogctl->info_lck);
5902 xtime = xlogctl->currentChunkStartTime;
5903 SpinLockRelease(&xlogctl->info_lck);
5909 * Returns time of receipt of current chunk of XLOG data, as well as
5910 * whether it was received from streaming replication or from archives.
5913 GetXLogReceiptTime(TimestampTz *rtime, bool *fromStream)
5916 * This must be executed in the startup process, since we don't export the
5917 * relevant state to shared memory.
5921 *rtime = XLogReceiptTime;
5922 *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
5926 * Note that text field supplied is a parameter name and does not require
5929 #define RecoveryRequiresIntParameter(param_name, currValue, minValue) \
5931 if ((currValue) < (minValue)) \
5933 (errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
5934 errmsg("hot standby is not possible because " \
5935 "%s = %d is a lower setting than on the master server " \
5936 "(its value was %d)", \
5943 * Check to see if required parameters are set high enough on this server
5944 * for various aspects of recovery operation.
5947 CheckRequiredParameterValues(void)
5950 * For archive recovery, the WAL must be generated with at least 'archive'
5953 if (InArchiveRecovery && ControlFile->wal_level == WAL_LEVEL_MINIMAL)
5956 (errmsg("WAL was generated with wal_level=minimal, data may be missing"),
5957 errhint("This happens if you temporarily set wal_level=minimal without taking a new base backup.")));
5961 * For Hot Standby, the WAL must be generated with 'hot_standby' mode, and
5962 * we must have at least as many backend slots as the primary.
5964 if (InArchiveRecovery && EnableHotStandby)
5966 if (ControlFile->wal_level < WAL_LEVEL_HOT_STANDBY)
5968 (errmsg("hot standby is not possible because wal_level was not set to \"hot_standby\" on the master server"),
5969 errhint("Either set wal_level to \"hot_standby\" on the master, or turn off hot_standby here.")));
5971 /* We ignore autovacuum_max_workers when we make this test. */
5972 RecoveryRequiresIntParameter("max_connections",
5974 ControlFile->MaxConnections);
5975 RecoveryRequiresIntParameter("max_worker_processes",
5976 max_worker_processes,
5977 ControlFile->max_worker_processes);
5978 RecoveryRequiresIntParameter("max_prepared_transactions",
5980 ControlFile->max_prepared_xacts);
5981 RecoveryRequiresIntParameter("max_locks_per_transaction",
5983 ControlFile->max_locks_per_xact);
5988 * This must be called ONCE during postmaster or standalone-backend startup
5993 XLogCtlInsert *Insert;
5994 CheckPoint checkPoint;
5996 bool reachedStopPoint = false;
5997 bool haveBackupLabel = false;
6001 XLogSegNo endLogSegNo;
6002 TimeLineID PrevTimeLineID;
6004 TransactionId oldestActiveXID;
6005 bool backupEndRequired = false;
6006 bool backupFromStandby = false;
6007 DBState dbstate_at_startup;
6008 XLogReaderState *xlogreader;
6009 XLogPageReadPrivate private;
6010 bool fast_promoted = false;
6013 * Read control file and check XLOG status looks valid.
6015 * Note: in most control paths, *ControlFile is already valid and we need
6016 * not do ReadControlFile() here, but might as well do it to be sure.
6020 if (ControlFile->state < DB_SHUTDOWNED ||
6021 ControlFile->state > DB_IN_PRODUCTION ||
6022 !XRecOffIsValid(ControlFile->checkPoint))
6024 (errmsg("control file contains invalid data")));
6026 if (ControlFile->state == DB_SHUTDOWNED)
6028 /* This is the expected case, so don't be chatty in standalone mode */
6029 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
6030 (errmsg("database system was shut down at %s",
6031 str_time(ControlFile->time))));
6033 else if (ControlFile->state == DB_SHUTDOWNED_IN_RECOVERY)
6035 (errmsg("database system was shut down in recovery at %s",
6036 str_time(ControlFile->time))));
6037 else if (ControlFile->state == DB_SHUTDOWNING)
6039 (errmsg("database system shutdown was interrupted; last known up at %s",
6040 str_time(ControlFile->time))));
6041 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
6043 (errmsg("database system was interrupted while in recovery at %s",
6044 str_time(ControlFile->time)),
6045 errhint("This probably means that some data is corrupted and"
6046 " you will have to use the last backup for recovery.")));
6047 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
6049 (errmsg("database system was interrupted while in recovery at log time %s",
6050 str_time(ControlFile->checkPointCopy.time)),
6051 errhint("If this has occurred more than once some data might be corrupted"
6052 " and you might need to choose an earlier recovery target.")));
6053 else if (ControlFile->state == DB_IN_PRODUCTION)
6055 (errmsg("database system was interrupted; last known up at %s",
6056 str_time(ControlFile->time))));
6058 /* This is just to allow attaching to startup process with a debugger */
6059 #ifdef XLOG_REPLAY_DELAY
6060 if (ControlFile->state != DB_SHUTDOWNED)
6061 pg_usleep(60000000L);
6065 * Verify that pg_xlog and pg_xlog/archive_status exist. In cases where
6066 * someone has performed a copy for PITR, these directories may have been
6067 * excluded and need to be re-created.
6069 ValidateXLOGDirectoryStructure();
6072 * Clear out any old relcache cache files. This is *necessary* if we do
6073 * any WAL replay, since that would probably result in the cache files
6074 * being out of sync with database reality. In theory we could leave them
6075 * in place if the database had been cleanly shut down, but it seems
6076 * safest to just remove them always and let them be rebuilt during the
6077 * first backend startup.
6079 RelationCacheInitFileRemove();
6082 * Initialize on the assumption we want to recover to the latest timeline
6083 * that's active according to pg_control.
6085 if (ControlFile->minRecoveryPointTLI >
6086 ControlFile->checkPointCopy.ThisTimeLineID)
6087 recoveryTargetTLI = ControlFile->minRecoveryPointTLI;
6089 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
6092 * Check for recovery control file, and if so set up state for offline
6095 readRecoveryCommandFile();
6098 * Save archive_cleanup_command in shared memory so that other processes
6101 strncpy(XLogCtl->archiveCleanupCommand,
6102 archiveCleanupCommand ? archiveCleanupCommand : "",
6103 sizeof(XLogCtl->archiveCleanupCommand));
6105 if (ArchiveRecoveryRequested)
6107 if (StandbyModeRequested)
6109 (errmsg("entering standby mode")));
6110 else if (recoveryTarget == RECOVERY_TARGET_XID)
6112 (errmsg("starting point-in-time recovery to XID %u",
6113 recoveryTargetXid)));
6114 else if (recoveryTarget == RECOVERY_TARGET_TIME)
6116 (errmsg("starting point-in-time recovery to %s",
6117 timestamptz_to_str(recoveryTargetTime))));
6118 else if (recoveryTarget == RECOVERY_TARGET_NAME)
6120 (errmsg("starting point-in-time recovery to \"%s\"",
6121 recoveryTargetName)));
6124 (errmsg("starting archive recovery")));
6128 * Take ownership of the wakeup latch if we're going to sleep during
6131 if (StandbyModeRequested)
6132 OwnLatch(&XLogCtl->recoveryWakeupLatch);
6134 /* Set up XLOG reader facility */
6135 MemSet(&private, 0, sizeof(XLogPageReadPrivate));
6136 xlogreader = XLogReaderAllocate(&XLogPageRead, &private);
6139 (errcode(ERRCODE_OUT_OF_MEMORY),
6140 errmsg("out of memory"),
6141 errdetail("Failed while allocating an XLog reading processor.")));
6142 xlogreader->system_identifier = ControlFile->system_identifier;
6144 if (read_backup_label(&checkPointLoc, &backupEndRequired,
6145 &backupFromStandby))
6148 * Archive recovery was requested, and thanks to the backup label
6149 * file, we know how far we need to replay to reach consistency. Enter
6150 * archive recovery directly.
6152 InArchiveRecovery = true;
6153 if (StandbyModeRequested)
6157 * When a backup_label file is present, we want to roll forward from
6158 * the checkpoint it identifies, rather than using pg_control.
6160 record = ReadCheckpointRecord(xlogreader, checkPointLoc, 0, true);
6163 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6164 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
6166 (errmsg("checkpoint record is at %X/%X",
6167 (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6168 InRecovery = true; /* force recovery even if SHUTDOWNED */
6171 * Make sure that REDO location exists. This may not be the case
6172 * if there was a crash during an online backup, which left a
6173 * backup_label around that references a WAL segment that's
6174 * already been archived.
6176 if (checkPoint.redo < checkPointLoc)
6178 if (!ReadRecord(xlogreader, checkPoint.redo, LOG, false))
6180 (errmsg("could not find redo location referenced by checkpoint record"),
6181 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6187 (errmsg("could not locate required checkpoint record"),
6188 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6189 wasShutdown = false; /* keep compiler quiet */
6191 /* set flag to delete it later */
6192 haveBackupLabel = true;
6197 * It's possible that archive recovery was requested, but we don't
6198 * know how far we need to replay the WAL before we reach consistency.
6199 * This can happen for example if a base backup is taken from a
6200 * running server using an atomic filesystem snapshot, without calling
6201 * pg_start/stop_backup. Or if you just kill a running master server
6202 * and put it into archive recovery by creating a recovery.conf file.
6204 * Our strategy in that case is to perform crash recovery first,
6205 * replaying all the WAL present in pg_xlog, and only enter archive
6206 * recovery after that.
6208 * But usually we already know how far we need to replay the WAL (up
6209 * to minRecoveryPoint, up to backupEndPoint, or until we see an
6210 * end-of-backup record), and we can enter archive recovery directly.
6212 if (ArchiveRecoveryRequested &&
6213 (ControlFile->minRecoveryPoint != InvalidXLogRecPtr ||
6214 ControlFile->backupEndRequired ||
6215 ControlFile->backupEndPoint != InvalidXLogRecPtr ||
6216 ControlFile->state == DB_SHUTDOWNED))
6218 InArchiveRecovery = true;
6219 if (StandbyModeRequested)
6224 * Get the last valid checkpoint record. If the latest one according
6225 * to pg_control is broken, try the next-to-last one.
6227 checkPointLoc = ControlFile->checkPoint;
6228 RedoStartLSN = ControlFile->checkPointCopy.redo;
6229 record = ReadCheckpointRecord(xlogreader, checkPointLoc, 1, true);
6233 (errmsg("checkpoint record is at %X/%X",
6234 (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6236 else if (StandbyMode)
6239 * The last valid checkpoint record required for a streaming
6240 * recovery exists in neither standby nor the primary.
6243 (errmsg("could not locate a valid checkpoint record")));
6247 checkPointLoc = ControlFile->prevCheckPoint;
6248 record = ReadCheckpointRecord(xlogreader, checkPointLoc, 2, true);
6252 (errmsg("using previous checkpoint record at %X/%X",
6253 (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6254 InRecovery = true; /* force recovery even if SHUTDOWNED */
6258 (errmsg("could not locate a valid checkpoint record")));
6260 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6261 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
6265 * If the location of the checkpoint record is not on the expected
6266 * timeline in the history of the requested timeline, we cannot proceed:
6267 * the backup is not part of the history of the requested timeline.
6269 Assert(expectedTLEs); /* was initialized by reading checkpoint
6271 if (tliOfPointInHistory(checkPointLoc, expectedTLEs) !=
6272 checkPoint.ThisTimeLineID)
6274 XLogRecPtr switchpoint;
6277 * tliSwitchPoint will throw an error if the checkpoint's timeline is
6278 * not in expectedTLEs at all.
6280 switchpoint = tliSwitchPoint(ControlFile->checkPointCopy.ThisTimeLineID, expectedTLEs, NULL);
6282 (errmsg("requested timeline %u is not a child of this server's history",
6284 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.",
6285 (uint32) (ControlFile->checkPoint >> 32),
6286 (uint32) ControlFile->checkPoint,
6287 ControlFile->checkPointCopy.ThisTimeLineID,
6288 (uint32) (switchpoint >> 32),
6289 (uint32) switchpoint)));
6293 * The min recovery point should be part of the requested timeline's
6296 if (!XLogRecPtrIsInvalid(ControlFile->minRecoveryPoint) &&
6297 tliOfPointInHistory(ControlFile->minRecoveryPoint - 1, expectedTLEs) !=
6298 ControlFile->minRecoveryPointTLI)
6300 (errmsg("requested timeline %u does not contain minimum recovery point %X/%X on timeline %u",
6302 (uint32) (ControlFile->minRecoveryPoint >> 32),
6303 (uint32) ControlFile->minRecoveryPoint,
6304 ControlFile->minRecoveryPointTLI)));
6306 LastRec = RecPtr = checkPointLoc;
6309 (errmsg("redo record is at %X/%X; shutdown %s",
6310 (uint32) (checkPoint.redo >> 32), (uint32) checkPoint.redo,
6311 wasShutdown ? "TRUE" : "FALSE")));
6313 (errmsg("next transaction ID: %u/%u; next OID: %u",
6314 checkPoint.nextXidEpoch, checkPoint.nextXid,
6315 checkPoint.nextOid)));
6317 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
6318 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
6320 (errmsg("oldest unfrozen transaction ID: %u, in database %u",
6321 checkPoint.oldestXid, checkPoint.oldestXidDB)));
6323 (errmsg("oldest MultiXactId: %u, in database %u",
6324 checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
6325 if (!TransactionIdIsNormal(checkPoint.nextXid))
6327 (errmsg("invalid next transaction ID")));
6329 /* initialize shared memory variables from the checkpoint record */
6330 ShmemVariableCache->nextXid = checkPoint.nextXid;
6331 ShmemVariableCache->nextOid = checkPoint.nextOid;
6332 ShmemVariableCache->oidCount = 0;
6333 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
6334 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
6335 SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
6336 XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
6337 XLogCtl->ckptXid = checkPoint.nextXid;
6340 * Initialize unlogged LSN. On a clean shutdown, it's restored from the
6341 * control file. On recovery, all unlogged relations are blown away, so
6342 * the unlogged LSN counter can be reset too.
6344 if (ControlFile->state == DB_SHUTDOWNED)
6345 XLogCtl->unloggedLSN = ControlFile->unloggedLSN;
6347 XLogCtl->unloggedLSN = 1;
6350 * We must replay WAL entries using the same TimeLineID they were created
6351 * under, so temporarily adopt the TLI indicated by the checkpoint (see
6352 * also xlog_redo()).
6354 ThisTimeLineID = checkPoint.ThisTimeLineID;
6357 * Copy any missing timeline history files between 'now' and the recovery
6358 * target timeline from archive to pg_xlog. While we don't need those
6359 * files ourselves - the history file of the recovery target timeline
6360 * covers all the previous timelines in the history too - a cascading
6361 * standby server might be interested in them. Or, if you archive the WAL
6362 * from this server to a different archive than the master, it'd be good
6363 * for all the history files to get archived there after failover, so that
6364 * you can use one of the old timelines as a PITR target. Timeline history
6365 * files are small, so it's better to copy them unnecessarily than not
6366 * copy them and regret later.
6368 restoreTimeLineHistoryFiles(ThisTimeLineID, recoveryTargetTLI);
6370 lastFullPageWrites = checkPoint.fullPageWrites;
6372 RedoRecPtr = XLogCtl->RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
6374 if (RecPtr < checkPoint.redo)
6376 (errmsg("invalid redo in checkpoint record")));
6379 * Check whether we need to force recovery from WAL. If it appears to
6380 * have been a clean shutdown and we did not have a recovery.conf file,
6381 * then assume no recovery needed.
6383 if (checkPoint.redo < RecPtr)
6387 (errmsg("invalid redo record in shutdown checkpoint")));
6390 else if (ControlFile->state != DB_SHUTDOWNED)
6392 else if (ArchiveRecoveryRequested)
6394 /* force recovery due to presence of recovery.conf */
6403 /* use volatile pointer to prevent code rearrangement */
6404 volatile XLogCtlData *xlogctl = XLogCtl;
6407 * Update pg_control to show that we are recovering and to show the
6408 * selected checkpoint as the place we are starting from. We also mark
6409 * pg_control with any minimum recovery stop point obtained from a
6410 * backup history file.
6412 dbstate_at_startup = ControlFile->state;
6413 if (InArchiveRecovery)
6414 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
6418 (errmsg("database system was not properly shut down; "
6419 "automatic recovery in progress")));
6420 if (recoveryTargetTLI > ControlFile->checkPointCopy.ThisTimeLineID)
6422 (errmsg("crash recovery starts in timeline %u "
6423 "and has target timeline %u",
6424 ControlFile->checkPointCopy.ThisTimeLineID,
6425 recoveryTargetTLI)));
6426 ControlFile->state = DB_IN_CRASH_RECOVERY;
6428 ControlFile->prevCheckPoint = ControlFile->checkPoint;
6429 ControlFile->checkPoint = checkPointLoc;
6430 ControlFile->checkPointCopy = checkPoint;
6431 if (InArchiveRecovery)
6433 /* initialize minRecoveryPoint if not set yet */
6434 if (ControlFile->minRecoveryPoint < checkPoint.redo)
6436 ControlFile->minRecoveryPoint = checkPoint.redo;
6437 ControlFile->minRecoveryPointTLI = checkPoint.ThisTimeLineID;
6442 * Set backupStartPoint if we're starting recovery from a base backup.
6444 * Set backupEndPoint and use minRecoveryPoint as the backup end
6445 * location if we're starting recovery from a base backup which was
6446 * taken from the standby. In this case, the database system status in
6447 * pg_control must indicate DB_IN_ARCHIVE_RECOVERY. If not, which
6448 * means that backup is corrupted, so we cancel recovery.
6450 if (haveBackupLabel)
6452 ControlFile->backupStartPoint = checkPoint.redo;
6453 ControlFile->backupEndRequired = backupEndRequired;
6455 if (backupFromStandby)
6457 if (dbstate_at_startup != DB_IN_ARCHIVE_RECOVERY)
6459 (errmsg("backup_label contains data inconsistent with control file"),
6460 errhint("This means that the backup is corrupted and you will "
6461 "have to use another backup for recovery.")));
6462 ControlFile->backupEndPoint = ControlFile->minRecoveryPoint;
6465 ControlFile->time = (pg_time_t) time(NULL);
6466 /* No need to hold ControlFileLock yet, we aren't up far enough */
6467 UpdateControlFile();
6469 /* initialize our local copy of minRecoveryPoint */
6470 minRecoveryPoint = ControlFile->minRecoveryPoint;
6471 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
6474 * Reset pgstat data, because it may be invalid after recovery.
6479 * If there was a backup label file, it's done its job and the info
6480 * has now been propagated into pg_control. We must get rid of the
6481 * label file so that if we crash during recovery, we'll pick up at
6482 * the latest recovery restartpoint instead of going all the way back
6483 * to the backup start point. It seems prudent though to just rename
6484 * the file out of the way rather than delete it completely.
6486 if (haveBackupLabel)
6488 unlink(BACKUP_LABEL_OLD);
6489 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
6491 (errcode_for_file_access(),
6492 errmsg("could not rename file \"%s\" to \"%s\": %m",
6493 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
6496 /* Check that the GUCs used to generate the WAL allow recovery */
6497 CheckRequiredParameterValues();
6500 * We're in recovery, so unlogged relations may be trashed and must be
6501 * reset. This should be done BEFORE allowing Hot Standby
6502 * connections, so that read-only backends don't try to read whatever
6503 * garbage is left over from before.
6505 ResetUnloggedRelations(UNLOGGED_RELATION_CLEANUP);
6508 * Likewise, delete any saved transaction snapshot files that got left
6509 * behind by crashed backends.
6511 DeleteAllExportedSnapshotFiles();
6514 * Initialize for Hot Standby, if enabled. We won't let backends in
6515 * yet, not until we've reached the min recovery point specified in
6516 * control file and we've established a recovery snapshot from a
6517 * running-xacts WAL record.
6519 if (ArchiveRecoveryRequested && EnableHotStandby)
6521 TransactionId *xids;
6525 (errmsg("initializing for hot standby")));
6527 InitRecoveryTransactionEnvironment();
6530 oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
6532 oldestActiveXID = checkPoint.oldestActiveXid;
6533 Assert(TransactionIdIsValid(oldestActiveXID));
6535 /* Tell procarray about the range of xids it has to deal with */
6536 ProcArrayInitRecovery(ShmemVariableCache->nextXid);
6539 * Startup commit log and subtrans only. Other SLRUs are not
6540 * maintained during recovery and need not be started yet.
6543 StartupSUBTRANS(oldestActiveXID);
6546 * If we're beginning at a shutdown checkpoint, we know that
6547 * nothing was running on the master at this point. So fake-up an
6548 * empty running-xacts record and use that here and now. Recover
6549 * additional standby state for prepared transactions.
6553 RunningTransactionsData running;
6554 TransactionId latestCompletedXid;
6557 * Construct a RunningTransactions snapshot representing a
6558 * shut down server, with only prepared transactions still
6559 * alive. We're never overflowed at this point because all
6560 * subxids are listed with their parent prepared transactions.
6562 running.xcnt = nxids;
6563 running.subxcnt = 0;
6564 running.subxid_overflow = false;
6565 running.nextXid = checkPoint.nextXid;
6566 running.oldestRunningXid = oldestActiveXID;
6567 latestCompletedXid = checkPoint.nextXid;
6568 TransactionIdRetreat(latestCompletedXid);
6569 Assert(TransactionIdIsNormal(latestCompletedXid));
6570 running.latestCompletedXid = latestCompletedXid;
6571 running.xids = xids;
6573 ProcArrayApplyRecoveryInfo(&running);
6575 StandbyRecoverPreparedTransactions(false);
6579 /* Initialize resource managers */
6580 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
6582 if (RmgrTable[rmid].rm_startup != NULL)
6583 RmgrTable[rmid].rm_startup();
6587 * Initialize shared replayEndRecPtr, lastReplayedEndRecPtr, and
6588 * recoveryLastXTime.
6590 * This is slightly confusing if we're starting from an online
6591 * checkpoint; we've just read and replayed the checkpoint record, but
6592 * we're going to start replay from its redo pointer, which precedes
6593 * the location of the checkpoint record itself. So even though the
6594 * last record we've replayed is indeed ReadRecPtr, we haven't
6595 * replayed all the preceding records yet. That's OK for the current
6596 * use of these variables.
6598 SpinLockAcquire(&xlogctl->info_lck);
6599 xlogctl->replayEndRecPtr = ReadRecPtr;
6600 xlogctl->replayEndTLI = ThisTimeLineID;
6601 xlogctl->lastReplayedEndRecPtr = EndRecPtr;
6602 xlogctl->lastReplayedTLI = ThisTimeLineID;
6603 xlogctl->recoveryLastXTime = 0;
6604 xlogctl->currentChunkStartTime = 0;
6605 xlogctl->recoveryPause = false;
6606 SpinLockRelease(&xlogctl->info_lck);
6608 /* Also ensure XLogReceiptTime has a sane value */
6609 XLogReceiptTime = GetCurrentTimestamp();
6612 * Let postmaster know we've started redo now, so that it can launch
6613 * checkpointer to perform restartpoints. We don't bother during
6614 * crash recovery as restartpoints can only be performed during
6615 * archive recovery. And we'd like to keep crash recovery simple, to
6616 * avoid introducing bugs that could affect you when recovering after
6619 * After this point, we can no longer assume that we're the only
6620 * process in addition to postmaster! Also, fsync requests are
6621 * subsequently to be handled by the checkpointer, not locally.
6623 if (ArchiveRecoveryRequested && IsUnderPostmaster)
6625 PublishStartupProcessInformation();
6626 SetForwardFsyncRequests();
6627 SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED);
6628 bgwriterLaunched = true;
6632 * Allow read-only connections immediately if we're consistent
6635 CheckRecoveryConsistency();
6638 * Find the first record that logically follows the checkpoint --- it
6639 * might physically precede it, though.
6641 if (checkPoint.redo < RecPtr)
6643 /* back up to find the record */
6644 record = ReadRecord(xlogreader, checkPoint.redo, PANIC, false);
6648 /* just have to read next record after CheckPoint */
6649 record = ReadRecord(xlogreader, InvalidXLogRecPtr, LOG, false);
6654 bool recoveryContinue = true;
6655 bool recoveryApply = true;
6656 ErrorContextCallback errcallback;
6662 (errmsg("redo starts at %X/%X",
6663 (uint32) (ReadRecPtr >> 32), (uint32) ReadRecPtr)));
6666 * main redo apply loop
6670 bool switchedTLI = false;
6674 (rmid == RM_XACT_ID && trace_recovery_messages <= DEBUG2) ||
6675 (rmid != RM_XACT_ID && trace_recovery_messages <= DEBUG3))
6679 initStringInfo(&buf);
6680 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
6681 (uint32) (ReadRecPtr >> 32), (uint32) ReadRecPtr,
6682 (uint32) (EndRecPtr >> 32), (uint32) EndRecPtr);
6683 xlog_outrec(&buf, record);
6684 appendStringInfo(&buf, " - ");
6685 RmgrTable[record->xl_rmid].rm_desc(&buf,
6687 XLogRecGetData(record));
6688 elog(LOG, "%s", buf.data);
6693 /* Handle interrupt signals of startup process */
6694 HandleStartupProcInterrupts();
6697 * Pause WAL replay, if requested by a hot-standby session via
6698 * SetRecoveryPause().
6700 * Note that we intentionally don't take the info_lck spinlock
6701 * here. We might therefore read a slightly stale value of
6702 * the recoveryPause flag, but it can't be very stale (no
6703 * worse than the last spinlock we did acquire). Since a
6704 * pause request is a pretty asynchronous thing anyway,
6705 * possibly responding to it one WAL record later than we
6706 * otherwise would is a minor issue, so it doesn't seem worth
6707 * adding another spinlock cycle to prevent that.
6709 if (xlogctl->recoveryPause)
6710 recoveryPausesHere();
6713 * Have we reached our recovery target?
6715 if (recoveryStopsHere(record, &recoveryApply))
6717 if (recoveryPauseAtTarget)
6719 SetRecoveryPause(true);
6720 recoveryPausesHere();
6722 reachedStopPoint = true; /* see below */
6723 recoveryContinue = false;
6725 /* Exit loop if we reached non-inclusive recovery target */
6730 /* Setup error traceback support for ereport() */
6731 errcallback.callback = rm_redo_error_callback;
6732 errcallback.arg = (void *) record;
6733 errcallback.previous = error_context_stack;
6734 error_context_stack = &errcallback;
6737 * ShmemVariableCache->nextXid must be beyond record's xid.
6739 * We don't expect anyone else to modify nextXid, hence we
6740 * don't need to hold a lock while examining it. We still
6741 * acquire the lock to modify it, though.
6743 if (TransactionIdFollowsOrEquals(record->xl_xid,
6744 ShmemVariableCache->nextXid))
6746 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
6747 ShmemVariableCache->nextXid = record->xl_xid;
6748 TransactionIdAdvance(ShmemVariableCache->nextXid);
6749 LWLockRelease(XidGenLock);
6753 * Before replaying this record, check if this record causes
6754 * the current timeline to change. The record is already
6755 * considered to be part of the new timeline, so we update
6756 * ThisTimeLineID before replaying it. That's important so
6757 * that replayEndTLI, which is recorded as the minimum
6758 * recovery point's TLI if recovery stops after this record,
6761 if (record->xl_rmid == RM_XLOG_ID)
6763 TimeLineID newTLI = ThisTimeLineID;
6764 TimeLineID prevTLI = ThisTimeLineID;
6765 uint8 info = record->xl_info & ~XLR_INFO_MASK;
6767 if (info == XLOG_CHECKPOINT_SHUTDOWN)
6769 CheckPoint checkPoint;
6771 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6772 newTLI = checkPoint.ThisTimeLineID;
6773 prevTLI = checkPoint.PrevTimeLineID;
6775 else if (info == XLOG_END_OF_RECOVERY)
6777 xl_end_of_recovery xlrec;
6779 memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_end_of_recovery));
6780 newTLI = xlrec.ThisTimeLineID;
6781 prevTLI = xlrec.PrevTimeLineID;
6784 if (newTLI != ThisTimeLineID)
6786 /* Check that it's OK to switch to this TLI */
6787 checkTimeLineSwitch(EndRecPtr, newTLI, prevTLI);
6789 /* Following WAL records should be run with new TLI */
6790 ThisTimeLineID = newTLI;
6796 * Update shared replayEndRecPtr before replaying this record,
6797 * so that XLogFlush will update minRecoveryPoint correctly.
6799 SpinLockAcquire(&xlogctl->info_lck);
6800 xlogctl->replayEndRecPtr = EndRecPtr;
6801 xlogctl->replayEndTLI = ThisTimeLineID;
6802 SpinLockRelease(&xlogctl->info_lck);
6805 * If we are attempting to enter Hot Standby mode, process
6808 if (standbyState >= STANDBY_INITIALIZED &&
6809 TransactionIdIsValid(record->xl_xid))
6810 RecordKnownAssignedTransactionIds(record->xl_xid);
6812 /* Now apply the WAL record itself */
6813 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
6815 /* Pop the error context stack */
6816 error_context_stack = errcallback.previous;
6819 * Update lastReplayedEndRecPtr after this record has been
6820 * successfully replayed.
6822 SpinLockAcquire(&xlogctl->info_lck);
6823 xlogctl->lastReplayedEndRecPtr = EndRecPtr;
6824 xlogctl->lastReplayedTLI = ThisTimeLineID;
6825 SpinLockRelease(&xlogctl->info_lck);
6827 /* Remember this record as the last-applied one */
6828 LastRec = ReadRecPtr;
6830 /* Allow read-only connections if we're consistent now */
6831 CheckRecoveryConsistency();
6834 * If this record was a timeline switch, wake up any
6835 * walsenders to notice that we are on a new timeline.
6837 if (switchedTLI && AllowCascadeReplication())
6840 /* Exit loop if we reached inclusive recovery target */
6841 if (!recoveryContinue)
6844 /* Else, try to fetch the next WAL record */
6845 record = ReadRecord(xlogreader, InvalidXLogRecPtr, LOG, false);
6846 } while (record != NULL);
6849 * end of main redo apply loop
6853 (errmsg("redo done at %X/%X",
6854 (uint32) (ReadRecPtr >> 32), (uint32) ReadRecPtr)));
6855 xtime = GetLatestXTime();
6858 (errmsg("last completed transaction was at log time %s",
6859 timestamptz_to_str(xtime))));
6864 /* there are no WAL records following the checkpoint */
6866 (errmsg("redo is not required")));
6871 * Kill WAL receiver, if it's still running, before we continue to write
6872 * the startup checkpoint record. It will trump over the checkpoint and
6873 * subsequent records if it's still alive when we start writing WAL.
6878 * We don't need the latch anymore. It's not strictly necessary to disown
6879 * it, but let's do it for the sake of tidiness.
6881 if (StandbyModeRequested)
6882 DisownLatch(&XLogCtl->recoveryWakeupLatch);
6885 * We are now done reading the xlog from stream. Turn off streaming
6886 * recovery to force fetching the files (which would be required at end of
6887 * recovery, e.g., timeline history file) from archive or pg_xlog.
6889 StandbyMode = false;
6892 * Re-fetch the last valid or last applied record, so we can identify the
6893 * exact endpoint of what we consider the valid portion of WAL.
6895 record = ReadRecord(xlogreader, LastRec, PANIC, false);
6896 EndOfLog = EndRecPtr;
6897 XLByteToPrevSeg(EndOfLog, endLogSegNo);
6900 * Complain if we did not roll forward far enough to render the backup
6901 * dump consistent. Note: it is indeed okay to look at the local variable
6902 * minRecoveryPoint here, even though ControlFile->minRecoveryPoint might
6903 * be further ahead --- ControlFile->minRecoveryPoint cannot have been
6904 * advanced beyond the WAL we processed.
6907 (EndOfLog < minRecoveryPoint ||
6908 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint)))
6910 if (reachedStopPoint)
6912 /* stopped because of stop request */
6914 (errmsg("requested recovery stop point is before consistent recovery point")));
6918 * Ran off end of WAL before reaching end-of-backup WAL record, or
6919 * minRecoveryPoint. That's usually a bad sign, indicating that you
6920 * tried to recover from an online backup but never called
6921 * pg_stop_backup(), or you didn't archive all the WAL up to that
6922 * point. However, this also happens in crash recovery, if the system
6923 * crashes while an online backup is in progress. We must not treat
6924 * that as an error, or the database will refuse to start up.
6926 if (ArchiveRecoveryRequested || ControlFile->backupEndRequired)
6928 if (ControlFile->backupEndRequired)
6930 (errmsg("WAL ends before end of online backup"),
6931 errhint("All WAL generated while online backup was taken must be available at recovery.")));
6932 else if (!XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
6934 (errmsg("WAL ends before end of online backup"),
6935 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.")));
6938 (errmsg("WAL ends before consistent recovery point")));
6943 * Consider whether we need to assign a new timeline ID.
6945 * If we are doing an archive recovery, we always assign a new ID. This
6946 * handles a couple of issues. If we stopped short of the end of WAL
6947 * during recovery, then we are clearly generating a new timeline and must
6948 * assign it a unique new ID. Even if we ran to the end, modifying the
6949 * current last segment is problematic because it may result in trying to
6950 * overwrite an already-archived copy of that segment, and we encourage
6951 * DBAs to make their archive_commands reject that. We can dodge the
6952 * problem by making the new active segment have a new timeline ID.
6954 * In a normal crash recovery, we can just extend the timeline we were in.
6956 PrevTimeLineID = ThisTimeLineID;
6957 if (ArchiveRecoveryRequested)
6961 Assert(InArchiveRecovery);
6963 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
6965 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
6968 * Create a comment for the history file to explain why and where
6971 if (recoveryTarget == RECOVERY_TARGET_XID)
6972 snprintf(reason, sizeof(reason),
6973 "%s transaction %u",
6974 recoveryStopAfter ? "after" : "before",
6976 else if (recoveryTarget == RECOVERY_TARGET_TIME)
6977 snprintf(reason, sizeof(reason),
6979 recoveryStopAfter ? "after" : "before",
6980 timestamptz_to_str(recoveryStopTime));
6981 else if (recoveryTarget == RECOVERY_TARGET_NAME)
6982 snprintf(reason, sizeof(reason),
6983 "at restore point \"%s\"",
6986 snprintf(reason, sizeof(reason), "no recovery target specified");
6988 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
6992 /* Save the selected TimeLineID in shared memory, too */
6993 XLogCtl->ThisTimeLineID = ThisTimeLineID;
6994 XLogCtl->PrevTimeLineID = PrevTimeLineID;
6997 * We are now done reading the old WAL. Turn off archive fetching if it
6998 * was active, and make a writable copy of the last WAL segment. (Note
6999 * that we also have a copy of the last block of the old WAL in readBuf;
7000 * we will use that below.)
7002 if (ArchiveRecoveryRequested)
7003 exitArchiveRecovery(xlogreader->readPageTLI, endLogSegNo);
7006 * Prepare to write WAL starting at EndOfLog position, and init xlog
7007 * buffer cache using the block containing the last record from the
7008 * previous incarnation.
7010 openLogSegNo = endLogSegNo;
7011 openLogFile = XLogFileOpen(openLogSegNo);
7013 Insert = &XLogCtl->Insert;
7014 Insert->PrevBytePos = XLogRecPtrToBytePos(LastRec);
7015 Insert->CurrBytePos = XLogRecPtrToBytePos(EndOfLog);
7018 * Tricky point here: readBuf contains the *last* block that the LastRec
7019 * record spans, not the one it starts in. The last block is indeed the
7020 * one we want to use.
7022 if (EndOfLog % XLOG_BLCKSZ != 0)
7027 XLogRecPtr pageBeginPtr;
7029 pageBeginPtr = EndOfLog - (EndOfLog % XLOG_BLCKSZ);
7030 Assert(readOff == pageBeginPtr % XLogSegSize);
7032 firstIdx = XLogRecPtrToBufIdx(EndOfLog);
7034 /* Copy the valid part of the last block, and zero the rest */
7035 page = &XLogCtl->pages[firstIdx * XLOG_BLCKSZ];
7036 len = EndOfLog % XLOG_BLCKSZ;
7037 memcpy(page, xlogreader->readBuf, len);
7038 memset(page + len, 0, XLOG_BLCKSZ - len);
7040 XLogCtl->xlblocks[firstIdx] = pageBeginPtr + XLOG_BLCKSZ;
7041 XLogCtl->InitializedUpTo = pageBeginPtr + XLOG_BLCKSZ;
7046 * There is no partial block to copy. Just set InitializedUpTo,
7047 * and let the first attempt to insert a log record to initialize
7050 XLogCtl->InitializedUpTo = EndOfLog;
7053 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
7055 XLogCtl->LogwrtResult = LogwrtResult;
7057 XLogCtl->LogwrtRqst.Write = EndOfLog;
7058 XLogCtl->LogwrtRqst.Flush = EndOfLog;
7060 /* Pre-scan prepared transactions to find out the range of XIDs present */
7061 oldestActiveXID = PrescanPreparedTransactions(NULL, NULL);
7064 * Update full_page_writes in shared memory and write an XLOG_FPW_CHANGE
7065 * record before resource manager writes cleanup WAL records or checkpoint
7066 * record is written.
7068 Insert->fullPageWrites = lastFullPageWrites;
7069 LocalSetXLogInsertAllowed();
7070 UpdateFullPageWrites();
7071 LocalXLogInsertAllowed = -1;
7078 * Resource managers might need to write WAL records, eg, to record
7079 * index cleanup actions. So temporarily enable XLogInsertAllowed in
7080 * this process only.
7082 LocalSetXLogInsertAllowed();
7085 * Allow resource managers to do any required cleanup.
7087 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
7089 if (RmgrTable[rmid].rm_cleanup != NULL)
7090 RmgrTable[rmid].rm_cleanup();
7093 /* Disallow XLogInsert again */
7094 LocalXLogInsertAllowed = -1;
7097 * Perform a checkpoint to update all our recovery activity to disk.
7099 * Note that we write a shutdown checkpoint rather than an on-line
7100 * one. This is not particularly critical, but since we may be
7101 * assigning a new TLI, using a shutdown checkpoint allows us to have
7102 * the rule that TLI only changes in shutdown checkpoints, which
7103 * allows some extra error checking in xlog_redo.
7105 * In fast promotion, only create a lightweight end-of-recovery record
7106 * instead of a full checkpoint. A checkpoint is requested later,
7107 * after we're fully out of recovery mode and already accepting
7110 if (bgwriterLaunched)
7114 checkPointLoc = ControlFile->prevCheckPoint;
7117 * Confirm the last checkpoint is available for us to recover
7118 * from if we fail. Note that we don't check for the secondary
7119 * checkpoint since that isn't available in most base backups.
7121 record = ReadCheckpointRecord(xlogreader, checkPointLoc, 1, false);
7124 fast_promoted = true;
7127 * Insert a special WAL record to mark the end of
7128 * recovery, since we aren't doing a checkpoint. That
7129 * means that the checkpointer process may likely be in
7130 * the middle of a time-smoothed restartpoint and could
7131 * continue to be for minutes after this. That sounds
7132 * strange, but the effect is roughly the same and it
7133 * would be stranger to try to come out of the
7134 * restartpoint and then checkpoint. We request a
7135 * checkpoint later anyway, just for safety.
7137 CreateEndOfRecoveryRecord();
7142 RequestCheckpoint(CHECKPOINT_END_OF_RECOVERY |
7143 CHECKPOINT_IMMEDIATE |
7147 CreateCheckPoint(CHECKPOINT_END_OF_RECOVERY | CHECKPOINT_IMMEDIATE);
7150 * And finally, execute the recovery_end_command, if any.
7152 if (recoveryEndCommand)
7153 ExecuteRecoveryCommand(recoveryEndCommand,
7154 "recovery_end_command",
7159 * Preallocate additional log files, if wanted.
7161 PreallocXlogFiles(EndOfLog);
7164 * Reset initial contents of unlogged relations. This has to be done
7165 * AFTER recovery is complete so that any unlogged relations created
7166 * during recovery also get picked up.
7169 ResetUnloggedRelations(UNLOGGED_RELATION_INIT);
7172 * Okay, we're officially UP.
7176 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7177 ControlFile->state = DB_IN_PRODUCTION;
7178 ControlFile->time = (pg_time_t) time(NULL);
7179 UpdateControlFile();
7180 LWLockRelease(ControlFileLock);
7182 /* start the archive_timeout timer running */
7183 XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
7185 /* also initialize latestCompletedXid, to nextXid - 1 */
7186 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
7187 ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
7188 TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);
7189 LWLockRelease(ProcArrayLock);
7192 * Start up the commit log and subtrans, if not already done for hot
7195 if (standbyState == STANDBY_DISABLED)
7198 StartupSUBTRANS(oldestActiveXID);
7202 * Perform end of recovery actions for any SLRUs that need it.
7207 /* Reload shared-memory state for prepared transactions */
7208 RecoverPreparedTransactions();
7211 * Shutdown the recovery environment. This must occur after
7212 * RecoverPreparedTransactions(), see notes for lock_twophase_recover()
7214 if (standbyState != STANDBY_DISABLED)
7215 ShutdownRecoveryTransactionEnvironment();
7217 /* Shut down xlogreader */
7223 XLogReaderFree(xlogreader);
7226 * If any of the critical GUCs have changed, log them before we allow
7227 * backends to write WAL.
7229 LocalSetXLogInsertAllowed();
7230 XLogReportParameters();
7233 * All done. Allow backends to write WAL. (Although the bool flag is
7234 * probably atomic in itself, we use the info_lck here to ensure that
7235 * there are no race conditions concerning visibility of other recent
7236 * updates to shared memory.)
7239 /* use volatile pointer to prevent code rearrangement */
7240 volatile XLogCtlData *xlogctl = XLogCtl;
7242 SpinLockAcquire(&xlogctl->info_lck);
7243 xlogctl->SharedRecoveryInProgress = false;
7244 SpinLockRelease(&xlogctl->info_lck);
7248 * If there were cascading standby servers connected to us, nudge any wal
7249 * sender processes to notice that we've been promoted.
7254 * If this was a fast promotion, request an (online) checkpoint now. This
7255 * isn't required for consistency, but the last restartpoint might be far
7256 * back, and in case of a crash, recovering from it might take a longer
7257 * than is appropriate now that we're not in standby mode anymore.
7260 RequestCheckpoint(CHECKPOINT_FORCE);
7264 * Checks if recovery has reached a consistent state. When consistency is
7265 * reached and we have a valid starting standby snapshot, tell postmaster
7266 * that it can start accepting read-only connections.
7269 CheckRecoveryConsistency(void)
7272 * During crash recovery, we don't reach a consistent state until we've
7273 * replayed all the WAL.
7275 if (XLogRecPtrIsInvalid(minRecoveryPoint))
7279 * Have we reached the point where our base backup was completed?
7281 if (!XLogRecPtrIsInvalid(ControlFile->backupEndPoint) &&
7282 ControlFile->backupEndPoint <= EndRecPtr)
7285 * We have reached the end of base backup, as indicated by pg_control.
7286 * The data on disk is now consistent. Reset backupStartPoint and
7287 * backupEndPoint, and update minRecoveryPoint to make sure we don't
7288 * allow starting up at an earlier point even if recovery is stopped
7289 * and restarted soon after this.
7291 elog(DEBUG1, "end of backup reached");
7293 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7295 if (ControlFile->minRecoveryPoint < EndRecPtr)
7296 ControlFile->minRecoveryPoint = EndRecPtr;
7298 ControlFile->backupStartPoint = InvalidXLogRecPtr;
7299 ControlFile->backupEndPoint = InvalidXLogRecPtr;
7300 ControlFile->backupEndRequired = false;
7301 UpdateControlFile();
7303 LWLockRelease(ControlFileLock);
7307 * Have we passed our safe starting point? Note that minRecoveryPoint is
7308 * known to be incorrectly set if ControlFile->backupEndRequired, until
7309 * the XLOG_BACKUP_RECORD arrives to advise us of the correct
7310 * minRecoveryPoint. All we know prior to that is that we're not
7313 if (!reachedConsistency && !ControlFile->backupEndRequired &&
7314 minRecoveryPoint <= XLogCtl->lastReplayedEndRecPtr &&
7315 XLogRecPtrIsInvalid(ControlFile->backupStartPoint))
7318 * Check to see if the XLOG sequence contained any unresolved
7319 * references to uninitialized pages.
7321 XLogCheckInvalidPages();
7323 reachedConsistency = true;
7325 (errmsg("consistent recovery state reached at %X/%X",
7326 (uint32) (XLogCtl->lastReplayedEndRecPtr >> 32),
7327 (uint32) XLogCtl->lastReplayedEndRecPtr)));
7331 * Have we got a valid starting snapshot that will allow queries to be
7332 * run? If so, we can tell postmaster that the database is consistent now,
7333 * enabling connections.
7335 if (standbyState == STANDBY_SNAPSHOT_READY &&
7336 !LocalHotStandbyActive &&
7337 reachedConsistency &&
7340 /* use volatile pointer to prevent code rearrangement */
7341 volatile XLogCtlData *xlogctl = XLogCtl;
7343 SpinLockAcquire(&xlogctl->info_lck);
7344 xlogctl->SharedHotStandbyActive = true;
7345 SpinLockRelease(&xlogctl->info_lck);
7347 LocalHotStandbyActive = true;
7349 SendPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY);
7354 * Is the system still in recovery?
7356 * Unlike testing InRecovery, this works in any process that's connected to
7359 * As a side-effect, we initialize the local TimeLineID and RedoRecPtr
7360 * variables the first time we see that recovery is finished.
7363 RecoveryInProgress(void)
7366 * We check shared state each time only until we leave recovery mode. We
7367 * can't re-enter recovery, so there's no need to keep checking after the
7368 * shared variable has once been seen false.
7370 if (!LocalRecoveryInProgress)
7374 /* use volatile pointer to prevent code rearrangement */
7375 volatile XLogCtlData *xlogctl = XLogCtl;
7377 /* spinlock is essential on machines with weak memory ordering! */
7378 SpinLockAcquire(&xlogctl->info_lck);
7379 LocalRecoveryInProgress = xlogctl->SharedRecoveryInProgress;
7380 SpinLockRelease(&xlogctl->info_lck);
7383 * Initialize TimeLineID and RedoRecPtr when we discover that recovery
7384 * is finished. InitPostgres() relies upon this behaviour to ensure
7385 * that InitXLOGAccess() is called at backend startup. (If you change
7386 * this, see also LocalSetXLogInsertAllowed.)
7388 if (!LocalRecoveryInProgress)
7391 return LocalRecoveryInProgress;
7396 * Is HotStandby active yet? This is only important in special backends
7397 * since normal backends won't ever be able to connect until this returns
7398 * true. Postmaster knows this by way of signal, not via shared memory.
7400 * Unlike testing standbyState, this works in any process that's connected to
7404 HotStandbyActive(void)
7407 * We check shared state each time only until Hot Standby is active. We
7408 * can't de-activate Hot Standby, so there's no need to keep checking
7409 * after the shared variable has once been seen true.
7411 if (LocalHotStandbyActive)
7415 /* use volatile pointer to prevent code rearrangement */
7416 volatile XLogCtlData *xlogctl = XLogCtl;
7418 /* spinlock is essential on machines with weak memory ordering! */
7419 SpinLockAcquire(&xlogctl->info_lck);
7420 LocalHotStandbyActive = xlogctl->SharedHotStandbyActive;
7421 SpinLockRelease(&xlogctl->info_lck);
7423 return LocalHotStandbyActive;
7428 * Is this process allowed to insert new WAL records?
7430 * Ordinarily this is essentially equivalent to !RecoveryInProgress().
7431 * But we also have provisions for forcing the result "true" or "false"
7432 * within specific processes regardless of the global state.
7435 XLogInsertAllowed(void)
7438 * If value is "unconditionally true" or "unconditionally false", just
7439 * return it. This provides the normal fast path once recovery is known
7442 if (LocalXLogInsertAllowed >= 0)
7443 return (bool) LocalXLogInsertAllowed;
7446 * Else, must check to see if we're still in recovery.
7448 if (RecoveryInProgress())
7452 * On exit from recovery, reset to "unconditionally true", since there is
7453 * no need to keep checking.
7455 LocalXLogInsertAllowed = 1;
7460 * Make XLogInsertAllowed() return true in the current process only.
7462 * Note: it is allowed to switch LocalXLogInsertAllowed back to -1 later,
7463 * and even call LocalSetXLogInsertAllowed() again after that.
7466 LocalSetXLogInsertAllowed(void)
7468 Assert(LocalXLogInsertAllowed == -1);
7469 LocalXLogInsertAllowed = 1;
7471 /* Initialize as RecoveryInProgress() would do when switching state */
7476 * Subroutine to try to fetch and validate a prior checkpoint record.
7478 * whichChkpt identifies the checkpoint (merely for reporting purposes).
7479 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
7482 ReadCheckpointRecord(XLogReaderState *xlogreader, XLogRecPtr RecPtr,
7483 int whichChkpt, bool report)
7487 if (!XRecOffIsValid(RecPtr))
7496 (errmsg("invalid primary checkpoint link in control file")));
7500 (errmsg("invalid secondary checkpoint link in control file")));
7504 (errmsg("invalid checkpoint link in backup_label file")));
7510 record = ReadRecord(xlogreader, RecPtr, LOG, true);
7521 (errmsg("invalid primary checkpoint record")));
7525 (errmsg("invalid secondary checkpoint record")));
7529 (errmsg("invalid checkpoint record")));
7534 if (record->xl_rmid != RM_XLOG_ID)
7540 (errmsg("invalid resource manager ID in primary checkpoint record")));
7544 (errmsg("invalid resource manager ID in secondary checkpoint record")));
7548 (errmsg("invalid resource manager ID in checkpoint record")));
7553 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
7554 record->xl_info != XLOG_CHECKPOINT_ONLINE)
7560 (errmsg("invalid xl_info in primary checkpoint record")));
7564 (errmsg("invalid xl_info in secondary checkpoint record")));
7568 (errmsg("invalid xl_info in checkpoint record")));
7573 if (record->xl_len != sizeof(CheckPoint) ||
7574 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
7580 (errmsg("invalid length of primary checkpoint record")));
7584 (errmsg("invalid length of secondary checkpoint record")));
7588 (errmsg("invalid length of checkpoint record")));
7597 * This must be called during startup of a backend process, except that
7598 * it need not be called in a standalone backend (which does StartupXLOG
7599 * instead). We need to initialize the local copies of ThisTimeLineID and
7602 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
7603 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
7604 * unnecessary however, since the postmaster itself never touches XLOG anyway.
7607 InitXLOGAccess(void)
7609 /* ThisTimeLineID doesn't change so we need no lock to copy it */
7610 ThisTimeLineID = XLogCtl->ThisTimeLineID;
7611 Assert(ThisTimeLineID != 0 || IsBootstrapProcessingMode());
7613 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
7614 (void) GetRedoRecPtr();
7618 * Return the current Redo pointer from shared memory.
7620 * As a side-effect, the local RedoRecPtr copy is updated.
7625 /* use volatile pointer to prevent code rearrangement */
7626 volatile XLogCtlData *xlogctl = XLogCtl;
7630 * The possibly not up-to-date copy in XlogCtl is enough. Even if we
7631 * grabbed a WAL insertion slot to read the master copy, someone might
7632 * update it just after we've released the lock.
7634 SpinLockAcquire(&xlogctl->info_lck);
7635 ptr = xlogctl->RedoRecPtr;
7636 SpinLockRelease(&xlogctl->info_lck);
7638 if (RedoRecPtr < ptr)
7645 * GetInsertRecPtr -- Returns the current insert position.
7647 * NOTE: The value *actually* returned is the position of the last full
7648 * xlog page. It lags behind the real insert position by at most 1 page.
7649 * For that, we don't need to scan through WAL insertion slots, and an
7650 * approximation is enough for the current usage of this function.
7653 GetInsertRecPtr(void)
7655 /* use volatile pointer to prevent code rearrangement */
7656 volatile XLogCtlData *xlogctl = XLogCtl;
7659 SpinLockAcquire(&xlogctl->info_lck);
7660 recptr = xlogctl->LogwrtRqst.Write;
7661 SpinLockRelease(&xlogctl->info_lck);
7667 * GetFlushRecPtr -- Returns the current flush position, ie, the last WAL
7668 * position known to be fsync'd to disk.
7671 GetFlushRecPtr(void)
7673 /* use volatile pointer to prevent code rearrangement */
7674 volatile XLogCtlData *xlogctl = XLogCtl;
7677 SpinLockAcquire(&xlogctl->info_lck);
7678 recptr = xlogctl->LogwrtResult.Flush;
7679 SpinLockRelease(&xlogctl->info_lck);
7685 * Get the time of the last xlog segment switch
7688 GetLastSegSwitchTime(void)
7692 /* Need WALWriteLock, but shared lock is sufficient */
7693 LWLockAcquire(WALWriteLock, LW_SHARED);
7694 result = XLogCtl->lastSegSwitchTime;
7695 LWLockRelease(WALWriteLock);
7701 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
7703 * This is exported for use by code that would like to have 64-bit XIDs.
7704 * We don't really support such things, but all XIDs within the system
7705 * can be presumed "close to" the result, and thus the epoch associated
7706 * with them can be determined.
7709 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
7711 uint32 ckptXidEpoch;
7712 TransactionId ckptXid;
7713 TransactionId nextXid;
7715 /* Must read checkpoint info first, else have race condition */
7717 /* use volatile pointer to prevent code rearrangement */
7718 volatile XLogCtlData *xlogctl = XLogCtl;
7720 SpinLockAcquire(&xlogctl->info_lck);
7721 ckptXidEpoch = xlogctl->ckptXidEpoch;
7722 ckptXid = xlogctl->ckptXid;
7723 SpinLockRelease(&xlogctl->info_lck);
7726 /* Now fetch current nextXid */
7727 nextXid = ReadNewTransactionId();
7730 * nextXid is certainly logically later than ckptXid. So if it's
7731 * numerically less, it must have wrapped into the next epoch.
7733 if (nextXid < ckptXid)
7737 *epoch = ckptXidEpoch;
7741 * This must be called ONCE during postmaster or standalone-backend shutdown
7744 ShutdownXLOG(int code, Datum arg)
7746 /* Don't be chatty in standalone mode */
7747 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
7748 (errmsg("shutting down")));
7750 if (RecoveryInProgress())
7751 CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
7755 * If archiving is enabled, rotate the last XLOG file so that all the
7756 * remaining records are archived (postmaster wakes up the archiver
7757 * process one more time at the end of shutdown). The checkpoint
7758 * record will go to the next XLOG file and won't be archived (yet).
7760 if (XLogArchivingActive() && XLogArchiveCommandSet())
7761 RequestXLogSwitch();
7763 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
7767 ShutdownMultiXact();
7769 /* Don't be chatty in standalone mode */
7770 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
7771 (errmsg("database system is shut down")));
7775 * Log start of a checkpoint.
7778 LogCheckpointStart(int flags, bool restartpoint)
7783 * XXX: This is hopelessly untranslatable. We could call gettext_noop for
7784 * the main message, but what about all the flags?
7787 msg = "restartpoint starting:%s%s%s%s%s%s%s";
7789 msg = "checkpoint starting:%s%s%s%s%s%s%s";
7792 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
7793 (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
7794 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
7795 (flags & CHECKPOINT_FORCE) ? " force" : "",
7796 (flags & CHECKPOINT_WAIT) ? " wait" : "",
7797 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
7798 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
7802 * Log end of a checkpoint.
7805 LogCheckpointEnd(bool restartpoint)
7817 uint64 average_sync_time;
7819 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
7821 TimestampDifference(CheckpointStats.ckpt_write_t,
7822 CheckpointStats.ckpt_sync_t,
7823 &write_secs, &write_usecs);
7825 TimestampDifference(CheckpointStats.ckpt_sync_t,
7826 CheckpointStats.ckpt_sync_end_t,
7827 &sync_secs, &sync_usecs);
7829 /* Accumulate checkpoint timing summary data, in milliseconds. */
7830 BgWriterStats.m_checkpoint_write_time +=
7831 write_secs * 1000 + write_usecs / 1000;
7832 BgWriterStats.m_checkpoint_sync_time +=
7833 sync_secs * 1000 + sync_usecs / 1000;
7836 * All of the published timing statistics are accounted for. Only
7837 * continue if a log message is to be written.
7839 if (!log_checkpoints)
7842 TimestampDifference(CheckpointStats.ckpt_start_t,
7843 CheckpointStats.ckpt_end_t,
7844 &total_secs, &total_usecs);
7847 * Timing values returned from CheckpointStats are in microseconds.
7848 * Convert to the second plus microsecond form that TimestampDifference
7849 * returns for homogeneous printing.
7851 longest_secs = (long) (CheckpointStats.ckpt_longest_sync / 1000000);
7852 longest_usecs = CheckpointStats.ckpt_longest_sync -
7853 (uint64) longest_secs *1000000;
7855 average_sync_time = 0;
7856 if (CheckpointStats.ckpt_sync_rels > 0)
7857 average_sync_time = CheckpointStats.ckpt_agg_sync_time /
7858 CheckpointStats.ckpt_sync_rels;
7859 average_secs = (long) (average_sync_time / 1000000);
7860 average_usecs = average_sync_time - (uint64) average_secs *1000000;
7863 elog(LOG, "restartpoint complete: wrote %d buffers (%.1f%%); "
7864 "%d transaction log file(s) added, %d removed, %d recycled; "
7865 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s; "
7866 "sync files=%d, longest=%ld.%03d s, average=%ld.%03d s",
7867 CheckpointStats.ckpt_bufs_written,
7868 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
7869 CheckpointStats.ckpt_segs_added,
7870 CheckpointStats.ckpt_segs_removed,
7871 CheckpointStats.ckpt_segs_recycled,
7872 write_secs, write_usecs / 1000,
7873 sync_secs, sync_usecs / 1000,
7874 total_secs, total_usecs / 1000,
7875 CheckpointStats.ckpt_sync_rels,
7876 longest_secs, longest_usecs / 1000,
7877 average_secs, average_usecs / 1000);
7879 elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
7880 "%d transaction log file(s) added, %d removed, %d recycled; "
7881 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s; "
7882 "sync files=%d, longest=%ld.%03d s, average=%ld.%03d s",
7883 CheckpointStats.ckpt_bufs_written,
7884 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
7885 CheckpointStats.ckpt_segs_added,
7886 CheckpointStats.ckpt_segs_removed,
7887 CheckpointStats.ckpt_segs_recycled,
7888 write_secs, write_usecs / 1000,
7889 sync_secs, sync_usecs / 1000,
7890 total_secs, total_usecs / 1000,
7891 CheckpointStats.ckpt_sync_rels,
7892 longest_secs, longest_usecs / 1000,
7893 average_secs, average_usecs / 1000);
7897 * Perform a checkpoint --- either during shutdown, or on-the-fly
7899 * flags is a bitwise OR of the following:
7900 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
7901 * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
7902 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
7903 * ignoring checkpoint_completion_target parameter.
7904 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
7905 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
7906 * CHECKPOINT_END_OF_RECOVERY).
7908 * Note: flags contains other bits, of interest here only for logging purposes.
7909 * In particular note that this routine is synchronous and does not pay
7910 * attention to CHECKPOINT_WAIT.
7912 * If !shutdown then we are writing an online checkpoint. This is a very special
7913 * kind of operation and WAL record because the checkpoint action occurs over
7914 * a period of time yet logically occurs at just a single LSN. The logical
7915 * position of the WAL record (redo ptr) is the same or earlier than the
7916 * physical position. When we replay WAL we locate the checkpoint via its
7917 * physical position then read the redo ptr and actually start replay at the
7918 * earlier logical position. Note that we don't write *anything* to WAL at
7919 * the logical position, so that location could be any other kind of WAL record.
7920 * All of this mechanism allows us to continue working while we checkpoint.
7921 * As a result, timing of actions is critical here and be careful to note that
7922 * this function will likely take minutes to execute on a busy system.
7925 CreateCheckPoint(int flags)
7927 /* use volatile pointer to prevent code rearrangement */
7928 volatile XLogCtlData *xlogctl = XLogCtl;
7930 CheckPoint checkPoint;
7932 XLogCtlInsert *Insert = &XLogCtl->Insert;
7935 XLogSegNo _logSegNo;
7936 XLogRecPtr curInsert;
7937 VirtualTransactionId *vxids;
7941 * An end-of-recovery checkpoint is really a shutdown checkpoint, just
7942 * issued at a different time.
7944 if (flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY))
7950 if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
7951 elog(ERROR, "can't create a checkpoint during recovery");
7954 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
7955 * (This is just pro forma, since in the present system structure there is
7956 * only one process that is allowed to issue checkpoints at any given
7959 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
7962 * Prepare to accumulate statistics.
7964 * Note: because it is possible for log_checkpoints to change while a
7965 * checkpoint proceeds, we always accumulate stats, even if
7966 * log_checkpoints is currently off.
7968 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
7969 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
7972 * Use a critical section to force system panic if we have trouble.
7974 START_CRIT_SECTION();
7978 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7979 ControlFile->state = DB_SHUTDOWNING;
7980 ControlFile->time = (pg_time_t) time(NULL);
7981 UpdateControlFile();
7982 LWLockRelease(ControlFileLock);
7986 * Let smgr prepare for checkpoint; this has to happen before we determine
7987 * the REDO pointer. Note that smgr must not do anything that'd have to
7988 * be undone if we decide no checkpoint is needed.
7992 /* Begin filling in the checkpoint WAL record */
7993 MemSet(&checkPoint, 0, sizeof(checkPoint));
7994 checkPoint.time = (pg_time_t) time(NULL);
7997 * For Hot Standby, derive the oldestActiveXid before we fix the redo
7998 * pointer. This allows us to begin accumulating changes to assemble our
7999 * starting snapshot of locks and transactions.
8001 if (!shutdown && XLogStandbyInfoActive())
8002 checkPoint.oldestActiveXid = GetOldestActiveTransactionId();
8004 checkPoint.oldestActiveXid = InvalidTransactionId;
8007 * We must block concurrent insertions while examining insert state to
8008 * determine the checkpoint REDO pointer.
8010 WALInsertSlotAcquire(true);
8011 curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
8014 * If this isn't a shutdown or forced checkpoint, and we have not inserted
8015 * any XLOG records since the start of the last checkpoint, skip the
8016 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
8017 * when the system is idle. That wastes log space, and more importantly it
8018 * exposes us to possible loss of both current and previous checkpoint
8019 * records if the machine crashes just as we're writing the update.
8020 * (Perhaps it'd make even more sense to checkpoint only when the previous
8021 * checkpoint record is in a different xlog page?)
8023 * We have to make two tests to determine that nothing has happened since
8024 * the start of the last checkpoint: current insertion point must match
8025 * the end of the last checkpoint record, and its redo pointer must point
8028 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
8029 CHECKPOINT_FORCE)) == 0)
8031 if (curInsert == ControlFile->checkPoint +
8032 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
8033 ControlFile->checkPoint == ControlFile->checkPointCopy.redo)
8035 WALInsertSlotRelease();
8036 LWLockRelease(CheckpointLock);
8043 * An end-of-recovery checkpoint is created before anyone is allowed to
8044 * write WAL. To allow us to write the checkpoint record, temporarily
8045 * enable XLogInsertAllowed. (This also ensures ThisTimeLineID is
8046 * initialized, which we need here and in AdvanceXLInsertBuffer.)
8048 if (flags & CHECKPOINT_END_OF_RECOVERY)
8049 LocalSetXLogInsertAllowed();
8051 checkPoint.ThisTimeLineID = ThisTimeLineID;
8052 if (flags & CHECKPOINT_END_OF_RECOVERY)
8053 checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8055 checkPoint.PrevTimeLineID = ThisTimeLineID;
8057 checkPoint.fullPageWrites = Insert->fullPageWrites;
8060 * Compute new REDO record ptr = location of next XLOG record.
8062 * NB: this is NOT necessarily where the checkpoint record itself will be,
8063 * since other backends may insert more XLOG records while we're off doing
8064 * the buffer flush work. Those XLOG records are logically after the
8065 * checkpoint, even though physically before it. Got that?
8067 freespace = INSERT_FREESPACE(curInsert);
8070 if (curInsert % XLogSegSize == 0)
8071 curInsert += SizeOfXLogLongPHD;
8073 curInsert += SizeOfXLogShortPHD;
8075 checkPoint.redo = curInsert;
8078 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
8079 * must be done while holding the insertion slots.
8081 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
8082 * pointing past where it really needs to point. This is okay; the only
8083 * consequence is that XLogInsert might back up whole buffers that it
8084 * didn't really need to. We can't postpone advancing RedoRecPtr because
8085 * XLogInserts that happen while we are dumping buffers must assume that
8086 * their buffer changes are not included in the checkpoint.
8088 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
8091 * Now we can release the WAL insertion slots, allowing other xacts to
8092 * proceed while we are flushing disk buffers.
8094 WALInsertSlotRelease();
8096 /* Update the info_lck-protected copy of RedoRecPtr as well */
8097 SpinLockAcquire(&xlogctl->info_lck);
8098 xlogctl->RedoRecPtr = checkPoint.redo;
8099 SpinLockRelease(&xlogctl->info_lck);
8102 * If enabled, log checkpoint start. We postpone this until now so as not
8103 * to log anything if we decided to skip the checkpoint.
8105 if (log_checkpoints)
8106 LogCheckpointStart(flags, false);
8108 TRACE_POSTGRESQL_CHECKPOINT_START(flags);
8111 * In some cases there are groups of actions that must all occur on one
8112 * side or the other of a checkpoint record. Before flushing the
8113 * checkpoint record we must explicitly wait for any backend currently
8114 * performing those groups of actions.
8116 * One example is end of transaction, so we must wait for any transactions
8117 * that are currently in commit critical sections. If an xact inserted
8118 * its commit record into XLOG just before the REDO point, then a crash
8119 * restart from the REDO point would not replay that record, which means
8120 * that our flushing had better include the xact's update of pg_clog. So
8121 * we wait till he's out of his commit critical section before proceeding.
8122 * See notes in RecordTransactionCommit().
8124 * Because we've already released the insertion slots, this test is a bit
8125 * fuzzy: it is possible that we will wait for xacts we didn't really need
8126 * to wait for. But the delay should be short and it seems better to make
8127 * checkpoint take a bit longer than to hold off insertions longer than
8129 * (In fact, the whole reason we have this issue is that xact.c does
8130 * commit record XLOG insertion and clog update as two separate steps
8131 * protected by different locks, but again that seems best on grounds of
8132 * minimizing lock contention.)
8134 * A transaction that has not yet set delayChkpt when we look cannot be at
8135 * risk, since he's not inserted his commit record yet; and one that's
8136 * already cleared it is not at risk either, since he's done fixing clog
8137 * and we will correctly flush the update below. So we cannot miss any
8138 * xacts we need to wait for.
8140 vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
8145 pg_usleep(10000L); /* wait for 10 msec */
8146 } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
8151 * Get the other info we need for the checkpoint record.
8153 LWLockAcquire(XidGenLock, LW_SHARED);
8154 checkPoint.nextXid = ShmemVariableCache->nextXid;
8155 checkPoint.oldestXid = ShmemVariableCache->oldestXid;
8156 checkPoint.oldestXidDB = ShmemVariableCache->oldestXidDB;
8157 LWLockRelease(XidGenLock);
8159 /* Increase XID epoch if we've wrapped around since last checkpoint */
8160 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
8161 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
8162 checkPoint.nextXidEpoch++;
8164 LWLockAcquire(OidGenLock, LW_SHARED);
8165 checkPoint.nextOid = ShmemVariableCache->nextOid;
8167 checkPoint.nextOid += ShmemVariableCache->oidCount;
8168 LWLockRelease(OidGenLock);
8170 MultiXactGetCheckptMulti(shutdown,
8171 &checkPoint.nextMulti,
8172 &checkPoint.nextMultiOffset,
8173 &checkPoint.oldestMulti,
8174 &checkPoint.oldestMultiDB);
8177 * Having constructed the checkpoint record, ensure all shmem disk buffers
8178 * and commit-log buffers are flushed to disk.
8180 * This I/O could fail for various reasons. If so, we will fail to
8181 * complete the checkpoint, but there is no reason to force a system
8182 * panic. Accordingly, exit critical section while doing it.
8186 CheckPointGuts(checkPoint.redo, flags);
8189 * Take a snapshot of running transactions and write this to WAL. This
8190 * allows us to reconstruct the state of running transactions during
8191 * archive recovery, if required. Skip, if this info disabled.
8193 * If we are shutting down, or Startup process is completing crash
8194 * recovery we don't need to write running xact data.
8196 if (!shutdown && XLogStandbyInfoActive())
8197 LogStandbySnapshot();
8199 START_CRIT_SECTION();
8202 * Now insert the checkpoint record into XLOG.
8204 rdata.data = (char *) (&checkPoint);
8205 rdata.len = sizeof(checkPoint);
8206 rdata.buffer = InvalidBuffer;
8209 recptr = XLogInsert(RM_XLOG_ID,
8210 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
8211 XLOG_CHECKPOINT_ONLINE,
8217 * We mustn't write any new WAL after a shutdown checkpoint, or it will be
8218 * overwritten at next startup. No-one should even try, this just allows
8219 * sanity-checking. In the case of an end-of-recovery checkpoint, we want
8220 * to just temporarily disable writing until the system has exited
8225 if (flags & CHECKPOINT_END_OF_RECOVERY)
8226 LocalXLogInsertAllowed = -1; /* return to "check" state */
8228 LocalXLogInsertAllowed = 0; /* never again write WAL */
8232 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
8233 * = end of actual checkpoint record.
8235 if (shutdown && checkPoint.redo != ProcLastRecPtr)
8237 (errmsg("concurrent transaction log activity while database system is shutting down")));
8240 * Select point at which we can truncate the log, which we base on the
8241 * prior checkpoint's earliest info.
8243 XLByteToSeg(ControlFile->checkPointCopy.redo, _logSegNo);
8246 * Update the control file.
8248 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8250 ControlFile->state = DB_SHUTDOWNED;
8251 ControlFile->prevCheckPoint = ControlFile->checkPoint;
8252 ControlFile->checkPoint = ProcLastRecPtr;
8253 ControlFile->checkPointCopy = checkPoint;
8254 ControlFile->time = (pg_time_t) time(NULL);
8255 /* crash recovery should always recover to the end of WAL */
8256 ControlFile->minRecoveryPoint = InvalidXLogRecPtr;
8257 ControlFile->minRecoveryPointTLI = 0;
8260 * Persist unloggedLSN value. It's reset on crash recovery, so this goes
8261 * unused on non-shutdown checkpoints, but seems useful to store it always
8262 * for debugging purposes.
8264 SpinLockAcquire(&XLogCtl->ulsn_lck);
8265 ControlFile->unloggedLSN = XLogCtl->unloggedLSN;
8266 SpinLockRelease(&XLogCtl->ulsn_lck);
8268 UpdateControlFile();
8269 LWLockRelease(ControlFileLock);
8271 /* Update shared-memory copy of checkpoint XID/epoch */
8273 /* use volatile pointer to prevent code rearrangement */
8274 volatile XLogCtlData *xlogctl = XLogCtl;
8276 SpinLockAcquire(&xlogctl->info_lck);
8277 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
8278 xlogctl->ckptXid = checkPoint.nextXid;
8279 SpinLockRelease(&xlogctl->info_lck);
8283 * We are now done with critical updates; no need for system panic if we
8284 * have trouble while fooling with old log segments.
8289 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
8294 * Delete old log files (those no longer needed even for previous
8295 * checkpoint or the standbys in XLOG streaming).
8299 KeepLogSeg(recptr, &_logSegNo);
8301 RemoveOldXlogFiles(_logSegNo, recptr);
8305 * Make more log segments if needed. (Do this after recycling old log
8306 * segments, since that may supply some of the needed files.)
8309 PreallocXlogFiles(recptr);
8312 * Truncate pg_subtrans if possible. We can throw away all data before
8313 * the oldest XMIN of any running transaction. No future transaction will
8314 * attempt to reference any pg_subtrans entry older than that (see Asserts
8315 * in subtrans.c). During recovery, though, we mustn't do this because
8316 * StartupSUBTRANS hasn't been called yet.
8318 if (!RecoveryInProgress())
8319 TruncateSUBTRANS(GetOldestXmin(true, false));
8321 /* Real work is done, but log and update stats before releasing lock. */
8322 LogCheckpointEnd(false);
8324 TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
8326 CheckpointStats.ckpt_segs_added,
8327 CheckpointStats.ckpt_segs_removed,
8328 CheckpointStats.ckpt_segs_recycled);
8330 LWLockRelease(CheckpointLock);
8334 * Mark the end of recovery in WAL though without running a full checkpoint.
8335 * We can expect that a restartpoint is likely to be in progress as we
8336 * do this, though we are unwilling to wait for it to complete. So be
8337 * careful to avoid taking the CheckpointLock anywhere here.
8339 * CreateRestartPoint() allows for the case where recovery may end before
8340 * the restartpoint completes so there is no concern of concurrent behaviour.
8343 CreateEndOfRecoveryRecord(void)
8345 xl_end_of_recovery xlrec;
8350 if (!RecoveryInProgress())
8351 elog(ERROR, "can only be used to end recovery");
8353 xlrec.end_time = time(NULL);
8355 WALInsertSlotAcquire(true);
8356 xlrec.ThisTimeLineID = ThisTimeLineID;
8357 xlrec.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8358 WALInsertSlotRelease();
8360 LocalSetXLogInsertAllowed();
8362 START_CRIT_SECTION();
8364 rdata.data = (char *) &xlrec;
8365 rdata.len = sizeof(xl_end_of_recovery);
8366 rdata.buffer = InvalidBuffer;
8369 recptr = XLogInsert(RM_XLOG_ID, XLOG_END_OF_RECOVERY, &rdata);
8374 * Update the control file so that crash recovery can follow the timeline
8375 * changes to this point.
8377 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8378 ControlFile->time = (pg_time_t) xlrec.end_time;
8379 ControlFile->minRecoveryPoint = recptr;
8380 ControlFile->minRecoveryPointTLI = ThisTimeLineID;
8381 UpdateControlFile();
8382 LWLockRelease(ControlFileLock);
8386 LocalXLogInsertAllowed = -1; /* return to "check" state */
8390 * Flush all data in shared memory to disk, and fsync
8392 * This is the common code shared between regular checkpoints and
8393 * recovery restartpoints.
8396 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
8399 CheckPointSUBTRANS();
8400 CheckPointMultiXact();
8401 CheckPointPredicate();
8402 CheckPointRelationMap();
8403 CheckPointBuffers(flags); /* performs all required fsyncs */
8404 /* We deliberately delay 2PC checkpointing as long as possible */
8405 CheckPointTwoPhase(checkPointRedo);
8409 * Save a checkpoint for recovery restart if appropriate
8411 * This function is called each time a checkpoint record is read from XLOG.
8412 * It must determine whether the checkpoint represents a safe restartpoint or
8413 * not. If so, the checkpoint record is stashed in shared memory so that
8414 * CreateRestartPoint can consult it. (Note that the latter function is
8415 * executed by the checkpointer, while this one will be executed by the
8419 RecoveryRestartPoint(const CheckPoint *checkPoint)
8423 /* use volatile pointer to prevent code rearrangement */
8424 volatile XLogCtlData *xlogctl = XLogCtl;
8427 * Is it safe to restartpoint? We must ask each of the resource managers
8428 * whether they have any partial state information that might prevent a
8429 * correct restart from this point. If so, we skip this opportunity, but
8430 * return at the next checkpoint record for another try.
8432 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
8434 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
8435 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
8437 elog(trace_recovery(DEBUG2),
8438 "RM %d not safe to record restart point at %X/%X",
8440 (uint32) (checkPoint->redo >> 32),
8441 (uint32) checkPoint->redo);
8447 * Also refrain from creating a restartpoint if we have seen any
8448 * references to non-existent pages. Restarting recovery from the
8449 * restartpoint would not see the references, so we would lose the
8450 * cross-check that the pages belonged to a relation that was dropped
8453 if (XLogHaveInvalidPages())
8455 elog(trace_recovery(DEBUG2),
8456 "could not record restart point at %X/%X because there "
8457 "are unresolved references to invalid pages",
8458 (uint32) (checkPoint->redo >> 32),
8459 (uint32) checkPoint->redo);
8464 * Copy the checkpoint record to shared memory, so that checkpointer can
8465 * work out the next time it wants to perform a restartpoint.
8467 SpinLockAcquire(&xlogctl->info_lck);
8468 xlogctl->lastCheckPointRecPtr = ReadRecPtr;
8469 xlogctl->lastCheckPoint = *checkPoint;
8470 SpinLockRelease(&xlogctl->info_lck);
8474 * Establish a restartpoint if possible.
8476 * This is similar to CreateCheckPoint, but is used during WAL recovery
8477 * to establish a point from which recovery can roll forward without
8478 * replaying the entire recovery log.
8480 * Returns true if a new restartpoint was established. We can only establish
8481 * a restartpoint if we have replayed a safe checkpoint record since last
8485 CreateRestartPoint(int flags)
8487 XLogRecPtr lastCheckPointRecPtr;
8488 CheckPoint lastCheckPoint;
8489 XLogSegNo _logSegNo;
8492 /* use volatile pointer to prevent code rearrangement */
8493 volatile XLogCtlData *xlogctl = XLogCtl;
8496 * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
8497 * happens at a time.
8499 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
8501 /* Get a local copy of the last safe checkpoint record. */
8502 SpinLockAcquire(&xlogctl->info_lck);
8503 lastCheckPointRecPtr = xlogctl->lastCheckPointRecPtr;
8504 lastCheckPoint = xlogctl->lastCheckPoint;
8505 SpinLockRelease(&xlogctl->info_lck);
8508 * Check that we're still in recovery mode. It's ok if we exit recovery
8509 * mode after this check, the restart point is valid anyway.
8511 if (!RecoveryInProgress())
8514 (errmsg("skipping restartpoint, recovery has already ended")));
8515 LWLockRelease(CheckpointLock);
8520 * If the last checkpoint record we've replayed is already our last
8521 * restartpoint, we can't perform a new restart point. We still update
8522 * minRecoveryPoint in that case, so that if this is a shutdown restart
8523 * point, we won't start up earlier than before. That's not strictly
8524 * necessary, but when hot standby is enabled, it would be rather weird if
8525 * the database opened up for read-only connections at a point-in-time
8526 * before the last shutdown. Such time travel is still possible in case of
8527 * immediate shutdown, though.
8529 * We don't explicitly advance minRecoveryPoint when we do create a
8530 * restartpoint. It's assumed that flushing the buffers will do that as a
8533 if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
8534 lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
8537 (errmsg("skipping restartpoint, already performed at %X/%X",
8538 (uint32) (lastCheckPoint.redo >> 32),
8539 (uint32) lastCheckPoint.redo)));
8541 UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
8542 if (flags & CHECKPOINT_IS_SHUTDOWN)
8544 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8545 ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
8546 ControlFile->time = (pg_time_t) time(NULL);
8547 UpdateControlFile();
8548 LWLockRelease(ControlFileLock);
8550 LWLockRelease(CheckpointLock);
8555 * Update the shared RedoRecPtr so that the startup process can calculate
8556 * the number of segments replayed since last restartpoint, and request a
8557 * restartpoint if it exceeds checkpoint_segments.
8559 * Like in CreateCheckPoint(), hold off insertions to update it, although
8560 * during recovery this is just pro forma, because no WAL insertions are
8563 WALInsertSlotAcquire(true);
8564 xlogctl->Insert.RedoRecPtr = lastCheckPoint.redo;
8565 WALInsertSlotRelease();
8567 /* Also update the info_lck-protected copy */
8568 SpinLockAcquire(&xlogctl->info_lck);
8569 xlogctl->RedoRecPtr = lastCheckPoint.redo;
8570 SpinLockRelease(&xlogctl->info_lck);
8573 * Prepare to accumulate statistics.
8575 * Note: because it is possible for log_checkpoints to change while a
8576 * checkpoint proceeds, we always accumulate stats, even if
8577 * log_checkpoints is currently off.
8579 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
8580 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
8582 if (log_checkpoints)
8583 LogCheckpointStart(flags, true);
8585 CheckPointGuts(lastCheckPoint.redo, flags);
8588 * Select point at which we can truncate the xlog, which we base on the
8589 * prior checkpoint's earliest info.
8591 XLByteToSeg(ControlFile->checkPointCopy.redo, _logSegNo);
8594 * Update pg_control, using current time. Check that it still shows
8595 * IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
8596 * this is a quick hack to make sure nothing really bad happens if somehow
8597 * we get here after the end-of-recovery checkpoint.
8599 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8600 if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY &&
8601 ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
8603 ControlFile->prevCheckPoint = ControlFile->checkPoint;
8604 ControlFile->checkPoint = lastCheckPointRecPtr;
8605 ControlFile->checkPointCopy = lastCheckPoint;
8606 ControlFile->time = (pg_time_t) time(NULL);
8607 if (flags & CHECKPOINT_IS_SHUTDOWN)
8608 ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
8609 UpdateControlFile();
8611 LWLockRelease(ControlFileLock);
8614 * Delete old log files (those no longer needed even for previous
8615 * checkpoint/restartpoint) to prevent the disk holding the xlog from
8620 XLogRecPtr receivePtr;
8621 XLogRecPtr replayPtr;
8622 TimeLineID replayTLI;
8626 * Get the current end of xlog replayed or received, whichever is
8629 receivePtr = GetWalRcvWriteRecPtr(NULL, NULL);
8630 replayPtr = GetXLogReplayRecPtr(&replayTLI);
8631 endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
8633 KeepLogSeg(endptr, &_logSegNo);
8637 * Try to recycle segments on a useful timeline. If we've been promoted
8638 * since the beginning of this restartpoint, use the new timeline
8639 * chosen at end of recovery (RecoveryInProgress() sets ThisTimeLineID
8640 * in that case). If we're still in recovery, use the timeline we're
8641 * currently replaying.
8643 * There is no guarantee that the WAL segments will be useful on the
8644 * current timeline; if recovery proceeds to a new timeline right
8645 * after this, the pre-allocated WAL segments on this timeline will
8646 * not be used, and will go wasted until recycled on the next
8647 * restartpoint. We'll live with that.
8649 if (RecoveryInProgress())
8650 ThisTimeLineID = replayTLI;
8652 RemoveOldXlogFiles(_logSegNo, endptr);
8655 * Make more log segments if needed. (Do this after recycling old log
8656 * segments, since that may supply some of the needed files.)
8658 PreallocXlogFiles(endptr);
8661 * ThisTimeLineID is normally not set when we're still in recovery.
8662 * However, recycling/preallocating segments above needed
8663 * ThisTimeLineID to determine which timeline to install the segments
8664 * on. Reset it now, to restore the normal state of affairs for
8665 * debugging purposes.
8667 if (RecoveryInProgress())
8672 * Truncate pg_subtrans if possible. We can throw away all data before
8673 * the oldest XMIN of any running transaction. No future transaction will
8674 * attempt to reference any pg_subtrans entry older than that (see Asserts
8675 * in subtrans.c). When hot standby is disabled, though, we mustn't do
8676 * this because StartupSUBTRANS hasn't been called yet.
8678 if (EnableHotStandby)
8679 TruncateSUBTRANS(GetOldestXmin(true, false));
8681 /* Real work is done, but log and update before releasing lock. */
8682 LogCheckpointEnd(true);
8684 xtime = GetLatestXTime();
8685 ereport((log_checkpoints ? LOG : DEBUG2),
8686 (errmsg("recovery restart point at %X/%X",
8687 (uint32) (lastCheckPoint.redo >> 32), (uint32) lastCheckPoint.redo),
8688 xtime ? errdetail("last completed transaction was at log time %s",
8689 timestamptz_to_str(xtime)) : 0));
8691 LWLockRelease(CheckpointLock);
8694 * Finally, execute archive_cleanup_command, if any.
8696 if (XLogCtl->archiveCleanupCommand[0])
8697 ExecuteRecoveryCommand(XLogCtl->archiveCleanupCommand,
8698 "archive_cleanup_command",
8705 * Retreat *logSegNo to the last segment that we need to retain because of
8706 * wal_keep_segments. This is calculated by subtracting wal_keep_segments
8707 * from the given xlog location, recptr.
8710 KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
8714 if (wal_keep_segments == 0)
8717 XLByteToSeg(recptr, segno);
8719 /* avoid underflow, don't go below 1 */
8720 if (segno <= wal_keep_segments)
8723 segno = segno - wal_keep_segments;
8725 /* don't delete WAL segments newer than the calculated segment */
8726 if (segno < *logSegNo)
8731 * Write a NEXTOID log record
8734 XLogPutNextOid(Oid nextOid)
8738 rdata.data = (char *) (&nextOid);
8739 rdata.len = sizeof(Oid);
8740 rdata.buffer = InvalidBuffer;
8742 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
8745 * We need not flush the NEXTOID record immediately, because any of the
8746 * just-allocated OIDs could only reach disk as part of a tuple insert or
8747 * update that would have its own XLOG record that must follow the NEXTOID
8748 * record. Therefore, the standard buffer LSN interlock applied to those
8749 * records will ensure no such OID reaches disk before the NEXTOID record
8752 * Note, however, that the above statement only covers state "within" the
8753 * database. When we use a generated OID as a file or directory name, we
8754 * are in a sense violating the basic WAL rule, because that filesystem
8755 * change may reach disk before the NEXTOID WAL record does. The impact
8756 * of this is that if a database crash occurs immediately afterward, we
8757 * might after restart re-generate the same OID and find that it conflicts
8758 * with the leftover file or directory. But since for safety's sake we
8759 * always loop until finding a nonconflicting filename, this poses no real
8760 * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
8765 * Write an XLOG SWITCH record.
8767 * Here we just blindly issue an XLogInsert request for the record.
8768 * All the magic happens inside XLogInsert.
8770 * The return value is either the end+1 address of the switch record,
8771 * or the end+1 address of the prior segment if we did not need to
8772 * write a switch record because we are already at segment start.
8775 RequestXLogSwitch(void)
8780 /* XLOG SWITCH, alone among xlog record types, has no data */
8781 rdata.buffer = InvalidBuffer;
8786 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
8792 * Write a RESTORE POINT record
8795 XLogRestorePoint(const char *rpName)
8799 xl_restore_point xlrec;
8801 xlrec.rp_time = GetCurrentTimestamp();
8802 strncpy(xlrec.rp_name, rpName, MAXFNAMELEN);
8804 rdata.buffer = InvalidBuffer;
8805 rdata.data = (char *) &xlrec;
8806 rdata.len = sizeof(xl_restore_point);
8809 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_RESTORE_POINT, &rdata);
8812 (errmsg("restore point \"%s\" created at %X/%X",
8813 rpName, (uint32) (RecPtr >> 32), (uint32) RecPtr)));
8819 * Write a backup block if needed when we are setting a hint. Note that
8820 * this may be called for a variety of page types, not just heaps.
8822 * Callable while holding just share lock on the buffer content.
8824 * We can't use the plain backup block mechanism since that relies on the
8825 * Buffer being exclusively locked. Since some modifications (setting LSN, hint
8826 * bits) are allowed in a sharelocked buffer that can lead to wal checksum
8827 * failures. So instead we copy the page and insert the copied data as normal
8830 * We only need to do something if page has not yet been full page written in
8831 * this checkpoint round. The LSN of the inserted wal record is returned if we
8832 * had to write, InvalidXLogRecPtr otherwise.
8834 * It is possible that multiple concurrent backends could attempt to write WAL
8835 * records. In that case, multiple copies of the same block would be recorded
8836 * in separate WAL records by different backends, though that is still OK from
8837 * a correctness perspective.
8840 XLogSaveBufferForHint(Buffer buffer, bool buffer_std)
8842 XLogRecPtr recptr = InvalidXLogRecPtr;
8844 XLogRecData rdata[2];
8848 * Ensure no checkpoint can change our view of RedoRecPtr.
8850 Assert(MyPgXact->delayChkpt);
8853 * Update RedoRecPtr so XLogCheckBuffer can make the right decision
8858 * Setup phony rdata element for use within XLogCheckBuffer only. We reuse
8859 * and reset rdata for any actual WAL record insert.
8861 rdata[0].buffer = buffer;
8862 rdata[0].buffer_std = buffer_std;
8865 * Check buffer while not holding an exclusive lock.
8867 if (XLogCheckBuffer(rdata, false, &lsn, &bkpb))
8869 char copied_buffer[BLCKSZ];
8870 char *origdata = (char *) BufferGetBlock(buffer);
8873 * Copy buffer so we don't have to worry about concurrent hint bit or
8874 * lsn updates. We assume pd_lower/upper cannot be changed without an
8875 * exclusive lock, so the contents bkp are not racy.
8877 * With buffer_std set to false, XLogCheckBuffer() sets hole_length and
8878 * hole_offset to 0; so the following code is safe for either case.
8880 memcpy(copied_buffer, origdata, bkpb.hole_offset);
8881 memcpy(copied_buffer + bkpb.hole_offset,
8882 origdata + bkpb.hole_offset + bkpb.hole_length,
8883 BLCKSZ - bkpb.hole_offset - bkpb.hole_length);
8886 * Header for backup block.
8888 rdata[0].data = (char *) &bkpb;
8889 rdata[0].len = sizeof(BkpBlock);
8890 rdata[0].buffer = InvalidBuffer;
8891 rdata[0].next = &(rdata[1]);
8894 * Save copy of the buffer.
8896 rdata[1].data = copied_buffer;
8897 rdata[1].len = BLCKSZ - bkpb.hole_length;
8898 rdata[1].buffer = InvalidBuffer;
8899 rdata[1].next = NULL;
8901 recptr = XLogInsert(RM_XLOG_ID, XLOG_FPI, rdata);
8908 * Check if any of the GUC parameters that are critical for hot standby
8909 * have changed, and update the value in pg_control file if necessary.
8912 XLogReportParameters(void)
8914 if (wal_level != ControlFile->wal_level ||
8915 MaxConnections != ControlFile->MaxConnections ||
8916 max_worker_processes != ControlFile->max_worker_processes ||
8917 max_prepared_xacts != ControlFile->max_prepared_xacts ||
8918 max_locks_per_xact != ControlFile->max_locks_per_xact)
8921 * The change in number of backend slots doesn't need to be WAL-logged
8922 * if archiving is not enabled, as you can't start archive recovery
8923 * with wal_level=minimal anyway. We don't really care about the
8924 * values in pg_control either if wal_level=minimal, but seems better
8925 * to keep them up-to-date to avoid confusion.
8927 if (wal_level != ControlFile->wal_level || XLogIsNeeded())
8930 xl_parameter_change xlrec;
8932 xlrec.MaxConnections = MaxConnections;
8933 xlrec.max_worker_processes = max_worker_processes;
8934 xlrec.max_prepared_xacts = max_prepared_xacts;
8935 xlrec.max_locks_per_xact = max_locks_per_xact;
8936 xlrec.wal_level = wal_level;
8938 rdata.buffer = InvalidBuffer;
8939 rdata.data = (char *) &xlrec;
8940 rdata.len = sizeof(xlrec);
8943 XLogInsert(RM_XLOG_ID, XLOG_PARAMETER_CHANGE, &rdata);
8946 ControlFile->MaxConnections = MaxConnections;
8947 ControlFile->max_worker_processes = max_worker_processes;
8948 ControlFile->max_prepared_xacts = max_prepared_xacts;
8949 ControlFile->max_locks_per_xact = max_locks_per_xact;
8950 ControlFile->wal_level = wal_level;
8951 UpdateControlFile();
8956 * Update full_page_writes in shared memory, and write an
8957 * XLOG_FPW_CHANGE record if necessary.
8959 * Note: this function assumes there is no other process running
8960 * concurrently that could update it.
8963 UpdateFullPageWrites(void)
8965 XLogCtlInsert *Insert = &XLogCtl->Insert;
8968 * Do nothing if full_page_writes has not been changed.
8970 * It's safe to check the shared full_page_writes without the lock,
8971 * because we assume that there is no concurrently running process which
8974 if (fullPageWrites == Insert->fullPageWrites)
8977 START_CRIT_SECTION();
8980 * It's always safe to take full page images, even when not strictly
8981 * required, but not the other round. So if we're setting full_page_writes
8982 * to true, first set it true and then write the WAL record. If we're
8983 * setting it to false, first write the WAL record and then set the global
8988 WALInsertSlotAcquire(true);
8989 Insert->fullPageWrites = true;
8990 WALInsertSlotRelease();
8994 * Write an XLOG_FPW_CHANGE record. This allows us to keep track of
8995 * full_page_writes during archive recovery, if required.
8997 if (XLogStandbyInfoActive() && !RecoveryInProgress())
9001 rdata.data = (char *) (&fullPageWrites);
9002 rdata.len = sizeof(bool);
9003 rdata.buffer = InvalidBuffer;
9006 XLogInsert(RM_XLOG_ID, XLOG_FPW_CHANGE, &rdata);
9009 if (!fullPageWrites)
9011 WALInsertSlotAcquire(true);
9012 Insert->fullPageWrites = false;
9013 WALInsertSlotRelease();
9019 * Check that it's OK to switch to new timeline during recovery.
9021 * 'lsn' is the address of the shutdown checkpoint record we're about to
9022 * replay. (Currently, timeline can only change at a shutdown checkpoint).
9025 checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI, TimeLineID prevTLI)
9027 /* Check that the record agrees on what the current (old) timeline is */
9028 if (prevTLI != ThisTimeLineID)
9030 (errmsg("unexpected previous timeline ID %u (current timeline ID %u) in checkpoint record",
9031 prevTLI, ThisTimeLineID)));
9034 * The new timeline better be in the list of timelines we expect to see,
9035 * according to the timeline history. It should also not decrease.
9037 if (newTLI < ThisTimeLineID || !tliInHistory(newTLI, expectedTLEs))
9039 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
9040 newTLI, ThisTimeLineID)));
9043 * If we have not yet reached min recovery point, and we're about to
9044 * switch to a timeline greater than the timeline of the min recovery
9045 * point: trouble. After switching to the new timeline, we could not
9046 * possibly visit the min recovery point on the correct timeline anymore.
9047 * This can happen if there is a newer timeline in the archive that
9048 * branched before the timeline the min recovery point is on, and you
9049 * attempt to do PITR to the new timeline.
9051 if (!XLogRecPtrIsInvalid(minRecoveryPoint) &&
9052 lsn < minRecoveryPoint &&
9053 newTLI > minRecoveryPointTLI)
9055 (errmsg("unexpected timeline ID %u in checkpoint record, before reaching minimum recovery point %X/%X on timeline %u",
9057 (uint32) (minRecoveryPoint >> 32),
9058 (uint32) minRecoveryPoint,
9059 minRecoveryPointTLI)));
9065 * XLOG resource manager's routines
9067 * Definitions of info values are in include/catalog/pg_control.h, though
9068 * not all record types are related to control file updates.
9071 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
9073 uint8 info = record->xl_info & ~XLR_INFO_MASK;
9075 /* Backup blocks are not used by XLOG rmgr */
9076 Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
9078 if (info == XLOG_NEXTOID)
9083 * We used to try to take the maximum of ShmemVariableCache->nextOid
9084 * and the recorded nextOid, but that fails if the OID counter wraps
9085 * around. Since no OID allocation should be happening during replay
9086 * anyway, better to just believe the record exactly. We still take
9087 * OidGenLock while setting the variable, just in case.
9089 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
9090 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9091 ShmemVariableCache->nextOid = nextOid;
9092 ShmemVariableCache->oidCount = 0;
9093 LWLockRelease(OidGenLock);
9095 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
9097 CheckPoint checkPoint;
9099 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9100 /* In a SHUTDOWN checkpoint, believe the counters exactly */
9101 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
9102 ShmemVariableCache->nextXid = checkPoint.nextXid;
9103 LWLockRelease(XidGenLock);
9104 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9105 ShmemVariableCache->nextOid = checkPoint.nextOid;
9106 ShmemVariableCache->oidCount = 0;
9107 LWLockRelease(OidGenLock);
9108 MultiXactSetNextMXact(checkPoint.nextMulti,
9109 checkPoint.nextMultiOffset);
9110 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
9111 SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
9114 * If we see a shutdown checkpoint while waiting for an end-of-backup
9115 * record, the backup was canceled and the end-of-backup record will
9118 if (ArchiveRecoveryRequested &&
9119 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint) &&
9120 XLogRecPtrIsInvalid(ControlFile->backupEndPoint))
9122 (errmsg("online backup was canceled, recovery cannot continue")));
9125 * If we see a shutdown checkpoint, we know that nothing was running
9126 * on the master at this point. So fake-up an empty running-xacts
9127 * record and use that here and now. Recover additional standby state
9128 * for prepared transactions.
9130 if (standbyState >= STANDBY_INITIALIZED)
9132 TransactionId *xids;
9134 TransactionId oldestActiveXID;
9135 TransactionId latestCompletedXid;
9136 RunningTransactionsData running;
9138 oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
9141 * Construct a RunningTransactions snapshot representing a shut
9142 * down server, with only prepared transactions still alive. We're
9143 * never overflowed at this point because all subxids are listed
9144 * with their parent prepared transactions.
9146 running.xcnt = nxids;
9147 running.subxcnt = 0;
9148 running.subxid_overflow = false;
9149 running.nextXid = checkPoint.nextXid;
9150 running.oldestRunningXid = oldestActiveXID;
9151 latestCompletedXid = checkPoint.nextXid;
9152 TransactionIdRetreat(latestCompletedXid);
9153 Assert(TransactionIdIsNormal(latestCompletedXid));
9154 running.latestCompletedXid = latestCompletedXid;
9155 running.xids = xids;
9157 ProcArrayApplyRecoveryInfo(&running);
9159 StandbyRecoverPreparedTransactions(true);
9162 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
9163 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
9164 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
9166 /* Update shared-memory copy of checkpoint XID/epoch */
9168 /* use volatile pointer to prevent code rearrangement */
9169 volatile XLogCtlData *xlogctl = XLogCtl;
9171 SpinLockAcquire(&xlogctl->info_lck);
9172 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
9173 xlogctl->ckptXid = checkPoint.nextXid;
9174 SpinLockRelease(&xlogctl->info_lck);
9178 * We should've already switched to the new TLI before replaying this
9181 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
9183 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
9184 checkPoint.ThisTimeLineID, ThisTimeLineID)));
9186 RecoveryRestartPoint(&checkPoint);
9188 else if (info == XLOG_CHECKPOINT_ONLINE)
9190 CheckPoint checkPoint;
9192 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9193 /* In an ONLINE checkpoint, treat the XID counter as a minimum */
9194 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
9195 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
9196 checkPoint.nextXid))
9197 ShmemVariableCache->nextXid = checkPoint.nextXid;
9198 LWLockRelease(XidGenLock);
9199 /* ... but still treat OID counter as exact */
9200 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9201 ShmemVariableCache->nextOid = checkPoint.nextOid;
9202 ShmemVariableCache->oidCount = 0;
9203 LWLockRelease(OidGenLock);
9204 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
9205 checkPoint.nextMultiOffset);
9206 if (TransactionIdPrecedes(ShmemVariableCache->oldestXid,
9207 checkPoint.oldestXid))
9208 SetTransactionIdLimit(checkPoint.oldestXid,
9209 checkPoint.oldestXidDB);
9210 MultiXactAdvanceOldest(checkPoint.oldestMulti,
9211 checkPoint.oldestMultiDB);
9213 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
9214 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
9215 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
9217 /* Update shared-memory copy of checkpoint XID/epoch */
9219 /* use volatile pointer to prevent code rearrangement */
9220 volatile XLogCtlData *xlogctl = XLogCtl;
9222 SpinLockAcquire(&xlogctl->info_lck);
9223 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
9224 xlogctl->ckptXid = checkPoint.nextXid;
9225 SpinLockRelease(&xlogctl->info_lck);
9228 /* TLI should not change in an on-line checkpoint */
9229 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
9231 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
9232 checkPoint.ThisTimeLineID, ThisTimeLineID)));
9234 RecoveryRestartPoint(&checkPoint);
9236 else if (info == XLOG_END_OF_RECOVERY)
9238 xl_end_of_recovery xlrec;
9240 memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_end_of_recovery));
9243 * For Hot Standby, we could treat this like a Shutdown Checkpoint,
9244 * but this case is rarer and harder to test, so the benefit doesn't
9245 * outweigh the potential extra cost of maintenance.
9249 * We should've already switched to the new TLI before replaying this
9252 if (xlrec.ThisTimeLineID != ThisTimeLineID)
9254 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
9255 xlrec.ThisTimeLineID, ThisTimeLineID)));
9257 else if (info == XLOG_NOOP)
9259 /* nothing to do here */
9261 else if (info == XLOG_SWITCH)
9263 /* nothing to do here */
9265 else if (info == XLOG_RESTORE_POINT)
9267 /* nothing to do here */
9269 else if (info == XLOG_FPI)
9275 * Full-page image (FPI) records contain a backup block stored "inline"
9276 * in the normal data since the locking when writing hint records isn't
9277 * sufficient to use the normal backup block mechanism, which assumes
9278 * exclusive lock on the buffer supplied.
9280 * Since the only change in these backup block are hint bits, there
9281 * are no recovery conflicts generated.
9283 * This also means there is no corresponding API call for this, so an
9284 * smgr implementation has no need to implement anything. Which means
9285 * nothing is needed in md.c etc
9287 data = XLogRecGetData(record);
9288 memcpy(&bkpb, data, sizeof(BkpBlock));
9289 data += sizeof(BkpBlock);
9291 RestoreBackupBlockContents(lsn, bkpb, data, false, false);
9293 else if (info == XLOG_BACKUP_END)
9295 XLogRecPtr startpoint;
9297 memcpy(&startpoint, XLogRecGetData(record), sizeof(startpoint));
9299 if (ControlFile->backupStartPoint == startpoint)
9302 * We have reached the end of base backup, the point where
9303 * pg_stop_backup() was done. The data on disk is now consistent.
9304 * Reset backupStartPoint, and update minRecoveryPoint to make
9305 * sure we don't allow starting up at an earlier point even if
9306 * recovery is stopped and restarted soon after this.
9308 elog(DEBUG1, "end of backup reached");
9310 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9312 if (ControlFile->minRecoveryPoint < lsn)
9314 ControlFile->minRecoveryPoint = lsn;
9315 ControlFile->minRecoveryPointTLI = ThisTimeLineID;
9317 ControlFile->backupStartPoint = InvalidXLogRecPtr;
9318 ControlFile->backupEndRequired = false;
9319 UpdateControlFile();
9321 LWLockRelease(ControlFileLock);
9324 else if (info == XLOG_PARAMETER_CHANGE)
9326 xl_parameter_change xlrec;
9328 /* Update our copy of the parameters in pg_control */
9329 memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_parameter_change));
9331 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9332 ControlFile->MaxConnections = xlrec.MaxConnections;
9333 ControlFile->max_worker_processes = xlrec.max_worker_processes;
9334 ControlFile->max_prepared_xacts = xlrec.max_prepared_xacts;
9335 ControlFile->max_locks_per_xact = xlrec.max_locks_per_xact;
9336 ControlFile->wal_level = xlrec.wal_level;
9339 * Update minRecoveryPoint to ensure that if recovery is aborted, we
9340 * recover back up to this point before allowing hot standby again.
9341 * This is particularly important if wal_level was set to 'archive'
9342 * before, and is now 'hot_standby', to ensure you don't run queries
9343 * against the WAL preceding the wal_level change. Same applies to
9344 * decreasing max_* settings.
9346 minRecoveryPoint = ControlFile->minRecoveryPoint;
9347 minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
9348 if (minRecoveryPoint != 0 && minRecoveryPoint < lsn)
9350 ControlFile->minRecoveryPoint = lsn;
9351 ControlFile->minRecoveryPointTLI = ThisTimeLineID;
9354 UpdateControlFile();
9355 LWLockRelease(ControlFileLock);
9357 /* Check to see if any changes to max_connections give problems */
9358 CheckRequiredParameterValues();
9360 else if (info == XLOG_FPW_CHANGE)
9362 /* use volatile pointer to prevent code rearrangement */
9363 volatile XLogCtlData *xlogctl = XLogCtl;
9366 memcpy(&fpw, XLogRecGetData(record), sizeof(bool));
9369 * Update the LSN of the last replayed XLOG_FPW_CHANGE record so that
9370 * do_pg_start_backup() and do_pg_stop_backup() can check whether
9371 * full_page_writes has been disabled during online backup.
9375 SpinLockAcquire(&xlogctl->info_lck);
9376 if (xlogctl->lastFpwDisableRecPtr < ReadRecPtr)
9377 xlogctl->lastFpwDisableRecPtr = ReadRecPtr;
9378 SpinLockRelease(&xlogctl->info_lck);
9381 /* Keep track of full_page_writes */
9382 lastFullPageWrites = fpw;
9389 xlog_outrec(StringInfo buf, XLogRecord *record)
9393 appendStringInfo(buf, "prev %X/%X; xid %u",
9394 (uint32) (record->xl_prev >> 32),
9395 (uint32) record->xl_prev,
9398 appendStringInfo(buf, "; len %u",
9401 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
9403 if (record->xl_info & XLR_BKP_BLOCK(i))
9404 appendStringInfo(buf, "; bkpb%d", i);
9407 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
9409 #endif /* WAL_DEBUG */
9413 * Return the (possible) sync flag used for opening a file, depending on the
9414 * value of the GUC wal_sync_method.
9417 get_sync_bit(int method)
9419 int o_direct_flag = 0;
9421 /* If fsync is disabled, never open in sync mode */
9426 * Optimize writes by bypassing kernel cache with O_DIRECT when using
9427 * O_SYNC/O_FSYNC and O_DSYNC. But only if archiving and streaming are
9428 * disabled, otherwise the archive command or walsender process will read
9429 * the WAL soon after writing it, which is guaranteed to cause a physical
9430 * read if we bypassed the kernel cache. We also skip the
9431 * posix_fadvise(POSIX_FADV_DONTNEED) call in XLogFileClose() for the same
9434 * Never use O_DIRECT in walreceiver process for similar reasons; the WAL
9435 * written by walreceiver is normally read by the startup process soon
9436 * after its written. Also, walreceiver performs unaligned writes, which
9437 * don't work with O_DIRECT, so it is required for correctness too.
9439 if (!XLogIsNeeded() && !AmWalReceiverProcess())
9440 o_direct_flag = PG_O_DIRECT;
9445 * enum values for all sync options are defined even if they are
9446 * not supported on the current platform. But if not, they are
9447 * not included in the enum option array, and therefore will never
9450 case SYNC_METHOD_FSYNC:
9451 case SYNC_METHOD_FSYNC_WRITETHROUGH:
9452 case SYNC_METHOD_FDATASYNC:
9454 #ifdef OPEN_SYNC_FLAG
9455 case SYNC_METHOD_OPEN:
9456 return OPEN_SYNC_FLAG | o_direct_flag;
9458 #ifdef OPEN_DATASYNC_FLAG
9459 case SYNC_METHOD_OPEN_DSYNC:
9460 return OPEN_DATASYNC_FLAG | o_direct_flag;
9463 /* can't happen (unless we are out of sync with option array) */
9464 elog(ERROR, "unrecognized wal_sync_method: %d", method);
9465 return 0; /* silence warning */
9473 assign_xlog_sync_method(int new_sync_method, void *extra)
9475 if (sync_method != new_sync_method)
9478 * To ensure that no blocks escape unsynced, force an fsync on the
9479 * currently open log segment (if any). Also, if the open flag is
9480 * changing, close the log file so it will be reopened (with new flag
9483 if (openLogFile >= 0)
9485 if (pg_fsync(openLogFile) != 0)
9487 (errcode_for_file_access(),
9488 errmsg("could not fsync log segment %s: %m",
9489 XLogFileNameP(ThisTimeLineID, openLogSegNo))));
9490 if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
9498 * Issue appropriate kind of fsync (if any) for an XLOG output file.
9500 * 'fd' is a file descriptor for the XLOG file to be fsync'd.
9501 * 'log' and 'seg' are for error reporting purposes.
9504 issue_xlog_fsync(int fd, XLogSegNo segno)
9506 switch (sync_method)
9508 case SYNC_METHOD_FSYNC:
9509 if (pg_fsync_no_writethrough(fd) != 0)
9511 (errcode_for_file_access(),
9512 errmsg("could not fsync log file %s: %m",
9513 XLogFileNameP(ThisTimeLineID, segno))));
9515 #ifdef HAVE_FSYNC_WRITETHROUGH
9516 case SYNC_METHOD_FSYNC_WRITETHROUGH:
9517 if (pg_fsync_writethrough(fd) != 0)
9519 (errcode_for_file_access(),
9520 errmsg("could not fsync write-through log file %s: %m",
9521 XLogFileNameP(ThisTimeLineID, segno))));
9524 #ifdef HAVE_FDATASYNC
9525 case SYNC_METHOD_FDATASYNC:
9526 if (pg_fdatasync(fd) != 0)
9528 (errcode_for_file_access(),
9529 errmsg("could not fdatasync log file %s: %m",
9530 XLogFileNameP(ThisTimeLineID, segno))));
9533 case SYNC_METHOD_OPEN:
9534 case SYNC_METHOD_OPEN_DSYNC:
9535 /* write synced it already */
9538 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
9544 * Return the filename of given log segment, as a palloc'd string.
9547 XLogFileNameP(TimeLineID tli, XLogSegNo segno)
9549 char *result = palloc(MAXFNAMELEN);
9551 XLogFileName(result, tli, segno);
9556 * do_pg_start_backup is the workhorse of the user-visible pg_start_backup()
9557 * function. It creates the necessary starting checkpoint and constructs the
9558 * backup label file.
9560 * There are two kind of backups: exclusive and non-exclusive. An exclusive
9561 * backup is started with pg_start_backup(), and there can be only one active
9562 * at a time. The backup label file of an exclusive backup is written to
9563 * $PGDATA/backup_label, and it is removed by pg_stop_backup().
9565 * A non-exclusive backup is used for the streaming base backups (see
9566 * src/backend/replication/basebackup.c). The difference to exclusive backups
9567 * is that the backup label file is not written to disk. Instead, its would-be
9568 * contents are returned in *labelfile, and the caller is responsible for
9569 * including it in the backup archive as 'backup_label'. There can be many
9570 * non-exclusive backups active at the same time, and they don't conflict
9571 * with an exclusive backup either.
9573 * Returns the minimum WAL position that must be present to restore from this
9574 * backup, and the corresponding timeline ID in *starttli_p.
9576 * Every successfully started non-exclusive backup must be stopped by calling
9577 * do_pg_stop_backup() or do_pg_abort_backup().
9580 do_pg_start_backup(const char *backupidstr, bool fast, TimeLineID *starttli_p,
9583 bool exclusive = (labelfile == NULL);
9584 bool backup_started_in_recovery = false;
9585 XLogRecPtr checkpointloc;
9586 XLogRecPtr startpoint;
9587 TimeLineID starttli;
9588 pg_time_t stamp_time;
9590 char xlogfilename[MAXFNAMELEN];
9591 XLogSegNo _logSegNo;
9592 struct stat stat_buf;
9594 StringInfoData labelfbuf;
9596 backup_started_in_recovery = RecoveryInProgress();
9598 if (!superuser() && !has_rolreplication(GetUserId()))
9600 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
9601 errmsg("must be superuser or replication role to run a backup")));
9604 * Currently only non-exclusive backup can be taken during recovery.
9606 if (backup_started_in_recovery && exclusive)
9608 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9609 errmsg("recovery is in progress"),
9610 errhint("WAL control functions cannot be executed during recovery.")));
9613 * During recovery, we don't need to check WAL level. Because, if WAL
9614 * level is not sufficient, it's impossible to get here during recovery.
9616 if (!backup_started_in_recovery && !XLogIsNeeded())
9618 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9619 errmsg("WAL level not sufficient for making an online backup"),
9620 errhint("wal_level must be set to \"archive\" or \"hot_standby\" at server start.")));
9622 if (strlen(backupidstr) > MAXPGPATH)
9624 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9625 errmsg("backup label too long (max %d bytes)",
9629 * Mark backup active in shared memory. We must do full-page WAL writes
9630 * during an on-line backup even if not doing so at other times, because
9631 * it's quite possible for the backup dump to obtain a "torn" (partially
9632 * written) copy of a database page if it reads the page concurrently with
9633 * our write to the same page. This can be fixed as long as the first
9634 * write to the page in the WAL sequence is a full-page write. Hence, we
9635 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
9636 * are no dirty pages in shared memory that might get dumped while the
9637 * backup is in progress without having a corresponding WAL record. (Once
9638 * the backup is complete, we need not force full-page writes anymore,
9639 * since we expect that any pages not modified during the backup interval
9640 * must have been correctly captured by the backup.)
9642 * Note that forcePageWrites has no effect during an online backup from
9645 * We must hold all the insertion slots to change the value of
9646 * forcePageWrites, to ensure adequate interlocking against XLogInsert().
9648 WALInsertSlotAcquire(true);
9651 if (XLogCtl->Insert.exclusiveBackup)
9653 WALInsertSlotRelease();
9655 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9656 errmsg("a backup is already in progress"),
9657 errhint("Run pg_stop_backup() and try again.")));
9659 XLogCtl->Insert.exclusiveBackup = true;
9662 XLogCtl->Insert.nonExclusiveBackups++;
9663 XLogCtl->Insert.forcePageWrites = true;
9664 WALInsertSlotRelease();
9666 /* Ensure we release forcePageWrites if fail below */
9667 PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) BoolGetDatum(exclusive));
9669 bool gotUniqueStartpoint = false;
9672 * Force an XLOG file switch before the checkpoint, to ensure that the
9673 * WAL segment the checkpoint is written to doesn't contain pages with
9674 * old timeline IDs. That would otherwise happen if you called
9675 * pg_start_backup() right after restoring from a PITR archive: the
9676 * first WAL segment containing the startup checkpoint has pages in
9677 * the beginning with the old timeline ID. That can cause trouble at
9678 * recovery: we won't have a history file covering the old timeline if
9679 * pg_xlog directory was not included in the base backup and the WAL
9680 * archive was cleared too before starting the backup.
9682 * This also ensures that we have emitted a WAL page header that has
9683 * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
9684 * Therefore, if a WAL archiver (such as pglesslog) is trying to
9685 * compress out removable backup blocks, it won't remove any that
9686 * occur after this point.
9688 * During recovery, we skip forcing XLOG file switch, which means that
9689 * the backup taken during recovery is not available for the special
9690 * recovery case described above.
9692 if (!backup_started_in_recovery)
9693 RequestXLogSwitch();
9700 * Force a CHECKPOINT. Aside from being necessary to prevent torn
9701 * page problems, this guarantees that two successive backup runs
9702 * will have different checkpoint positions and hence different
9703 * history file names, even if nothing happened in between.
9705 * During recovery, establish a restartpoint if possible. We use
9706 * the last restartpoint as the backup starting checkpoint. This
9707 * means that two successive backup runs can have same checkpoint
9710 * Since the fact that we are executing do_pg_start_backup()
9711 * during recovery means that checkpointer is running, we can use
9712 * RequestCheckpoint() to establish a restartpoint.
9714 * We use CHECKPOINT_IMMEDIATE only if requested by user (via
9715 * passing fast = true). Otherwise this can take awhile.
9717 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT |
9718 (fast ? CHECKPOINT_IMMEDIATE : 0));
9721 * Now we need to fetch the checkpoint record location, and also
9722 * its REDO pointer. The oldest point in WAL that would be needed
9723 * to restore starting from the checkpoint is precisely the REDO
9726 LWLockAcquire(ControlFileLock, LW_SHARED);
9727 checkpointloc = ControlFile->checkPoint;
9728 startpoint = ControlFile->checkPointCopy.redo;
9729 starttli = ControlFile->checkPointCopy.ThisTimeLineID;
9730 checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
9731 LWLockRelease(ControlFileLock);
9733 if (backup_started_in_recovery)
9735 /* use volatile pointer to prevent code rearrangement */
9736 volatile XLogCtlData *xlogctl = XLogCtl;
9740 * Check to see if all WAL replayed during online backup
9741 * (i.e., since last restartpoint used as backup starting
9742 * checkpoint) contain full-page writes.
9744 SpinLockAcquire(&xlogctl->info_lck);
9745 recptr = xlogctl->lastFpwDisableRecPtr;
9746 SpinLockRelease(&xlogctl->info_lck);
9748 if (!checkpointfpw || startpoint <= recptr)
9750 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9751 errmsg("WAL generated with full_page_writes=off was replayed "
9752 "since last restartpoint"),
9753 errhint("This means that the backup being taken on the standby "
9754 "is corrupt and should not be used. "
9755 "Enable full_page_writes and run CHECKPOINT on the master, "
9756 "and then try an online backup again.")));
9759 * During recovery, since we don't use the end-of-backup WAL
9760 * record and don't write the backup history file, the
9761 * starting WAL location doesn't need to be unique. This means
9762 * that two base backups started at the same time might use
9763 * the same checkpoint as starting locations.
9765 gotUniqueStartpoint = true;
9769 * If two base backups are started at the same time (in WAL sender
9770 * processes), we need to make sure that they use different
9771 * checkpoints as starting locations, because we use the starting
9772 * WAL location as a unique identifier for the base backup in the
9773 * end-of-backup WAL record and when we write the backup history
9774 * file. Perhaps it would be better generate a separate unique ID
9775 * for each backup instead of forcing another checkpoint, but
9776 * taking a checkpoint right after another is not that expensive
9777 * either because only few buffers have been dirtied yet.
9779 WALInsertSlotAcquire(true);
9780 if (XLogCtl->Insert.lastBackupStart < startpoint)
9782 XLogCtl->Insert.lastBackupStart = startpoint;
9783 gotUniqueStartpoint = true;
9785 WALInsertSlotRelease();
9786 } while (!gotUniqueStartpoint);
9788 XLByteToSeg(startpoint, _logSegNo);
9789 XLogFileName(xlogfilename, ThisTimeLineID, _logSegNo);
9792 * Construct backup label file
9794 initStringInfo(&labelfbuf);
9796 /* Use the log timezone here, not the session timezone */
9797 stamp_time = (pg_time_t) time(NULL);
9798 pg_strftime(strfbuf, sizeof(strfbuf),
9799 "%Y-%m-%d %H:%M:%S %Z",
9800 pg_localtime(&stamp_time, log_timezone));
9801 appendStringInfo(&labelfbuf, "START WAL LOCATION: %X/%X (file %s)\n",
9802 (uint32) (startpoint >> 32), (uint32) startpoint, xlogfilename);
9803 appendStringInfo(&labelfbuf, "CHECKPOINT LOCATION: %X/%X\n",
9804 (uint32) (checkpointloc >> 32), (uint32) checkpointloc);
9805 appendStringInfo(&labelfbuf, "BACKUP METHOD: %s\n",
9806 exclusive ? "pg_start_backup" : "streamed");
9807 appendStringInfo(&labelfbuf, "BACKUP FROM: %s\n",
9808 backup_started_in_recovery ? "standby" : "master");
9809 appendStringInfo(&labelfbuf, "START TIME: %s\n", strfbuf);
9810 appendStringInfo(&labelfbuf, "LABEL: %s\n", backupidstr);
9813 * Okay, write the file, or return its contents to caller.
9818 * Check for existing backup label --- implies a backup is already
9819 * running. (XXX given that we checked exclusiveBackup above,
9820 * maybe it would be OK to just unlink any such label file?)
9822 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
9824 if (errno != ENOENT)
9826 (errcode_for_file_access(),
9827 errmsg("could not stat file \"%s\": %m",
9828 BACKUP_LABEL_FILE)));
9832 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9833 errmsg("a backup is already in progress"),
9834 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
9835 BACKUP_LABEL_FILE)));
9837 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
9841 (errcode_for_file_access(),
9842 errmsg("could not create file \"%s\": %m",
9843 BACKUP_LABEL_FILE)));
9844 if (fwrite(labelfbuf.data, labelfbuf.len, 1, fp) != 1 ||
9846 pg_fsync(fileno(fp)) != 0 ||
9850 (errcode_for_file_access(),
9851 errmsg("could not write file \"%s\": %m",
9852 BACKUP_LABEL_FILE)));
9853 pfree(labelfbuf.data);
9856 *labelfile = labelfbuf.data;
9858 PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) BoolGetDatum(exclusive));
9861 * We're done. As a convenience, return the starting WAL location.
9864 *starttli_p = starttli;
9868 /* Error cleanup callback for pg_start_backup */
9870 pg_start_backup_callback(int code, Datum arg)
9872 bool exclusive = DatumGetBool(arg);
9874 /* Update backup counters and forcePageWrites on failure */
9875 WALInsertSlotAcquire(true);
9878 Assert(XLogCtl->Insert.exclusiveBackup);
9879 XLogCtl->Insert.exclusiveBackup = false;
9883 Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
9884 XLogCtl->Insert.nonExclusiveBackups--;
9887 if (!XLogCtl->Insert.exclusiveBackup &&
9888 XLogCtl->Insert.nonExclusiveBackups == 0)
9890 XLogCtl->Insert.forcePageWrites = false;
9892 WALInsertSlotRelease();
9896 * do_pg_stop_backup is the workhorse of the user-visible pg_stop_backup()
9899 * If labelfile is NULL, this stops an exclusive backup. Otherwise this stops
9900 * the non-exclusive backup specified by 'labelfile'.
9902 * Returns the last WAL position that must be present to restore from this
9903 * backup, and the corresponding timeline ID in *stoptli_p.
9906 do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
9908 bool exclusive = (labelfile == NULL);
9909 bool backup_started_in_recovery = false;
9910 XLogRecPtr startpoint;
9911 XLogRecPtr stoppoint;
9914 pg_time_t stamp_time;
9916 char histfilepath[MAXPGPATH];
9917 char startxlogfilename[MAXFNAMELEN];
9918 char stopxlogfilename[MAXFNAMELEN];
9919 char lastxlogfilename[MAXFNAMELEN];
9920 char histfilename[MAXFNAMELEN];
9921 char backupfrom[20];
9922 XLogSegNo _logSegNo;
9926 int seconds_before_warning;
9928 bool reported_waiting = false;
9934 backup_started_in_recovery = RecoveryInProgress();
9936 if (!superuser() && !has_rolreplication(GetUserId()))
9938 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
9939 (errmsg("must be superuser or replication role to run a backup"))));
9942 * Currently only non-exclusive backup can be taken during recovery.
9944 if (backup_started_in_recovery && exclusive)
9946 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9947 errmsg("recovery is in progress"),
9948 errhint("WAL control functions cannot be executed during recovery.")));
9951 * During recovery, we don't need to check WAL level. Because, if WAL
9952 * level is not sufficient, it's impossible to get here during recovery.
9954 if (!backup_started_in_recovery && !XLogIsNeeded())
9956 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9957 errmsg("WAL level not sufficient for making an online backup"),
9958 errhint("wal_level must be set to \"archive\" or \"hot_standby\" at server start.")));
9961 * OK to update backup counters and forcePageWrites
9963 WALInsertSlotAcquire(true);
9965 XLogCtl->Insert.exclusiveBackup = false;
9969 * The user-visible pg_start/stop_backup() functions that operate on
9970 * exclusive backups can be called at any time, but for non-exclusive
9971 * backups, it is expected that each do_pg_start_backup() call is
9972 * matched by exactly one do_pg_stop_backup() call.
9974 Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
9975 XLogCtl->Insert.nonExclusiveBackups--;
9978 if (!XLogCtl->Insert.exclusiveBackup &&
9979 XLogCtl->Insert.nonExclusiveBackups == 0)
9981 XLogCtl->Insert.forcePageWrites = false;
9983 WALInsertSlotRelease();
9988 * Read the existing label file into memory.
9990 struct stat statbuf;
9993 if (stat(BACKUP_LABEL_FILE, &statbuf))
9995 if (errno != ENOENT)
9997 (errcode_for_file_access(),
9998 errmsg("could not stat file \"%s\": %m",
9999 BACKUP_LABEL_FILE)));
10001 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10002 errmsg("a backup is not in progress")));
10005 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
10009 (errcode_for_file_access(),
10010 errmsg("could not read file \"%s\": %m",
10011 BACKUP_LABEL_FILE)));
10013 labelfile = palloc(statbuf.st_size + 1);
10014 r = fread(labelfile, statbuf.st_size, 1, lfp);
10015 labelfile[statbuf.st_size] = '\0';
10018 * Close and remove the backup label file
10020 if (r != 1 || ferror(lfp) || FreeFile(lfp))
10022 (errcode_for_file_access(),
10023 errmsg("could not read file \"%s\": %m",
10024 BACKUP_LABEL_FILE)));
10025 if (unlink(BACKUP_LABEL_FILE) != 0)
10027 (errcode_for_file_access(),
10028 errmsg("could not remove file \"%s\": %m",
10029 BACKUP_LABEL_FILE)));
10033 * Read and parse the START WAL LOCATION line (this code is pretty crude,
10034 * but we are not expecting any variability in the file format).
10036 if (sscanf(labelfile, "START WAL LOCATION: %X/%X (file %24s)%c",
10037 &hi, &lo, startxlogfilename,
10038 &ch) != 4 || ch != '\n')
10040 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10041 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10042 startpoint = ((uint64) hi) << 32 | lo;
10043 remaining = strchr(labelfile, '\n') + 1; /* %n is not portable enough */
10046 * Parse the BACKUP FROM line. If we are taking an online backup from the
10047 * standby, we confirm that the standby has not been promoted during the
10050 ptr = strstr(remaining, "BACKUP FROM:");
10051 if (!ptr || sscanf(ptr, "BACKUP FROM: %19s\n", backupfrom) != 1)
10053 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10054 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10055 if (strcmp(backupfrom, "standby") == 0 && !backup_started_in_recovery)
10057 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10058 errmsg("the standby was promoted during online backup"),
10059 errhint("This means that the backup being taken is corrupt "
10060 "and should not be used. "
10061 "Try taking another online backup.")));
10064 * During recovery, we don't write an end-of-backup record. We assume that
10065 * pg_control was backed up last and its minimum recovery point can be
10066 * available as the backup end location. Since we don't have an
10067 * end-of-backup record, we use the pg_control value to check whether
10068 * we've reached the end of backup when starting recovery from this
10069 * backup. We have no way of checking if pg_control wasn't backed up last
10072 * We don't force a switch to new WAL file and wait for all the required
10073 * files to be archived. This is okay if we use the backup to start the
10074 * standby. But, if it's for an archive recovery, to ensure all the
10075 * required files are available, a user should wait for them to be
10076 * archived, or include them into the backup.
10078 * We return the current minimum recovery point as the backup end
10079 * location. Note that it can be greater than the exact backup end
10080 * location if the minimum recovery point is updated after the backup of
10081 * pg_control. This is harmless for current uses.
10083 * XXX currently a backup history file is for informational and debug
10084 * purposes only. It's not essential for an online backup. Furthermore,
10085 * even if it's created, it will not be archived during recovery because
10086 * an archiver is not invoked. So it doesn't seem worthwhile to write a
10087 * backup history file during recovery.
10089 if (backup_started_in_recovery)
10091 /* use volatile pointer to prevent code rearrangement */
10092 volatile XLogCtlData *xlogctl = XLogCtl;
10096 * Check to see if all WAL replayed during online backup contain
10097 * full-page writes.
10099 SpinLockAcquire(&xlogctl->info_lck);
10100 recptr = xlogctl->lastFpwDisableRecPtr;
10101 SpinLockRelease(&xlogctl->info_lck);
10103 if (startpoint <= recptr)
10105 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10106 errmsg("WAL generated with full_page_writes=off was replayed "
10107 "during online backup"),
10108 errhint("This means that the backup being taken on the standby "
10109 "is corrupt and should not be used. "
10110 "Enable full_page_writes and run CHECKPOINT on the master, "
10111 "and then try an online backup again.")));
10114 LWLockAcquire(ControlFileLock, LW_SHARED);
10115 stoppoint = ControlFile->minRecoveryPoint;
10116 stoptli = ControlFile->minRecoveryPointTLI;
10117 LWLockRelease(ControlFileLock);
10120 *stoptli_p = stoptli;
10125 * Write the backup-end xlog record
10127 rdata.data = (char *) (&startpoint);
10128 rdata.len = sizeof(startpoint);
10129 rdata.buffer = InvalidBuffer;
10131 stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END, &rdata);
10132 stoptli = ThisTimeLineID;
10135 * Force a switch to a new xlog segment file, so that the backup is valid
10136 * as soon as archiver moves out the current segment file.
10138 RequestXLogSwitch();
10140 XLByteToPrevSeg(stoppoint, _logSegNo);
10141 XLogFileName(stopxlogfilename, ThisTimeLineID, _logSegNo);
10143 /* Use the log timezone here, not the session timezone */
10144 stamp_time = (pg_time_t) time(NULL);
10145 pg_strftime(strfbuf, sizeof(strfbuf),
10146 "%Y-%m-%d %H:%M:%S %Z",
10147 pg_localtime(&stamp_time, log_timezone));
10150 * Write the backup history file
10152 XLByteToSeg(startpoint, _logSegNo);
10153 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logSegNo,
10154 (uint32) (startpoint % XLogSegSize));
10155 fp = AllocateFile(histfilepath, "w");
10158 (errcode_for_file_access(),
10159 errmsg("could not create file \"%s\": %m",
10161 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
10162 (uint32) (startpoint >> 32), (uint32) startpoint, startxlogfilename);
10163 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
10164 (uint32) (stoppoint >> 32), (uint32) stoppoint, stopxlogfilename);
10165 /* transfer remaining lines from label to history file */
10166 fprintf(fp, "%s", remaining);
10167 fprintf(fp, "STOP TIME: %s\n", strfbuf);
10168 if (fflush(fp) || ferror(fp) || FreeFile(fp))
10170 (errcode_for_file_access(),
10171 errmsg("could not write file \"%s\": %m",
10175 * Clean out any no-longer-needed history files. As a side effect, this
10176 * will post a .ready file for the newly created history file, notifying
10177 * the archiver that history file may be archived immediately.
10179 CleanupBackupHistory();
10182 * If archiving is enabled, wait for all the required WAL files to be
10183 * archived before returning. If archiving isn't enabled, the required WAL
10184 * needs to be transported via streaming replication (hopefully with
10185 * wal_keep_segments set high enough), or some more exotic mechanism like
10186 * polling and copying files from pg_xlog with script. We have no
10187 * knowledge of those mechanisms, so it's up to the user to ensure that he
10188 * gets all the required WAL.
10190 * We wait until both the last WAL file filled during backup and the
10191 * history file have been archived, and assume that the alphabetic sorting
10192 * property of the WAL files ensures any earlier WAL files are safely
10193 * archived as well.
10195 * We wait forever, since archive_command is supposed to work and we
10196 * assume the admin wanted his backup to work completely. If you don't
10197 * wish to wait, you can set statement_timeout. Also, some notices are
10198 * issued to clue in anyone who might be doing this interactively.
10200 if (waitforarchive && XLogArchivingActive())
10202 XLByteToPrevSeg(stoppoint, _logSegNo);
10203 XLogFileName(lastxlogfilename, ThisTimeLineID, _logSegNo);
10205 XLByteToSeg(startpoint, _logSegNo);
10206 BackupHistoryFileName(histfilename, ThisTimeLineID, _logSegNo,
10207 (uint32) (startpoint % XLogSegSize));
10209 seconds_before_warning = 60;
10212 while (XLogArchiveIsBusy(lastxlogfilename) ||
10213 XLogArchiveIsBusy(histfilename))
10215 CHECK_FOR_INTERRUPTS();
10217 if (!reported_waiting && waits > 5)
10220 (errmsg("pg_stop_backup cleanup done, waiting for required WAL segments to be archived")));
10221 reported_waiting = true;
10224 pg_usleep(1000000L);
10226 if (++waits >= seconds_before_warning)
10228 seconds_before_warning *= 2; /* This wraps in >10 years... */
10230 (errmsg("pg_stop_backup still waiting for all required WAL segments to be archived (%d seconds elapsed)",
10232 errhint("Check that your archive_command is executing properly. "
10233 "pg_stop_backup can be canceled safely, "
10234 "but the database backup will not be usable without all the WAL segments.")));
10239 (errmsg("pg_stop_backup complete, all required WAL segments have been archived")));
10241 else if (waitforarchive)
10243 (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
10246 * We're done. As a convenience, return the ending WAL location.
10249 *stoptli_p = stoptli;
10255 * do_pg_abort_backup: abort a running backup
10257 * This does just the most basic steps of do_pg_stop_backup(), by taking the
10258 * system out of backup mode, thus making it a lot more safe to call from
10259 * an error handler.
10261 * NB: This is only for aborting a non-exclusive backup that doesn't write
10262 * backup_label. A backup started with pg_stop_backup() needs to be finished
10263 * with pg_stop_backup().
10266 do_pg_abort_backup(void)
10268 WALInsertSlotAcquire(true);
10269 Assert(XLogCtl->Insert.nonExclusiveBackups > 0);
10270 XLogCtl->Insert.nonExclusiveBackups--;
10272 if (!XLogCtl->Insert.exclusiveBackup &&
10273 XLogCtl->Insert.nonExclusiveBackups == 0)
10275 XLogCtl->Insert.forcePageWrites = false;
10277 WALInsertSlotRelease();
10281 * Get latest redo apply position.
10283 * Exported to allow WALReceiver to read the pointer directly.
10286 GetXLogReplayRecPtr(TimeLineID *replayTLI)
10288 /* use volatile pointer to prevent code rearrangement */
10289 volatile XLogCtlData *xlogctl = XLogCtl;
10293 SpinLockAcquire(&xlogctl->info_lck);
10294 recptr = xlogctl->lastReplayedEndRecPtr;
10295 tli = xlogctl->lastReplayedTLI;
10296 SpinLockRelease(&xlogctl->info_lck);
10304 * Get latest WAL insert pointer
10307 GetXLogInsertRecPtr(void)
10309 volatile XLogCtlInsert *Insert = &XLogCtl->Insert;
10310 uint64 current_bytepos;
10312 SpinLockAcquire(&Insert->insertpos_lck);
10313 current_bytepos = Insert->CurrBytePos;
10314 SpinLockRelease(&Insert->insertpos_lck);
10316 return XLogBytePosToRecPtr(current_bytepos);
10320 * Get latest WAL write pointer
10323 GetXLogWriteRecPtr(void)
10326 /* use volatile pointer to prevent code rearrangement */
10327 volatile XLogCtlData *xlogctl = XLogCtl;
10329 SpinLockAcquire(&xlogctl->info_lck);
10330 LogwrtResult = xlogctl->LogwrtResult;
10331 SpinLockRelease(&xlogctl->info_lck);
10334 return LogwrtResult.Write;
10338 * Returns the redo pointer of the last checkpoint or restartpoint. This is
10339 * the oldest point in WAL that we still need, if we have to restart recovery.
10342 GetOldestRestartPoint(XLogRecPtr *oldrecptr, TimeLineID *oldtli)
10344 LWLockAcquire(ControlFileLock, LW_SHARED);
10345 *oldrecptr = ControlFile->checkPointCopy.redo;
10346 *oldtli = ControlFile->checkPointCopy.ThisTimeLineID;
10347 LWLockRelease(ControlFileLock);
10351 * read_backup_label: check to see if a backup_label file is present
10353 * If we see a backup_label during recovery, we assume that we are recovering
10354 * from a backup dump file, and we therefore roll forward from the checkpoint
10355 * identified by the label file, NOT what pg_control says. This avoids the
10356 * problem that pg_control might have been archived one or more checkpoints
10357 * later than the start of the dump, and so if we rely on it as the start
10358 * point, we will fail to restore a consistent database state.
10360 * Returns TRUE if a backup_label was found (and fills the checkpoint
10361 * location and its REDO location into *checkPointLoc and RedoStartLSN,
10362 * respectively); returns FALSE if not. If this backup_label came from a
10363 * streamed backup, *backupEndRequired is set to TRUE. If this backup_label
10364 * was created during recovery, *backupFromStandby is set to TRUE.
10367 read_backup_label(XLogRecPtr *checkPointLoc, bool *backupEndRequired,
10368 bool *backupFromStandby)
10370 char startxlogfilename[MAXFNAMELEN];
10374 char backuptype[20];
10375 char backupfrom[20];
10379 *backupEndRequired = false;
10380 *backupFromStandby = false;
10383 * See if label file is present
10385 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
10388 if (errno != ENOENT)
10390 (errcode_for_file_access(),
10391 errmsg("could not read file \"%s\": %m",
10392 BACKUP_LABEL_FILE)));
10393 return false; /* it's not there, all is fine */
10397 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
10398 * is pretty crude, but we are not expecting any variability in the file
10401 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
10402 &hi, &lo, &tli, startxlogfilename, &ch) != 5 || ch != '\n')
10404 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10405 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10406 RedoStartLSN = ((uint64) hi) << 32 | lo;
10407 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
10408 &hi, &lo, &ch) != 3 || ch != '\n')
10410 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10411 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10412 *checkPointLoc = ((uint64) hi) << 32 | lo;
10415 * BACKUP METHOD and BACKUP FROM lines are new in 9.2. We can't restore
10416 * from an older backup anyway, but since the information on it is not
10417 * strictly required, don't error out if it's missing for some reason.
10419 if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
10421 if (strcmp(backuptype, "streamed") == 0)
10422 *backupEndRequired = true;
10425 if (fscanf(lfp, "BACKUP FROM: %19s\n", backupfrom) == 1)
10427 if (strcmp(backupfrom, "standby") == 0)
10428 *backupFromStandby = true;
10431 if (ferror(lfp) || FreeFile(lfp))
10433 (errcode_for_file_access(),
10434 errmsg("could not read file \"%s\": %m",
10435 BACKUP_LABEL_FILE)));
10441 * Error context callback for errors occurring during rm_redo().
10444 rm_redo_error_callback(void *arg)
10446 XLogRecord *record = (XLogRecord *) arg;
10447 StringInfoData buf;
10449 initStringInfo(&buf);
10450 RmgrTable[record->xl_rmid].rm_desc(&buf,
10452 XLogRecGetData(record));
10454 /* don't bother emitting empty description */
10456 errcontext("xlog redo %s", buf.data);
10462 * BackupInProgress: check if online backup mode is active
10464 * This is done by checking for existence of the "backup_label" file.
10467 BackupInProgress(void)
10469 struct stat stat_buf;
10471 return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
10475 * CancelBackup: rename the "backup_label" file to cancel backup mode
10477 * If the "backup_label" file exists, it will be renamed to "backup_label.old".
10478 * Note that this will render an online backup in progress useless.
10479 * To correctly finish an online backup, pg_stop_backup must be called.
10484 struct stat stat_buf;
10486 /* if the file is not there, return */
10487 if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
10490 /* remove leftover file from previously canceled backup if it exists */
10491 unlink(BACKUP_LABEL_OLD);
10493 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) == 0)
10496 (errmsg("online backup mode canceled"),
10497 errdetail("\"%s\" was renamed to \"%s\".",
10498 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
10503 (errcode_for_file_access(),
10504 errmsg("online backup mode was not canceled"),
10505 errdetail("Could not rename \"%s\" to \"%s\": %m.",
10506 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
10511 * Read the XLOG page containing RecPtr into readBuf (if not read already).
10512 * Returns number of bytes read, if the page is read successfully, or -1
10513 * in case of errors. When errors occur, they are ereport'ed, but only
10514 * if they have not been previously reported.
10516 * This is responsible for restoring files from archive as needed, as well
10517 * as for waiting for the requested WAL record to arrive in standby mode.
10519 * 'emode' specifies the log level used for reporting "file not found" or
10520 * "end of WAL" situations in archive recovery, or in standby mode when a
10521 * trigger file is found. If set to WARNING or below, XLogPageRead() returns
10522 * false in those situations, on higher log levels the ereport() won't
10525 * In standby mode, if after a successful return of XLogPageRead() the
10526 * caller finds the record it's interested in to be broken, it should
10527 * ereport the error with the level determined by
10528 * emode_for_corrupt_record(), and then set lastSourceFailed
10529 * and call XLogPageRead() again with the same arguments. This lets
10530 * XLogPageRead() to try fetching the record from another source, or to
10534 XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
10535 XLogRecPtr targetRecPtr, char *readBuf, TimeLineID *readTLI)
10537 XLogPageReadPrivate *private =
10538 (XLogPageReadPrivate *) xlogreader->private_data;
10539 int emode = private->emode;
10540 uint32 targetPageOff;
10541 XLogSegNo targetSegNo PG_USED_FOR_ASSERTS_ONLY;
10543 XLByteToSeg(targetPagePtr, targetSegNo);
10544 targetPageOff = targetPagePtr % XLogSegSize;
10547 * See if we need to switch to a new segment because the requested record
10548 * is not in the currently open one.
10550 if (readFile >= 0 && !XLByteInSeg(targetPagePtr, readSegNo))
10553 * Request a restartpoint if we've replayed too much xlog since the
10556 if (StandbyModeRequested && bgwriterLaunched)
10558 if (XLogCheckpointNeeded(readSegNo))
10560 (void) GetRedoRecPtr();
10561 if (XLogCheckpointNeeded(readSegNo))
10562 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
10571 XLByteToSeg(targetPagePtr, readSegNo);
10574 /* See if we need to retrieve more data */
10575 if (readFile < 0 ||
10576 (readSource == XLOG_FROM_STREAM &&
10577 receivedUpto < targetPagePtr + reqLen))
10579 if (!WaitForWALToBecomeAvailable(targetPagePtr + reqLen,
10580 private->randAccess,
10581 private->fetching_ckpt,
10595 * At this point, we have the right segment open and if we're streaming we
10596 * know the requested record is in it.
10598 Assert(readFile != -1);
10601 * If the current segment is being streamed from master, calculate how
10602 * much of the current page we have received already. We know the
10603 * requested record has been received, but this is for the benefit of
10604 * future calls, to allow quick exit at the top of this function.
10606 if (readSource == XLOG_FROM_STREAM)
10608 if (((targetPagePtr) / XLOG_BLCKSZ) != (receivedUpto / XLOG_BLCKSZ))
10609 readLen = XLOG_BLCKSZ;
10611 readLen = receivedUpto % XLogSegSize - targetPageOff;
10614 readLen = XLOG_BLCKSZ;
10616 /* Read the requested page */
10617 readOff = targetPageOff;
10618 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
10620 char fname[MAXFNAMELEN];
10622 XLogFileName(fname, curFileTLI, readSegNo);
10623 ereport(emode_for_corrupt_record(emode, targetPagePtr + reqLen),
10624 (errcode_for_file_access(),
10625 errmsg("could not seek in log segment %s to offset %u: %m",
10627 goto next_record_is_invalid;
10630 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
10632 char fname[MAXFNAMELEN];
10634 XLogFileName(fname, curFileTLI, readSegNo);
10635 ereport(emode_for_corrupt_record(emode, targetPagePtr + reqLen),
10636 (errcode_for_file_access(),
10637 errmsg("could not read from log segment %s, offset %u: %m",
10639 goto next_record_is_invalid;
10642 Assert(targetSegNo == readSegNo);
10643 Assert(targetPageOff == readOff);
10644 Assert(reqLen <= readLen);
10646 *readTLI = curFileTLI;
10649 next_record_is_invalid:
10650 lastSourceFailed = true;
10658 /* In standby-mode, keep trying */
10666 * Open the WAL segment containing WAL position 'RecPtr'.
10668 * The segment can be fetched via restore_command, or via walreceiver having
10669 * streamed the record, or it can already be present in pg_xlog. Checking
10670 * pg_xlog is mainly for crash recovery, but it will be polled in standby mode
10671 * too, in case someone copies a new segment directly to pg_xlog. That is not
10672 * documented or recommended, though.
10674 * If 'fetching_ckpt' is true, we're fetching a checkpoint record, and should
10675 * prepare to read WAL starting from RedoStartLSN after this.
10677 * 'RecPtr' might not point to the beginning of the record we're interested
10678 * in, it might also point to the page or segment header. In that case,
10679 * 'tliRecPtr' is the position of the WAL record we're interested in. It is
10680 * used to decide which timeline to stream the requested WAL from.
10682 * If the the record is not immediately available, the function returns false
10683 * if we're not in standby mode. In standby mode, waits for it to become
10686 * When the requested record becomes available, the function opens the file
10687 * containing it (if not open already), and returns true. When end of standby
10688 * mode is triggered by the user, and there is no more WAL available, returns
10692 WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
10693 bool fetching_ckpt, XLogRecPtr tliRecPtr)
10695 static pg_time_t last_fail_time = 0;
10699 * Standby mode is implemented by a state machine:
10701 * 1. Read from archive (XLOG_FROM_ARCHIVE)
10702 * 2. Read from pg_xlog (XLOG_FROM_PG_XLOG)
10703 * 3. Check trigger file
10704 * 4. Read from primary server via walreceiver (XLOG_FROM_STREAM)
10705 * 5. Rescan timelines
10706 * 6. Sleep 5 seconds, and loop back to 1.
10708 * Failure to read from the current source advances the state machine to
10709 * the next state. In addition, successfully reading a file from pg_xlog
10710 * moves the state machine from state 2 back to state 1 (we always prefer
10711 * files in the archive over files in pg_xlog).
10713 * 'currentSource' indicates the current state. There are no currentSource
10714 * values for "check trigger", "rescan timelines", and "sleep" states,
10715 * those actions are taken when reading from the previous source fails, as
10716 * part of advancing to the next state.
10719 if (!InArchiveRecovery)
10720 currentSource = XLOG_FROM_PG_XLOG;
10721 else if (currentSource == 0)
10722 currentSource = XLOG_FROM_ARCHIVE;
10726 int oldSource = currentSource;
10729 * First check if we failed to read from the current source, and
10730 * advance the state machine if so. The failure to read might've
10731 * happened outside this function, e.g when a CRC check fails on a
10732 * record, or within this loop.
10734 if (lastSourceFailed)
10736 switch (currentSource)
10738 case XLOG_FROM_ARCHIVE:
10739 currentSource = XLOG_FROM_PG_XLOG;
10742 case XLOG_FROM_PG_XLOG:
10745 * Check to see if the trigger file exists. Note that we
10746 * do this only after failure, so when you create the
10747 * trigger file, we still finish replaying as much as we
10748 * can from archive and pg_xlog before failover.
10750 if (StandbyMode && CheckForStandbyTrigger())
10757 * Not in standby mode, and we've now tried the archive
10764 * If primary_conninfo is set, launch walreceiver to try
10765 * to stream the missing WAL.
10767 * If fetching_ckpt is TRUE, RecPtr points to the initial
10768 * checkpoint location. In that case, we use RedoStartLSN
10769 * as the streaming start position instead of RecPtr, so
10770 * that when we later jump backwards to start redo at
10771 * RedoStartLSN, we will have the logs streamed already.
10773 if (PrimaryConnInfo)
10780 ptr = RedoStartLSN;
10781 tli = ControlFile->checkPointCopy.ThisTimeLineID;
10786 tli = tliOfPointInHistory(tliRecPtr, expectedTLEs);
10788 if (curFileTLI > 0 && tli < curFileTLI)
10789 elog(ERROR, "according to history file, WAL location %X/%X belongs to timeline %u, but previous recovered WAL file came from timeline %u",
10790 (uint32) (ptr >> 32), (uint32) ptr,
10794 RequestXLogStreaming(tli, ptr, PrimaryConnInfo);
10799 * Move to XLOG_FROM_STREAM state in either case. We'll
10800 * get immediate failure if we didn't launch walreceiver,
10801 * and move on to the next state.
10803 currentSource = XLOG_FROM_STREAM;
10806 case XLOG_FROM_STREAM:
10809 * Failure while streaming. Most likely, we got here
10810 * because streaming replication was terminated, or
10811 * promotion was triggered. But we also get here if we
10812 * find an invalid record in the WAL streamed from master,
10813 * in which case something is seriously wrong. There's
10814 * little chance that the problem will just go away, but
10815 * PANIC is not good for availability either, especially
10816 * in hot standby mode. So, we treat that the same as
10817 * disconnection, and retry from archive/pg_xlog again.
10818 * The WAL in the archive should be identical to what was
10819 * streamed, so it's unlikely that it helps, but one can
10824 * Before we leave XLOG_FROM_STREAM state, make sure that
10825 * walreceiver is not active, so that it won't overwrite
10826 * WAL that we restore from archive.
10828 if (WalRcvStreaming())
10832 * Before we sleep, re-scan for possible new timelines if
10833 * we were requested to recover to the latest timeline.
10835 if (recoveryTargetIsLatest)
10837 if (rescanLatestTimeLine())
10839 currentSource = XLOG_FROM_ARCHIVE;
10845 * XLOG_FROM_STREAM is the last state in our state
10846 * machine, so we've exhausted all the options for
10847 * obtaining the requested WAL. We're going to loop back
10848 * and retry from the archive, but if it hasn't been long
10849 * since last attempt, sleep 5 seconds to avoid
10852 now = (pg_time_t) time(NULL);
10853 if ((now - last_fail_time) < 5)
10855 pg_usleep(1000000L * (5 - (now - last_fail_time)));
10856 now = (pg_time_t) time(NULL);
10858 last_fail_time = now;
10859 currentSource = XLOG_FROM_ARCHIVE;
10863 elog(ERROR, "unexpected WAL source %d", currentSource);
10866 else if (currentSource == XLOG_FROM_PG_XLOG)
10869 * We just successfully read a file in pg_xlog. We prefer files in
10870 * the archive over ones in pg_xlog, so try the next file again
10871 * from the archive first.
10873 if (InArchiveRecovery)
10874 currentSource = XLOG_FROM_ARCHIVE;
10877 if (currentSource != oldSource)
10878 elog(DEBUG2, "switched WAL source from %s to %s after %s",
10879 xlogSourceNames[oldSource], xlogSourceNames[currentSource],
10880 lastSourceFailed ? "failure" : "success");
10883 * We've now handled possible failure. Try to read from the chosen
10886 lastSourceFailed = false;
10888 switch (currentSource)
10890 case XLOG_FROM_ARCHIVE:
10891 case XLOG_FROM_PG_XLOG:
10892 /* Close any old file we might have open. */
10898 /* Reset curFileTLI if random fetch. */
10903 * Try to restore the file from archive, or read an existing
10904 * file from pg_xlog.
10906 readFile = XLogFileReadAnyTLI(readSegNo, DEBUG2, currentSource);
10908 return true; /* success! */
10911 * Nope, not found in archive or pg_xlog.
10913 lastSourceFailed = true;
10916 case XLOG_FROM_STREAM:
10921 * Check if WAL receiver is still active.
10923 if (!WalRcvStreaming())
10925 lastSourceFailed = true;
10930 * Walreceiver is active, so see if new data has arrived.
10932 * We only advance XLogReceiptTime when we obtain fresh
10933 * WAL from walreceiver and observe that we had already
10934 * processed everything before the most recent "chunk"
10935 * that it flushed to disk. In steady state where we are
10936 * keeping up with the incoming data, XLogReceiptTime will
10937 * be updated on each cycle. When we are behind,
10938 * XLogReceiptTime will not advance, so the grace time
10939 * allotted to conflicting queries will decrease.
10941 if (RecPtr < receivedUpto)
10945 XLogRecPtr latestChunkStart;
10947 receivedUpto = GetWalRcvWriteRecPtr(&latestChunkStart, &receiveTLI);
10948 if (RecPtr < receivedUpto && receiveTLI == curFileTLI)
10951 if (latestChunkStart <= RecPtr)
10953 XLogReceiptTime = GetCurrentTimestamp();
10954 SetCurrentChunkStartTime(XLogReceiptTime);
10963 * Great, streamed far enough. Open the file if it's
10964 * not open already. Also read the timeline history
10965 * file if we haven't initialized timeline history
10966 * yet; it should be streamed over and present in
10967 * pg_xlog by now. Use XLOG_FROM_STREAM so that
10968 * source info is set correctly and XLogReceiptTime
10974 expectedTLEs = readTimeLineHistory(receiveTLI);
10975 readFile = XLogFileRead(readSegNo, PANIC,
10977 XLOG_FROM_STREAM, false);
10978 Assert(readFile >= 0);
10982 /* just make sure source info is correct... */
10983 readSource = XLOG_FROM_STREAM;
10984 XLogReceiptSource = XLOG_FROM_STREAM;
10991 * Data not here yet. Check for trigger, then wait for
10992 * walreceiver to wake us up when new WAL arrives.
10994 if (CheckForStandbyTrigger())
10997 * Note that we don't "return false" immediately here.
10998 * After being triggered, we still want to replay all
10999 * the WAL that was already streamed. It's in pg_xlog
11000 * now, so we just treat this as a failure, and the
11001 * state machine will move on to replay the streamed
11002 * WAL from pg_xlog, and then recheck the trigger and
11005 lastSourceFailed = true;
11010 * Wait for more WAL to arrive. Time out after 5 seconds,
11011 * like when polling the archive, to react to a trigger
11014 WaitLatch(&XLogCtl->recoveryWakeupLatch,
11015 WL_LATCH_SET | WL_TIMEOUT,
11017 ResetLatch(&XLogCtl->recoveryWakeupLatch);
11022 elog(ERROR, "unexpected WAL source %d", currentSource);
11026 * This possibly-long loop needs to handle interrupts of startup
11029 HandleStartupProcInterrupts();
11030 } while (StandbyMode);
11036 * Determine what log level should be used to report a corrupt WAL record
11037 * in the current WAL page, previously read by XLogPageRead().
11039 * 'emode' is the error mode that would be used to report a file-not-found
11040 * or legitimate end-of-WAL situation. Generally, we use it as-is, but if
11041 * we're retrying the exact same record that we've tried previously, only
11042 * complain the first time to keep the noise down. However, we only do when
11043 * reading from pg_xlog, because we don't expect any invalid records in archive
11044 * or in records streamed from master. Files in the archive should be complete,
11045 * and we should never hit the end of WAL because we stop and wait for more WAL
11046 * to arrive before replaying it.
11048 * NOTE: This function remembers the RecPtr value it was last called with,
11049 * to suppress repeated messages about the same record. Only call this when
11050 * you are about to ereport(), or you might cause a later message to be
11051 * erroneously suppressed.
11054 emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
11056 static XLogRecPtr lastComplaint = 0;
11058 if (readSource == XLOG_FROM_PG_XLOG && emode == LOG)
11060 if (RecPtr == lastComplaint)
11063 lastComplaint = RecPtr;
11069 * Check to see whether the user-specified trigger file exists and whether a
11070 * promote request has arrived. If either condition holds, return true.
11073 CheckForStandbyTrigger(void)
11075 struct stat stat_buf;
11076 static bool triggered = false;
11081 if (IsPromoteTriggered())
11084 * In 9.1 and 9.2 the postmaster unlinked the promote file inside the
11085 * signal handler. It now leaves the file in place and lets the
11086 * Startup process do the unlink. This allows Startup to know whether
11087 * it should create a full checkpoint before starting up (fallback
11088 * mode). Fast promotion takes precedence.
11090 if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
11092 unlink(PROMOTE_SIGNAL_FILE);
11093 unlink(FALLBACK_PROMOTE_SIGNAL_FILE);
11094 fast_promote = true;
11096 else if (stat(FALLBACK_PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
11098 unlink(FALLBACK_PROMOTE_SIGNAL_FILE);
11099 fast_promote = false;
11102 ereport(LOG, (errmsg("received promote request")));
11104 ResetPromoteTriggered();
11109 if (TriggerFile == NULL)
11112 if (stat(TriggerFile, &stat_buf) == 0)
11115 (errmsg("trigger file found: %s", TriggerFile)));
11116 unlink(TriggerFile);
11118 fast_promote = true;
11125 * Check to see if a promote request has arrived. Should be
11126 * called by postmaster after receiving SIGUSR1.
11129 CheckPromoteSignal(void)
11131 struct stat stat_buf;
11133 if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0 ||
11134 stat(FALLBACK_PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
11141 * Wake up startup process to replay newly arrived WAL, or to notice that
11142 * failover has been requested.
11145 WakeupRecovery(void)
11147 SetLatch(&XLogCtl->recoveryWakeupLatch);
11151 * Update the WalWriterSleeping flag.
11154 SetWalWriterSleeping(bool sleeping)
11156 /* use volatile pointer to prevent code rearrangement */
11157 volatile XLogCtlData *xlogctl = XLogCtl;
11159 SpinLockAcquire(&xlogctl->info_lck);
11160 xlogctl->WalWriterSleeping = sleeping;
11161 SpinLockRelease(&xlogctl->info_lck);