Improve comment about GetWALAvailability's WALAVAIL_REMOVED code.
[pgsql.git] / src / backend / access / transam / xlog.c
blobcc0d9a05d9fd886029fd3e8223761418bb91a680
1 /*-------------------------------------------------------------------------
3 * xlog.c
4 * PostgreSQL write-ahead log manager
6 * The Write-Ahead Log (WAL) functionality is split into several source
7 * files, in addition to this one:
9 * xloginsert.c - Functions for constructing WAL records
10 * xlogrecovery.c - WAL recovery and standby code
11 * xlogreader.c - Facility for reading WAL files and parsing WAL records
12 * xlogutils.c - Helper functions for WAL redo routines
14 * This file contains functions for coordinating database startup and
15 * checkpointing, and managing the write-ahead log buffers when the
16 * system is running.
18 * StartupXLOG() is the main entry point of the startup process. It
19 * coordinates database startup, performing WAL recovery, and the
20 * transition from WAL recovery into normal operations.
22 * XLogInsertRecord() inserts a WAL record into the WAL buffers. Most
23 * callers should not call this directly, but use the functions in
24 * xloginsert.c to construct the WAL record. XLogFlush() can be used
25 * to force the WAL to disk.
27 * In addition to those, there are many other functions for interrogating
28 * the current system state, and for starting/stopping backups.
31 * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
32 * Portions Copyright (c) 1994, Regents of the University of California
34 * src/backend/access/transam/xlog.c
36 *-------------------------------------------------------------------------
39 #include "postgres.h"
41 #include <ctype.h>
42 #include <math.h>
43 #include <time.h>
44 #include <fcntl.h>
45 #include <sys/stat.h>
46 #include <sys/time.h>
47 #include <unistd.h>
49 #include "access/clog.h"
50 #include "access/commit_ts.h"
51 #include "access/heaptoast.h"
52 #include "access/multixact.h"
53 #include "access/rewriteheap.h"
54 #include "access/subtrans.h"
55 #include "access/timeline.h"
56 #include "access/transam.h"
57 #include "access/twophase.h"
58 #include "access/xact.h"
59 #include "access/xlog_internal.h"
60 #include "access/xlogarchive.h"
61 #include "access/xloginsert.h"
62 #include "access/xlogprefetcher.h"
63 #include "access/xlogreader.h"
64 #include "access/xlogrecovery.h"
65 #include "access/xlogutils.h"
66 #include "backup/basebackup.h"
67 #include "catalog/catversion.h"
68 #include "catalog/pg_control.h"
69 #include "catalog/pg_database.h"
70 #include "common/controldata_utils.h"
71 #include "common/file_utils.h"
72 #include "executor/instrument.h"
73 #include "miscadmin.h"
74 #include "pg_trace.h"
75 #include "pgstat.h"
76 #include "port/atomics.h"
77 #include "port/pg_iovec.h"
78 #include "postmaster/bgwriter.h"
79 #include "postmaster/startup.h"
80 #include "postmaster/walwriter.h"
81 #include "replication/logical.h"
82 #include "replication/origin.h"
83 #include "replication/slot.h"
84 #include "replication/snapbuild.h"
85 #include "replication/walreceiver.h"
86 #include "replication/walsender.h"
87 #include "storage/bufmgr.h"
88 #include "storage/fd.h"
89 #include "storage/ipc.h"
90 #include "storage/large_object.h"
91 #include "storage/latch.h"
92 #include "storage/pmsignal.h"
93 #include "storage/predicate.h"
94 #include "storage/proc.h"
95 #include "storage/procarray.h"
96 #include "storage/reinit.h"
97 #include "storage/smgr.h"
98 #include "storage/spin.h"
99 #include "storage/sync.h"
100 #include "utils/guc_hooks.h"
101 #include "utils/guc_tables.h"
102 #include "utils/memutils.h"
103 #include "utils/ps_status.h"
104 #include "utils/relmapper.h"
105 #include "utils/pg_rusage.h"
106 #include "utils/snapmgr.h"
107 #include "utils/timeout.h"
108 #include "utils/timestamp.h"
109 #include "utils/varlena.h"
111 extern uint32 bootstrap_data_checksum_version;
113 /* timeline ID to be used when bootstrapping */
114 #define BootstrapTimeLineID 1
116 /* User-settable parameters */
117 int max_wal_size_mb = 1024; /* 1 GB */
118 int min_wal_size_mb = 80; /* 80 MB */
119 int wal_keep_size_mb = 0;
120 int XLOGbuffers = -1;
121 int XLogArchiveTimeout = 0;
122 int XLogArchiveMode = ARCHIVE_MODE_OFF;
123 char *XLogArchiveCommand = NULL;
124 bool EnableHotStandby = false;
125 bool fullPageWrites = true;
126 bool wal_log_hints = false;
127 int wal_compression = WAL_COMPRESSION_NONE;
128 char *wal_consistency_checking_string = NULL;
129 bool *wal_consistency_checking = NULL;
130 bool wal_init_zero = true;
131 bool wal_recycle = true;
132 bool log_checkpoints = true;
133 int sync_method = DEFAULT_SYNC_METHOD;
134 int wal_level = WAL_LEVEL_REPLICA;
135 int CommitDelay = 0; /* precommit delay in microseconds */
136 int CommitSiblings = 5; /* # concurrent xacts needed to sleep */
137 int wal_retrieve_retry_interval = 5000;
138 int max_slot_wal_keep_size_mb = -1;
139 int wal_decode_buffer_size = 512 * 1024;
140 bool track_wal_io_timing = false;
142 #ifdef WAL_DEBUG
143 bool XLOG_DEBUG = false;
144 #endif
146 int wal_segment_size = DEFAULT_XLOG_SEG_SIZE;
149 * Number of WAL insertion locks to use. A higher value allows more insertions
150 * to happen concurrently, but adds some CPU overhead to flushing the WAL,
151 * which needs to iterate all the locks.
153 #define NUM_XLOGINSERT_LOCKS 8
156 * Max distance from last checkpoint, before triggering a new xlog-based
157 * checkpoint.
159 int CheckPointSegments;
161 /* Estimated distance between checkpoints, in bytes */
162 static double CheckPointDistanceEstimate = 0;
163 static double PrevCheckPointDistance = 0;
166 * Track whether there were any deferred checks for custom resource managers
167 * specified in wal_consistency_checking.
169 static bool check_wal_consistency_checking_deferred = false;
172 * GUC support
174 const struct config_enum_entry sync_method_options[] = {
175 {"fsync", SYNC_METHOD_FSYNC, false},
176 #ifdef HAVE_FSYNC_WRITETHROUGH
177 {"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
178 #endif
179 {"fdatasync", SYNC_METHOD_FDATASYNC, false},
180 #ifdef O_SYNC
181 {"open_sync", SYNC_METHOD_OPEN, false},
182 #endif
183 #ifdef O_DSYNC
184 {"open_datasync", SYNC_METHOD_OPEN_DSYNC, false},
185 #endif
186 {NULL, 0, false}
191 * Although only "on", "off", and "always" are documented,
192 * we accept all the likely variants of "on" and "off".
194 const struct config_enum_entry archive_mode_options[] = {
195 {"always", ARCHIVE_MODE_ALWAYS, false},
196 {"on", ARCHIVE_MODE_ON, false},
197 {"off", ARCHIVE_MODE_OFF, false},
198 {"true", ARCHIVE_MODE_ON, true},
199 {"false", ARCHIVE_MODE_OFF, true},
200 {"yes", ARCHIVE_MODE_ON, true},
201 {"no", ARCHIVE_MODE_OFF, true},
202 {"1", ARCHIVE_MODE_ON, true},
203 {"0", ARCHIVE_MODE_OFF, true},
204 {NULL, 0, false}
208 * Statistics for current checkpoint are collected in this global struct.
209 * Because only the checkpointer or a stand-alone backend can perform
210 * checkpoints, this will be unused in normal backends.
212 CheckpointStatsData CheckpointStats;
215 * During recovery, lastFullPageWrites keeps track of full_page_writes that
216 * the replayed WAL records indicate. It's initialized with full_page_writes
217 * that the recovery starting checkpoint record indicates, and then updated
218 * each time XLOG_FPW_CHANGE record is replayed.
220 static bool lastFullPageWrites;
223 * Local copy of the state tracked by SharedRecoveryState in shared memory,
224 * It is false if SharedRecoveryState is RECOVERY_STATE_DONE. True actually
225 * means "not known, need to check the shared state".
227 static bool LocalRecoveryInProgress = true;
230 * Local state for XLogInsertAllowed():
231 * 1: unconditionally allowed to insert XLOG
232 * 0: unconditionally not allowed to insert XLOG
233 * -1: must check RecoveryInProgress(); disallow until it is false
234 * Most processes start with -1 and transition to 1 after seeing that recovery
235 * is not in progress. But we can also force the value for special cases.
236 * The coding in XLogInsertAllowed() depends on the first two of these states
237 * being numerically the same as bool true and false.
239 static int LocalXLogInsertAllowed = -1;
242 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
243 * current backend. It is updated for all inserts. XactLastRecEnd points to
244 * end+1 of the last record, and is reset when we end a top-level transaction,
245 * or start a new one; so it can be used to tell if the current transaction has
246 * created any XLOG records.
248 * While in parallel mode, this may not be fully up to date. When committing,
249 * a transaction can assume this covers all xlog records written either by the
250 * user backend or by any parallel worker which was present at any point during
251 * the transaction. But when aborting, or when still in parallel mode, other
252 * parallel backends may have written WAL records at later LSNs than the value
253 * stored here. The parallel leader advances its own copy, when necessary,
254 * in WaitForParallelWorkersToFinish.
256 XLogRecPtr ProcLastRecPtr = InvalidXLogRecPtr;
257 XLogRecPtr XactLastRecEnd = InvalidXLogRecPtr;
258 XLogRecPtr XactLastCommitEnd = InvalidXLogRecPtr;
261 * RedoRecPtr is this backend's local copy of the REDO record pointer
262 * (which is almost but not quite the same as a pointer to the most recent
263 * CHECKPOINT record). We update this from the shared-memory copy,
264 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
265 * hold an insertion lock). See XLogInsertRecord for details. We are also
266 * allowed to update from XLogCtl->RedoRecPtr if we hold the info_lck;
267 * see GetRedoRecPtr.
269 * NB: Code that uses this variable must be prepared not only for the
270 * possibility that it may be arbitrarily out of date, but also for the
271 * possibility that it might be set to InvalidXLogRecPtr. We used to
272 * initialize it as a side effect of the first call to RecoveryInProgress(),
273 * which meant that most code that might use it could assume that it had a
274 * real if perhaps stale value. That's no longer the case.
276 static XLogRecPtr RedoRecPtr;
279 * doPageWrites is this backend's local copy of (fullPageWrites ||
280 * runningBackups > 0). It is used together with RedoRecPtr to decide whether
281 * a full-page image of a page need to be taken.
283 * NB: Initially this is false, and there's no guarantee that it will be
284 * initialized to any other value before it is first used. Any code that
285 * makes use of it must recheck the value after obtaining a WALInsertLock,
286 * and respond appropriately if it turns out that the previous value wasn't
287 * accurate.
289 static bool doPageWrites;
291 /*----------
292 * Shared-memory data structures for XLOG control
294 * LogwrtRqst indicates a byte position that we need to write and/or fsync
295 * the log up to (all records before that point must be written or fsynced).
296 * LogwrtResult indicates the byte positions we have already written/fsynced.
297 * These structs are identical but are declared separately to indicate their
298 * slightly different functions.
300 * To read XLogCtl->LogwrtResult, you must hold either info_lck or
301 * WALWriteLock. To update it, you need to hold both locks. The point of
302 * this arrangement is that the value can be examined by code that already
303 * holds WALWriteLock without needing to grab info_lck as well. In addition
304 * to the shared variable, each backend has a private copy of LogwrtResult,
305 * which is updated when convenient.
307 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
308 * (protected by info_lck), but we don't need to cache any copies of it.
310 * info_lck is only held long enough to read/update the protected variables,
311 * so it's a plain spinlock. The other locks are held longer (potentially
312 * over I/O operations), so we use LWLocks for them. These locks are:
314 * WALBufMappingLock: must be held to replace a page in the WAL buffer cache.
315 * It is only held while initializing and changing the mapping. If the
316 * contents of the buffer being replaced haven't been written yet, the mapping
317 * lock is released while the write is done, and reacquired afterwards.
319 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
320 * XLogFlush).
322 * ControlFileLock: must be held to read/update control file or create
323 * new log file.
325 *----------
328 typedef struct XLogwrtRqst
330 XLogRecPtr Write; /* last byte + 1 to write out */
331 XLogRecPtr Flush; /* last byte + 1 to flush */
332 } XLogwrtRqst;
334 typedef struct XLogwrtResult
336 XLogRecPtr Write; /* last byte + 1 written out */
337 XLogRecPtr Flush; /* last byte + 1 flushed */
338 } XLogwrtResult;
341 * Inserting to WAL is protected by a small fixed number of WAL insertion
342 * locks. To insert to the WAL, you must hold one of the locks - it doesn't
343 * matter which one. To lock out other concurrent insertions, you must hold
344 * of them. Each WAL insertion lock consists of a lightweight lock, plus an
345 * indicator of how far the insertion has progressed (insertingAt).
347 * The insertingAt values are read when a process wants to flush WAL from
348 * the in-memory buffers to disk, to check that all the insertions to the
349 * region the process is about to write out have finished. You could simply
350 * wait for all currently in-progress insertions to finish, but the
351 * insertingAt indicator allows you to ignore insertions to later in the WAL,
352 * so that you only wait for the insertions that are modifying the buffers
353 * you're about to write out.
355 * This isn't just an optimization. If all the WAL buffers are dirty, an
356 * inserter that's holding a WAL insert lock might need to evict an old WAL
357 * buffer, which requires flushing the WAL. If it's possible for an inserter
358 * to block on another inserter unnecessarily, deadlock can arise when two
359 * inserters holding a WAL insert lock wait for each other to finish their
360 * insertion.
362 * Small WAL records that don't cross a page boundary never update the value,
363 * the WAL record is just copied to the page and the lock is released. But
364 * to avoid the deadlock-scenario explained above, the indicator is always
365 * updated before sleeping while holding an insertion lock.
367 * lastImportantAt contains the LSN of the last important WAL record inserted
368 * using a given lock. This value is used to detect if there has been
369 * important WAL activity since the last time some action, like a checkpoint,
370 * was performed - allowing to not repeat the action if not. The LSN is
371 * updated for all insertions, unless the XLOG_MARK_UNIMPORTANT flag was
372 * set. lastImportantAt is never cleared, only overwritten by the LSN of newer
373 * records. Tracking the WAL activity directly in WALInsertLock has the
374 * advantage of not needing any additional locks to update the value.
376 typedef struct
378 LWLock lock;
379 XLogRecPtr insertingAt;
380 XLogRecPtr lastImportantAt;
381 } WALInsertLock;
384 * All the WAL insertion locks are allocated as an array in shared memory. We
385 * force the array stride to be a power of 2, which saves a few cycles in
386 * indexing, but more importantly also ensures that individual slots don't
387 * cross cache line boundaries. (Of course, we have to also ensure that the
388 * array start address is suitably aligned.)
390 typedef union WALInsertLockPadded
392 WALInsertLock l;
393 char pad[PG_CACHE_LINE_SIZE];
394 } WALInsertLockPadded;
397 * Session status of running backup, used for sanity checks in SQL-callable
398 * functions to start and stop backups.
400 static SessionBackupState sessionBackupState = SESSION_BACKUP_NONE;
403 * Shared state data for WAL insertion.
405 typedef struct XLogCtlInsert
407 slock_t insertpos_lck; /* protects CurrBytePos and PrevBytePos */
410 * CurrBytePos is the end of reserved WAL. The next record will be
411 * inserted at that position. PrevBytePos is the start position of the
412 * previously inserted (or rather, reserved) record - it is copied to the
413 * prev-link of the next record. These are stored as "usable byte
414 * positions" rather than XLogRecPtrs (see XLogBytePosToRecPtr()).
416 uint64 CurrBytePos;
417 uint64 PrevBytePos;
420 * Make sure the above heavily-contended spinlock and byte positions are
421 * on their own cache line. In particular, the RedoRecPtr and full page
422 * write variables below should be on a different cache line. They are
423 * read on every WAL insertion, but updated rarely, and we don't want
424 * those reads to steal the cache line containing Curr/PrevBytePos.
426 char pad[PG_CACHE_LINE_SIZE];
429 * fullPageWrites is the authoritative value used by all backends to
430 * determine whether to write full-page image to WAL. This shared value,
431 * instead of the process-local fullPageWrites, is required because, when
432 * full_page_writes is changed by SIGHUP, we must WAL-log it before it
433 * actually affects WAL-logging by backends. Checkpointer sets at startup
434 * or after SIGHUP.
436 * To read these fields, you must hold an insertion lock. To modify them,
437 * you must hold ALL the locks.
439 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
440 bool fullPageWrites;
443 * runningBackups is a counter indicating the number of backups currently
444 * in progress. lastBackupStart is the latest checkpoint redo location
445 * used as a starting point for an online backup.
447 int runningBackups;
448 XLogRecPtr lastBackupStart;
451 * WAL insertion locks.
453 WALInsertLockPadded *WALInsertLocks;
454 } XLogCtlInsert;
457 * Total shared-memory state for XLOG.
459 typedef struct XLogCtlData
461 XLogCtlInsert Insert;
463 /* Protected by info_lck: */
464 XLogwrtRqst LogwrtRqst;
465 XLogRecPtr RedoRecPtr; /* a recent copy of Insert->RedoRecPtr */
466 FullTransactionId ckptFullXid; /* nextXid of latest checkpoint */
467 XLogRecPtr asyncXactLSN; /* LSN of newest async commit/abort */
468 XLogRecPtr replicationSlotMinLSN; /* oldest LSN needed by any slot */
470 XLogSegNo lastRemovedSegNo; /* latest removed/recycled XLOG segment */
472 /* Fake LSN counter, for unlogged relations. Protected by ulsn_lck. */
473 XLogRecPtr unloggedLSN;
474 slock_t ulsn_lck;
476 /* Time and LSN of last xlog segment switch. Protected by WALWriteLock. */
477 pg_time_t lastSegSwitchTime;
478 XLogRecPtr lastSegSwitchLSN;
481 * Protected by info_lck and WALWriteLock (you must hold either lock to
482 * read it, but both to update)
484 XLogwrtResult LogwrtResult;
487 * Latest initialized page in the cache (last byte position + 1).
489 * To change the identity of a buffer (and InitializedUpTo), you need to
490 * hold WALBufMappingLock. To change the identity of a buffer that's
491 * still dirty, the old page needs to be written out first, and for that
492 * you need WALWriteLock, and you need to ensure that there are no
493 * in-progress insertions to the page by calling
494 * WaitXLogInsertionsToFinish().
496 XLogRecPtr InitializedUpTo;
499 * These values do not change after startup, although the pointed-to pages
500 * and xlblocks values certainly do. xlblocks values are protected by
501 * WALBufMappingLock.
503 char *pages; /* buffers for unwritten XLOG pages */
504 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
505 int XLogCacheBlck; /* highest allocated xlog buffer index */
508 * InsertTimeLineID is the timeline into which new WAL is being inserted
509 * and flushed. It is zero during recovery, and does not change once set.
511 * If we create 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 InsertTimeLineID.
515 TimeLineID InsertTimeLineID;
516 TimeLineID PrevTimeLineID;
519 * SharedRecoveryState indicates if we're still in crash or archive
520 * recovery. Protected by info_lck.
522 RecoveryState SharedRecoveryState;
525 * InstallXLogFileSegmentActive indicates whether the checkpointer should
526 * arrange for future segments by recycling and/or PreallocXlogFiles().
527 * Protected by ControlFileLock. Only the startup process changes it. If
528 * true, anyone can use InstallXLogFileSegment(). If false, the startup
529 * process owns the exclusive right to install segments, by reading from
530 * the archive and possibly replacing existing files.
532 bool InstallXLogFileSegmentActive;
535 * WalWriterSleeping indicates whether the WAL writer is currently in
536 * low-power mode (and hence should be nudged if an async commit occurs).
537 * Protected by info_lck.
539 bool WalWriterSleeping;
542 * During recovery, we keep a copy of the latest checkpoint record here.
543 * lastCheckPointRecPtr points to start of checkpoint record and
544 * lastCheckPointEndPtr points to end+1 of checkpoint record. Used by the
545 * checkpointer when it wants to create a restartpoint.
547 * Protected by info_lck.
549 XLogRecPtr lastCheckPointRecPtr;
550 XLogRecPtr lastCheckPointEndPtr;
551 CheckPoint lastCheckPoint;
554 * lastFpwDisableRecPtr points to the start of the last replayed
555 * XLOG_FPW_CHANGE record that instructs full_page_writes is disabled.
557 XLogRecPtr lastFpwDisableRecPtr;
559 slock_t info_lck; /* locks shared variables shown above */
560 } XLogCtlData;
562 static XLogCtlData *XLogCtl = NULL;
564 /* a private copy of XLogCtl->Insert.WALInsertLocks, for convenience */
565 static WALInsertLockPadded *WALInsertLocks = NULL;
568 * We maintain an image of pg_control in shared memory.
570 static ControlFileData *ControlFile = NULL;
573 * Calculate the amount of space left on the page after 'endptr'. Beware
574 * multiple evaluation!
576 #define INSERT_FREESPACE(endptr) \
577 (((endptr) % XLOG_BLCKSZ == 0) ? 0 : (XLOG_BLCKSZ - (endptr) % XLOG_BLCKSZ))
579 /* Macro to advance to next buffer index. */
580 #define NextBufIdx(idx) \
581 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
584 * XLogRecPtrToBufIdx returns the index of the WAL buffer that holds, or
585 * would hold if it was in cache, the page containing 'recptr'.
587 #define XLogRecPtrToBufIdx(recptr) \
588 (((recptr) / XLOG_BLCKSZ) % (XLogCtl->XLogCacheBlck + 1))
591 * These are the number of bytes in a WAL page usable for WAL data.
593 #define UsableBytesInPage (XLOG_BLCKSZ - SizeOfXLogShortPHD)
596 * Convert values of GUCs measured in megabytes to equiv. segment count.
597 * Rounds down.
599 #define ConvertToXSegs(x, segsize) XLogMBVarToSegs((x), (segsize))
601 /* The number of bytes in a WAL segment usable for WAL data. */
602 static int UsableBytesInSegment;
605 * Private, possibly out-of-date copy of shared LogwrtResult.
606 * See discussion above.
608 static XLogwrtResult LogwrtResult = {0, 0};
611 * openLogFile is -1 or a kernel FD for an open log file segment.
612 * openLogSegNo identifies the segment, and openLogTLI the corresponding TLI.
613 * These variables are only used to write the XLOG, and so will normally refer
614 * to the active segment.
616 * Note: call Reserve/ReleaseExternalFD to track consumption of this FD.
618 static int openLogFile = -1;
619 static XLogSegNo openLogSegNo = 0;
620 static TimeLineID openLogTLI = 0;
623 * Local copies of equivalent fields in the control file. When running
624 * crash recovery, LocalMinRecoveryPoint is set to InvalidXLogRecPtr as we
625 * expect to replay all the WAL available, and updateMinRecoveryPoint is
626 * switched to false to prevent any updates while replaying records.
627 * Those values are kept consistent as long as crash recovery runs.
629 static XLogRecPtr LocalMinRecoveryPoint;
630 static TimeLineID LocalMinRecoveryPointTLI;
631 static bool updateMinRecoveryPoint = true;
633 /* For WALInsertLockAcquire/Release functions */
634 static int MyLockNo = 0;
635 static bool holdingAllLocks = false;
637 #ifdef WAL_DEBUG
638 static MemoryContext walDebugCxt = NULL;
639 #endif
641 static void CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI,
642 XLogRecPtr EndOfLog,
643 TimeLineID newTLI);
644 static void CheckRequiredParameterValues(void);
645 static void XLogReportParameters(void);
646 static int LocalSetXLogInsertAllowed(void);
647 static void CreateEndOfRecoveryRecord(void);
648 static XLogRecPtr CreateOverwriteContrecordRecord(XLogRecPtr aborted_lsn,
649 XLogRecPtr pagePtr,
650 TimeLineID newTLI);
651 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
652 static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo);
653 static XLogRecPtr XLogGetReplicationSlotMinimumLSN(void);
655 static void AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli,
656 bool opportunistic);
657 static void XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible);
658 static bool InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
659 bool find_free, XLogSegNo max_segno,
660 TimeLineID tli);
661 static void XLogFileClose(void);
662 static void PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli);
663 static void RemoveTempXlogFiles(void);
664 static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr,
665 XLogRecPtr endptr, TimeLineID insertTLI);
666 static void RemoveXlogFile(const struct dirent *segment_de,
667 XLogSegNo recycleSegNo, XLogSegNo *endlogSegNo,
668 TimeLineID insertTLI);
669 static void UpdateLastRemovedPtr(char *filename);
670 static void ValidateXLOGDirectoryStructure(void);
671 static void CleanupBackupHistory(void);
672 static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
673 static bool PerformRecoveryXLogAction(void);
674 static void InitControlFile(uint64 sysidentifier);
675 static void WriteControlFile(void);
676 static void ReadControlFile(void);
677 static void UpdateControlFile(void);
678 static char *str_time(pg_time_t tnow);
680 static int get_sync_bit(int method);
682 static void CopyXLogRecordToWAL(int write_len, bool isLogSwitch,
683 XLogRecData *rdata,
684 XLogRecPtr StartPos, XLogRecPtr EndPos,
685 TimeLineID tli);
686 static void ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos,
687 XLogRecPtr *EndPos, XLogRecPtr *PrevPtr);
688 static bool ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos,
689 XLogRecPtr *PrevPtr);
690 static XLogRecPtr WaitXLogInsertionsToFinish(XLogRecPtr upto);
691 static char *GetXLogBuffer(XLogRecPtr ptr, TimeLineID tli);
692 static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos);
693 static XLogRecPtr XLogBytePosToEndRecPtr(uint64 bytepos);
694 static uint64 XLogRecPtrToBytePos(XLogRecPtr ptr);
695 static void GetOldestRestartPointFileName(char *fname);
697 static void WALInsertLockAcquire(void);
698 static void WALInsertLockAcquireExclusive(void);
699 static void WALInsertLockRelease(void);
700 static void WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt);
703 * Insert an XLOG record represented by an already-constructed chain of data
704 * chunks. This is a low-level routine; to construct the WAL record header
705 * and data, use the higher-level routines in xloginsert.c.
707 * If 'fpw_lsn' is valid, it is the oldest LSN among the pages that this
708 * WAL record applies to, that were not included in the record as full page
709 * images. If fpw_lsn <= RedoRecPtr, the function does not perform the
710 * insertion and returns InvalidXLogRecPtr. The caller can then recalculate
711 * which pages need a full-page image, and retry. If fpw_lsn is invalid, the
712 * record is always inserted.
714 * 'flags' gives more in-depth control on the record being inserted. See
715 * XLogSetRecordFlags() for details.
717 * 'topxid_included' tells whether the top-transaction id is logged along with
718 * current subtransaction. See XLogRecordAssemble().
720 * The first XLogRecData in the chain must be for the record header, and its
721 * data must be MAXALIGNed. XLogInsertRecord fills in the xl_prev and
722 * xl_crc fields in the header, the rest of the header must already be filled
723 * by the caller.
725 * Returns XLOG pointer to end of record (beginning of next record).
726 * This can be used as LSN for data pages affected by the logged action.
727 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
728 * before the data page can be written out. This implements the basic
729 * WAL rule "write the log before the data".)
731 XLogRecPtr
732 XLogInsertRecord(XLogRecData *rdata,
733 XLogRecPtr fpw_lsn,
734 uint8 flags,
735 int num_fpi,
736 bool topxid_included)
738 XLogCtlInsert *Insert = &XLogCtl->Insert;
739 pg_crc32c rdata_crc;
740 bool inserted;
741 XLogRecord *rechdr = (XLogRecord *) rdata->data;
742 uint8 info = rechdr->xl_info & ~XLR_INFO_MASK;
743 bool isLogSwitch = (rechdr->xl_rmid == RM_XLOG_ID &&
744 info == XLOG_SWITCH);
745 XLogRecPtr StartPos;
746 XLogRecPtr EndPos;
747 bool prevDoPageWrites = doPageWrites;
748 TimeLineID insertTLI;
750 /* we assume that all of the record header is in the first chunk */
751 Assert(rdata->len >= SizeOfXLogRecord);
753 /* cross-check on whether we should be here or not */
754 if (!XLogInsertAllowed())
755 elog(ERROR, "cannot make new WAL entries during recovery");
758 * Given that we're not in recovery, InsertTimeLineID is set and can't
759 * change, so we can read it without a lock.
761 insertTLI = XLogCtl->InsertTimeLineID;
763 /*----------
765 * We have now done all the preparatory work we can without holding a
766 * lock or modifying shared state. From here on, inserting the new WAL
767 * record to the shared WAL buffer cache is a two-step process:
769 * 1. Reserve the right amount of space from the WAL. The current head of
770 * reserved space is kept in Insert->CurrBytePos, and is protected by
771 * insertpos_lck.
773 * 2. Copy the record to the reserved WAL space. This involves finding the
774 * correct WAL buffer containing the reserved space, and copying the
775 * record in place. This can be done concurrently in multiple processes.
777 * To keep track of which insertions are still in-progress, each concurrent
778 * inserter acquires an insertion lock. In addition to just indicating that
779 * an insertion is in progress, the lock tells others how far the inserter
780 * has progressed. There is a small fixed number of insertion locks,
781 * determined by NUM_XLOGINSERT_LOCKS. When an inserter crosses a page
782 * boundary, it updates the value stored in the lock to the how far it has
783 * inserted, to allow the previous buffer to be flushed.
785 * Holding onto an insertion lock also protects RedoRecPtr and
786 * fullPageWrites from changing until the insertion is finished.
788 * Step 2 can usually be done completely in parallel. If the required WAL
789 * page is not initialized yet, you have to grab WALBufMappingLock to
790 * initialize it, but the WAL writer tries to do that ahead of insertions
791 * to avoid that from happening in the critical path.
793 *----------
795 START_CRIT_SECTION();
796 if (isLogSwitch)
797 WALInsertLockAcquireExclusive();
798 else
799 WALInsertLockAcquire();
802 * Check to see if my copy of RedoRecPtr is out of date. If so, may have
803 * to go back and have the caller recompute everything. This can only
804 * happen just after a checkpoint, so it's better to be slow in this case
805 * and fast otherwise.
807 * Also check to see if fullPageWrites was just turned on or there's a
808 * running backup (which forces full-page writes); if we weren't already
809 * doing full-page writes then go back and recompute.
811 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
812 * affect the contents of the XLOG record, so we'll update our local copy
813 * but not force a recomputation. (If doPageWrites was just turned off,
814 * we could recompute the record without full pages, but we choose not to
815 * bother.)
817 if (RedoRecPtr != Insert->RedoRecPtr)
819 Assert(RedoRecPtr < Insert->RedoRecPtr);
820 RedoRecPtr = Insert->RedoRecPtr;
822 doPageWrites = (Insert->fullPageWrites || Insert->runningBackups > 0);
824 if (doPageWrites &&
825 (!prevDoPageWrites ||
826 (fpw_lsn != InvalidXLogRecPtr && fpw_lsn <= RedoRecPtr)))
829 * Oops, some buffer now needs to be backed up that the caller didn't
830 * back up. Start over.
832 WALInsertLockRelease();
833 END_CRIT_SECTION();
834 return InvalidXLogRecPtr;
838 * Reserve space for the record in the WAL. This also sets the xl_prev
839 * pointer.
841 if (isLogSwitch)
842 inserted = ReserveXLogSwitch(&StartPos, &EndPos, &rechdr->xl_prev);
843 else
845 ReserveXLogInsertLocation(rechdr->xl_tot_len, &StartPos, &EndPos,
846 &rechdr->xl_prev);
847 inserted = true;
850 if (inserted)
853 * Now that xl_prev has been filled in, calculate CRC of the record
854 * header.
856 rdata_crc = rechdr->xl_crc;
857 COMP_CRC32C(rdata_crc, rechdr, offsetof(XLogRecord, xl_crc));
858 FIN_CRC32C(rdata_crc);
859 rechdr->xl_crc = rdata_crc;
862 * All the record data, including the header, is now ready to be
863 * inserted. Copy the record in the space reserved.
865 CopyXLogRecordToWAL(rechdr->xl_tot_len, isLogSwitch, rdata,
866 StartPos, EndPos, insertTLI);
869 * Unless record is flagged as not important, update LSN of last
870 * important record in the current slot. When holding all locks, just
871 * update the first one.
873 if ((flags & XLOG_MARK_UNIMPORTANT) == 0)
875 int lockno = holdingAllLocks ? 0 : MyLockNo;
877 WALInsertLocks[lockno].l.lastImportantAt = StartPos;
880 else
883 * This was an xlog-switch record, but the current insert location was
884 * already exactly at the beginning of a segment, so there was no need
885 * to do anything.
890 * Done! Let others know that we're finished.
892 WALInsertLockRelease();
894 END_CRIT_SECTION();
896 MarkCurrentTransactionIdLoggedIfAny();
899 * Mark top transaction id is logged (if needed) so that we should not try
900 * to log it again with the next WAL record in the current subtransaction.
902 if (topxid_included)
903 MarkSubxactTopXidLogged();
906 * Update shared LogwrtRqst.Write, if we crossed page boundary.
908 if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
910 SpinLockAcquire(&XLogCtl->info_lck);
911 /* advance global request to include new block(s) */
912 if (XLogCtl->LogwrtRqst.Write < EndPos)
913 XLogCtl->LogwrtRqst.Write = EndPos;
914 /* update local result copy while I have the chance */
915 LogwrtResult = XLogCtl->LogwrtResult;
916 SpinLockRelease(&XLogCtl->info_lck);
920 * If this was an XLOG_SWITCH record, flush the record and the empty
921 * padding space that fills the rest of the segment, and perform
922 * end-of-segment actions (eg, notifying archiver).
924 if (isLogSwitch)
926 TRACE_POSTGRESQL_WAL_SWITCH();
927 XLogFlush(EndPos);
930 * Even though we reserved the rest of the segment for us, which is
931 * reflected in EndPos, we return a pointer to just the end of the
932 * xlog-switch record.
934 if (inserted)
936 EndPos = StartPos + SizeOfXLogRecord;
937 if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
939 uint64 offset = XLogSegmentOffset(EndPos, wal_segment_size);
941 if (offset == EndPos % XLOG_BLCKSZ)
942 EndPos += SizeOfXLogLongPHD;
943 else
944 EndPos += SizeOfXLogShortPHD;
949 #ifdef WAL_DEBUG
950 if (XLOG_DEBUG)
952 static XLogReaderState *debug_reader = NULL;
953 XLogRecord *record;
954 DecodedXLogRecord *decoded;
955 StringInfoData buf;
956 StringInfoData recordBuf;
957 char *errormsg = NULL;
958 MemoryContext oldCxt;
960 oldCxt = MemoryContextSwitchTo(walDebugCxt);
962 initStringInfo(&buf);
963 appendStringInfo(&buf, "INSERT @ %X/%X: ", LSN_FORMAT_ARGS(EndPos));
966 * We have to piece together the WAL record data from the XLogRecData
967 * entries, so that we can pass it to the rm_desc function as one
968 * contiguous chunk.
970 initStringInfo(&recordBuf);
971 for (; rdata != NULL; rdata = rdata->next)
972 appendBinaryStringInfo(&recordBuf, rdata->data, rdata->len);
974 /* We also need temporary space to decode the record. */
975 record = (XLogRecord *) recordBuf.data;
976 decoded = (DecodedXLogRecord *)
977 palloc(DecodeXLogRecordRequiredSpace(record->xl_tot_len));
979 if (!debug_reader)
980 debug_reader = XLogReaderAllocate(wal_segment_size, NULL,
981 XL_ROUTINE(), NULL);
983 if (!debug_reader)
985 appendStringInfoString(&buf, "error decoding record: out of memory while allocating a WAL reading processor");
987 else if (!DecodeXLogRecord(debug_reader,
988 decoded,
989 record,
990 EndPos,
991 &errormsg))
993 appendStringInfo(&buf, "error decoding record: %s",
994 errormsg ? errormsg : "no error message");
996 else
998 appendStringInfoString(&buf, " - ");
1000 debug_reader->record = decoded;
1001 xlog_outdesc(&buf, debug_reader);
1002 debug_reader->record = NULL;
1004 elog(LOG, "%s", buf.data);
1006 pfree(decoded);
1007 pfree(buf.data);
1008 pfree(recordBuf.data);
1009 MemoryContextSwitchTo(oldCxt);
1011 #endif
1014 * Update our global variables
1016 ProcLastRecPtr = StartPos;
1017 XactLastRecEnd = EndPos;
1019 /* Report WAL traffic to the instrumentation. */
1020 if (inserted)
1022 pgWalUsage.wal_bytes += rechdr->xl_tot_len;
1023 pgWalUsage.wal_records++;
1024 pgWalUsage.wal_fpi += num_fpi;
1027 return EndPos;
1031 * Reserves the right amount of space for a record of given size from the WAL.
1032 * *StartPos is set to the beginning of the reserved section, *EndPos to
1033 * its end+1. *PrevPtr is set to the beginning of the previous record; it is
1034 * used to set the xl_prev of this record.
1036 * This is the performance critical part of XLogInsert that must be serialized
1037 * across backends. The rest can happen mostly in parallel. Try to keep this
1038 * section as short as possible, insertpos_lck can be heavily contended on a
1039 * busy system.
1041 * NB: The space calculation here must match the code in CopyXLogRecordToWAL,
1042 * where we actually copy the record to the reserved space.
1044 static void
1045 ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos, XLogRecPtr *EndPos,
1046 XLogRecPtr *PrevPtr)
1048 XLogCtlInsert *Insert = &XLogCtl->Insert;
1049 uint64 startbytepos;
1050 uint64 endbytepos;
1051 uint64 prevbytepos;
1053 size = MAXALIGN(size);
1055 /* All (non xlog-switch) records should contain data. */
1056 Assert(size > SizeOfXLogRecord);
1059 * The duration the spinlock needs to be held is minimized by minimizing
1060 * the calculations that have to be done while holding the lock. The
1061 * current tip of reserved WAL is kept in CurrBytePos, as a byte position
1062 * that only counts "usable" bytes in WAL, that is, it excludes all WAL
1063 * page headers. The mapping between "usable" byte positions and physical
1064 * positions (XLogRecPtrs) can be done outside the locked region, and
1065 * because the usable byte position doesn't include any headers, reserving
1066 * X bytes from WAL is almost as simple as "CurrBytePos += X".
1068 SpinLockAcquire(&Insert->insertpos_lck);
1070 startbytepos = Insert->CurrBytePos;
1071 endbytepos = startbytepos + size;
1072 prevbytepos = Insert->PrevBytePos;
1073 Insert->CurrBytePos = endbytepos;
1074 Insert->PrevBytePos = startbytepos;
1076 SpinLockRelease(&Insert->insertpos_lck);
1078 *StartPos = XLogBytePosToRecPtr(startbytepos);
1079 *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1080 *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1083 * Check that the conversions between "usable byte positions" and
1084 * XLogRecPtrs work consistently in both directions.
1086 Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1087 Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1088 Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1092 * Like ReserveXLogInsertLocation(), but for an xlog-switch record.
1094 * A log-switch record is handled slightly differently. The rest of the
1095 * segment will be reserved for this insertion, as indicated by the returned
1096 * *EndPos value. However, if we are already at the beginning of the current
1097 * segment, *StartPos and *EndPos are set to the current location without
1098 * reserving any space, and the function returns false.
1100 static bool
1101 ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
1103 XLogCtlInsert *Insert = &XLogCtl->Insert;
1104 uint64 startbytepos;
1105 uint64 endbytepos;
1106 uint64 prevbytepos;
1107 uint32 size = MAXALIGN(SizeOfXLogRecord);
1108 XLogRecPtr ptr;
1109 uint32 segleft;
1112 * These calculations are a bit heavy-weight to be done while holding a
1113 * spinlock, but since we're holding all the WAL insertion locks, there
1114 * are no other inserters competing for it. GetXLogInsertRecPtr() does
1115 * compete for it, but that's not called very frequently.
1117 SpinLockAcquire(&Insert->insertpos_lck);
1119 startbytepos = Insert->CurrBytePos;
1121 ptr = XLogBytePosToEndRecPtr(startbytepos);
1122 if (XLogSegmentOffset(ptr, wal_segment_size) == 0)
1124 SpinLockRelease(&Insert->insertpos_lck);
1125 *EndPos = *StartPos = ptr;
1126 return false;
1129 endbytepos = startbytepos + size;
1130 prevbytepos = Insert->PrevBytePos;
1132 *StartPos = XLogBytePosToRecPtr(startbytepos);
1133 *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1135 segleft = wal_segment_size - XLogSegmentOffset(*EndPos, wal_segment_size);
1136 if (segleft != wal_segment_size)
1138 /* consume the rest of the segment */
1139 *EndPos += segleft;
1140 endbytepos = XLogRecPtrToBytePos(*EndPos);
1142 Insert->CurrBytePos = endbytepos;
1143 Insert->PrevBytePos = startbytepos;
1145 SpinLockRelease(&Insert->insertpos_lck);
1147 *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1149 Assert(XLogSegmentOffset(*EndPos, wal_segment_size) == 0);
1150 Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1151 Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1152 Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1154 return true;
1158 * Subroutine of XLogInsertRecord. Copies a WAL record to an already-reserved
1159 * area in the WAL.
1161 static void
1162 CopyXLogRecordToWAL(int write_len, bool isLogSwitch, XLogRecData *rdata,
1163 XLogRecPtr StartPos, XLogRecPtr EndPos, TimeLineID tli)
1165 char *currpos;
1166 int freespace;
1167 int written;
1168 XLogRecPtr CurrPos;
1169 XLogPageHeader pagehdr;
1172 * Get a pointer to the right place in the right WAL buffer to start
1173 * inserting to.
1175 CurrPos = StartPos;
1176 currpos = GetXLogBuffer(CurrPos, tli);
1177 freespace = INSERT_FREESPACE(CurrPos);
1180 * there should be enough space for at least the first field (xl_tot_len)
1181 * on this page.
1183 Assert(freespace >= sizeof(uint32));
1185 /* Copy record data */
1186 written = 0;
1187 while (rdata != NULL)
1189 char *rdata_data = rdata->data;
1190 int rdata_len = rdata->len;
1192 while (rdata_len > freespace)
1195 * Write what fits on this page, and continue on the next page.
1197 Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || freespace == 0);
1198 memcpy(currpos, rdata_data, freespace);
1199 rdata_data += freespace;
1200 rdata_len -= freespace;
1201 written += freespace;
1202 CurrPos += freespace;
1205 * Get pointer to beginning of next page, and set the xlp_rem_len
1206 * in the page header. Set XLP_FIRST_IS_CONTRECORD.
1208 * It's safe to set the contrecord flag and xlp_rem_len without a
1209 * lock on the page. All the other flags were already set when the
1210 * page was initialized, in AdvanceXLInsertBuffer, and we're the
1211 * only backend that needs to set the contrecord flag.
1213 currpos = GetXLogBuffer(CurrPos, tli);
1214 pagehdr = (XLogPageHeader) currpos;
1215 pagehdr->xlp_rem_len = write_len - written;
1216 pagehdr->xlp_info |= XLP_FIRST_IS_CONTRECORD;
1218 /* skip over the page header */
1219 if (XLogSegmentOffset(CurrPos, wal_segment_size) == 0)
1221 CurrPos += SizeOfXLogLongPHD;
1222 currpos += SizeOfXLogLongPHD;
1224 else
1226 CurrPos += SizeOfXLogShortPHD;
1227 currpos += SizeOfXLogShortPHD;
1229 freespace = INSERT_FREESPACE(CurrPos);
1232 Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || rdata_len == 0);
1233 memcpy(currpos, rdata_data, rdata_len);
1234 currpos += rdata_len;
1235 CurrPos += rdata_len;
1236 freespace -= rdata_len;
1237 written += rdata_len;
1239 rdata = rdata->next;
1241 Assert(written == write_len);
1244 * If this was an xlog-switch, it's not enough to write the switch record,
1245 * we also have to consume all the remaining space in the WAL segment. We
1246 * have already reserved that space, but we need to actually fill it.
1248 if (isLogSwitch && XLogSegmentOffset(CurrPos, wal_segment_size) != 0)
1250 /* An xlog-switch record doesn't contain any data besides the header */
1251 Assert(write_len == SizeOfXLogRecord);
1253 /* Assert that we did reserve the right amount of space */
1254 Assert(XLogSegmentOffset(EndPos, wal_segment_size) == 0);
1256 /* Use up all the remaining space on the current page */
1257 CurrPos += freespace;
1260 * Cause all remaining pages in the segment to be flushed, leaving the
1261 * XLog position where it should be, at the start of the next segment.
1262 * We do this one page at a time, to make sure we don't deadlock
1263 * against ourselves if wal_buffers < wal_segment_size.
1265 while (CurrPos < EndPos)
1268 * The minimal action to flush the page would be to call
1269 * WALInsertLockUpdateInsertingAt(CurrPos) followed by
1270 * AdvanceXLInsertBuffer(...). The page would be left initialized
1271 * mostly to zeros, except for the page header (always the short
1272 * variant, as this is never a segment's first page).
1274 * The large vistas of zeros are good for compressibility, but the
1275 * headers interrupting them every XLOG_BLCKSZ (with values that
1276 * differ from page to page) are not. The effect varies with
1277 * compression tool, but bzip2 for instance compresses about an
1278 * order of magnitude worse if those headers are left in place.
1280 * Rather than complicating AdvanceXLInsertBuffer itself (which is
1281 * called in heavily-loaded circumstances as well as this lightly-
1282 * loaded one) with variant behavior, we just use GetXLogBuffer
1283 * (which itself calls the two methods we need) to get the pointer
1284 * and zero most of the page. Then we just zero the page header.
1286 currpos = GetXLogBuffer(CurrPos, tli);
1287 MemSet(currpos, 0, SizeOfXLogShortPHD);
1289 CurrPos += XLOG_BLCKSZ;
1292 else
1294 /* Align the end position, so that the next record starts aligned */
1295 CurrPos = MAXALIGN64(CurrPos);
1298 if (CurrPos != EndPos)
1299 elog(PANIC, "space reserved for WAL record does not match what was written");
1303 * Acquire a WAL insertion lock, for inserting to WAL.
1305 static void
1306 WALInsertLockAcquire(void)
1308 bool immed;
1311 * It doesn't matter which of the WAL insertion locks we acquire, so try
1312 * the one we used last time. If the system isn't particularly busy, it's
1313 * a good bet that it's still available, and it's good to have some
1314 * affinity to a particular lock so that you don't unnecessarily bounce
1315 * cache lines between processes when there's no contention.
1317 * If this is the first time through in this backend, pick a lock
1318 * (semi-)randomly. This allows the locks to be used evenly if you have a
1319 * lot of very short connections.
1321 static int lockToTry = -1;
1323 if (lockToTry == -1)
1324 lockToTry = MyProc->pgprocno % NUM_XLOGINSERT_LOCKS;
1325 MyLockNo = lockToTry;
1328 * The insertingAt value is initially set to 0, as we don't know our
1329 * insert location yet.
1331 immed = LWLockAcquire(&WALInsertLocks[MyLockNo].l.lock, LW_EXCLUSIVE);
1332 if (!immed)
1335 * If we couldn't get the lock immediately, try another lock next
1336 * time. On a system with more insertion locks than concurrent
1337 * inserters, this causes all the inserters to eventually migrate to a
1338 * lock that no-one else is using. On a system with more inserters
1339 * than locks, it still helps to distribute the inserters evenly
1340 * across the locks.
1342 lockToTry = (lockToTry + 1) % NUM_XLOGINSERT_LOCKS;
1347 * Acquire all WAL insertion locks, to prevent other backends from inserting
1348 * to WAL.
1350 static void
1351 WALInsertLockAcquireExclusive(void)
1353 int i;
1356 * When holding all the locks, all but the last lock's insertingAt
1357 * indicator is set to 0xFFFFFFFFFFFFFFFF, which is higher than any real
1358 * XLogRecPtr value, to make sure that no-one blocks waiting on those.
1360 for (i = 0; i < NUM_XLOGINSERT_LOCKS - 1; i++)
1362 LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
1363 LWLockUpdateVar(&WALInsertLocks[i].l.lock,
1364 &WALInsertLocks[i].l.insertingAt,
1365 PG_UINT64_MAX);
1367 /* Variable value reset to 0 at release */
1368 LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
1370 holdingAllLocks = true;
1374 * Release our insertion lock (or locks, if we're holding them all).
1376 * NB: Reset all variables to 0, so they cause LWLockWaitForVar to block the
1377 * next time the lock is acquired.
1379 static void
1380 WALInsertLockRelease(void)
1382 if (holdingAllLocks)
1384 int i;
1386 for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1387 LWLockReleaseClearVar(&WALInsertLocks[i].l.lock,
1388 &WALInsertLocks[i].l.insertingAt,
1391 holdingAllLocks = false;
1393 else
1395 LWLockReleaseClearVar(&WALInsertLocks[MyLockNo].l.lock,
1396 &WALInsertLocks[MyLockNo].l.insertingAt,
1402 * Update our insertingAt value, to let others know that we've finished
1403 * inserting up to that point.
1405 static void
1406 WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt)
1408 if (holdingAllLocks)
1411 * We use the last lock to mark our actual position, see comments in
1412 * WALInsertLockAcquireExclusive.
1414 LWLockUpdateVar(&WALInsertLocks[NUM_XLOGINSERT_LOCKS - 1].l.lock,
1415 &WALInsertLocks[NUM_XLOGINSERT_LOCKS - 1].l.insertingAt,
1416 insertingAt);
1418 else
1419 LWLockUpdateVar(&WALInsertLocks[MyLockNo].l.lock,
1420 &WALInsertLocks[MyLockNo].l.insertingAt,
1421 insertingAt);
1425 * Wait for any WAL insertions < upto to finish.
1427 * Returns the location of the oldest insertion that is still in-progress.
1428 * Any WAL prior to that point has been fully copied into WAL buffers, and
1429 * can be flushed out to disk. Because this waits for any insertions older
1430 * than 'upto' to finish, the return value is always >= 'upto'.
1432 * Note: When you are about to write out WAL, you must call this function
1433 * *before* acquiring WALWriteLock, to avoid deadlocks. This function might
1434 * need to wait for an insertion to finish (or at least advance to next
1435 * uninitialized page), and the inserter might need to evict an old WAL buffer
1436 * to make room for a new one, which in turn requires WALWriteLock.
1438 static XLogRecPtr
1439 WaitXLogInsertionsToFinish(XLogRecPtr upto)
1441 uint64 bytepos;
1442 XLogRecPtr reservedUpto;
1443 XLogRecPtr finishedUpto;
1444 XLogCtlInsert *Insert = &XLogCtl->Insert;
1445 int i;
1447 if (MyProc == NULL)
1448 elog(PANIC, "cannot wait without a PGPROC structure");
1450 /* Read the current insert position */
1451 SpinLockAcquire(&Insert->insertpos_lck);
1452 bytepos = Insert->CurrBytePos;
1453 SpinLockRelease(&Insert->insertpos_lck);
1454 reservedUpto = XLogBytePosToEndRecPtr(bytepos);
1457 * No-one should request to flush a piece of WAL that hasn't even been
1458 * reserved yet. However, it can happen if there is a block with a bogus
1459 * LSN on disk, for example. XLogFlush checks for that situation and
1460 * complains, but only after the flush. Here we just assume that to mean
1461 * that all WAL that has been reserved needs to be finished. In this
1462 * corner-case, the return value can be smaller than 'upto' argument.
1464 if (upto > reservedUpto)
1466 ereport(LOG,
1467 (errmsg("request to flush past end of generated WAL; request %X/%X, current position %X/%X",
1468 LSN_FORMAT_ARGS(upto), LSN_FORMAT_ARGS(reservedUpto))));
1469 upto = reservedUpto;
1473 * Loop through all the locks, sleeping on any in-progress insert older
1474 * than 'upto'.
1476 * finishedUpto is our return value, indicating the point upto which all
1477 * the WAL insertions have been finished. Initialize it to the head of
1478 * reserved WAL, and as we iterate through the insertion locks, back it
1479 * out for any insertion that's still in progress.
1481 finishedUpto = reservedUpto;
1482 for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1484 XLogRecPtr insertingat = InvalidXLogRecPtr;
1489 * See if this insertion is in progress. LWLockWaitForVar will
1490 * wait for the lock to be released, or for the 'value' to be set
1491 * by a LWLockUpdateVar call. When a lock is initially acquired,
1492 * its value is 0 (InvalidXLogRecPtr), which means that we don't
1493 * know where it's inserting yet. We will have to wait for it. If
1494 * it's a small insertion, the record will most likely fit on the
1495 * same page and the inserter will release the lock without ever
1496 * calling LWLockUpdateVar. But if it has to sleep, it will
1497 * advertise the insertion point with LWLockUpdateVar before
1498 * sleeping.
1500 if (LWLockWaitForVar(&WALInsertLocks[i].l.lock,
1501 &WALInsertLocks[i].l.insertingAt,
1502 insertingat, &insertingat))
1504 /* the lock was free, so no insertion in progress */
1505 insertingat = InvalidXLogRecPtr;
1506 break;
1510 * This insertion is still in progress. Have to wait, unless the
1511 * inserter has proceeded past 'upto'.
1513 } while (insertingat < upto);
1515 if (insertingat != InvalidXLogRecPtr && insertingat < finishedUpto)
1516 finishedUpto = insertingat;
1518 return finishedUpto;
1522 * Get a pointer to the right location in the WAL buffer containing the
1523 * given XLogRecPtr.
1525 * If the page is not initialized yet, it is initialized. That might require
1526 * evicting an old dirty buffer from the buffer cache, which means I/O.
1528 * The caller must ensure that the page containing the requested location
1529 * isn't evicted yet, and won't be evicted. The way to ensure that is to
1530 * hold onto a WAL insertion lock with the insertingAt position set to
1531 * something <= ptr. GetXLogBuffer() will update insertingAt if it needs
1532 * to evict an old page from the buffer. (This means that once you call
1533 * GetXLogBuffer() with a given 'ptr', you must not access anything before
1534 * that point anymore, and must not call GetXLogBuffer() with an older 'ptr'
1535 * later, because older buffers might be recycled already)
1537 static char *
1538 GetXLogBuffer(XLogRecPtr ptr, TimeLineID tli)
1540 int idx;
1541 XLogRecPtr endptr;
1542 static uint64 cachedPage = 0;
1543 static char *cachedPos = NULL;
1544 XLogRecPtr expectedEndPtr;
1547 * Fast path for the common case that we need to access again the same
1548 * page as last time.
1550 if (ptr / XLOG_BLCKSZ == cachedPage)
1552 Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1553 Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1554 return cachedPos + ptr % XLOG_BLCKSZ;
1558 * The XLog buffer cache is organized so that a page is always loaded to a
1559 * particular buffer. That way we can easily calculate the buffer a given
1560 * page must be loaded into, from the XLogRecPtr alone.
1562 idx = XLogRecPtrToBufIdx(ptr);
1565 * See what page is loaded in the buffer at the moment. It could be the
1566 * page we're looking for, or something older. It can't be anything newer
1567 * - that would imply the page we're looking for has already been written
1568 * out to disk and evicted, and the caller is responsible for making sure
1569 * that doesn't happen.
1571 * However, we don't hold a lock while we read the value. If someone has
1572 * just initialized the page, it's possible that we get a "torn read" of
1573 * the XLogRecPtr if 64-bit fetches are not atomic on this platform. In
1574 * that case we will see a bogus value. That's ok, we'll grab the mapping
1575 * lock (in AdvanceXLInsertBuffer) and retry if we see anything else than
1576 * the page we're looking for. But it means that when we do this unlocked
1577 * read, we might see a value that appears to be ahead of the page we're
1578 * looking for. Don't PANIC on that, until we've verified the value while
1579 * holding the lock.
1581 expectedEndPtr = ptr;
1582 expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
1584 endptr = XLogCtl->xlblocks[idx];
1585 if (expectedEndPtr != endptr)
1587 XLogRecPtr initializedUpto;
1590 * Before calling AdvanceXLInsertBuffer(), which can block, let others
1591 * know how far we're finished with inserting the record.
1593 * NB: If 'ptr' points to just after the page header, advertise a
1594 * position at the beginning of the page rather than 'ptr' itself. If
1595 * there are no other insertions running, someone might try to flush
1596 * up to our advertised location. If we advertised a position after
1597 * the page header, someone might try to flush the page header, even
1598 * though page might actually not be initialized yet. As the first
1599 * inserter on the page, we are effectively responsible for making
1600 * sure that it's initialized, before we let insertingAt to move past
1601 * the page header.
1603 if (ptr % XLOG_BLCKSZ == SizeOfXLogShortPHD &&
1604 XLogSegmentOffset(ptr, wal_segment_size) > XLOG_BLCKSZ)
1605 initializedUpto = ptr - SizeOfXLogShortPHD;
1606 else if (ptr % XLOG_BLCKSZ == SizeOfXLogLongPHD &&
1607 XLogSegmentOffset(ptr, wal_segment_size) < XLOG_BLCKSZ)
1608 initializedUpto = ptr - SizeOfXLogLongPHD;
1609 else
1610 initializedUpto = ptr;
1612 WALInsertLockUpdateInsertingAt(initializedUpto);
1614 AdvanceXLInsertBuffer(ptr, tli, false);
1615 endptr = XLogCtl->xlblocks[idx];
1617 if (expectedEndPtr != endptr)
1618 elog(PANIC, "could not find WAL buffer for %X/%X",
1619 LSN_FORMAT_ARGS(ptr));
1621 else
1624 * Make sure the initialization of the page is visible to us, and
1625 * won't arrive later to overwrite the WAL data we write on the page.
1627 pg_memory_barrier();
1631 * Found the buffer holding this page. Return a pointer to the right
1632 * offset within the page.
1634 cachedPage = ptr / XLOG_BLCKSZ;
1635 cachedPos = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
1637 Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1638 Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1640 return cachedPos + ptr % XLOG_BLCKSZ;
1644 * Converts a "usable byte position" to XLogRecPtr. A usable byte position
1645 * is the position starting from the beginning of WAL, excluding all WAL
1646 * page headers.
1648 static XLogRecPtr
1649 XLogBytePosToRecPtr(uint64 bytepos)
1651 uint64 fullsegs;
1652 uint64 fullpages;
1653 uint64 bytesleft;
1654 uint32 seg_offset;
1655 XLogRecPtr result;
1657 fullsegs = bytepos / UsableBytesInSegment;
1658 bytesleft = bytepos % UsableBytesInSegment;
1660 if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
1662 /* fits on first page of segment */
1663 seg_offset = bytesleft + SizeOfXLogLongPHD;
1665 else
1667 /* account for the first page on segment with long header */
1668 seg_offset = XLOG_BLCKSZ;
1669 bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
1671 fullpages = bytesleft / UsableBytesInPage;
1672 bytesleft = bytesleft % UsableBytesInPage;
1674 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
1677 XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
1679 return result;
1683 * Like XLogBytePosToRecPtr, but if the position is at a page boundary,
1684 * returns a pointer to the beginning of the page (ie. before page header),
1685 * not to where the first xlog record on that page would go to. This is used
1686 * when converting a pointer to the end of a record.
1688 static XLogRecPtr
1689 XLogBytePosToEndRecPtr(uint64 bytepos)
1691 uint64 fullsegs;
1692 uint64 fullpages;
1693 uint64 bytesleft;
1694 uint32 seg_offset;
1695 XLogRecPtr result;
1697 fullsegs = bytepos / UsableBytesInSegment;
1698 bytesleft = bytepos % UsableBytesInSegment;
1700 if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
1702 /* fits on first page of segment */
1703 if (bytesleft == 0)
1704 seg_offset = 0;
1705 else
1706 seg_offset = bytesleft + SizeOfXLogLongPHD;
1708 else
1710 /* account for the first page on segment with long header */
1711 seg_offset = XLOG_BLCKSZ;
1712 bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
1714 fullpages = bytesleft / UsableBytesInPage;
1715 bytesleft = bytesleft % UsableBytesInPage;
1717 if (bytesleft == 0)
1718 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
1719 else
1720 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
1723 XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
1725 return result;
1729 * Convert an XLogRecPtr to a "usable byte position".
1731 static uint64
1732 XLogRecPtrToBytePos(XLogRecPtr ptr)
1734 uint64 fullsegs;
1735 uint32 fullpages;
1736 uint32 offset;
1737 uint64 result;
1739 XLByteToSeg(ptr, fullsegs, wal_segment_size);
1741 fullpages = (XLogSegmentOffset(ptr, wal_segment_size)) / XLOG_BLCKSZ;
1742 offset = ptr % XLOG_BLCKSZ;
1744 if (fullpages == 0)
1746 result = fullsegs * UsableBytesInSegment;
1747 if (offset > 0)
1749 Assert(offset >= SizeOfXLogLongPHD);
1750 result += offset - SizeOfXLogLongPHD;
1753 else
1755 result = fullsegs * UsableBytesInSegment +
1756 (XLOG_BLCKSZ - SizeOfXLogLongPHD) + /* account for first page */
1757 (fullpages - 1) * UsableBytesInPage; /* full pages */
1758 if (offset > 0)
1760 Assert(offset >= SizeOfXLogShortPHD);
1761 result += offset - SizeOfXLogShortPHD;
1765 return result;
1769 * Initialize XLOG buffers, writing out old buffers if they still contain
1770 * unwritten data, upto the page containing 'upto'. Or if 'opportunistic' is
1771 * true, initialize as many pages as we can without having to write out
1772 * unwritten data. Any new pages are initialized to zeros, with pages headers
1773 * initialized properly.
1775 static void
1776 AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli, bool opportunistic)
1778 XLogCtlInsert *Insert = &XLogCtl->Insert;
1779 int nextidx;
1780 XLogRecPtr OldPageRqstPtr;
1781 XLogwrtRqst WriteRqst;
1782 XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
1783 XLogRecPtr NewPageBeginPtr;
1784 XLogPageHeader NewPage;
1785 int npages pg_attribute_unused() = 0;
1787 LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
1790 * Now that we have the lock, check if someone initialized the page
1791 * already.
1793 while (upto >= XLogCtl->InitializedUpTo || opportunistic)
1795 nextidx = XLogRecPtrToBufIdx(XLogCtl->InitializedUpTo);
1798 * Get ending-offset of the buffer page we need to replace (this may
1799 * be zero if the buffer hasn't been used yet). Fall through if it's
1800 * already written out.
1802 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1803 if (LogwrtResult.Write < OldPageRqstPtr)
1806 * Nope, got work to do. If we just want to pre-initialize as much
1807 * as we can without flushing, give up now.
1809 if (opportunistic)
1810 break;
1812 /* Before waiting, get info_lck and update LogwrtResult */
1813 SpinLockAcquire(&XLogCtl->info_lck);
1814 if (XLogCtl->LogwrtRqst.Write < OldPageRqstPtr)
1815 XLogCtl->LogwrtRqst.Write = OldPageRqstPtr;
1816 LogwrtResult = XLogCtl->LogwrtResult;
1817 SpinLockRelease(&XLogCtl->info_lck);
1820 * Now that we have an up-to-date LogwrtResult value, see if we
1821 * still need to write it or if someone else already did.
1823 if (LogwrtResult.Write < OldPageRqstPtr)
1826 * Must acquire write lock. Release WALBufMappingLock first,
1827 * to make sure that all insertions that we need to wait for
1828 * can finish (up to this same position). Otherwise we risk
1829 * deadlock.
1831 LWLockRelease(WALBufMappingLock);
1833 WaitXLogInsertionsToFinish(OldPageRqstPtr);
1835 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1837 LogwrtResult = XLogCtl->LogwrtResult;
1838 if (LogwrtResult.Write >= OldPageRqstPtr)
1840 /* OK, someone wrote it already */
1841 LWLockRelease(WALWriteLock);
1843 else
1845 /* Have to write it ourselves */
1846 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
1847 WriteRqst.Write = OldPageRqstPtr;
1848 WriteRqst.Flush = 0;
1849 XLogWrite(WriteRqst, tli, false);
1850 LWLockRelease(WALWriteLock);
1851 PendingWalStats.wal_buffers_full++;
1852 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
1854 /* Re-acquire WALBufMappingLock and retry */
1855 LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
1856 continue;
1861 * Now the next buffer slot is free and we can set it up to be the
1862 * next output page.
1864 NewPageBeginPtr = XLogCtl->InitializedUpTo;
1865 NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
1867 Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
1869 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1872 * Be sure to re-zero the buffer so that bytes beyond what we've
1873 * written will look like zeroes and not valid XLOG records...
1875 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1878 * Fill the new page's header
1880 NewPage->xlp_magic = XLOG_PAGE_MAGIC;
1882 /* NewPage->xlp_info = 0; */ /* done by memset */
1883 NewPage->xlp_tli = tli;
1884 NewPage->xlp_pageaddr = NewPageBeginPtr;
1886 /* NewPage->xlp_rem_len = 0; */ /* done by memset */
1889 * If online backup is not in progress, mark the header to indicate
1890 * that WAL records beginning in this page have removable backup
1891 * blocks. This allows the WAL archiver to know whether it is safe to
1892 * compress archived WAL data by transforming full-block records into
1893 * the non-full-block format. It is sufficient to record this at the
1894 * page level because we force a page switch (in fact a segment
1895 * switch) when starting a backup, so the flag will be off before any
1896 * records can be written during the backup. At the end of a backup,
1897 * the last page will be marked as all unsafe when perhaps only part
1898 * is unsafe, but at worst the archiver would miss the opportunity to
1899 * compress a few records.
1901 if (Insert->runningBackups == 0)
1902 NewPage->xlp_info |= XLP_BKP_REMOVABLE;
1905 * If first page of an XLOG segment file, make it a long header.
1907 if ((XLogSegmentOffset(NewPage->xlp_pageaddr, wal_segment_size)) == 0)
1909 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1911 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1912 NewLongPage->xlp_seg_size = wal_segment_size;
1913 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1914 NewPage->xlp_info |= XLP_LONG_HEADER;
1918 * Make sure the initialization of the page becomes visible to others
1919 * before the xlblocks update. GetXLogBuffer() reads xlblocks without
1920 * holding a lock.
1922 pg_write_barrier();
1924 *((volatile XLogRecPtr *) &XLogCtl->xlblocks[nextidx]) = NewPageEndPtr;
1926 XLogCtl->InitializedUpTo = NewPageEndPtr;
1928 npages++;
1930 LWLockRelease(WALBufMappingLock);
1932 #ifdef WAL_DEBUG
1933 if (XLOG_DEBUG && npages > 0)
1935 elog(DEBUG1, "initialized %d pages, up to %X/%X",
1936 npages, LSN_FORMAT_ARGS(NewPageEndPtr));
1938 #endif
1942 * Calculate CheckPointSegments based on max_wal_size_mb and
1943 * checkpoint_completion_target.
1945 static void
1946 CalculateCheckpointSegments(void)
1948 double target;
1950 /*-------
1951 * Calculate the distance at which to trigger a checkpoint, to avoid
1952 * exceeding max_wal_size_mb. This is based on two assumptions:
1954 * a) we keep WAL for only one checkpoint cycle (prior to PG11 we kept
1955 * WAL for two checkpoint cycles to allow us to recover from the
1956 * secondary checkpoint if the first checkpoint failed, though we
1957 * only did this on the primary anyway, not on standby. Keeping just
1958 * one checkpoint simplifies processing and reduces disk space in
1959 * many smaller databases.)
1960 * b) during checkpoint, we consume checkpoint_completion_target *
1961 * number of segments consumed between checkpoints.
1962 *-------
1964 target = (double) ConvertToXSegs(max_wal_size_mb, wal_segment_size) /
1965 (1.0 + CheckPointCompletionTarget);
1967 /* round down */
1968 CheckPointSegments = (int) target;
1970 if (CheckPointSegments < 1)
1971 CheckPointSegments = 1;
1974 void
1975 assign_max_wal_size(int newval, void *extra)
1977 max_wal_size_mb = newval;
1978 CalculateCheckpointSegments();
1981 void
1982 assign_checkpoint_completion_target(double newval, void *extra)
1984 CheckPointCompletionTarget = newval;
1985 CalculateCheckpointSegments();
1989 * At a checkpoint, how many WAL segments to recycle as preallocated future
1990 * XLOG segments? Returns the highest segment that should be preallocated.
1992 static XLogSegNo
1993 XLOGfileslop(XLogRecPtr lastredoptr)
1995 XLogSegNo minSegNo;
1996 XLogSegNo maxSegNo;
1997 double distance;
1998 XLogSegNo recycleSegNo;
2001 * Calculate the segment numbers that min_wal_size_mb and max_wal_size_mb
2002 * correspond to. Always recycle enough segments to meet the minimum, and
2003 * remove enough segments to stay below the maximum.
2005 minSegNo = lastredoptr / wal_segment_size +
2006 ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
2007 maxSegNo = lastredoptr / wal_segment_size +
2008 ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
2011 * Between those limits, recycle enough segments to get us through to the
2012 * estimated end of next checkpoint.
2014 * To estimate where the next checkpoint will finish, assume that the
2015 * system runs steadily consuming CheckPointDistanceEstimate bytes between
2016 * every checkpoint.
2018 distance = (1.0 + CheckPointCompletionTarget) * CheckPointDistanceEstimate;
2019 /* add 10% for good measure. */
2020 distance *= 1.10;
2022 recycleSegNo = (XLogSegNo) ceil(((double) lastredoptr + distance) /
2023 wal_segment_size);
2025 if (recycleSegNo < minSegNo)
2026 recycleSegNo = minSegNo;
2027 if (recycleSegNo > maxSegNo)
2028 recycleSegNo = maxSegNo;
2030 return recycleSegNo;
2034 * Check whether we've consumed enough xlog space that a checkpoint is needed.
2036 * new_segno indicates a log file that has just been filled up (or read
2037 * during recovery). We measure the distance from RedoRecPtr to new_segno
2038 * and see if that exceeds CheckPointSegments.
2040 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
2042 bool
2043 XLogCheckpointNeeded(XLogSegNo new_segno)
2045 XLogSegNo old_segno;
2047 XLByteToSeg(RedoRecPtr, old_segno, wal_segment_size);
2049 if (new_segno >= old_segno + (uint64) (CheckPointSegments - 1))
2050 return true;
2051 return false;
2055 * Write and/or fsync the log at least as far as WriteRqst indicates.
2057 * If flexible == true, we don't have to write as far as WriteRqst, but
2058 * may stop at any convenient boundary (such as a cache or logfile boundary).
2059 * This option allows us to avoid uselessly issuing multiple writes when a
2060 * single one would do.
2062 * Must be called with WALWriteLock held. WaitXLogInsertionsToFinish(WriteRqst)
2063 * must be called before grabbing the lock, to make sure the data is ready to
2064 * write.
2066 static void
2067 XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible)
2069 bool ispartialpage;
2070 bool last_iteration;
2071 bool finishing_seg;
2072 int curridx;
2073 int npages;
2074 int startidx;
2075 uint32 startoffset;
2077 /* We should always be inside a critical section here */
2078 Assert(CritSectionCount > 0);
2081 * Update local LogwrtResult (caller probably did this already, but...)
2083 LogwrtResult = XLogCtl->LogwrtResult;
2086 * Since successive pages in the xlog cache are consecutively allocated,
2087 * we can usually gather multiple pages together and issue just one
2088 * write() call. npages is the number of pages we have determined can be
2089 * written together; startidx is the cache block index of the first one,
2090 * and startoffset is the file offset at which it should go. The latter
2091 * two variables are only valid when npages > 0, but we must initialize
2092 * all of them to keep the compiler quiet.
2094 npages = 0;
2095 startidx = 0;
2096 startoffset = 0;
2099 * Within the loop, curridx is the cache block index of the page to
2100 * consider writing. Begin at the buffer containing the next unwritten
2101 * page, or last partially written page.
2103 curridx = XLogRecPtrToBufIdx(LogwrtResult.Write);
2105 while (LogwrtResult.Write < WriteRqst.Write)
2108 * Make sure we're not ahead of the insert process. This could happen
2109 * if we're passed a bogus WriteRqst.Write that is past the end of the
2110 * last page that's been initialized by AdvanceXLInsertBuffer.
2112 XLogRecPtr EndPtr = XLogCtl->xlblocks[curridx];
2114 if (LogwrtResult.Write >= EndPtr)
2115 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
2116 LSN_FORMAT_ARGS(LogwrtResult.Write),
2117 LSN_FORMAT_ARGS(EndPtr));
2119 /* Advance LogwrtResult.Write to end of current buffer page */
2120 LogwrtResult.Write = EndPtr;
2121 ispartialpage = WriteRqst.Write < LogwrtResult.Write;
2123 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
2124 wal_segment_size))
2127 * Switch to new logfile segment. We cannot have any pending
2128 * pages here (since we dump what we have at segment end).
2130 Assert(npages == 0);
2131 if (openLogFile >= 0)
2132 XLogFileClose();
2133 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2134 wal_segment_size);
2135 openLogTLI = tli;
2137 /* create/use new log file */
2138 openLogFile = XLogFileInit(openLogSegNo, tli);
2139 ReserveExternalFD();
2142 /* Make sure we have the current logfile open */
2143 if (openLogFile < 0)
2145 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2146 wal_segment_size);
2147 openLogTLI = tli;
2148 openLogFile = XLogFileOpen(openLogSegNo, tli);
2149 ReserveExternalFD();
2152 /* Add current page to the set of pending pages-to-dump */
2153 if (npages == 0)
2155 /* first of group */
2156 startidx = curridx;
2157 startoffset = XLogSegmentOffset(LogwrtResult.Write - XLOG_BLCKSZ,
2158 wal_segment_size);
2160 npages++;
2163 * Dump the set if this will be the last loop iteration, or if we are
2164 * at the last page of the cache area (since the next page won't be
2165 * contiguous in memory), or if we are at the end of the logfile
2166 * segment.
2168 last_iteration = WriteRqst.Write <= LogwrtResult.Write;
2170 finishing_seg = !ispartialpage &&
2171 (startoffset + npages * XLOG_BLCKSZ) >= wal_segment_size;
2173 if (last_iteration ||
2174 curridx == XLogCtl->XLogCacheBlck ||
2175 finishing_seg)
2177 char *from;
2178 Size nbytes;
2179 Size nleft;
2180 int written;
2181 instr_time start;
2183 /* OK to write the page(s) */
2184 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
2185 nbytes = npages * (Size) XLOG_BLCKSZ;
2186 nleft = nbytes;
2189 errno = 0;
2191 /* Measure I/O timing to write WAL data */
2192 if (track_wal_io_timing)
2193 INSTR_TIME_SET_CURRENT(start);
2195 pgstat_report_wait_start(WAIT_EVENT_WAL_WRITE);
2196 written = pg_pwrite(openLogFile, from, nleft, startoffset);
2197 pgstat_report_wait_end();
2200 * Increment the I/O timing and the number of times WAL data
2201 * were written out to disk.
2203 if (track_wal_io_timing)
2205 instr_time duration;
2207 INSTR_TIME_SET_CURRENT(duration);
2208 INSTR_TIME_SUBTRACT(duration, start);
2209 PendingWalStats.wal_write_time += INSTR_TIME_GET_MICROSEC(duration);
2212 PendingWalStats.wal_write++;
2214 if (written <= 0)
2216 char xlogfname[MAXFNAMELEN];
2217 int save_errno;
2219 if (errno == EINTR)
2220 continue;
2222 save_errno = errno;
2223 XLogFileName(xlogfname, tli, openLogSegNo,
2224 wal_segment_size);
2225 errno = save_errno;
2226 ereport(PANIC,
2227 (errcode_for_file_access(),
2228 errmsg("could not write to log file %s "
2229 "at offset %u, length %zu: %m",
2230 xlogfname, startoffset, nleft)));
2232 nleft -= written;
2233 from += written;
2234 startoffset += written;
2235 } while (nleft > 0);
2237 npages = 0;
2240 * If we just wrote the whole last page of a logfile segment,
2241 * fsync the segment immediately. This avoids having to go back
2242 * and re-open prior segments when an fsync request comes along
2243 * later. Doing it here ensures that one and only one backend will
2244 * perform this fsync.
2246 * This is also the right place to notify the Archiver that the
2247 * segment is ready to copy to archival storage, and to update the
2248 * timer for archive_timeout, and to signal for a checkpoint if
2249 * too many logfile segments have been used since the last
2250 * checkpoint.
2252 if (finishing_seg)
2254 issue_xlog_fsync(openLogFile, openLogSegNo, tli);
2256 /* signal that we need to wakeup walsenders later */
2257 WalSndWakeupRequest();
2259 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
2261 if (XLogArchivingActive())
2262 XLogArchiveNotifySeg(openLogSegNo, tli);
2264 XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
2265 XLogCtl->lastSegSwitchLSN = LogwrtResult.Flush;
2268 * Request a checkpoint if we've consumed too much xlog since
2269 * the last one. For speed, we first check using the local
2270 * copy of RedoRecPtr, which might be out of date; if it looks
2271 * like a checkpoint is needed, forcibly update RedoRecPtr and
2272 * recheck.
2274 if (IsUnderPostmaster && XLogCheckpointNeeded(openLogSegNo))
2276 (void) GetRedoRecPtr();
2277 if (XLogCheckpointNeeded(openLogSegNo))
2278 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
2283 if (ispartialpage)
2285 /* Only asked to write a partial page */
2286 LogwrtResult.Write = WriteRqst.Write;
2287 break;
2289 curridx = NextBufIdx(curridx);
2291 /* If flexible, break out of loop as soon as we wrote something */
2292 if (flexible && npages == 0)
2293 break;
2296 Assert(npages == 0);
2299 * If asked to flush, do so
2301 if (LogwrtResult.Flush < WriteRqst.Flush &&
2302 LogwrtResult.Flush < LogwrtResult.Write)
2305 * Could get here without iterating above loop, in which case we might
2306 * have no open file or the wrong one. However, we do not need to
2307 * fsync more than one file.
2309 if (sync_method != SYNC_METHOD_OPEN &&
2310 sync_method != SYNC_METHOD_OPEN_DSYNC)
2312 if (openLogFile >= 0 &&
2313 !XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
2314 wal_segment_size))
2315 XLogFileClose();
2316 if (openLogFile < 0)
2318 XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2319 wal_segment_size);
2320 openLogTLI = tli;
2321 openLogFile = XLogFileOpen(openLogSegNo, tli);
2322 ReserveExternalFD();
2325 issue_xlog_fsync(openLogFile, openLogSegNo, tli);
2328 /* signal that we need to wakeup walsenders later */
2329 WalSndWakeupRequest();
2331 LogwrtResult.Flush = LogwrtResult.Write;
2335 * Update shared-memory status
2337 * We make sure that the shared 'request' values do not fall behind the
2338 * 'result' values. This is not absolutely essential, but it saves some
2339 * code in a couple of places.
2342 SpinLockAcquire(&XLogCtl->info_lck);
2343 XLogCtl->LogwrtResult = LogwrtResult;
2344 if (XLogCtl->LogwrtRqst.Write < LogwrtResult.Write)
2345 XLogCtl->LogwrtRqst.Write = LogwrtResult.Write;
2346 if (XLogCtl->LogwrtRqst.Flush < LogwrtResult.Flush)
2347 XLogCtl->LogwrtRqst.Flush = LogwrtResult.Flush;
2348 SpinLockRelease(&XLogCtl->info_lck);
2353 * Record the LSN for an asynchronous transaction commit/abort
2354 * and nudge the WALWriter if there is work for it to do.
2355 * (This should not be called for synchronous commits.)
2357 void
2358 XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
2360 XLogRecPtr WriteRqstPtr = asyncXactLSN;
2361 bool sleeping;
2363 SpinLockAcquire(&XLogCtl->info_lck);
2364 LogwrtResult = XLogCtl->LogwrtResult;
2365 sleeping = XLogCtl->WalWriterSleeping;
2366 if (XLogCtl->asyncXactLSN < asyncXactLSN)
2367 XLogCtl->asyncXactLSN = asyncXactLSN;
2368 SpinLockRelease(&XLogCtl->info_lck);
2371 * If the WALWriter is sleeping, we should kick it to make it come out of
2372 * low-power mode. Otherwise, determine whether there's a full page of
2373 * WAL available to write.
2375 if (!sleeping)
2377 /* back off to last completed page boundary */
2378 WriteRqstPtr -= WriteRqstPtr % XLOG_BLCKSZ;
2380 /* if we have already flushed that far, we're done */
2381 if (WriteRqstPtr <= LogwrtResult.Flush)
2382 return;
2386 * Nudge the WALWriter: it has a full page of WAL to write, or we want it
2387 * to come out of low-power mode so that this async commit will reach disk
2388 * within the expected amount of time.
2390 if (ProcGlobal->walwriterLatch)
2391 SetLatch(ProcGlobal->walwriterLatch);
2395 * Record the LSN up to which we can remove WAL because it's not required by
2396 * any replication slot.
2398 void
2399 XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
2401 SpinLockAcquire(&XLogCtl->info_lck);
2402 XLogCtl->replicationSlotMinLSN = lsn;
2403 SpinLockRelease(&XLogCtl->info_lck);
2408 * Return the oldest LSN we must retain to satisfy the needs of some
2409 * replication slot.
2411 static XLogRecPtr
2412 XLogGetReplicationSlotMinimumLSN(void)
2414 XLogRecPtr retval;
2416 SpinLockAcquire(&XLogCtl->info_lck);
2417 retval = XLogCtl->replicationSlotMinLSN;
2418 SpinLockRelease(&XLogCtl->info_lck);
2420 return retval;
2424 * Advance minRecoveryPoint in control file.
2426 * If we crash during recovery, we must reach this point again before the
2427 * database is consistent.
2429 * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
2430 * is only updated if it's not already greater than or equal to 'lsn'.
2432 static void
2433 UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
2435 /* Quick check using our local copy of the variable */
2436 if (!updateMinRecoveryPoint || (!force && lsn <= LocalMinRecoveryPoint))
2437 return;
2440 * An invalid minRecoveryPoint means that we need to recover all the WAL,
2441 * i.e., we're doing crash recovery. We never modify the control file's
2442 * value in that case, so we can short-circuit future checks here too. The
2443 * local values of minRecoveryPoint and minRecoveryPointTLI should not be
2444 * updated until crash recovery finishes. We only do this for the startup
2445 * process as it should not update its own reference of minRecoveryPoint
2446 * until it has finished crash recovery to make sure that all WAL
2447 * available is replayed in this case. This also saves from extra locks
2448 * taken on the control file from the startup process.
2450 if (XLogRecPtrIsInvalid(LocalMinRecoveryPoint) && InRecovery)
2452 updateMinRecoveryPoint = false;
2453 return;
2456 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2458 /* update local copy */
2459 LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
2460 LocalMinRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
2462 if (XLogRecPtrIsInvalid(LocalMinRecoveryPoint))
2463 updateMinRecoveryPoint = false;
2464 else if (force || LocalMinRecoveryPoint < lsn)
2466 XLogRecPtr newMinRecoveryPoint;
2467 TimeLineID newMinRecoveryPointTLI;
2470 * To avoid having to update the control file too often, we update it
2471 * all the way to the last record being replayed, even though 'lsn'
2472 * would suffice for correctness. This also allows the 'force' case
2473 * to not need a valid 'lsn' value.
2475 * Another important reason for doing it this way is that the passed
2476 * 'lsn' value could be bogus, i.e., past the end of available WAL, if
2477 * the caller got it from a corrupted heap page. Accepting such a
2478 * value as the min recovery point would prevent us from coming up at
2479 * all. Instead, we just log a warning and continue with recovery.
2480 * (See also the comments about corrupt LSNs in XLogFlush.)
2482 newMinRecoveryPoint = GetCurrentReplayRecPtr(&newMinRecoveryPointTLI);
2483 if (!force && newMinRecoveryPoint < lsn)
2484 elog(WARNING,
2485 "xlog min recovery request %X/%X is past current point %X/%X",
2486 LSN_FORMAT_ARGS(lsn), LSN_FORMAT_ARGS(newMinRecoveryPoint));
2488 /* update control file */
2489 if (ControlFile->minRecoveryPoint < newMinRecoveryPoint)
2491 ControlFile->minRecoveryPoint = newMinRecoveryPoint;
2492 ControlFile->minRecoveryPointTLI = newMinRecoveryPointTLI;
2493 UpdateControlFile();
2494 LocalMinRecoveryPoint = newMinRecoveryPoint;
2495 LocalMinRecoveryPointTLI = newMinRecoveryPointTLI;
2497 ereport(DEBUG2,
2498 (errmsg_internal("updated min recovery point to %X/%X on timeline %u",
2499 LSN_FORMAT_ARGS(newMinRecoveryPoint),
2500 newMinRecoveryPointTLI)));
2503 LWLockRelease(ControlFileLock);
2507 * Ensure that all XLOG data through the given position is flushed to disk.
2509 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
2510 * already held, and we try to avoid acquiring it if possible.
2512 void
2513 XLogFlush(XLogRecPtr record)
2515 XLogRecPtr WriteRqstPtr;
2516 XLogwrtRqst WriteRqst;
2517 TimeLineID insertTLI = XLogCtl->InsertTimeLineID;
2520 * During REDO, we are reading not writing WAL. Therefore, instead of
2521 * trying to flush the WAL, we should update minRecoveryPoint instead. We
2522 * test XLogInsertAllowed(), not InRecovery, because we need checkpointer
2523 * to act this way too, and because when it tries to write the
2524 * end-of-recovery checkpoint, it should indeed flush.
2526 if (!XLogInsertAllowed())
2528 UpdateMinRecoveryPoint(record, false);
2529 return;
2532 /* Quick exit if already known flushed */
2533 if (record <= LogwrtResult.Flush)
2534 return;
2536 #ifdef WAL_DEBUG
2537 if (XLOG_DEBUG)
2538 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
2539 LSN_FORMAT_ARGS(record),
2540 LSN_FORMAT_ARGS(LogwrtResult.Write),
2541 LSN_FORMAT_ARGS(LogwrtResult.Flush));
2542 #endif
2544 START_CRIT_SECTION();
2547 * Since fsync is usually a horribly expensive operation, we try to
2548 * piggyback as much data as we can on each fsync: if we see any more data
2549 * entered into the xlog buffer, we'll write and fsync that too, so that
2550 * the final value of LogwrtResult.Flush is as large as possible. This
2551 * gives us some chance of avoiding another fsync immediately after.
2554 /* initialize to given target; may increase below */
2555 WriteRqstPtr = record;
2558 * Now wait until we get the write lock, or someone else does the flush
2559 * for us.
2561 for (;;)
2563 XLogRecPtr insertpos;
2565 /* read LogwrtResult and update local state */
2566 SpinLockAcquire(&XLogCtl->info_lck);
2567 if (WriteRqstPtr < XLogCtl->LogwrtRqst.Write)
2568 WriteRqstPtr = XLogCtl->LogwrtRqst.Write;
2569 LogwrtResult = XLogCtl->LogwrtResult;
2570 SpinLockRelease(&XLogCtl->info_lck);
2572 /* done already? */
2573 if (record <= LogwrtResult.Flush)
2574 break;
2577 * Before actually performing the write, wait for all in-flight
2578 * insertions to the pages we're about to write to finish.
2580 insertpos = WaitXLogInsertionsToFinish(WriteRqstPtr);
2583 * Try to get the write lock. If we can't get it immediately, wait
2584 * until it's released, and recheck if we still need to do the flush
2585 * or if the backend that held the lock did it for us already. This
2586 * helps to maintain a good rate of group committing when the system
2587 * is bottlenecked by the speed of fsyncing.
2589 if (!LWLockAcquireOrWait(WALWriteLock, LW_EXCLUSIVE))
2592 * The lock is now free, but we didn't acquire it yet. Before we
2593 * do, loop back to check if someone else flushed the record for
2594 * us already.
2596 continue;
2599 /* Got the lock; recheck whether request is satisfied */
2600 LogwrtResult = XLogCtl->LogwrtResult;
2601 if (record <= LogwrtResult.Flush)
2603 LWLockRelease(WALWriteLock);
2604 break;
2608 * Sleep before flush! By adding a delay here, we may give further
2609 * backends the opportunity to join the backlog of group commit
2610 * followers; this can significantly improve transaction throughput,
2611 * at the risk of increasing transaction latency.
2613 * We do not sleep if enableFsync is not turned on, nor if there are
2614 * fewer than CommitSiblings other backends with active transactions.
2616 if (CommitDelay > 0 && enableFsync &&
2617 MinimumActiveBackends(CommitSiblings))
2619 pg_usleep(CommitDelay);
2622 * Re-check how far we can now flush the WAL. It's generally not
2623 * safe to call WaitXLogInsertionsToFinish while holding
2624 * WALWriteLock, because an in-progress insertion might need to
2625 * also grab WALWriteLock to make progress. But we know that all
2626 * the insertions up to insertpos have already finished, because
2627 * that's what the earlier WaitXLogInsertionsToFinish() returned.
2628 * We're only calling it again to allow insertpos to be moved
2629 * further forward, not to actually wait for anyone.
2631 insertpos = WaitXLogInsertionsToFinish(insertpos);
2634 /* try to write/flush later additions to XLOG as well */
2635 WriteRqst.Write = insertpos;
2636 WriteRqst.Flush = insertpos;
2638 XLogWrite(WriteRqst, insertTLI, false);
2640 LWLockRelease(WALWriteLock);
2641 /* done */
2642 break;
2645 END_CRIT_SECTION();
2647 /* wake up walsenders now that we've released heavily contended locks */
2648 WalSndWakeupProcessRequests();
2651 * If we still haven't flushed to the request point then we have a
2652 * problem; most likely, the requested flush point is past end of XLOG.
2653 * This has been seen to occur when a disk page has a corrupted LSN.
2655 * Formerly we treated this as a PANIC condition, but that hurts the
2656 * system's robustness rather than helping it: we do not want to take down
2657 * the whole system due to corruption on one data page. In particular, if
2658 * the bad page is encountered again during recovery then we would be
2659 * unable to restart the database at all! (This scenario actually
2660 * happened in the field several times with 7.1 releases.) As of 8.4, bad
2661 * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
2662 * the only time we can reach here during recovery is while flushing the
2663 * end-of-recovery checkpoint record, and we don't expect that to have a
2664 * bad LSN.
2666 * Note that for calls from xact.c, the ERROR will be promoted to PANIC
2667 * since xact.c calls this routine inside a critical section. However,
2668 * calls from bufmgr.c are not within critical sections and so we will not
2669 * force a restart for a bad LSN on a data page.
2671 if (LogwrtResult.Flush < record)
2672 elog(ERROR,
2673 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
2674 LSN_FORMAT_ARGS(record),
2675 LSN_FORMAT_ARGS(LogwrtResult.Flush));
2679 * Write & flush xlog, but without specifying exactly where to.
2681 * We normally write only completed blocks; but if there is nothing to do on
2682 * that basis, we check for unwritten async commits in the current incomplete
2683 * block, and write through the latest one of those. Thus, if async commits
2684 * are not being used, we will write complete blocks only.
2686 * If, based on the above, there's anything to write we do so immediately. But
2687 * to avoid calling fsync, fdatasync et. al. at a rate that'd impact
2688 * concurrent IO, we only flush WAL every wal_writer_delay ms, or if there's
2689 * more than wal_writer_flush_after unflushed blocks.
2691 * We can guarantee that async commits reach disk after at most three
2692 * wal_writer_delay cycles. (When flushing complete blocks, we allow XLogWrite
2693 * to write "flexibly", meaning it can stop at the end of the buffer ring;
2694 * this makes a difference only with very high load or long wal_writer_delay,
2695 * but imposes one extra cycle for the worst case for async commits.)
2697 * This routine is invoked periodically by the background walwriter process.
2699 * Returns true if there was any work to do, even if we skipped flushing due
2700 * to wal_writer_delay/wal_writer_flush_after.
2702 bool
2703 XLogBackgroundFlush(void)
2705 XLogwrtRqst WriteRqst;
2706 bool flexible = true;
2707 static TimestampTz lastflush;
2708 TimestampTz now;
2709 int flushbytes;
2710 TimeLineID insertTLI;
2712 /* XLOG doesn't need flushing during recovery */
2713 if (RecoveryInProgress())
2714 return false;
2717 * Since we're not in recovery, InsertTimeLineID is set and can't change,
2718 * so we can read it without a lock.
2720 insertTLI = XLogCtl->InsertTimeLineID;
2722 /* read LogwrtResult and update local state */
2723 SpinLockAcquire(&XLogCtl->info_lck);
2724 LogwrtResult = XLogCtl->LogwrtResult;
2725 WriteRqst = XLogCtl->LogwrtRqst;
2726 SpinLockRelease(&XLogCtl->info_lck);
2728 /* back off to last completed page boundary */
2729 WriteRqst.Write -= WriteRqst.Write % XLOG_BLCKSZ;
2731 /* if we have already flushed that far, consider async commit records */
2732 if (WriteRqst.Write <= LogwrtResult.Flush)
2734 SpinLockAcquire(&XLogCtl->info_lck);
2735 WriteRqst.Write = XLogCtl->asyncXactLSN;
2736 SpinLockRelease(&XLogCtl->info_lck);
2737 flexible = false; /* ensure it all gets written */
2741 * If already known flushed, we're done. Just need to check if we are
2742 * holding an open file handle to a logfile that's no longer in use,
2743 * preventing the file from being deleted.
2745 if (WriteRqst.Write <= LogwrtResult.Flush)
2747 if (openLogFile >= 0)
2749 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
2750 wal_segment_size))
2752 XLogFileClose();
2755 return false;
2759 * Determine how far to flush WAL, based on the wal_writer_delay and
2760 * wal_writer_flush_after GUCs.
2762 now = GetCurrentTimestamp();
2763 flushbytes =
2764 WriteRqst.Write / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
2766 if (WalWriterFlushAfter == 0 || lastflush == 0)
2768 /* first call, or block based limits disabled */
2769 WriteRqst.Flush = WriteRqst.Write;
2770 lastflush = now;
2772 else if (TimestampDifferenceExceeds(lastflush, now, WalWriterDelay))
2775 * Flush the writes at least every WalWriterDelay ms. This is
2776 * important to bound the amount of time it takes for an asynchronous
2777 * commit to hit disk.
2779 WriteRqst.Flush = WriteRqst.Write;
2780 lastflush = now;
2782 else if (flushbytes >= WalWriterFlushAfter)
2784 /* exceeded wal_writer_flush_after blocks, flush */
2785 WriteRqst.Flush = WriteRqst.Write;
2786 lastflush = now;
2788 else
2790 /* no flushing, this time round */
2791 WriteRqst.Flush = 0;
2794 #ifdef WAL_DEBUG
2795 if (XLOG_DEBUG)
2796 elog(LOG, "xlog bg flush request write %X/%X; flush: %X/%X, current is write %X/%X; flush %X/%X",
2797 LSN_FORMAT_ARGS(WriteRqst.Write),
2798 LSN_FORMAT_ARGS(WriteRqst.Flush),
2799 LSN_FORMAT_ARGS(LogwrtResult.Write),
2800 LSN_FORMAT_ARGS(LogwrtResult.Flush));
2801 #endif
2803 START_CRIT_SECTION();
2805 /* now wait for any in-progress insertions to finish and get write lock */
2806 WaitXLogInsertionsToFinish(WriteRqst.Write);
2807 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2808 LogwrtResult = XLogCtl->LogwrtResult;
2809 if (WriteRqst.Write > LogwrtResult.Write ||
2810 WriteRqst.Flush > LogwrtResult.Flush)
2812 XLogWrite(WriteRqst, insertTLI, flexible);
2814 LWLockRelease(WALWriteLock);
2816 END_CRIT_SECTION();
2818 /* wake up walsenders now that we've released heavily contended locks */
2819 WalSndWakeupProcessRequests();
2822 * Great, done. To take some work off the critical path, try to initialize
2823 * as many of the no-longer-needed WAL buffers for future use as we can.
2825 AdvanceXLInsertBuffer(InvalidXLogRecPtr, insertTLI, true);
2828 * If we determined that we need to write data, but somebody else
2829 * wrote/flushed already, it should be considered as being active, to
2830 * avoid hibernating too early.
2832 return true;
2836 * Test whether XLOG data has been flushed up to (at least) the given position.
2838 * Returns true if a flush is still needed. (It may be that someone else
2839 * is already in process of flushing that far, however.)
2841 bool
2842 XLogNeedsFlush(XLogRecPtr record)
2845 * During recovery, we don't flush WAL but update minRecoveryPoint
2846 * instead. So "needs flush" is taken to mean whether minRecoveryPoint
2847 * would need to be updated.
2849 if (RecoveryInProgress())
2852 * An invalid minRecoveryPoint means that we need to recover all the
2853 * WAL, i.e., we're doing crash recovery. We never modify the control
2854 * file's value in that case, so we can short-circuit future checks
2855 * here too. This triggers a quick exit path for the startup process,
2856 * which cannot update its local copy of minRecoveryPoint as long as
2857 * it has not replayed all WAL available when doing crash recovery.
2859 if (XLogRecPtrIsInvalid(LocalMinRecoveryPoint) && InRecovery)
2860 updateMinRecoveryPoint = false;
2862 /* Quick exit if already known to be updated or cannot be updated */
2863 if (record <= LocalMinRecoveryPoint || !updateMinRecoveryPoint)
2864 return false;
2867 * Update local copy of minRecoveryPoint. But if the lock is busy,
2868 * just return a conservative guess.
2870 if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
2871 return true;
2872 LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
2873 LocalMinRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
2874 LWLockRelease(ControlFileLock);
2877 * Check minRecoveryPoint for any other process than the startup
2878 * process doing crash recovery, which should not update the control
2879 * file value if crash recovery is still running.
2881 if (XLogRecPtrIsInvalid(LocalMinRecoveryPoint))
2882 updateMinRecoveryPoint = false;
2884 /* check again */
2885 if (record <= LocalMinRecoveryPoint || !updateMinRecoveryPoint)
2886 return false;
2887 else
2888 return true;
2891 /* Quick exit if already known flushed */
2892 if (record <= LogwrtResult.Flush)
2893 return false;
2895 /* read LogwrtResult and update local state */
2896 SpinLockAcquire(&XLogCtl->info_lck);
2897 LogwrtResult = XLogCtl->LogwrtResult;
2898 SpinLockRelease(&XLogCtl->info_lck);
2900 /* check again */
2901 if (record <= LogwrtResult.Flush)
2902 return false;
2904 return true;
2908 * Try to make a given XLOG file segment exist.
2910 * logsegno: identify segment.
2912 * *added: on return, true if this call raised the number of extant segments.
2914 * path: on return, this char[MAXPGPATH] has the path to the logsegno file.
2916 * Returns -1 or FD of opened file. A -1 here is not an error; a caller
2917 * wanting an open segment should attempt to open "path", which usually will
2918 * succeed. (This is weird, but it's efficient for the callers.)
2920 static int
2921 XLogFileInitInternal(XLogSegNo logsegno, TimeLineID logtli,
2922 bool *added, char *path)
2924 char tmppath[MAXPGPATH];
2925 XLogSegNo installed_segno;
2926 XLogSegNo max_segno;
2927 int fd;
2928 int save_errno;
2930 Assert(logtli != 0);
2932 XLogFilePath(path, logtli, logsegno, wal_segment_size);
2935 * Try to use existent file (checkpoint maker may have created it already)
2937 *added = false;
2938 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
2939 if (fd < 0)
2941 if (errno != ENOENT)
2942 ereport(ERROR,
2943 (errcode_for_file_access(),
2944 errmsg("could not open file \"%s\": %m", path)));
2946 else
2947 return fd;
2950 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
2951 * another process is doing the same thing. If so, we will end up
2952 * pre-creating an extra log segment. That seems OK, and better than
2953 * holding the lock throughout this lengthy process.
2955 elog(DEBUG2, "creating and filling new WAL file");
2957 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2959 unlink(tmppath);
2961 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
2962 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
2963 if (fd < 0)
2964 ereport(ERROR,
2965 (errcode_for_file_access(),
2966 errmsg("could not create file \"%s\": %m", tmppath)));
2968 pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_WRITE);
2969 save_errno = 0;
2970 if (wal_init_zero)
2972 ssize_t rc;
2975 * Zero-fill the file. With this setting, we do this the hard way to
2976 * ensure that all the file space has really been allocated. On
2977 * platforms that allow "holes" in files, just seeking to the end
2978 * doesn't allocate intermediate space. This way, we know that we
2979 * have all the space and (after the fsync below) that all the
2980 * indirect blocks are down on disk. Therefore, fdatasync(2) or
2981 * O_DSYNC will be sufficient to sync future writes to the log file.
2983 rc = pg_pwrite_zeros(fd, wal_segment_size);
2985 if (rc < 0)
2986 save_errno = errno;
2988 else
2991 * Otherwise, seeking to the end and writing a solitary byte is
2992 * enough.
2994 errno = 0;
2995 if (pg_pwrite(fd, "\0", 1, wal_segment_size - 1) != 1)
2997 /* if write didn't set errno, assume no disk space */
2998 save_errno = errno ? errno : ENOSPC;
3001 pgstat_report_wait_end();
3003 if (save_errno)
3006 * If we fail to make the file, delete it to release disk space
3008 unlink(tmppath);
3010 close(fd);
3012 errno = save_errno;
3014 ereport(ERROR,
3015 (errcode_for_file_access(),
3016 errmsg("could not write to file \"%s\": %m", tmppath)));
3019 pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_SYNC);
3020 if (pg_fsync(fd) != 0)
3022 save_errno = errno;
3023 close(fd);
3024 errno = save_errno;
3025 ereport(ERROR,
3026 (errcode_for_file_access(),
3027 errmsg("could not fsync file \"%s\": %m", tmppath)));
3029 pgstat_report_wait_end();
3031 if (close(fd) != 0)
3032 ereport(ERROR,
3033 (errcode_for_file_access(),
3034 errmsg("could not close file \"%s\": %m", tmppath)));
3037 * Now move the segment into place with its final name. Cope with
3038 * possibility that someone else has created the file while we were
3039 * filling ours: if so, use ours to pre-create a future log segment.
3041 installed_segno = logsegno;
3044 * XXX: What should we use as max_segno? We used to use XLOGfileslop when
3045 * that was a constant, but that was always a bit dubious: normally, at a
3046 * checkpoint, XLOGfileslop was the offset from the checkpoint record, but
3047 * here, it was the offset from the insert location. We can't do the
3048 * normal XLOGfileslop calculation here because we don't have access to
3049 * the prior checkpoint's redo location. So somewhat arbitrarily, just use
3050 * CheckPointSegments.
3052 max_segno = logsegno + CheckPointSegments;
3053 if (InstallXLogFileSegment(&installed_segno, tmppath, true, max_segno,
3054 logtli))
3056 *added = true;
3057 elog(DEBUG2, "done creating and filling new WAL file");
3059 else
3062 * No need for any more future segments, or InstallXLogFileSegment()
3063 * failed to rename the file into place. If the rename failed, a
3064 * caller opening the file may fail.
3066 unlink(tmppath);
3067 elog(DEBUG2, "abandoned new WAL file");
3070 return -1;
3074 * Create a new XLOG file segment, or open a pre-existing one.
3076 * logsegno: identify segment to be created/opened.
3078 * Returns FD of opened file.
3080 * Note: errors here are ERROR not PANIC because we might or might not be
3081 * inside a critical section (eg, during checkpoint there is no reason to
3082 * take down the system on failure). They will promote to PANIC if we are
3083 * in a critical section.
3086 XLogFileInit(XLogSegNo logsegno, TimeLineID logtli)
3088 bool ignore_added;
3089 char path[MAXPGPATH];
3090 int fd;
3092 Assert(logtli != 0);
3094 fd = XLogFileInitInternal(logsegno, logtli, &ignore_added, path);
3095 if (fd >= 0)
3096 return fd;
3098 /* Now open original target segment (might not be file I just made) */
3099 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
3100 if (fd < 0)
3101 ereport(ERROR,
3102 (errcode_for_file_access(),
3103 errmsg("could not open file \"%s\": %m", path)));
3104 return fd;
3108 * Create a new XLOG file segment by copying a pre-existing one.
3110 * destsegno: identify segment to be created.
3112 * srcTLI, srcsegno: identify segment to be copied (could be from
3113 * a different timeline)
3115 * upto: how much of the source file to copy (the rest is filled with
3116 * zeros)
3118 * Currently this is only used during recovery, and so there are no locking
3119 * considerations. But we should be just as tense as XLogFileInit to avoid
3120 * emplacing a bogus file.
3122 static void
3123 XLogFileCopy(TimeLineID destTLI, XLogSegNo destsegno,
3124 TimeLineID srcTLI, XLogSegNo srcsegno,
3125 int upto)
3127 char path[MAXPGPATH];
3128 char tmppath[MAXPGPATH];
3129 PGAlignedXLogBlock buffer;
3130 int srcfd;
3131 int fd;
3132 int nbytes;
3135 * Open the source file
3137 XLogFilePath(path, srcTLI, srcsegno, wal_segment_size);
3138 srcfd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3139 if (srcfd < 0)
3140 ereport(ERROR,
3141 (errcode_for_file_access(),
3142 errmsg("could not open file \"%s\": %m", path)));
3145 * Copy into a temp file name.
3147 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3149 unlink(tmppath);
3151 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3152 fd = OpenTransientFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3153 if (fd < 0)
3154 ereport(ERROR,
3155 (errcode_for_file_access(),
3156 errmsg("could not create file \"%s\": %m", tmppath)));
3159 * Do the data copying.
3161 for (nbytes = 0; nbytes < wal_segment_size; nbytes += sizeof(buffer))
3163 int nread;
3165 nread = upto - nbytes;
3168 * The part that is not read from the source file is filled with
3169 * zeros.
3171 if (nread < sizeof(buffer))
3172 memset(buffer.data, 0, sizeof(buffer));
3174 if (nread > 0)
3176 int r;
3178 if (nread > sizeof(buffer))
3179 nread = sizeof(buffer);
3180 pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_READ);
3181 r = read(srcfd, buffer.data, nread);
3182 if (r != nread)
3184 if (r < 0)
3185 ereport(ERROR,
3186 (errcode_for_file_access(),
3187 errmsg("could not read file \"%s\": %m",
3188 path)));
3189 else
3190 ereport(ERROR,
3191 (errcode(ERRCODE_DATA_CORRUPTED),
3192 errmsg("could not read file \"%s\": read %d of %zu",
3193 path, r, (Size) nread)));
3195 pgstat_report_wait_end();
3197 errno = 0;
3198 pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_WRITE);
3199 if ((int) write(fd, buffer.data, sizeof(buffer)) != (int) sizeof(buffer))
3201 int save_errno = errno;
3204 * If we fail to make the file, delete it to release disk space
3206 unlink(tmppath);
3207 /* if write didn't set errno, assume problem is no disk space */
3208 errno = save_errno ? save_errno : ENOSPC;
3210 ereport(ERROR,
3211 (errcode_for_file_access(),
3212 errmsg("could not write to file \"%s\": %m", tmppath)));
3214 pgstat_report_wait_end();
3217 pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_SYNC);
3218 if (pg_fsync(fd) != 0)
3219 ereport(data_sync_elevel(ERROR),
3220 (errcode_for_file_access(),
3221 errmsg("could not fsync file \"%s\": %m", tmppath)));
3222 pgstat_report_wait_end();
3224 if (CloseTransientFile(fd) != 0)
3225 ereport(ERROR,
3226 (errcode_for_file_access(),
3227 errmsg("could not close file \"%s\": %m", tmppath)));
3229 if (CloseTransientFile(srcfd) != 0)
3230 ereport(ERROR,
3231 (errcode_for_file_access(),
3232 errmsg("could not close file \"%s\": %m", path)));
3235 * Now move the segment into place with its final name.
3237 if (!InstallXLogFileSegment(&destsegno, tmppath, false, 0, destTLI))
3238 elog(ERROR, "InstallXLogFileSegment should not have failed");
3242 * Install a new XLOG segment file as a current or future log segment.
3244 * This is used both to install a newly-created segment (which has a temp
3245 * filename while it's being created) and to recycle an old segment.
3247 * *segno: identify segment to install as (or first possible target).
3248 * When find_free is true, this is modified on return to indicate the
3249 * actual installation location or last segment searched.
3251 * tmppath: initial name of file to install. It will be renamed into place.
3253 * find_free: if true, install the new segment at the first empty segno
3254 * number at or after the passed numbers. If false, install the new segment
3255 * exactly where specified, deleting any existing segment file there.
3257 * max_segno: maximum segment number to install the new file as. Fail if no
3258 * free slot is found between *segno and max_segno. (Ignored when find_free
3259 * is false.)
3261 * tli: The timeline on which the new segment should be installed.
3263 * Returns true if the file was installed successfully. false indicates that
3264 * max_segno limit was exceeded, the startup process has disabled this
3265 * function for now, or an error occurred while renaming the file into place.
3267 static bool
3268 InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
3269 bool find_free, XLogSegNo max_segno, TimeLineID tli)
3271 char path[MAXPGPATH];
3272 struct stat stat_buf;
3274 Assert(tli != 0);
3276 XLogFilePath(path, tli, *segno, wal_segment_size);
3278 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3279 if (!XLogCtl->InstallXLogFileSegmentActive)
3281 LWLockRelease(ControlFileLock);
3282 return false;
3285 if (!find_free)
3287 /* Force installation: get rid of any pre-existing segment file */
3288 durable_unlink(path, DEBUG1);
3290 else
3292 /* Find a free slot to put it in */
3293 while (stat(path, &stat_buf) == 0)
3295 if ((*segno) >= max_segno)
3297 /* Failed to find a free slot within specified range */
3298 LWLockRelease(ControlFileLock);
3299 return false;
3301 (*segno)++;
3302 XLogFilePath(path, tli, *segno, wal_segment_size);
3306 Assert(access(path, F_OK) != 0 && errno == ENOENT);
3307 if (durable_rename(tmppath, path, LOG) != 0)
3309 LWLockRelease(ControlFileLock);
3310 /* durable_rename already emitted log message */
3311 return false;
3314 LWLockRelease(ControlFileLock);
3316 return true;
3320 * Open a pre-existing logfile segment for writing.
3323 XLogFileOpen(XLogSegNo segno, TimeLineID tli)
3325 char path[MAXPGPATH];
3326 int fd;
3328 XLogFilePath(path, tli, segno, wal_segment_size);
3330 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
3331 if (fd < 0)
3332 ereport(PANIC,
3333 (errcode_for_file_access(),
3334 errmsg("could not open file \"%s\": %m", path)));
3336 return fd;
3340 * Close the current logfile segment for writing.
3342 static void
3343 XLogFileClose(void)
3345 Assert(openLogFile >= 0);
3348 * WAL segment files will not be re-read in normal operation, so we advise
3349 * the OS to release any cached pages. But do not do so if WAL archiving
3350 * or streaming is active, because archiver and walsender process could
3351 * use the cache to read the WAL segment.
3353 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3354 if (!XLogIsNeeded())
3355 (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3356 #endif
3358 if (close(openLogFile) != 0)
3360 char xlogfname[MAXFNAMELEN];
3361 int save_errno = errno;
3363 XLogFileName(xlogfname, openLogTLI, openLogSegNo, wal_segment_size);
3364 errno = save_errno;
3365 ereport(PANIC,
3366 (errcode_for_file_access(),
3367 errmsg("could not close file \"%s\": %m", xlogfname)));
3370 openLogFile = -1;
3371 ReleaseExternalFD();
3375 * Preallocate log files beyond the specified log endpoint.
3377 * XXX this is currently extremely conservative, since it forces only one
3378 * future log segment to exist, and even that only if we are 75% done with
3379 * the current one. This is only appropriate for very low-WAL-volume systems.
3380 * High-volume systems will be OK once they've built up a sufficient set of
3381 * recycled log segments, but the startup transient is likely to include
3382 * a lot of segment creations by foreground processes, which is not so good.
3384 * XLogFileInitInternal() can ereport(ERROR). All known causes indicate big
3385 * trouble; for example, a full filesystem is one cause. The checkpoint WAL
3386 * and/or ControlFile updates already completed. If a RequestCheckpoint()
3387 * initiated the present checkpoint and an ERROR ends this function, the
3388 * command that called RequestCheckpoint() fails. That's not ideal, but it's
3389 * not worth contorting more functions to use caller-specified elevel values.
3390 * (With or without RequestCheckpoint(), an ERROR forestalls some inessential
3391 * reporting and resource reclamation.)
3393 static void
3394 PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli)
3396 XLogSegNo _logSegNo;
3397 int lf;
3398 bool added;
3399 char path[MAXPGPATH];
3400 uint64 offset;
3402 if (!XLogCtl->InstallXLogFileSegmentActive)
3403 return; /* unlocked check says no */
3405 XLByteToPrevSeg(endptr, _logSegNo, wal_segment_size);
3406 offset = XLogSegmentOffset(endptr - 1, wal_segment_size);
3407 if (offset >= (uint32) (0.75 * wal_segment_size))
3409 _logSegNo++;
3410 lf = XLogFileInitInternal(_logSegNo, tli, &added, path);
3411 if (lf >= 0)
3412 close(lf);
3413 if (added)
3414 CheckpointStats.ckpt_segs_added++;
3419 * Throws an error if the given log segment has already been removed or
3420 * recycled. The caller should only pass a segment that it knows to have
3421 * existed while the server has been running, as this function always
3422 * succeeds if no WAL segments have been removed since startup.
3423 * 'tli' is only used in the error message.
3425 * Note: this function guarantees to keep errno unchanged on return.
3426 * This supports callers that use this to possibly deliver a better
3427 * error message about a missing file, while still being able to throw
3428 * a normal file-access error afterwards, if this does return.
3430 void
3431 CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
3433 int save_errno = errno;
3434 XLogSegNo lastRemovedSegNo;
3436 SpinLockAcquire(&XLogCtl->info_lck);
3437 lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3438 SpinLockRelease(&XLogCtl->info_lck);
3440 if (segno <= lastRemovedSegNo)
3442 char filename[MAXFNAMELEN];
3444 XLogFileName(filename, tli, segno, wal_segment_size);
3445 errno = save_errno;
3446 ereport(ERROR,
3447 (errcode_for_file_access(),
3448 errmsg("requested WAL segment %s has already been removed",
3449 filename)));
3451 errno = save_errno;
3455 * Return the last WAL segment removed, or 0 if no segment has been removed
3456 * since startup.
3458 * NB: the result can be out of date arbitrarily fast, the caller has to deal
3459 * with that.
3461 XLogSegNo
3462 XLogGetLastRemovedSegno(void)
3464 XLogSegNo lastRemovedSegNo;
3466 SpinLockAcquire(&XLogCtl->info_lck);
3467 lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3468 SpinLockRelease(&XLogCtl->info_lck);
3470 return lastRemovedSegNo;
3475 * Update the last removed segno pointer in shared memory, to reflect that the
3476 * given XLOG file has been removed.
3478 static void
3479 UpdateLastRemovedPtr(char *filename)
3481 uint32 tli;
3482 XLogSegNo segno;
3484 XLogFromFileName(filename, &tli, &segno, wal_segment_size);
3486 SpinLockAcquire(&XLogCtl->info_lck);
3487 if (segno > XLogCtl->lastRemovedSegNo)
3488 XLogCtl->lastRemovedSegNo = segno;
3489 SpinLockRelease(&XLogCtl->info_lck);
3493 * Remove all temporary log files in pg_wal
3495 * This is called at the beginning of recovery after a previous crash,
3496 * at a point where no other processes write fresh WAL data.
3498 static void
3499 RemoveTempXlogFiles(void)
3501 DIR *xldir;
3502 struct dirent *xlde;
3504 elog(DEBUG2, "removing all temporary WAL segments");
3506 xldir = AllocateDir(XLOGDIR);
3507 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3509 char path[MAXPGPATH];
3511 if (strncmp(xlde->d_name, "xlogtemp.", 9) != 0)
3512 continue;
3514 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3515 unlink(path);
3516 elog(DEBUG2, "removed temporary WAL segment \"%s\"", path);
3518 FreeDir(xldir);
3522 * Recycle or remove all log files older or equal to passed segno.
3524 * endptr is current (or recent) end of xlog, and lastredoptr is the
3525 * redo pointer of the last checkpoint. These are used to determine
3526 * whether we want to recycle rather than delete no-longer-wanted log files.
3528 * insertTLI is the current timeline for XLOG insertion. Any recycled
3529 * segments should be reused for this timeline.
3531 static void
3532 RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr,
3533 TimeLineID insertTLI)
3535 DIR *xldir;
3536 struct dirent *xlde;
3537 char lastoff[MAXFNAMELEN];
3538 XLogSegNo endlogSegNo;
3539 XLogSegNo recycleSegNo;
3541 /* Initialize info about where to try to recycle to */
3542 XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
3543 recycleSegNo = XLOGfileslop(lastredoptr);
3546 * Construct a filename of the last segment to be kept. The timeline ID
3547 * doesn't matter, we ignore that in the comparison. (During recovery,
3548 * InsertTimeLineID isn't set, so we can't use that.)
3550 XLogFileName(lastoff, 0, segno, wal_segment_size);
3552 elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
3553 lastoff);
3555 xldir = AllocateDir(XLOGDIR);
3557 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3559 /* Ignore files that are not XLOG segments */
3560 if (!IsXLogFileName(xlde->d_name) &&
3561 !IsPartialXLogFileName(xlde->d_name))
3562 continue;
3565 * We ignore the timeline part of the XLOG segment identifiers in
3566 * deciding whether a segment is still needed. This ensures that we
3567 * won't prematurely remove a segment from a parent timeline. We could
3568 * probably be a little more proactive about removing segments of
3569 * non-parent timelines, but that would be a whole lot more
3570 * complicated.
3572 * We use the alphanumeric sorting property of the filenames to decide
3573 * which ones are earlier than the lastoff segment.
3575 if (strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
3577 if (XLogArchiveCheckDone(xlde->d_name))
3579 /* Update the last removed location in shared memory first */
3580 UpdateLastRemovedPtr(xlde->d_name);
3582 RemoveXlogFile(xlde, recycleSegNo, &endlogSegNo, insertTLI);
3587 FreeDir(xldir);
3591 * Remove WAL files that are not part of the given timeline's history.
3593 * This is called during recovery, whenever we switch to follow a new
3594 * timeline, and at the end of recovery when we create a new timeline. We
3595 * wouldn't otherwise care about extra WAL files lying in pg_wal, but they
3596 * might be leftover pre-allocated or recycled WAL segments on the old timeline
3597 * that we haven't used yet, and contain garbage. If we just leave them in
3598 * pg_wal, they will eventually be archived, and we can't let that happen.
3599 * Files that belong to our timeline history are valid, because we have
3600 * successfully replayed them, but from others we can't be sure.
3602 * 'switchpoint' is the current point in WAL where we switch to new timeline,
3603 * and 'newTLI' is the new timeline we switch to.
3605 void
3606 RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
3608 DIR *xldir;
3609 struct dirent *xlde;
3610 char switchseg[MAXFNAMELEN];
3611 XLogSegNo endLogSegNo;
3612 XLogSegNo switchLogSegNo;
3613 XLogSegNo recycleSegNo;
3616 * Initialize info about where to begin the work. This will recycle,
3617 * somewhat arbitrarily, 10 future segments.
3619 XLByteToPrevSeg(switchpoint, switchLogSegNo, wal_segment_size);
3620 XLByteToSeg(switchpoint, endLogSegNo, wal_segment_size);
3621 recycleSegNo = endLogSegNo + 10;
3624 * Construct a filename of the last segment to be kept.
3626 XLogFileName(switchseg, newTLI, switchLogSegNo, wal_segment_size);
3628 elog(DEBUG2, "attempting to remove WAL segments newer than log file %s",
3629 switchseg);
3631 xldir = AllocateDir(XLOGDIR);
3633 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3635 /* Ignore files that are not XLOG segments */
3636 if (!IsXLogFileName(xlde->d_name))
3637 continue;
3640 * Remove files that are on a timeline older than the new one we're
3641 * switching to, but with a segment number >= the first segment on the
3642 * new timeline.
3644 if (strncmp(xlde->d_name, switchseg, 8) < 0 &&
3645 strcmp(xlde->d_name + 8, switchseg + 8) > 0)
3648 * If the file has already been marked as .ready, however, don't
3649 * remove it yet. It should be OK to remove it - files that are
3650 * not part of our timeline history are not required for recovery
3651 * - but seems safer to let them be archived and removed later.
3653 if (!XLogArchiveIsReady(xlde->d_name))
3654 RemoveXlogFile(xlde, recycleSegNo, &endLogSegNo, newTLI);
3658 FreeDir(xldir);
3662 * Recycle or remove a log file that's no longer needed.
3664 * segment_de is the dirent structure of the segment to recycle or remove.
3665 * recycleSegNo is the segment number to recycle up to. endlogSegNo is
3666 * the segment number of the current (or recent) end of WAL.
3668 * endlogSegNo gets incremented if the segment is recycled so as it is not
3669 * checked again with future callers of this function.
3671 * insertTLI is the current timeline for XLOG insertion. Any recycled segments
3672 * should be used for this timeline.
3674 static void
3675 RemoveXlogFile(const struct dirent *segment_de,
3676 XLogSegNo recycleSegNo, XLogSegNo *endlogSegNo,
3677 TimeLineID insertTLI)
3679 char path[MAXPGPATH];
3680 #ifdef WIN32
3681 char newpath[MAXPGPATH];
3682 #endif
3683 const char *segname = segment_de->d_name;
3685 snprintf(path, MAXPGPATH, XLOGDIR "/%s", segname);
3688 * Before deleting the file, see if it can be recycled as a future log
3689 * segment. Only recycle normal files, because we don't want to recycle
3690 * symbolic links pointing to a separate archive directory.
3692 if (wal_recycle &&
3693 *endlogSegNo <= recycleSegNo &&
3694 XLogCtl->InstallXLogFileSegmentActive && /* callee rechecks this */
3695 get_dirent_type(path, segment_de, false, DEBUG2) == PGFILETYPE_REG &&
3696 InstallXLogFileSegment(endlogSegNo, path,
3697 true, recycleSegNo, insertTLI))
3699 ereport(DEBUG2,
3700 (errmsg_internal("recycled write-ahead log file \"%s\"",
3701 segname)));
3702 CheckpointStats.ckpt_segs_recycled++;
3703 /* Needn't recheck that slot on future iterations */
3704 (*endlogSegNo)++;
3706 else
3708 /* No need for any more future segments, or recycling failed ... */
3709 int rc;
3711 ereport(DEBUG2,
3712 (errmsg_internal("removing write-ahead log file \"%s\"",
3713 segname)));
3715 #ifdef WIN32
3718 * On Windows, if another process (e.g another backend) holds the file
3719 * open in FILE_SHARE_DELETE mode, unlink will succeed, but the file
3720 * will still show up in directory listing until the last handle is
3721 * closed. To avoid confusing the lingering deleted file for a live
3722 * WAL file that needs to be archived, rename it before deleting it.
3724 * If another process holds the file open without FILE_SHARE_DELETE
3725 * flag, rename will fail. We'll try again at the next checkpoint.
3727 snprintf(newpath, MAXPGPATH, "%s.deleted", path);
3728 if (rename(path, newpath) != 0)
3730 ereport(LOG,
3731 (errcode_for_file_access(),
3732 errmsg("could not rename file \"%s\": %m",
3733 path)));
3734 return;
3736 rc = durable_unlink(newpath, LOG);
3737 #else
3738 rc = durable_unlink(path, LOG);
3739 #endif
3740 if (rc != 0)
3742 /* Message already logged by durable_unlink() */
3743 return;
3745 CheckpointStats.ckpt_segs_removed++;
3748 XLogArchiveCleanup(segname);
3752 * Verify whether pg_wal and pg_wal/archive_status exist.
3753 * If the latter does not exist, recreate it.
3755 * It is not the goal of this function to verify the contents of these
3756 * directories, but to help in cases where someone has performed a cluster
3757 * copy for PITR purposes but omitted pg_wal from the copy.
3759 * We could also recreate pg_wal if it doesn't exist, but a deliberate
3760 * policy decision was made not to. It is fairly common for pg_wal to be
3761 * a symlink, and if that was the DBA's intent then automatically making a
3762 * plain directory would result in degraded performance with no notice.
3764 static void
3765 ValidateXLOGDirectoryStructure(void)
3767 char path[MAXPGPATH];
3768 struct stat stat_buf;
3770 /* Check for pg_wal; if it doesn't exist, error out */
3771 if (stat(XLOGDIR, &stat_buf) != 0 ||
3772 !S_ISDIR(stat_buf.st_mode))
3773 ereport(FATAL,
3774 (errmsg("required WAL directory \"%s\" does not exist",
3775 XLOGDIR)));
3777 /* Check for archive_status */
3778 snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
3779 if (stat(path, &stat_buf) == 0)
3781 /* Check for weird cases where it exists but isn't a directory */
3782 if (!S_ISDIR(stat_buf.st_mode))
3783 ereport(FATAL,
3784 (errmsg("required WAL directory \"%s\" does not exist",
3785 path)));
3787 else
3789 ereport(LOG,
3790 (errmsg("creating missing WAL directory \"%s\"", path)));
3791 if (MakePGDirectory(path) < 0)
3792 ereport(FATAL,
3793 (errmsg("could not create missing directory \"%s\": %m",
3794 path)));
3799 * Remove previous backup history files. This also retries creation of
3800 * .ready files for any backup history files for which XLogArchiveNotify
3801 * failed earlier.
3803 static void
3804 CleanupBackupHistory(void)
3806 DIR *xldir;
3807 struct dirent *xlde;
3808 char path[MAXPGPATH + sizeof(XLOGDIR)];
3810 xldir = AllocateDir(XLOGDIR);
3812 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3814 if (IsBackupHistoryFileName(xlde->d_name))
3816 if (XLogArchiveCheckDone(xlde->d_name))
3818 elog(DEBUG2, "removing WAL backup history file \"%s\"",
3819 xlde->d_name);
3820 snprintf(path, sizeof(path), XLOGDIR "/%s", xlde->d_name);
3821 unlink(path);
3822 XLogArchiveCleanup(xlde->d_name);
3827 FreeDir(xldir);
3831 * I/O routines for pg_control
3833 * *ControlFile is a buffer in shared memory that holds an image of the
3834 * contents of pg_control. WriteControlFile() initializes pg_control
3835 * given a preloaded buffer, ReadControlFile() loads the buffer from
3836 * the pg_control file (during postmaster or standalone-backend startup),
3837 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3838 * InitControlFile() fills the buffer with initial values.
3840 * For simplicity, WriteControlFile() initializes the fields of pg_control
3841 * that are related to checking backend/database compatibility, and
3842 * ReadControlFile() verifies they are correct. We could split out the
3843 * I/O and compatibility-check functions, but there seems no need currently.
3846 static void
3847 InitControlFile(uint64 sysidentifier)
3849 char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
3852 * Generate a random nonce. This is used for authentication requests that
3853 * will fail because the user does not exist. The nonce is used to create
3854 * a genuine-looking password challenge for the non-existent user, in lieu
3855 * of an actual stored password.
3857 if (!pg_strong_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
3858 ereport(PANIC,
3859 (errcode(ERRCODE_INTERNAL_ERROR),
3860 errmsg("could not generate secret authorization token")));
3862 memset(ControlFile, 0, sizeof(ControlFileData));
3863 /* Initialize pg_control status fields */
3864 ControlFile->system_identifier = sysidentifier;
3865 memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
3866 ControlFile->state = DB_SHUTDOWNED;
3867 ControlFile->unloggedLSN = FirstNormalUnloggedLSN;
3869 /* Set important parameter values for use when replaying WAL */
3870 ControlFile->MaxConnections = MaxConnections;
3871 ControlFile->max_worker_processes = max_worker_processes;
3872 ControlFile->max_wal_senders = max_wal_senders;
3873 ControlFile->max_prepared_xacts = max_prepared_xacts;
3874 ControlFile->max_locks_per_xact = max_locks_per_xact;
3875 ControlFile->wal_level = wal_level;
3876 ControlFile->wal_log_hints = wal_log_hints;
3877 ControlFile->track_commit_timestamp = track_commit_timestamp;
3878 ControlFile->data_checksum_version = bootstrap_data_checksum_version;
3881 static void
3882 WriteControlFile(void)
3884 int fd;
3885 char buffer[PG_CONTROL_FILE_SIZE]; /* need not be aligned */
3888 * Initialize version and compatibility-check fields
3890 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3891 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3893 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3894 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3896 ControlFile->blcksz = BLCKSZ;
3897 ControlFile->relseg_size = RELSEG_SIZE;
3898 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3899 ControlFile->xlog_seg_size = wal_segment_size;
3901 ControlFile->nameDataLen = NAMEDATALEN;
3902 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3904 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
3905 ControlFile->loblksize = LOBLKSIZE;
3907 ControlFile->float8ByVal = FLOAT8PASSBYVAL;
3909 /* Contents are protected with a CRC */
3910 INIT_CRC32C(ControlFile->crc);
3911 COMP_CRC32C(ControlFile->crc,
3912 (char *) ControlFile,
3913 offsetof(ControlFileData, crc));
3914 FIN_CRC32C(ControlFile->crc);
3917 * We write out PG_CONTROL_FILE_SIZE bytes into pg_control, zero-padding
3918 * the excess over sizeof(ControlFileData). This reduces the odds of
3919 * premature-EOF errors when reading pg_control. We'll still fail when we
3920 * check the contents of the file, but hopefully with a more specific
3921 * error than "couldn't read pg_control".
3923 memset(buffer, 0, PG_CONTROL_FILE_SIZE);
3924 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3926 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3927 O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3928 if (fd < 0)
3929 ereport(PANIC,
3930 (errcode_for_file_access(),
3931 errmsg("could not create file \"%s\": %m",
3932 XLOG_CONTROL_FILE)));
3934 errno = 0;
3935 pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_WRITE);
3936 if (write(fd, buffer, PG_CONTROL_FILE_SIZE) != PG_CONTROL_FILE_SIZE)
3938 /* if write didn't set errno, assume problem is no disk space */
3939 if (errno == 0)
3940 errno = ENOSPC;
3941 ereport(PANIC,
3942 (errcode_for_file_access(),
3943 errmsg("could not write to file \"%s\": %m",
3944 XLOG_CONTROL_FILE)));
3946 pgstat_report_wait_end();
3948 pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_SYNC);
3949 if (pg_fsync(fd) != 0)
3950 ereport(PANIC,
3951 (errcode_for_file_access(),
3952 errmsg("could not fsync file \"%s\": %m",
3953 XLOG_CONTROL_FILE)));
3954 pgstat_report_wait_end();
3956 if (close(fd) != 0)
3957 ereport(PANIC,
3958 (errcode_for_file_access(),
3959 errmsg("could not close file \"%s\": %m",
3960 XLOG_CONTROL_FILE)));
3963 static void
3964 ReadControlFile(void)
3966 pg_crc32c crc;
3967 int fd;
3968 static char wal_segsz_str[20];
3969 int r;
3972 * Read data...
3974 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3975 O_RDWR | PG_BINARY);
3976 if (fd < 0)
3977 ereport(PANIC,
3978 (errcode_for_file_access(),
3979 errmsg("could not open file \"%s\": %m",
3980 XLOG_CONTROL_FILE)));
3982 pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_READ);
3983 r = read(fd, ControlFile, sizeof(ControlFileData));
3984 if (r != sizeof(ControlFileData))
3986 if (r < 0)
3987 ereport(PANIC,
3988 (errcode_for_file_access(),
3989 errmsg("could not read file \"%s\": %m",
3990 XLOG_CONTROL_FILE)));
3991 else
3992 ereport(PANIC,
3993 (errcode(ERRCODE_DATA_CORRUPTED),
3994 errmsg("could not read file \"%s\": read %d of %zu",
3995 XLOG_CONTROL_FILE, r, sizeof(ControlFileData))));
3997 pgstat_report_wait_end();
3999 close(fd);
4002 * Check for expected pg_control format version. If this is wrong, the
4003 * CRC check will likely fail because we'll be checking the wrong number
4004 * of bytes. Complaining about wrong version will probably be more
4005 * enlightening than complaining about wrong CRC.
4008 if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
4009 ereport(FATAL,
4010 (errmsg("database files are incompatible with server"),
4011 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4012 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4013 ControlFile->pg_control_version, ControlFile->pg_control_version,
4014 PG_CONTROL_VERSION, PG_CONTROL_VERSION),
4015 errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4017 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
4018 ereport(FATAL,
4019 (errmsg("database files are incompatible with server"),
4020 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4021 " but the server was compiled with PG_CONTROL_VERSION %d.",
4022 ControlFile->pg_control_version, PG_CONTROL_VERSION),
4023 errhint("It looks like you need to initdb.")));
4025 /* Now check the CRC. */
4026 INIT_CRC32C(crc);
4027 COMP_CRC32C(crc,
4028 (char *) ControlFile,
4029 offsetof(ControlFileData, crc));
4030 FIN_CRC32C(crc);
4032 if (!EQ_CRC32C(crc, ControlFile->crc))
4033 ereport(FATAL,
4034 (errmsg("incorrect checksum in control file")));
4037 * Do compatibility checking immediately. If the database isn't
4038 * compatible with the backend executable, we want to abort before we can
4039 * possibly do any damage.
4041 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
4042 ereport(FATAL,
4043 (errmsg("database files are incompatible with server"),
4044 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
4045 " but the server was compiled with CATALOG_VERSION_NO %d.",
4046 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
4047 errhint("It looks like you need to initdb.")));
4048 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4049 ereport(FATAL,
4050 (errmsg("database files are incompatible with server"),
4051 errdetail("The database cluster was initialized with MAXALIGN %d,"
4052 " but the server was compiled with MAXALIGN %d.",
4053 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
4054 errhint("It looks like you need to initdb.")));
4055 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
4056 ereport(FATAL,
4057 (errmsg("database files are incompatible with server"),
4058 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4059 errhint("It looks like you need to initdb.")));
4060 if (ControlFile->blcksz != BLCKSZ)
4061 ereport(FATAL,
4062 (errmsg("database files are incompatible with server"),
4063 errdetail("The database cluster was initialized with BLCKSZ %d,"
4064 " but the server was compiled with BLCKSZ %d.",
4065 ControlFile->blcksz, BLCKSZ),
4066 errhint("It looks like you need to recompile or initdb.")));
4067 if (ControlFile->relseg_size != RELSEG_SIZE)
4068 ereport(FATAL,
4069 (errmsg("database files are incompatible with server"),
4070 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
4071 " but the server was compiled with RELSEG_SIZE %d.",
4072 ControlFile->relseg_size, RELSEG_SIZE),
4073 errhint("It looks like you need to recompile or initdb.")));
4074 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4075 ereport(FATAL,
4076 (errmsg("database files are incompatible with server"),
4077 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
4078 " but the server was compiled with XLOG_BLCKSZ %d.",
4079 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4080 errhint("It looks like you need to recompile or initdb.")));
4081 if (ControlFile->nameDataLen != NAMEDATALEN)
4082 ereport(FATAL,
4083 (errmsg("database files are incompatible with server"),
4084 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
4085 " but the server was compiled with NAMEDATALEN %d.",
4086 ControlFile->nameDataLen, NAMEDATALEN),
4087 errhint("It looks like you need to recompile or initdb.")));
4088 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4089 ereport(FATAL,
4090 (errmsg("database files are incompatible with server"),
4091 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
4092 " but the server was compiled with INDEX_MAX_KEYS %d.",
4093 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
4094 errhint("It looks like you need to recompile or initdb.")));
4095 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
4096 ereport(FATAL,
4097 (errmsg("database files are incompatible with server"),
4098 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
4099 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
4100 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4101 errhint("It looks like you need to recompile or initdb.")));
4102 if (ControlFile->loblksize != LOBLKSIZE)
4103 ereport(FATAL,
4104 (errmsg("database files are incompatible with server"),
4105 errdetail("The database cluster was initialized with LOBLKSIZE %d,"
4106 " but the server was compiled with LOBLKSIZE %d.",
4107 ControlFile->loblksize, (int) LOBLKSIZE),
4108 errhint("It looks like you need to recompile or initdb.")));
4110 #ifdef USE_FLOAT8_BYVAL
4111 if (ControlFile->float8ByVal != true)
4112 ereport(FATAL,
4113 (errmsg("database files are incompatible with server"),
4114 errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4115 " but the server was compiled with USE_FLOAT8_BYVAL."),
4116 errhint("It looks like you need to recompile or initdb.")));
4117 #else
4118 if (ControlFile->float8ByVal != false)
4119 ereport(FATAL,
4120 (errmsg("database files are incompatible with server"),
4121 errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4122 " but the server was compiled without USE_FLOAT8_BYVAL."),
4123 errhint("It looks like you need to recompile or initdb.")));
4124 #endif
4126 wal_segment_size = ControlFile->xlog_seg_size;
4128 if (!IsValidWalSegSize(wal_segment_size))
4129 ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4130 errmsg_plural("WAL segment size must be a power of two between 1 MB and 1 GB, but the control file specifies %d byte",
4131 "WAL segment size must be a power of two between 1 MB and 1 GB, but the control file specifies %d bytes",
4132 wal_segment_size,
4133 wal_segment_size)));
4135 snprintf(wal_segsz_str, sizeof(wal_segsz_str), "%d", wal_segment_size);
4136 SetConfigOption("wal_segment_size", wal_segsz_str, PGC_INTERNAL,
4137 PGC_S_DYNAMIC_DEFAULT);
4139 /* check and update variables dependent on wal_segment_size */
4140 if (ConvertToXSegs(min_wal_size_mb, wal_segment_size) < 2)
4141 ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4142 errmsg("\"min_wal_size\" must be at least twice \"wal_segment_size\"")));
4144 if (ConvertToXSegs(max_wal_size_mb, wal_segment_size) < 2)
4145 ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4146 errmsg("\"max_wal_size\" must be at least twice \"wal_segment_size\"")));
4148 UsableBytesInSegment =
4149 (wal_segment_size / XLOG_BLCKSZ * UsableBytesInPage) -
4150 (SizeOfXLogLongPHD - SizeOfXLogShortPHD);
4152 CalculateCheckpointSegments();
4154 /* Make the initdb settings visible as GUC variables, too */
4155 SetConfigOption("data_checksums", DataChecksumsEnabled() ? "yes" : "no",
4156 PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
4160 * Utility wrapper to update the control file. Note that the control
4161 * file gets flushed.
4163 static void
4164 UpdateControlFile(void)
4166 update_controlfile(DataDir, ControlFile, true);
4170 * Returns the unique system identifier from control file.
4172 uint64
4173 GetSystemIdentifier(void)
4175 Assert(ControlFile != NULL);
4176 return ControlFile->system_identifier;
4180 * Returns the random nonce from control file.
4182 char *
4183 GetMockAuthenticationNonce(void)
4185 Assert(ControlFile != NULL);
4186 return ControlFile->mock_authentication_nonce;
4190 * Are checksums enabled for data pages?
4192 bool
4193 DataChecksumsEnabled(void)
4195 Assert(ControlFile != NULL);
4196 return (ControlFile->data_checksum_version > 0);
4200 * Returns a fake LSN for unlogged relations.
4202 * Each call generates an LSN that is greater than any previous value
4203 * returned. The current counter value is saved and restored across clean
4204 * shutdowns, but like unlogged relations, does not survive a crash. This can
4205 * be used in lieu of real LSN values returned by XLogInsert, if you need an
4206 * LSN-like increasing sequence of numbers without writing any WAL.
4208 XLogRecPtr
4209 GetFakeLSNForUnloggedRel(void)
4211 XLogRecPtr nextUnloggedLSN;
4213 /* increment the unloggedLSN counter, need SpinLock */
4214 SpinLockAcquire(&XLogCtl->ulsn_lck);
4215 nextUnloggedLSN = XLogCtl->unloggedLSN++;
4216 SpinLockRelease(&XLogCtl->ulsn_lck);
4218 return nextUnloggedLSN;
4222 * Auto-tune the number of XLOG buffers.
4224 * The preferred setting for wal_buffers is about 3% of shared_buffers, with
4225 * a maximum of one XLOG segment (there is little reason to think that more
4226 * is helpful, at least so long as we force an fsync when switching log files)
4227 * and a minimum of 8 blocks (which was the default value prior to PostgreSQL
4228 * 9.1, when auto-tuning was added).
4230 * This should not be called until NBuffers has received its final value.
4232 static int
4233 XLOGChooseNumBuffers(void)
4235 int xbuffers;
4237 xbuffers = NBuffers / 32;
4238 if (xbuffers > (wal_segment_size / XLOG_BLCKSZ))
4239 xbuffers = (wal_segment_size / XLOG_BLCKSZ);
4240 if (xbuffers < 8)
4241 xbuffers = 8;
4242 return xbuffers;
4246 * GUC check_hook for wal_buffers
4248 bool
4249 check_wal_buffers(int *newval, void **extra, GucSource source)
4252 * -1 indicates a request for auto-tune.
4254 if (*newval == -1)
4257 * If we haven't yet changed the boot_val default of -1, just let it
4258 * be. We'll fix it when XLOGShmemSize is called.
4260 if (XLOGbuffers == -1)
4261 return true;
4263 /* Otherwise, substitute the auto-tune value */
4264 *newval = XLOGChooseNumBuffers();
4268 * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
4269 * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
4270 * the case, we just silently treat such values as a request for the
4271 * minimum. (We could throw an error instead, but that doesn't seem very
4272 * helpful.)
4274 if (*newval < 4)
4275 *newval = 4;
4277 return true;
4281 * GUC check_hook for wal_consistency_checking
4283 bool
4284 check_wal_consistency_checking(char **newval, void **extra, GucSource source)
4286 char *rawstring;
4287 List *elemlist;
4288 ListCell *l;
4289 bool newwalconsistency[RM_MAX_ID + 1];
4291 /* Initialize the array */
4292 MemSet(newwalconsistency, 0, (RM_MAX_ID + 1) * sizeof(bool));
4294 /* Need a modifiable copy of string */
4295 rawstring = pstrdup(*newval);
4297 /* Parse string into list of identifiers */
4298 if (!SplitIdentifierString(rawstring, ',', &elemlist))
4300 /* syntax error in list */
4301 GUC_check_errdetail("List syntax is invalid.");
4302 pfree(rawstring);
4303 list_free(elemlist);
4304 return false;
4307 foreach(l, elemlist)
4309 char *tok = (char *) lfirst(l);
4310 int rmid;
4312 /* Check for 'all'. */
4313 if (pg_strcasecmp(tok, "all") == 0)
4315 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4316 if (RmgrIdExists(rmid) && GetRmgr(rmid).rm_mask != NULL)
4317 newwalconsistency[rmid] = true;
4319 else
4321 /* Check if the token matches any known resource manager. */
4322 bool found = false;
4324 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4326 if (RmgrIdExists(rmid) && GetRmgr(rmid).rm_mask != NULL &&
4327 pg_strcasecmp(tok, GetRmgr(rmid).rm_name) == 0)
4329 newwalconsistency[rmid] = true;
4330 found = true;
4331 break;
4334 if (!found)
4337 * During startup, it might be a not-yet-loaded custom
4338 * resource manager. Defer checking until
4339 * InitializeWalConsistencyChecking().
4341 if (!process_shared_preload_libraries_done)
4343 check_wal_consistency_checking_deferred = true;
4345 else
4347 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
4348 pfree(rawstring);
4349 list_free(elemlist);
4350 return false;
4356 pfree(rawstring);
4357 list_free(elemlist);
4359 /* assign new value */
4360 *extra = guc_malloc(ERROR, (RM_MAX_ID + 1) * sizeof(bool));
4361 memcpy(*extra, newwalconsistency, (RM_MAX_ID + 1) * sizeof(bool));
4362 return true;
4366 * GUC assign_hook for wal_consistency_checking
4368 void
4369 assign_wal_consistency_checking(const char *newval, void *extra)
4372 * If some checks were deferred, it's possible that the checks will fail
4373 * later during InitializeWalConsistencyChecking(). But in that case, the
4374 * postmaster will exit anyway, so it's safe to proceed with the
4375 * assignment.
4377 * Any built-in resource managers specified are assigned immediately,
4378 * which affects WAL created before shared_preload_libraries are
4379 * processed. Any custom resource managers specified won't be assigned
4380 * until after shared_preload_libraries are processed, but that's OK
4381 * because WAL for a custom resource manager can't be written before the
4382 * module is loaded anyway.
4384 wal_consistency_checking = extra;
4388 * InitializeWalConsistencyChecking: run after loading custom resource managers
4390 * If any unknown resource managers were specified in the
4391 * wal_consistency_checking GUC, processing was deferred. Now that
4392 * shared_preload_libraries have been loaded, process wal_consistency_checking
4393 * again.
4395 void
4396 InitializeWalConsistencyChecking(void)
4398 Assert(process_shared_preload_libraries_done);
4400 if (check_wal_consistency_checking_deferred)
4402 struct config_generic *guc;
4404 guc = find_option("wal_consistency_checking", false, false, ERROR);
4406 check_wal_consistency_checking_deferred = false;
4408 set_config_option_ext("wal_consistency_checking",
4409 wal_consistency_checking_string,
4410 guc->scontext, guc->source, guc->srole,
4411 GUC_ACTION_SET, true, ERROR, false);
4413 /* checking should not be deferred again */
4414 Assert(!check_wal_consistency_checking_deferred);
4419 * GUC show_hook for archive_command
4421 const char *
4422 show_archive_command(void)
4424 if (XLogArchivingActive())
4425 return XLogArchiveCommand;
4426 else
4427 return "(disabled)";
4431 * GUC show_hook for in_hot_standby
4433 const char *
4434 show_in_hot_standby(void)
4437 * We display the actual state based on shared memory, so that this GUC
4438 * reports up-to-date state if examined intra-query. The underlying
4439 * variable (in_hot_standby_guc) changes only when we transmit a new value
4440 * to the client.
4442 return RecoveryInProgress() ? "on" : "off";
4447 * Read the control file, set respective GUCs.
4449 * This is to be called during startup, including a crash recovery cycle,
4450 * unless in bootstrap mode, where no control file yet exists. As there's no
4451 * usable shared memory yet (its sizing can depend on the contents of the
4452 * control file!), first store the contents in local memory. XLOGShmemInit()
4453 * will then copy it to shared memory later.
4455 * reset just controls whether previous contents are to be expected (in the
4456 * reset case, there's a dangling pointer into old shared memory), or not.
4458 void
4459 LocalProcessControlFile(bool reset)
4461 Assert(reset || ControlFile == NULL);
4462 ControlFile = palloc(sizeof(ControlFileData));
4463 ReadControlFile();
4467 * Initialization of shared memory for XLOG
4469 Size
4470 XLOGShmemSize(void)
4472 Size size;
4475 * If the value of wal_buffers is -1, use the preferred auto-tune value.
4476 * This isn't an amazingly clean place to do this, but we must wait till
4477 * NBuffers has received its final value, and must do it before using the
4478 * value of XLOGbuffers to do anything important.
4480 * We prefer to report this value's source as PGC_S_DYNAMIC_DEFAULT.
4481 * However, if the DBA explicitly set wal_buffers = -1 in the config file,
4482 * then PGC_S_DYNAMIC_DEFAULT will fail to override that and we must force
4483 * the matter with PGC_S_OVERRIDE.
4485 if (XLOGbuffers == -1)
4487 char buf[32];
4489 snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
4490 SetConfigOption("wal_buffers", buf, PGC_POSTMASTER,
4491 PGC_S_DYNAMIC_DEFAULT);
4492 if (XLOGbuffers == -1) /* failed to apply it? */
4493 SetConfigOption("wal_buffers", buf, PGC_POSTMASTER,
4494 PGC_S_OVERRIDE);
4496 Assert(XLOGbuffers > 0);
4498 /* XLogCtl */
4499 size = sizeof(XLogCtlData);
4501 /* WAL insertion locks, plus alignment */
4502 size = add_size(size, mul_size(sizeof(WALInsertLockPadded), NUM_XLOGINSERT_LOCKS + 1));
4503 /* xlblocks array */
4504 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
4505 /* extra alignment padding for XLOG I/O buffers */
4506 size = add_size(size, XLOG_BLCKSZ);
4507 /* and the buffers themselves */
4508 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4511 * Note: we don't count ControlFileData, it comes out of the "slop factor"
4512 * added by CreateSharedMemoryAndSemaphores. This lets us use this
4513 * routine again below to compute the actual allocation size.
4516 return size;
4519 void
4520 XLOGShmemInit(void)
4522 bool foundCFile,
4523 foundXLog;
4524 char *allocptr;
4525 int i;
4526 ControlFileData *localControlFile;
4528 #ifdef WAL_DEBUG
4531 * Create a memory context for WAL debugging that's exempt from the normal
4532 * "no pallocs in critical section" rule. Yes, that can lead to a PANIC if
4533 * an allocation fails, but wal_debug is not for production use anyway.
4535 if (walDebugCxt == NULL)
4537 walDebugCxt = AllocSetContextCreate(TopMemoryContext,
4538 "WAL Debug",
4539 ALLOCSET_DEFAULT_SIZES);
4540 MemoryContextAllowInCriticalSection(walDebugCxt, true);
4542 #endif
4545 XLogCtl = (XLogCtlData *)
4546 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4548 localControlFile = ControlFile;
4549 ControlFile = (ControlFileData *)
4550 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4552 if (foundCFile || foundXLog)
4554 /* both should be present or neither */
4555 Assert(foundCFile && foundXLog);
4557 /* Initialize local copy of WALInsertLocks */
4558 WALInsertLocks = XLogCtl->Insert.WALInsertLocks;
4560 if (localControlFile)
4561 pfree(localControlFile);
4562 return;
4564 memset(XLogCtl, 0, sizeof(XLogCtlData));
4567 * Already have read control file locally, unless in bootstrap mode. Move
4568 * contents into shared memory.
4570 if (localControlFile)
4572 memcpy(ControlFile, localControlFile, sizeof(ControlFileData));
4573 pfree(localControlFile);
4577 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4578 * multiple of the alignment for same, so no extra alignment padding is
4579 * needed here.
4581 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4582 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4583 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4584 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4587 /* WAL insertion locks. Ensure they're aligned to the full padded size */
4588 allocptr += sizeof(WALInsertLockPadded) -
4589 ((uintptr_t) allocptr) % sizeof(WALInsertLockPadded);
4590 WALInsertLocks = XLogCtl->Insert.WALInsertLocks =
4591 (WALInsertLockPadded *) allocptr;
4592 allocptr += sizeof(WALInsertLockPadded) * NUM_XLOGINSERT_LOCKS;
4594 for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
4596 LWLockInitialize(&WALInsertLocks[i].l.lock, LWTRANCHE_WAL_INSERT);
4597 WALInsertLocks[i].l.insertingAt = InvalidXLogRecPtr;
4598 WALInsertLocks[i].l.lastImportantAt = InvalidXLogRecPtr;
4602 * Align the start of the page buffers to a full xlog block size boundary.
4603 * This simplifies some calculations in XLOG insertion. It is also
4604 * required for O_DIRECT.
4606 allocptr = (char *) TYPEALIGN(XLOG_BLCKSZ, allocptr);
4607 XLogCtl->pages = allocptr;
4608 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4611 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4612 * in additional info.)
4614 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4615 XLogCtl->SharedRecoveryState = RECOVERY_STATE_CRASH;
4616 XLogCtl->InstallXLogFileSegmentActive = false;
4617 XLogCtl->WalWriterSleeping = false;
4619 SpinLockInit(&XLogCtl->Insert.insertpos_lck);
4620 SpinLockInit(&XLogCtl->info_lck);
4621 SpinLockInit(&XLogCtl->ulsn_lck);
4625 * This func must be called ONCE on system install. It creates pg_control
4626 * and the initial XLOG segment.
4628 void
4629 BootStrapXLOG(void)
4631 CheckPoint checkPoint;
4632 char *buffer;
4633 XLogPageHeader page;
4634 XLogLongPageHeader longpage;
4635 XLogRecord *record;
4636 char *recptr;
4637 uint64 sysidentifier;
4638 struct timeval tv;
4639 pg_crc32c crc;
4641 /* allow ordinary WAL segment creation, like StartupXLOG() would */
4642 SetInstallXLogFileSegmentActive();
4645 * Select a hopefully-unique system identifier code for this installation.
4646 * We use the result of gettimeofday(), including the fractional seconds
4647 * field, as being about as unique as we can easily get. (Think not to
4648 * use random(), since it hasn't been seeded and there's no portable way
4649 * to seed it other than the system clock value...) The upper half of the
4650 * uint64 value is just the tv_sec part, while the lower half contains the
4651 * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
4652 * PID for a little extra uniqueness. A person knowing this encoding can
4653 * determine the initialization time of the installation, which could
4654 * perhaps be useful sometimes.
4656 gettimeofday(&tv, NULL);
4657 sysidentifier = ((uint64) tv.tv_sec) << 32;
4658 sysidentifier |= ((uint64) tv.tv_usec) << 12;
4659 sysidentifier |= getpid() & 0xFFF;
4661 /* page buffer must be aligned suitably for O_DIRECT */
4662 buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
4663 page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
4664 memset(page, 0, XLOG_BLCKSZ);
4667 * Set up information for the initial checkpoint record
4669 * The initial checkpoint record is written to the beginning of the WAL
4670 * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
4671 * used, so that we can use 0/0 to mean "before any valid WAL segment".
4673 checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
4674 checkPoint.ThisTimeLineID = BootstrapTimeLineID;
4675 checkPoint.PrevTimeLineID = BootstrapTimeLineID;
4676 checkPoint.fullPageWrites = fullPageWrites;
4677 checkPoint.nextXid =
4678 FullTransactionIdFromEpochAndXid(0, FirstNormalTransactionId);
4679 checkPoint.nextOid = FirstGenbkiObjectId;
4680 checkPoint.nextMulti = FirstMultiXactId;
4681 checkPoint.nextMultiOffset = 0;
4682 checkPoint.oldestXid = FirstNormalTransactionId;
4683 checkPoint.oldestXidDB = Template1DbOid;
4684 checkPoint.oldestMulti = FirstMultiXactId;
4685 checkPoint.oldestMultiDB = Template1DbOid;
4686 checkPoint.oldestCommitTsXid = InvalidTransactionId;
4687 checkPoint.newestCommitTsXid = InvalidTransactionId;
4688 checkPoint.time = (pg_time_t) time(NULL);
4689 checkPoint.oldestActiveXid = InvalidTransactionId;
4691 ShmemVariableCache->nextXid = checkPoint.nextXid;
4692 ShmemVariableCache->nextOid = checkPoint.nextOid;
4693 ShmemVariableCache->oidCount = 0;
4694 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4695 AdvanceOldestClogXid(checkPoint.oldestXid);
4696 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
4697 SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
4698 SetCommitTsLimit(InvalidTransactionId, InvalidTransactionId);
4700 /* Set up the XLOG page header */
4701 page->xlp_magic = XLOG_PAGE_MAGIC;
4702 page->xlp_info = XLP_LONG_HEADER;
4703 page->xlp_tli = BootstrapTimeLineID;
4704 page->xlp_pageaddr = wal_segment_size;
4705 longpage = (XLogLongPageHeader) page;
4706 longpage->xlp_sysid = sysidentifier;
4707 longpage->xlp_seg_size = wal_segment_size;
4708 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4710 /* Insert the initial checkpoint record */
4711 recptr = ((char *) page + SizeOfXLogLongPHD);
4712 record = (XLogRecord *) recptr;
4713 record->xl_prev = 0;
4714 record->xl_xid = InvalidTransactionId;
4715 record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
4716 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4717 record->xl_rmid = RM_XLOG_ID;
4718 recptr += SizeOfXLogRecord;
4719 /* fill the XLogRecordDataHeaderShort struct */
4720 *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
4721 *(recptr++) = sizeof(checkPoint);
4722 memcpy(recptr, &checkPoint, sizeof(checkPoint));
4723 recptr += sizeof(checkPoint);
4724 Assert(recptr - (char *) record == record->xl_tot_len);
4726 INIT_CRC32C(crc);
4727 COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
4728 COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
4729 FIN_CRC32C(crc);
4730 record->xl_crc = crc;
4732 /* Create first XLOG segment file */
4733 openLogTLI = BootstrapTimeLineID;
4734 openLogFile = XLogFileInit(1, BootstrapTimeLineID);
4737 * We needn't bother with Reserve/ReleaseExternalFD here, since we'll
4738 * close the file again in a moment.
4741 /* Write the first page with the initial record */
4742 errno = 0;
4743 pgstat_report_wait_start(WAIT_EVENT_WAL_BOOTSTRAP_WRITE);
4744 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4746 /* if write didn't set errno, assume problem is no disk space */
4747 if (errno == 0)
4748 errno = ENOSPC;
4749 ereport(PANIC,
4750 (errcode_for_file_access(),
4751 errmsg("could not write bootstrap write-ahead log file: %m")));
4753 pgstat_report_wait_end();
4755 pgstat_report_wait_start(WAIT_EVENT_WAL_BOOTSTRAP_SYNC);
4756 if (pg_fsync(openLogFile) != 0)
4757 ereport(PANIC,
4758 (errcode_for_file_access(),
4759 errmsg("could not fsync bootstrap write-ahead log file: %m")));
4760 pgstat_report_wait_end();
4762 if (close(openLogFile) != 0)
4763 ereport(PANIC,
4764 (errcode_for_file_access(),
4765 errmsg("could not close bootstrap write-ahead log file: %m")));
4767 openLogFile = -1;
4769 /* Now create pg_control */
4770 InitControlFile(sysidentifier);
4771 ControlFile->time = checkPoint.time;
4772 ControlFile->checkPoint = checkPoint.redo;
4773 ControlFile->checkPointCopy = checkPoint;
4775 /* some additional ControlFile fields are set in WriteControlFile() */
4776 WriteControlFile();
4778 /* Bootstrap the commit log, too */
4779 BootStrapCLOG();
4780 BootStrapCommitTs();
4781 BootStrapSUBTRANS();
4782 BootStrapMultiXact();
4784 pfree(buffer);
4787 * Force control file to be read - in contrast to normal processing we'd
4788 * otherwise never run the checks and GUC related initializations therein.
4790 ReadControlFile();
4793 static char *
4794 str_time(pg_time_t tnow)
4796 static char buf[128];
4798 pg_strftime(buf, sizeof(buf),
4799 "%Y-%m-%d %H:%M:%S %Z",
4800 pg_localtime(&tnow, log_timezone));
4802 return buf;
4806 * Initialize the first WAL segment on new timeline.
4808 static void
4809 XLogInitNewTimeline(TimeLineID endTLI, XLogRecPtr endOfLog, TimeLineID newTLI)
4811 char xlogfname[MAXFNAMELEN];
4812 XLogSegNo endLogSegNo;
4813 XLogSegNo startLogSegNo;
4815 /* we always switch to a new timeline after archive recovery */
4816 Assert(endTLI != newTLI);
4819 * Update min recovery point one last time.
4821 UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
4824 * Calculate the last segment on the old timeline, and the first segment
4825 * on the new timeline. If the switch happens in the middle of a segment,
4826 * they are the same, but if the switch happens exactly at a segment
4827 * boundary, startLogSegNo will be endLogSegNo + 1.
4829 XLByteToPrevSeg(endOfLog, endLogSegNo, wal_segment_size);
4830 XLByteToSeg(endOfLog, startLogSegNo, wal_segment_size);
4833 * Initialize the starting WAL segment for the new timeline. If the switch
4834 * happens in the middle of a segment, copy data from the last WAL segment
4835 * of the old timeline up to the switch point, to the starting WAL segment
4836 * on the new timeline.
4838 if (endLogSegNo == startLogSegNo)
4841 * Make a copy of the file on the new timeline.
4843 * Writing WAL isn't allowed yet, so there are no locking
4844 * considerations. But we should be just as tense as XLogFileInit to
4845 * avoid emplacing a bogus file.
4847 XLogFileCopy(newTLI, endLogSegNo, endTLI, endLogSegNo,
4848 XLogSegmentOffset(endOfLog, wal_segment_size));
4850 else
4853 * The switch happened at a segment boundary, so just create the next
4854 * segment on the new timeline.
4856 int fd;
4858 fd = XLogFileInit(startLogSegNo, newTLI);
4860 if (close(fd) != 0)
4862 int save_errno = errno;
4864 XLogFileName(xlogfname, newTLI, startLogSegNo, wal_segment_size);
4865 errno = save_errno;
4866 ereport(ERROR,
4867 (errcode_for_file_access(),
4868 errmsg("could not close file \"%s\": %m", xlogfname)));
4873 * Let's just make real sure there are not .ready or .done flags posted
4874 * for the new segment.
4876 XLogFileName(xlogfname, newTLI, startLogSegNo, wal_segment_size);
4877 XLogArchiveCleanup(xlogfname);
4881 * Perform cleanup actions at the conclusion of archive recovery.
4883 static void
4884 CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI, XLogRecPtr EndOfLog,
4885 TimeLineID newTLI)
4888 * Execute the recovery_end_command, if any.
4890 if (recoveryEndCommand && strcmp(recoveryEndCommand, "") != 0)
4892 char lastRestartPointFname[MAXFNAMELEN];
4894 GetOldestRestartPointFileName(lastRestartPointFname);
4895 shell_recovery_end(lastRestartPointFname);
4899 * We switched to a new timeline. Clean up segments on the old timeline.
4901 * If there are any higher-numbered segments on the old timeline, remove
4902 * them. They might contain valid WAL, but they might also be
4903 * pre-allocated files containing garbage. In any case, they are not part
4904 * of the new timeline's history so we don't need them.
4906 RemoveNonParentXlogFiles(EndOfLog, newTLI);
4909 * If the switch happened in the middle of a segment, what to do with the
4910 * last, partial segment on the old timeline? If we don't archive it, and
4911 * the server that created the WAL never archives it either (e.g. because
4912 * it was hit by a meteor), it will never make it to the archive. That's
4913 * OK from our point of view, because the new segment that we created with
4914 * the new TLI contains all the WAL from the old timeline up to the switch
4915 * point. But if you later try to do PITR to the "missing" WAL on the old
4916 * timeline, recovery won't find it in the archive. It's physically
4917 * present in the new file with new TLI, but recovery won't look there
4918 * when it's recovering to the older timeline. On the other hand, if we
4919 * archive the partial segment, and the original server on that timeline
4920 * is still running and archives the completed version of the same segment
4921 * later, it will fail. (We used to do that in 9.4 and below, and it
4922 * caused such problems).
4924 * As a compromise, we rename the last segment with the .partial suffix,
4925 * and archive it. Archive recovery will never try to read .partial
4926 * segments, so they will normally go unused. But in the odd PITR case,
4927 * the administrator can copy them manually to the pg_wal directory
4928 * (removing the suffix). They can be useful in debugging, too.
4930 * If a .done or .ready file already exists for the old timeline, however,
4931 * we had already determined that the segment is complete, so we can let
4932 * it be archived normally. (In particular, if it was restored from the
4933 * archive to begin with, it's expected to have a .done file).
4935 if (XLogSegmentOffset(EndOfLog, wal_segment_size) != 0 &&
4936 XLogArchivingActive())
4938 char origfname[MAXFNAMELEN];
4939 XLogSegNo endLogSegNo;
4941 XLByteToPrevSeg(EndOfLog, endLogSegNo, wal_segment_size);
4942 XLogFileName(origfname, EndOfLogTLI, endLogSegNo, wal_segment_size);
4944 if (!XLogArchiveIsReadyOrDone(origfname))
4946 char origpath[MAXPGPATH];
4947 char partialfname[MAXFNAMELEN];
4948 char partialpath[MAXPGPATH];
4950 XLogFilePath(origpath, EndOfLogTLI, endLogSegNo, wal_segment_size);
4951 snprintf(partialfname, MAXFNAMELEN, "%s.partial", origfname);
4952 snprintf(partialpath, MAXPGPATH, "%s.partial", origpath);
4955 * Make sure there's no .done or .ready file for the .partial
4956 * file.
4958 XLogArchiveCleanup(partialfname);
4960 durable_rename(origpath, partialpath, ERROR);
4961 XLogArchiveNotify(partialfname);
4967 * Check to see if required parameters are set high enough on this server
4968 * for various aspects of recovery operation.
4970 * Note that all the parameters which this function tests need to be
4971 * listed in Administrator's Overview section in high-availability.sgml.
4972 * If you change them, don't forget to update the list.
4974 static void
4975 CheckRequiredParameterValues(void)
4978 * For archive recovery, the WAL must be generated with at least 'replica'
4979 * wal_level.
4981 if (ArchiveRecoveryRequested && ControlFile->wal_level == WAL_LEVEL_MINIMAL)
4983 ereport(FATAL,
4984 (errmsg("WAL was generated with wal_level=minimal, cannot continue recovering"),
4985 errdetail("This happens if you temporarily set wal_level=minimal on the server."),
4986 errhint("Use a backup taken after setting wal_level to higher than minimal.")));
4990 * For Hot Standby, the WAL must be generated with 'replica' mode, and we
4991 * must have at least as many backend slots as the primary.
4993 if (ArchiveRecoveryRequested && EnableHotStandby)
4995 /* We ignore autovacuum_max_workers when we make this test. */
4996 RecoveryRequiresIntParameter("max_connections",
4997 MaxConnections,
4998 ControlFile->MaxConnections);
4999 RecoveryRequiresIntParameter("max_worker_processes",
5000 max_worker_processes,
5001 ControlFile->max_worker_processes);
5002 RecoveryRequiresIntParameter("max_wal_senders",
5003 max_wal_senders,
5004 ControlFile->max_wal_senders);
5005 RecoveryRequiresIntParameter("max_prepared_transactions",
5006 max_prepared_xacts,
5007 ControlFile->max_prepared_xacts);
5008 RecoveryRequiresIntParameter("max_locks_per_transaction",
5009 max_locks_per_xact,
5010 ControlFile->max_locks_per_xact);
5015 * This must be called ONCE during postmaster or standalone-backend startup
5017 void
5018 StartupXLOG(void)
5020 XLogCtlInsert *Insert;
5021 CheckPoint checkPoint;
5022 bool wasShutdown;
5023 bool didCrash;
5024 bool haveTblspcMap;
5025 bool haveBackupLabel;
5026 XLogRecPtr EndOfLog;
5027 TimeLineID EndOfLogTLI;
5028 TimeLineID newTLI;
5029 bool performedWalRecovery;
5030 EndOfWalRecoveryInfo *endOfRecoveryInfo;
5031 XLogRecPtr abortedRecPtr;
5032 XLogRecPtr missingContrecPtr;
5033 TransactionId oldestActiveXID;
5034 bool promoted = false;
5037 * We should have an aux process resource owner to use, and we should not
5038 * be in a transaction that's installed some other resowner.
5040 Assert(AuxProcessResourceOwner != NULL);
5041 Assert(CurrentResourceOwner == NULL ||
5042 CurrentResourceOwner == AuxProcessResourceOwner);
5043 CurrentResourceOwner = AuxProcessResourceOwner;
5046 * Check that contents look valid.
5048 if (!XRecOffIsValid(ControlFile->checkPoint))
5049 ereport(FATAL,
5050 (errmsg("control file contains invalid checkpoint location")));
5052 switch (ControlFile->state)
5054 case DB_SHUTDOWNED:
5057 * This is the expected case, so don't be chatty in standalone
5058 * mode
5060 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
5061 (errmsg("database system was shut down at %s",
5062 str_time(ControlFile->time))));
5063 break;
5065 case DB_SHUTDOWNED_IN_RECOVERY:
5066 ereport(LOG,
5067 (errmsg("database system was shut down in recovery at %s",
5068 str_time(ControlFile->time))));
5069 break;
5071 case DB_SHUTDOWNING:
5072 ereport(LOG,
5073 (errmsg("database system shutdown was interrupted; last known up at %s",
5074 str_time(ControlFile->time))));
5075 break;
5077 case DB_IN_CRASH_RECOVERY:
5078 ereport(LOG,
5079 (errmsg("database system was interrupted while in recovery at %s",
5080 str_time(ControlFile->time)),
5081 errhint("This probably means that some data is corrupted and"
5082 " you will have to use the last backup for recovery.")));
5083 break;
5085 case DB_IN_ARCHIVE_RECOVERY:
5086 ereport(LOG,
5087 (errmsg("database system was interrupted while in recovery at log time %s",
5088 str_time(ControlFile->checkPointCopy.time)),
5089 errhint("If this has occurred more than once some data might be corrupted"
5090 " and you might need to choose an earlier recovery target.")));
5091 break;
5093 case DB_IN_PRODUCTION:
5094 ereport(LOG,
5095 (errmsg("database system was interrupted; last known up at %s",
5096 str_time(ControlFile->time))));
5097 break;
5099 default:
5100 ereport(FATAL,
5101 (errmsg("control file contains invalid database cluster state")));
5104 /* This is just to allow attaching to startup process with a debugger */
5105 #ifdef XLOG_REPLAY_DELAY
5106 if (ControlFile->state != DB_SHUTDOWNED)
5107 pg_usleep(60000000L);
5108 #endif
5111 * Verify that pg_wal and pg_wal/archive_status exist. In cases where
5112 * someone has performed a copy for PITR, these directories may have been
5113 * excluded and need to be re-created.
5115 ValidateXLOGDirectoryStructure();
5117 /* Set up timeout handler needed to report startup progress. */
5118 if (!IsBootstrapProcessingMode())
5119 RegisterTimeout(STARTUP_PROGRESS_TIMEOUT,
5120 startup_progress_timeout_handler);
5122 /*----------
5123 * If we previously crashed, perform a couple of actions:
5125 * - The pg_wal directory may still include some temporary WAL segments
5126 * used when creating a new segment, so perform some clean up to not
5127 * bloat this path. This is done first as there is no point to sync
5128 * this temporary data.
5130 * - There might be data which we had written, intending to fsync it, but
5131 * which we had not actually fsync'd yet. Therefore, a power failure in
5132 * the near future might cause earlier unflushed writes to be lost, even
5133 * though more recent data written to disk from here on would be
5134 * persisted. To avoid that, fsync the entire data directory.
5136 if (ControlFile->state != DB_SHUTDOWNED &&
5137 ControlFile->state != DB_SHUTDOWNED_IN_RECOVERY)
5139 RemoveTempXlogFiles();
5140 SyncDataDirectory();
5141 didCrash = true;
5143 else
5144 didCrash = false;
5147 * Prepare for WAL recovery if needed.
5149 * InitWalRecovery analyzes the control file and the backup label file, if
5150 * any. It updates the in-memory ControlFile buffer according to the
5151 * starting checkpoint, and sets InRecovery and ArchiveRecoveryRequested.
5152 * It also applies the tablespace map file, if any.
5154 InitWalRecovery(ControlFile, &wasShutdown,
5155 &haveBackupLabel, &haveTblspcMap);
5156 checkPoint = ControlFile->checkPointCopy;
5158 /* initialize shared memory variables from the checkpoint record */
5159 ShmemVariableCache->nextXid = checkPoint.nextXid;
5160 ShmemVariableCache->nextOid = checkPoint.nextOid;
5161 ShmemVariableCache->oidCount = 0;
5162 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5163 AdvanceOldestClogXid(checkPoint.oldestXid);
5164 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5165 SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5166 SetCommitTsLimit(checkPoint.oldestCommitTsXid,
5167 checkPoint.newestCommitTsXid);
5168 XLogCtl->ckptFullXid = checkPoint.nextXid;
5171 * Clear out any old relcache cache files. This is *necessary* if we do
5172 * any WAL replay, since that would probably result in the cache files
5173 * being out of sync with database reality. In theory we could leave them
5174 * in place if the database had been cleanly shut down, but it seems
5175 * safest to just remove them always and let them be rebuilt during the
5176 * first backend startup. These files needs to be removed from all
5177 * directories including pg_tblspc, however the symlinks are created only
5178 * after reading tablespace_map file in case of archive recovery from
5179 * backup, so needs to clear old relcache files here after creating
5180 * symlinks.
5182 RelationCacheInitFileRemove();
5185 * Initialize replication slots, before there's a chance to remove
5186 * required resources.
5188 StartupReplicationSlots();
5191 * Startup logical state, needs to be setup now so we have proper data
5192 * during crash recovery.
5194 StartupReorderBuffer();
5197 * Startup CLOG. This must be done after ShmemVariableCache->nextXid has
5198 * been initialized and before we accept connections or begin WAL replay.
5200 StartupCLOG();
5203 * Startup MultiXact. We need to do this early to be able to replay
5204 * truncations.
5206 StartupMultiXact();
5209 * Ditto for commit timestamps. Activate the facility if the setting is
5210 * enabled in the control file, as there should be no tracking of commit
5211 * timestamps done when the setting was disabled. This facility can be
5212 * started or stopped when replaying a XLOG_PARAMETER_CHANGE record.
5214 if (ControlFile->track_commit_timestamp)
5215 StartupCommitTs();
5218 * Recover knowledge about replay progress of known replication partners.
5220 StartupReplicationOrigin();
5223 * Initialize unlogged LSN. On a clean shutdown, it's restored from the
5224 * control file. On recovery, all unlogged relations are blown away, so
5225 * the unlogged LSN counter can be reset too.
5227 if (ControlFile->state == DB_SHUTDOWNED)
5228 XLogCtl->unloggedLSN = ControlFile->unloggedLSN;
5229 else
5230 XLogCtl->unloggedLSN = FirstNormalUnloggedLSN;
5233 * Copy any missing timeline history files between 'now' and the recovery
5234 * target timeline from archive to pg_wal. While we don't need those files
5235 * ourselves - the history file of the recovery target timeline covers all
5236 * the previous timelines in the history too - a cascading standby server
5237 * might be interested in them. Or, if you archive the WAL from this
5238 * server to a different archive than the primary, it'd be good for all
5239 * the history files to get archived there after failover, so that you can
5240 * use one of the old timelines as a PITR target. Timeline history files
5241 * are small, so it's better to copy them unnecessarily than not copy them
5242 * and regret later.
5244 restoreTimeLineHistoryFiles(checkPoint.ThisTimeLineID, recoveryTargetTLI);
5247 * Before running in recovery, scan pg_twophase and fill in its status to
5248 * be able to work on entries generated by redo. Doing a scan before
5249 * taking any recovery action has the merit to discard any 2PC files that
5250 * are newer than the first record to replay, saving from any conflicts at
5251 * replay. This avoids as well any subsequent scans when doing recovery
5252 * of the on-disk two-phase data.
5254 restoreTwoPhaseData();
5257 * When starting with crash recovery, reset pgstat data - it might not be
5258 * valid. Otherwise restore pgstat data. It's safe to do this here,
5259 * because postmaster will not yet have started any other processes.
5261 * NB: Restoring replication slot stats relies on slot state to have
5262 * already been restored from disk.
5264 * TODO: With a bit of extra work we could just start with a pgstat file
5265 * associated with the checkpoint redo location we're starting from.
5267 if (didCrash)
5268 pgstat_discard_stats();
5269 else
5270 pgstat_restore_stats();
5272 lastFullPageWrites = checkPoint.fullPageWrites;
5274 RedoRecPtr = XLogCtl->RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
5275 doPageWrites = lastFullPageWrites;
5277 /* REDO */
5278 if (InRecovery)
5280 /* Initialize state for RecoveryInProgress() */
5281 SpinLockAcquire(&XLogCtl->info_lck);
5282 if (InArchiveRecovery)
5283 XLogCtl->SharedRecoveryState = RECOVERY_STATE_ARCHIVE;
5284 else
5285 XLogCtl->SharedRecoveryState = RECOVERY_STATE_CRASH;
5286 SpinLockRelease(&XLogCtl->info_lck);
5289 * Update pg_control to show that we are recovering and to show the
5290 * selected checkpoint as the place we are starting from. We also mark
5291 * pg_control with any minimum recovery stop point obtained from a
5292 * backup history file.
5294 * No need to hold ControlFileLock yet, we aren't up far enough.
5296 UpdateControlFile();
5299 * If there was a backup label file, it's done its job and the info
5300 * has now been propagated into pg_control. We must get rid of the
5301 * label file so that if we crash during recovery, we'll pick up at
5302 * the latest recovery restartpoint instead of going all the way back
5303 * to the backup start point. It seems prudent though to just rename
5304 * the file out of the way rather than delete it completely.
5306 if (haveBackupLabel)
5308 unlink(BACKUP_LABEL_OLD);
5309 durable_rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, FATAL);
5313 * If there was a tablespace_map file, it's done its job and the
5314 * symlinks have been created. We must get rid of the map file so
5315 * that if we crash during recovery, we don't create symlinks again.
5316 * It seems prudent though to just rename the file out of the way
5317 * rather than delete it completely.
5319 if (haveTblspcMap)
5321 unlink(TABLESPACE_MAP_OLD);
5322 durable_rename(TABLESPACE_MAP, TABLESPACE_MAP_OLD, FATAL);
5326 * Initialize our local copy of minRecoveryPoint. When doing crash
5327 * recovery we want to replay up to the end of WAL. Particularly, in
5328 * the case of a promoted standby minRecoveryPoint value in the
5329 * control file is only updated after the first checkpoint. However,
5330 * if the instance crashes before the first post-recovery checkpoint
5331 * is completed then recovery will use a stale location causing the
5332 * startup process to think that there are still invalid page
5333 * references when checking for data consistency.
5335 if (InArchiveRecovery)
5337 LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
5338 LocalMinRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
5340 else
5342 LocalMinRecoveryPoint = InvalidXLogRecPtr;
5343 LocalMinRecoveryPointTLI = 0;
5346 /* Check that the GUCs used to generate the WAL allow recovery */
5347 CheckRequiredParameterValues();
5350 * We're in recovery, so unlogged relations may be trashed and must be
5351 * reset. This should be done BEFORE allowing Hot Standby
5352 * connections, so that read-only backends don't try to read whatever
5353 * garbage is left over from before.
5355 ResetUnloggedRelations(UNLOGGED_RELATION_CLEANUP);
5358 * Likewise, delete any saved transaction snapshot files that got left
5359 * behind by crashed backends.
5361 DeleteAllExportedSnapshotFiles();
5364 * Initialize for Hot Standby, if enabled. We won't let backends in
5365 * yet, not until we've reached the min recovery point specified in
5366 * control file and we've established a recovery snapshot from a
5367 * running-xacts WAL record.
5369 if (ArchiveRecoveryRequested && EnableHotStandby)
5371 TransactionId *xids;
5372 int nxids;
5374 ereport(DEBUG1,
5375 (errmsg_internal("initializing for hot standby")));
5377 InitRecoveryTransactionEnvironment();
5379 if (wasShutdown)
5380 oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
5381 else
5382 oldestActiveXID = checkPoint.oldestActiveXid;
5383 Assert(TransactionIdIsValid(oldestActiveXID));
5385 /* Tell procarray about the range of xids it has to deal with */
5386 ProcArrayInitRecovery(XidFromFullTransactionId(ShmemVariableCache->nextXid));
5389 * Startup subtrans only. CLOG, MultiXact and commit timestamp
5390 * have already been started up and other SLRUs are not maintained
5391 * during recovery and need not be started yet.
5393 StartupSUBTRANS(oldestActiveXID);
5396 * If we're beginning at a shutdown checkpoint, we know that
5397 * nothing was running on the primary at this point. So fake-up an
5398 * empty running-xacts record and use that here and now. Recover
5399 * additional standby state for prepared transactions.
5401 if (wasShutdown)
5403 RunningTransactionsData running;
5404 TransactionId latestCompletedXid;
5407 * Construct a RunningTransactions snapshot representing a
5408 * shut down server, with only prepared transactions still
5409 * alive. We're never overflowed at this point because all
5410 * subxids are listed with their parent prepared transactions.
5412 running.xcnt = nxids;
5413 running.subxcnt = 0;
5414 running.subxid_overflow = false;
5415 running.nextXid = XidFromFullTransactionId(checkPoint.nextXid);
5416 running.oldestRunningXid = oldestActiveXID;
5417 latestCompletedXid = XidFromFullTransactionId(checkPoint.nextXid);
5418 TransactionIdRetreat(latestCompletedXid);
5419 Assert(TransactionIdIsNormal(latestCompletedXid));
5420 running.latestCompletedXid = latestCompletedXid;
5421 running.xids = xids;
5423 ProcArrayApplyRecoveryInfo(&running);
5425 StandbyRecoverPreparedTransactions();
5430 * We're all set for replaying the WAL now. Do it.
5432 PerformWalRecovery();
5433 performedWalRecovery = true;
5435 else
5436 performedWalRecovery = false;
5439 * Finish WAL recovery.
5441 endOfRecoveryInfo = FinishWalRecovery();
5442 EndOfLog = endOfRecoveryInfo->endOfLog;
5443 EndOfLogTLI = endOfRecoveryInfo->endOfLogTLI;
5444 abortedRecPtr = endOfRecoveryInfo->abortedRecPtr;
5445 missingContrecPtr = endOfRecoveryInfo->missingContrecPtr;
5448 * Reset ps status display, so as no information related to recovery
5449 * shows up.
5451 set_ps_display("");
5454 * When recovering from a backup (we are in recovery, and archive recovery
5455 * was requested), complain if we did not roll forward far enough to reach
5456 * the point where the database is consistent. For regular online
5457 * backup-from-primary, that means reaching the end-of-backup WAL record
5458 * (at which point we reset backupStartPoint to be Invalid), for
5459 * backup-from-replica (which can't inject records into the WAL stream),
5460 * that point is when we reach the minRecoveryPoint in pg_control (which
5461 * we purposefully copy last when backing up from a replica). For
5462 * pg_rewind (which creates a backup_label with a method of "pg_rewind")
5463 * or snapshot-style backups (which don't), backupEndRequired will be set
5464 * to false.
5466 * Note: it is indeed okay to look at the local variable
5467 * LocalMinRecoveryPoint here, even though ControlFile->minRecoveryPoint
5468 * might be further ahead --- ControlFile->minRecoveryPoint cannot have
5469 * been advanced beyond the WAL we processed.
5471 if (InRecovery &&
5472 (EndOfLog < LocalMinRecoveryPoint ||
5473 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint)))
5476 * Ran off end of WAL before reaching end-of-backup WAL record, or
5477 * minRecoveryPoint. That's a bad sign, indicating that you tried to
5478 * recover from an online backup but never called pg_backup_stop(), or
5479 * you didn't archive all the WAL needed.
5481 if (ArchiveRecoveryRequested || ControlFile->backupEndRequired)
5483 if (!XLogRecPtrIsInvalid(ControlFile->backupStartPoint) || ControlFile->backupEndRequired)
5484 ereport(FATAL,
5485 (errmsg("WAL ends before end of online backup"),
5486 errhint("All WAL generated while online backup was taken must be available at recovery.")));
5487 else
5488 ereport(FATAL,
5489 (errmsg("WAL ends before consistent recovery point")));
5494 * Reset unlogged relations to the contents of their INIT fork. This is
5495 * done AFTER recovery is complete so as to include any unlogged relations
5496 * created during recovery, but BEFORE recovery is marked as having
5497 * completed successfully. Otherwise we'd not retry if any of the post
5498 * end-of-recovery steps fail.
5500 if (InRecovery)
5501 ResetUnloggedRelations(UNLOGGED_RELATION_INIT);
5504 * Pre-scan prepared transactions to find out the range of XIDs present.
5505 * This information is not quite needed yet, but it is positioned here so
5506 * as potential problems are detected before any on-disk change is done.
5508 oldestActiveXID = PrescanPreparedTransactions(NULL, NULL);
5511 * Allow ordinary WAL segment creation before possibly switching to a new
5512 * timeline, which creates a new segment, and after the last ReadRecord().
5514 SetInstallXLogFileSegmentActive();
5517 * Consider whether we need to assign a new timeline ID.
5519 * If we did archive recovery, we always assign a new ID. This handles a
5520 * couple of issues. If we stopped short of the end of WAL during
5521 * recovery, then we are clearly generating a new timeline and must assign
5522 * it a unique new ID. Even if we ran to the end, modifying the current
5523 * last segment is problematic because it may result in trying to
5524 * overwrite an already-archived copy of that segment, and we encourage
5525 * DBAs to make their archive_commands reject that. We can dodge the
5526 * problem by making the new active segment have a new timeline ID.
5528 * In a normal crash recovery, we can just extend the timeline we were in.
5530 newTLI = endOfRecoveryInfo->lastRecTLI;
5531 if (ArchiveRecoveryRequested)
5533 newTLI = findNewestTimeLine(recoveryTargetTLI) + 1;
5534 ereport(LOG,
5535 (errmsg("selected new timeline ID: %u", newTLI)));
5538 * Make a writable copy of the last WAL segment. (Note that we also
5539 * have a copy of the last block of the old WAL in
5540 * endOfRecovery->lastPage; we will use that below.)
5542 XLogInitNewTimeline(EndOfLogTLI, EndOfLog, newTLI);
5545 * Remove the signal files out of the way, so that we don't
5546 * accidentally re-enter archive recovery mode in a subsequent crash.
5548 if (endOfRecoveryInfo->standby_signal_file_found)
5549 durable_unlink(STANDBY_SIGNAL_FILE, FATAL);
5551 if (endOfRecoveryInfo->recovery_signal_file_found)
5552 durable_unlink(RECOVERY_SIGNAL_FILE, FATAL);
5555 * Write the timeline history file, and have it archived. After this
5556 * point (or rather, as soon as the file is archived), the timeline
5557 * will appear as "taken" in the WAL archive and to any standby
5558 * servers. If we crash before actually switching to the new
5559 * timeline, standby servers will nevertheless think that we switched
5560 * to the new timeline, and will try to connect to the new timeline.
5561 * To minimize the window for that, try to do as little as possible
5562 * between here and writing the end-of-recovery record.
5564 writeTimeLineHistory(newTLI, recoveryTargetTLI,
5565 EndOfLog, endOfRecoveryInfo->recoveryStopReason);
5567 ereport(LOG,
5568 (errmsg("archive recovery complete")));
5571 /* Save the selected TimeLineID in shared memory, too */
5572 XLogCtl->InsertTimeLineID = newTLI;
5573 XLogCtl->PrevTimeLineID = endOfRecoveryInfo->lastRecTLI;
5576 * Actually, if WAL ended in an incomplete record, skip the parts that
5577 * made it through and start writing after the portion that persisted.
5578 * (It's critical to first write an OVERWRITE_CONTRECORD message, which
5579 * we'll do as soon as we're open for writing new WAL.)
5581 if (!XLogRecPtrIsInvalid(missingContrecPtr))
5584 * We should only have a missingContrecPtr if we're not switching to
5585 * a new timeline. When a timeline switch occurs, WAL is copied from
5586 * the old timeline to the new only up to the end of the last complete
5587 * record, so there can't be an incomplete WAL record that we need to
5588 * disregard.
5590 Assert(newTLI == endOfRecoveryInfo->lastRecTLI);
5591 Assert(!XLogRecPtrIsInvalid(abortedRecPtr));
5592 EndOfLog = missingContrecPtr;
5596 * Prepare to write WAL starting at EndOfLog location, and init xlog
5597 * buffer cache using the block containing the last record from the
5598 * previous incarnation.
5600 Insert = &XLogCtl->Insert;
5601 Insert->PrevBytePos = XLogRecPtrToBytePos(endOfRecoveryInfo->lastRec);
5602 Insert->CurrBytePos = XLogRecPtrToBytePos(EndOfLog);
5605 * Tricky point here: lastPage contains the *last* block that the LastRec
5606 * record spans, not the one it starts in. The last block is indeed the
5607 * one we want to use.
5609 if (EndOfLog % XLOG_BLCKSZ != 0)
5611 char *page;
5612 int len;
5613 int firstIdx;
5615 firstIdx = XLogRecPtrToBufIdx(EndOfLog);
5616 len = EndOfLog - endOfRecoveryInfo->lastPageBeginPtr;
5617 Assert(len < XLOG_BLCKSZ);
5619 /* Copy the valid part of the last block, and zero the rest */
5620 page = &XLogCtl->pages[firstIdx * XLOG_BLCKSZ];
5621 memcpy(page, endOfRecoveryInfo->lastPage, len);
5622 memset(page + len, 0, XLOG_BLCKSZ - len);
5624 XLogCtl->xlblocks[firstIdx] = endOfRecoveryInfo->lastPageBeginPtr + XLOG_BLCKSZ;
5625 XLogCtl->InitializedUpTo = endOfRecoveryInfo->lastPageBeginPtr + XLOG_BLCKSZ;
5627 else
5630 * There is no partial block to copy. Just set InitializedUpTo, and
5631 * let the first attempt to insert a log record to initialize the next
5632 * buffer.
5634 XLogCtl->InitializedUpTo = EndOfLog;
5637 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5639 XLogCtl->LogwrtResult = LogwrtResult;
5641 XLogCtl->LogwrtRqst.Write = EndOfLog;
5642 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5645 * Preallocate additional log files, if wanted.
5647 PreallocXlogFiles(EndOfLog, newTLI);
5650 * Okay, we're officially UP.
5652 InRecovery = false;
5654 /* start the archive_timeout timer and LSN running */
5655 XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
5656 XLogCtl->lastSegSwitchLSN = EndOfLog;
5658 /* also initialize latestCompletedXid, to nextXid - 1 */
5659 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
5660 ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
5661 FullTransactionIdRetreat(&ShmemVariableCache->latestCompletedXid);
5662 LWLockRelease(ProcArrayLock);
5665 * Start up subtrans, if not already done for hot standby. (commit
5666 * timestamps are started below, if necessary.)
5668 if (standbyState == STANDBY_DISABLED)
5669 StartupSUBTRANS(oldestActiveXID);
5672 * Perform end of recovery actions for any SLRUs that need it.
5674 TrimCLOG();
5675 TrimMultiXact();
5677 /* Reload shared-memory state for prepared transactions */
5678 RecoverPreparedTransactions();
5680 /* Shut down xlogreader */
5681 ShutdownWalRecovery();
5683 /* Enable WAL writes for this backend only. */
5684 LocalSetXLogInsertAllowed();
5686 /* If necessary, write overwrite-contrecord before doing anything else */
5687 if (!XLogRecPtrIsInvalid(abortedRecPtr))
5689 Assert(!XLogRecPtrIsInvalid(missingContrecPtr));
5690 CreateOverwriteContrecordRecord(abortedRecPtr, missingContrecPtr, newTLI);
5694 * Update full_page_writes in shared memory and write an XLOG_FPW_CHANGE
5695 * record before resource manager writes cleanup WAL records or checkpoint
5696 * record is written.
5698 Insert->fullPageWrites = lastFullPageWrites;
5699 UpdateFullPageWrites();
5702 * Emit checkpoint or end-of-recovery record in XLOG, if required.
5704 if (performedWalRecovery)
5705 promoted = PerformRecoveryXLogAction();
5708 * If any of the critical GUCs have changed, log them before we allow
5709 * backends to write WAL.
5711 XLogReportParameters();
5713 /* If this is archive recovery, perform post-recovery cleanup actions. */
5714 if (ArchiveRecoveryRequested)
5715 CleanupAfterArchiveRecovery(EndOfLogTLI, EndOfLog, newTLI);
5718 * Local WAL inserts enabled, so it's time to finish initialization of
5719 * commit timestamp.
5721 CompleteCommitTsInitialization();
5724 * All done with end-of-recovery actions.
5726 * Now allow backends to write WAL and update the control file status in
5727 * consequence. SharedRecoveryState, that controls if backends can write
5728 * WAL, is updated while holding ControlFileLock to prevent other backends
5729 * to look at an inconsistent state of the control file in shared memory.
5730 * There is still a small window during which backends can write WAL and
5731 * the control file is still referring to a system not in DB_IN_PRODUCTION
5732 * state while looking at the on-disk control file.
5734 * Also, we use info_lck to update SharedRecoveryState to ensure that
5735 * there are no race conditions concerning visibility of other recent
5736 * updates to shared memory.
5738 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5739 ControlFile->state = DB_IN_PRODUCTION;
5741 SpinLockAcquire(&XLogCtl->info_lck);
5742 XLogCtl->SharedRecoveryState = RECOVERY_STATE_DONE;
5743 SpinLockRelease(&XLogCtl->info_lck);
5745 UpdateControlFile();
5746 LWLockRelease(ControlFileLock);
5749 * Shutdown the recovery environment. This must occur after
5750 * RecoverPreparedTransactions() (see notes in lock_twophase_recover())
5751 * and after switching SharedRecoveryState to RECOVERY_STATE_DONE so as
5752 * any session building a snapshot will not rely on KnownAssignedXids as
5753 * RecoveryInProgress() would return false at this stage. This is
5754 * particularly critical for prepared 2PC transactions, that would still
5755 * need to be included in snapshots once recovery has ended.
5757 if (standbyState != STANDBY_DISABLED)
5758 ShutdownRecoveryTransactionEnvironment();
5761 * If there were cascading standby servers connected to us, nudge any wal
5762 * sender processes to notice that we've been promoted.
5764 WalSndWakeup();
5767 * If this was a promotion, request an (online) checkpoint now. This isn't
5768 * required for consistency, but the last restartpoint might be far back,
5769 * and in case of a crash, recovering from it might take a longer than is
5770 * appropriate now that we're not in standby mode anymore.
5772 if (promoted)
5773 RequestCheckpoint(CHECKPOINT_FORCE);
5777 * Callback from PerformWalRecovery(), called when we switch from crash
5778 * recovery to archive recovery mode. Updates the control file accordingly.
5780 void
5781 SwitchIntoArchiveRecovery(XLogRecPtr EndRecPtr, TimeLineID replayTLI)
5783 /* initialize minRecoveryPoint to this record */
5784 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5785 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
5786 if (ControlFile->minRecoveryPoint < EndRecPtr)
5788 ControlFile->minRecoveryPoint = EndRecPtr;
5789 ControlFile->minRecoveryPointTLI = replayTLI;
5791 /* update local copy */
5792 LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
5793 LocalMinRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
5796 * The startup process can update its local copy of minRecoveryPoint from
5797 * this point.
5799 updateMinRecoveryPoint = true;
5801 UpdateControlFile();
5804 * We update SharedRecoveryState while holding the lock on ControlFileLock
5805 * so both states are consistent in shared memory.
5807 SpinLockAcquire(&XLogCtl->info_lck);
5808 XLogCtl->SharedRecoveryState = RECOVERY_STATE_ARCHIVE;
5809 SpinLockRelease(&XLogCtl->info_lck);
5811 LWLockRelease(ControlFileLock);
5815 * Callback from PerformWalRecovery(), called when we reach the end of backup.
5816 * Updates the control file accordingly.
5818 void
5819 ReachedEndOfBackup(XLogRecPtr EndRecPtr, TimeLineID tli)
5822 * We have reached the end of base backup, as indicated by pg_control. The
5823 * data on disk is now consistent (unless minRecovery point is further
5824 * ahead, which can happen if we crashed during previous recovery). Reset
5825 * backupStartPoint and backupEndPoint, and update minRecoveryPoint to
5826 * make sure we don't allow starting up at an earlier point even if
5827 * recovery is stopped and restarted soon after this.
5829 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5831 if (ControlFile->minRecoveryPoint < EndRecPtr)
5833 ControlFile->minRecoveryPoint = EndRecPtr;
5834 ControlFile->minRecoveryPointTLI = tli;
5837 ControlFile->backupStartPoint = InvalidXLogRecPtr;
5838 ControlFile->backupEndPoint = InvalidXLogRecPtr;
5839 ControlFile->backupEndRequired = false;
5840 UpdateControlFile();
5842 LWLockRelease(ControlFileLock);
5846 * Perform whatever XLOG actions are necessary at end of REDO.
5848 * The goal here is to make sure that we'll be able to recover properly if
5849 * we crash again. If we choose to write a checkpoint, we'll write a shutdown
5850 * checkpoint rather than an on-line one. This is not particularly critical,
5851 * but since we may be assigning a new TLI, using a shutdown checkpoint allows
5852 * us to have the rule that TLI only changes in shutdown checkpoints, which
5853 * allows some extra error checking in xlog_redo.
5855 static bool
5856 PerformRecoveryXLogAction(void)
5858 bool promoted = false;
5861 * Perform a checkpoint to update all our recovery activity to disk.
5863 * Note that we write a shutdown checkpoint rather than an on-line one.
5864 * This is not particularly critical, but since we may be assigning a new
5865 * TLI, using a shutdown checkpoint allows us to have the rule that TLI
5866 * only changes in shutdown checkpoints, which allows some extra error
5867 * checking in xlog_redo.
5869 * In promotion, only create a lightweight end-of-recovery record instead
5870 * of a full checkpoint. A checkpoint is requested later, after we're
5871 * fully out of recovery mode and already accepting queries.
5873 if (ArchiveRecoveryRequested && IsUnderPostmaster &&
5874 PromoteIsTriggered())
5876 promoted = true;
5879 * Insert a special WAL record to mark the end of recovery, since we
5880 * aren't doing a checkpoint. That means that the checkpointer process
5881 * may likely be in the middle of a time-smoothed restartpoint and
5882 * could continue to be for minutes after this. That sounds strange,
5883 * but the effect is roughly the same and it would be stranger to try
5884 * to come out of the restartpoint and then checkpoint. We request a
5885 * checkpoint later anyway, just for safety.
5887 CreateEndOfRecoveryRecord();
5889 else
5891 RequestCheckpoint(CHECKPOINT_END_OF_RECOVERY |
5892 CHECKPOINT_IMMEDIATE |
5893 CHECKPOINT_WAIT);
5896 return promoted;
5900 * Is the system still in recovery?
5902 * Unlike testing InRecovery, this works in any process that's connected to
5903 * shared memory.
5905 bool
5906 RecoveryInProgress(void)
5909 * We check shared state each time only until we leave recovery mode. We
5910 * can't re-enter recovery, so there's no need to keep checking after the
5911 * shared variable has once been seen false.
5913 if (!LocalRecoveryInProgress)
5914 return false;
5915 else
5918 * use volatile pointer to make sure we make a fresh read of the
5919 * shared variable.
5921 volatile XLogCtlData *xlogctl = XLogCtl;
5923 LocalRecoveryInProgress = (xlogctl->SharedRecoveryState != RECOVERY_STATE_DONE);
5926 * Note: We don't need a memory barrier when we're still in recovery.
5927 * We might exit recovery immediately after return, so the caller
5928 * can't rely on 'true' meaning that we're still in recovery anyway.
5931 return LocalRecoveryInProgress;
5936 * Returns current recovery state from shared memory.
5938 * This returned state is kept consistent with the contents of the control
5939 * file. See details about the possible values of RecoveryState in xlog.h.
5941 RecoveryState
5942 GetRecoveryState(void)
5944 RecoveryState retval;
5946 SpinLockAcquire(&XLogCtl->info_lck);
5947 retval = XLogCtl->SharedRecoveryState;
5948 SpinLockRelease(&XLogCtl->info_lck);
5950 return retval;
5954 * Is this process allowed to insert new WAL records?
5956 * Ordinarily this is essentially equivalent to !RecoveryInProgress().
5957 * But we also have provisions for forcing the result "true" or "false"
5958 * within specific processes regardless of the global state.
5960 bool
5961 XLogInsertAllowed(void)
5964 * If value is "unconditionally true" or "unconditionally false", just
5965 * return it. This provides the normal fast path once recovery is known
5966 * done.
5968 if (LocalXLogInsertAllowed >= 0)
5969 return (bool) LocalXLogInsertAllowed;
5972 * Else, must check to see if we're still in recovery.
5974 if (RecoveryInProgress())
5975 return false;
5978 * On exit from recovery, reset to "unconditionally true", since there is
5979 * no need to keep checking.
5981 LocalXLogInsertAllowed = 1;
5982 return true;
5986 * Make XLogInsertAllowed() return true in the current process only.
5988 * Note: it is allowed to switch LocalXLogInsertAllowed back to -1 later,
5989 * and even call LocalSetXLogInsertAllowed() again after that.
5991 * Returns the previous value of LocalXLogInsertAllowed.
5993 static int
5994 LocalSetXLogInsertAllowed(void)
5996 int oldXLogAllowed = LocalXLogInsertAllowed;
5998 LocalXLogInsertAllowed = 1;
6000 return oldXLogAllowed;
6004 * Return the current Redo pointer from shared memory.
6006 * As a side-effect, the local RedoRecPtr copy is updated.
6008 XLogRecPtr
6009 GetRedoRecPtr(void)
6011 XLogRecPtr ptr;
6014 * The possibly not up-to-date copy in XlogCtl is enough. Even if we
6015 * grabbed a WAL insertion lock to read the authoritative value in
6016 * Insert->RedoRecPtr, someone might update it just after we've released
6017 * the lock.
6019 SpinLockAcquire(&XLogCtl->info_lck);
6020 ptr = XLogCtl->RedoRecPtr;
6021 SpinLockRelease(&XLogCtl->info_lck);
6023 if (RedoRecPtr < ptr)
6024 RedoRecPtr = ptr;
6026 return RedoRecPtr;
6030 * Return information needed to decide whether a modified block needs a
6031 * full-page image to be included in the WAL record.
6033 * The returned values are cached copies from backend-private memory, and
6034 * possibly out-of-date or, indeed, uninitialized, in which case they will
6035 * be InvalidXLogRecPtr and false, respectively. XLogInsertRecord will
6036 * re-check them against up-to-date values, while holding the WAL insert lock.
6038 void
6039 GetFullPageWriteInfo(XLogRecPtr *RedoRecPtr_p, bool *doPageWrites_p)
6041 *RedoRecPtr_p = RedoRecPtr;
6042 *doPageWrites_p = doPageWrites;
6046 * GetInsertRecPtr -- Returns the current insert position.
6048 * NOTE: The value *actually* returned is the position of the last full
6049 * xlog page. It lags behind the real insert position by at most 1 page.
6050 * For that, we don't need to scan through WAL insertion locks, and an
6051 * approximation is enough for the current usage of this function.
6053 XLogRecPtr
6054 GetInsertRecPtr(void)
6056 XLogRecPtr recptr;
6058 SpinLockAcquire(&XLogCtl->info_lck);
6059 recptr = XLogCtl->LogwrtRqst.Write;
6060 SpinLockRelease(&XLogCtl->info_lck);
6062 return recptr;
6066 * GetFlushRecPtr -- Returns the current flush position, ie, the last WAL
6067 * position known to be fsync'd to disk. This should only be used on a
6068 * system that is known not to be in recovery.
6070 XLogRecPtr
6071 GetFlushRecPtr(TimeLineID *insertTLI)
6073 Assert(XLogCtl->SharedRecoveryState == RECOVERY_STATE_DONE);
6075 SpinLockAcquire(&XLogCtl->info_lck);
6076 LogwrtResult = XLogCtl->LogwrtResult;
6077 SpinLockRelease(&XLogCtl->info_lck);
6080 * If we're writing and flushing WAL, the time line can't be changing, so
6081 * no lock is required.
6083 if (insertTLI)
6084 *insertTLI = XLogCtl->InsertTimeLineID;
6086 return LogwrtResult.Flush;
6090 * GetWALInsertionTimeLine -- Returns the current timeline of a system that
6091 * is not in recovery.
6093 TimeLineID
6094 GetWALInsertionTimeLine(void)
6096 Assert(XLogCtl->SharedRecoveryState == RECOVERY_STATE_DONE);
6098 /* Since the value can't be changing, no lock is required. */
6099 return XLogCtl->InsertTimeLineID;
6103 * GetLastImportantRecPtr -- Returns the LSN of the last important record
6104 * inserted. All records not explicitly marked as unimportant are considered
6105 * important.
6107 * The LSN is determined by computing the maximum of
6108 * WALInsertLocks[i].lastImportantAt.
6110 XLogRecPtr
6111 GetLastImportantRecPtr(void)
6113 XLogRecPtr res = InvalidXLogRecPtr;
6114 int i;
6116 for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
6118 XLogRecPtr last_important;
6121 * Need to take a lock to prevent torn reads of the LSN, which are
6122 * possible on some of the supported platforms. WAL insert locks only
6123 * support exclusive mode, so we have to use that.
6125 LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
6126 last_important = WALInsertLocks[i].l.lastImportantAt;
6127 LWLockRelease(&WALInsertLocks[i].l.lock);
6129 if (res < last_important)
6130 res = last_important;
6133 return res;
6137 * Get the time and LSN of the last xlog segment switch
6139 pg_time_t
6140 GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
6142 pg_time_t result;
6144 /* Need WALWriteLock, but shared lock is sufficient */
6145 LWLockAcquire(WALWriteLock, LW_SHARED);
6146 result = XLogCtl->lastSegSwitchTime;
6147 *lastSwitchLSN = XLogCtl->lastSegSwitchLSN;
6148 LWLockRelease(WALWriteLock);
6150 return result;
6154 * This must be called ONCE during postmaster or standalone-backend shutdown
6156 void
6157 ShutdownXLOG(int code, Datum arg)
6160 * We should have an aux process resource owner to use, and we should not
6161 * be in a transaction that's installed some other resowner.
6163 Assert(AuxProcessResourceOwner != NULL);
6164 Assert(CurrentResourceOwner == NULL ||
6165 CurrentResourceOwner == AuxProcessResourceOwner);
6166 CurrentResourceOwner = AuxProcessResourceOwner;
6168 /* Don't be chatty in standalone mode */
6169 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
6170 (errmsg("shutting down")));
6173 * Signal walsenders to move to stopping state.
6175 WalSndInitStopping();
6178 * Wait for WAL senders to be in stopping state. This prevents commands
6179 * from writing new WAL.
6181 WalSndWaitStopping();
6183 if (RecoveryInProgress())
6184 CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
6185 else
6188 * If archiving is enabled, rotate the last XLOG file so that all the
6189 * remaining records are archived (postmaster wakes up the archiver
6190 * process one more time at the end of shutdown). The checkpoint
6191 * record will go to the next XLOG file and won't be archived (yet).
6193 if (XLogArchivingActive())
6194 RequestXLogSwitch(false);
6196 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
6201 * Log start of a checkpoint.
6203 static void
6204 LogCheckpointStart(int flags, bool restartpoint)
6206 if (restartpoint)
6207 ereport(LOG,
6208 /* translator: the placeholders show checkpoint options */
6209 (errmsg("restartpoint starting:%s%s%s%s%s%s%s%s",
6210 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
6211 (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
6212 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
6213 (flags & CHECKPOINT_FORCE) ? " force" : "",
6214 (flags & CHECKPOINT_WAIT) ? " wait" : "",
6215 (flags & CHECKPOINT_CAUSE_XLOG) ? " wal" : "",
6216 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "",
6217 (flags & CHECKPOINT_FLUSH_ALL) ? " flush-all" : "")));
6218 else
6219 ereport(LOG,
6220 /* translator: the placeholders show checkpoint options */
6221 (errmsg("checkpoint starting:%s%s%s%s%s%s%s%s",
6222 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
6223 (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
6224 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
6225 (flags & CHECKPOINT_FORCE) ? " force" : "",
6226 (flags & CHECKPOINT_WAIT) ? " wait" : "",
6227 (flags & CHECKPOINT_CAUSE_XLOG) ? " wal" : "",
6228 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "",
6229 (flags & CHECKPOINT_FLUSH_ALL) ? " flush-all" : "")));
6233 * Log end of a checkpoint.
6235 static void
6236 LogCheckpointEnd(bool restartpoint)
6238 long write_msecs,
6239 sync_msecs,
6240 total_msecs,
6241 longest_msecs,
6242 average_msecs;
6243 uint64 average_sync_time;
6245 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
6247 write_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_write_t,
6248 CheckpointStats.ckpt_sync_t);
6250 sync_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_sync_t,
6251 CheckpointStats.ckpt_sync_end_t);
6253 /* Accumulate checkpoint timing summary data, in milliseconds. */
6254 PendingCheckpointerStats.checkpoint_write_time += write_msecs;
6255 PendingCheckpointerStats.checkpoint_sync_time += sync_msecs;
6258 * All of the published timing statistics are accounted for. Only
6259 * continue if a log message is to be written.
6261 if (!log_checkpoints)
6262 return;
6264 total_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_start_t,
6265 CheckpointStats.ckpt_end_t);
6268 * Timing values returned from CheckpointStats are in microseconds.
6269 * Convert to milliseconds for consistent printing.
6271 longest_msecs = (long) ((CheckpointStats.ckpt_longest_sync + 999) / 1000);
6273 average_sync_time = 0;
6274 if (CheckpointStats.ckpt_sync_rels > 0)
6275 average_sync_time = CheckpointStats.ckpt_agg_sync_time /
6276 CheckpointStats.ckpt_sync_rels;
6277 average_msecs = (long) ((average_sync_time + 999) / 1000);
6280 * ControlFileLock is not required to see ControlFile->checkPoint and
6281 * ->checkPointCopy here as we are the only updator of those variables at
6282 * this moment.
6284 if (restartpoint)
6285 ereport(LOG,
6286 (errmsg("restartpoint complete: wrote %d buffers (%.1f%%); "
6287 "%d WAL file(s) added, %d removed, %d recycled; "
6288 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s; "
6289 "sync files=%d, longest=%ld.%03d s, average=%ld.%03d s; "
6290 "distance=%d kB, estimate=%d kB; "
6291 "lsn=%X/%X, redo lsn=%X/%X",
6292 CheckpointStats.ckpt_bufs_written,
6293 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
6294 CheckpointStats.ckpt_segs_added,
6295 CheckpointStats.ckpt_segs_removed,
6296 CheckpointStats.ckpt_segs_recycled,
6297 write_msecs / 1000, (int) (write_msecs % 1000),
6298 sync_msecs / 1000, (int) (sync_msecs % 1000),
6299 total_msecs / 1000, (int) (total_msecs % 1000),
6300 CheckpointStats.ckpt_sync_rels,
6301 longest_msecs / 1000, (int) (longest_msecs % 1000),
6302 average_msecs / 1000, (int) (average_msecs % 1000),
6303 (int) (PrevCheckPointDistance / 1024.0),
6304 (int) (CheckPointDistanceEstimate / 1024.0),
6305 LSN_FORMAT_ARGS(ControlFile->checkPoint),
6306 LSN_FORMAT_ARGS(ControlFile->checkPointCopy.redo))));
6307 else
6308 ereport(LOG,
6309 (errmsg("checkpoint complete: wrote %d buffers (%.1f%%); "
6310 "%d WAL file(s) added, %d removed, %d recycled; "
6311 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s; "
6312 "sync files=%d, longest=%ld.%03d s, average=%ld.%03d s; "
6313 "distance=%d kB, estimate=%d kB; "
6314 "lsn=%X/%X, redo lsn=%X/%X",
6315 CheckpointStats.ckpt_bufs_written,
6316 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
6317 CheckpointStats.ckpt_segs_added,
6318 CheckpointStats.ckpt_segs_removed,
6319 CheckpointStats.ckpt_segs_recycled,
6320 write_msecs / 1000, (int) (write_msecs % 1000),
6321 sync_msecs / 1000, (int) (sync_msecs % 1000),
6322 total_msecs / 1000, (int) (total_msecs % 1000),
6323 CheckpointStats.ckpt_sync_rels,
6324 longest_msecs / 1000, (int) (longest_msecs % 1000),
6325 average_msecs / 1000, (int) (average_msecs % 1000),
6326 (int) (PrevCheckPointDistance / 1024.0),
6327 (int) (CheckPointDistanceEstimate / 1024.0),
6328 LSN_FORMAT_ARGS(ControlFile->checkPoint),
6329 LSN_FORMAT_ARGS(ControlFile->checkPointCopy.redo))));
6333 * Update the estimate of distance between checkpoints.
6335 * The estimate is used to calculate the number of WAL segments to keep
6336 * preallocated, see XLOGfileslop().
6338 static void
6339 UpdateCheckPointDistanceEstimate(uint64 nbytes)
6342 * To estimate the number of segments consumed between checkpoints, keep a
6343 * moving average of the amount of WAL generated in previous checkpoint
6344 * cycles. However, if the load is bursty, with quiet periods and busy
6345 * periods, we want to cater for the peak load. So instead of a plain
6346 * moving average, let the average decline slowly if the previous cycle
6347 * used less WAL than estimated, but bump it up immediately if it used
6348 * more.
6350 * When checkpoints are triggered by max_wal_size, this should converge to
6351 * CheckpointSegments * wal_segment_size,
6353 * Note: This doesn't pay any attention to what caused the checkpoint.
6354 * Checkpoints triggered manually with CHECKPOINT command, or by e.g.
6355 * starting a base backup, are counted the same as those created
6356 * automatically. The slow-decline will largely mask them out, if they are
6357 * not frequent. If they are frequent, it seems reasonable to count them
6358 * in as any others; if you issue a manual checkpoint every 5 minutes and
6359 * never let a timed checkpoint happen, it makes sense to base the
6360 * preallocation on that 5 minute interval rather than whatever
6361 * checkpoint_timeout is set to.
6363 PrevCheckPointDistance = nbytes;
6364 if (CheckPointDistanceEstimate < nbytes)
6365 CheckPointDistanceEstimate = nbytes;
6366 else
6367 CheckPointDistanceEstimate =
6368 (0.90 * CheckPointDistanceEstimate + 0.10 * (double) nbytes);
6372 * Update the ps display for a process running a checkpoint. Note that
6373 * this routine should not do any allocations so as it can be called
6374 * from a critical section.
6376 static void
6377 update_checkpoint_display(int flags, bool restartpoint, bool reset)
6380 * The status is reported only for end-of-recovery and shutdown
6381 * checkpoints or shutdown restartpoints. Updating the ps display is
6382 * useful in those situations as it may not be possible to rely on
6383 * pg_stat_activity to see the status of the checkpointer or the startup
6384 * process.
6386 if ((flags & (CHECKPOINT_END_OF_RECOVERY | CHECKPOINT_IS_SHUTDOWN)) == 0)
6387 return;
6389 if (reset)
6390 set_ps_display("");
6391 else
6393 char activitymsg[128];
6395 snprintf(activitymsg, sizeof(activitymsg), "performing %s%s%s",
6396 (flags & CHECKPOINT_END_OF_RECOVERY) ? "end-of-recovery " : "",
6397 (flags & CHECKPOINT_IS_SHUTDOWN) ? "shutdown " : "",
6398 restartpoint ? "restartpoint" : "checkpoint");
6399 set_ps_display(activitymsg);
6405 * Perform a checkpoint --- either during shutdown, or on-the-fly
6407 * flags is a bitwise OR of the following:
6408 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
6409 * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
6410 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
6411 * ignoring checkpoint_completion_target parameter.
6412 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
6413 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
6414 * CHECKPOINT_END_OF_RECOVERY).
6415 * CHECKPOINT_FLUSH_ALL: also flush buffers of unlogged tables.
6417 * Note: flags contains other bits, of interest here only for logging purposes.
6418 * In particular note that this routine is synchronous and does not pay
6419 * attention to CHECKPOINT_WAIT.
6421 * If !shutdown then we are writing an online checkpoint. This is a very special
6422 * kind of operation and WAL record because the checkpoint action occurs over
6423 * a period of time yet logically occurs at just a single LSN. The logical
6424 * position of the WAL record (redo ptr) is the same or earlier than the
6425 * physical position. When we replay WAL we locate the checkpoint via its
6426 * physical position then read the redo ptr and actually start replay at the
6427 * earlier logical position. Note that we don't write *anything* to WAL at
6428 * the logical position, so that location could be any other kind of WAL record.
6429 * All of this mechanism allows us to continue working while we checkpoint.
6430 * As a result, timing of actions is critical here and be careful to note that
6431 * this function will likely take minutes to execute on a busy system.
6433 void
6434 CreateCheckPoint(int flags)
6436 bool shutdown;
6437 CheckPoint checkPoint;
6438 XLogRecPtr recptr;
6439 XLogSegNo _logSegNo;
6440 XLogCtlInsert *Insert = &XLogCtl->Insert;
6441 uint32 freespace;
6442 XLogRecPtr PriorRedoPtr;
6443 XLogRecPtr curInsert;
6444 XLogRecPtr last_important_lsn;
6445 VirtualTransactionId *vxids;
6446 int nvxids;
6447 int oldXLogAllowed = 0;
6450 * An end-of-recovery checkpoint is really a shutdown checkpoint, just
6451 * issued at a different time.
6453 if (flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY))
6454 shutdown = true;
6455 else
6456 shutdown = false;
6458 /* sanity check */
6459 if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
6460 elog(ERROR, "can't create a checkpoint during recovery");
6463 * Prepare to accumulate statistics.
6465 * Note: because it is possible for log_checkpoints to change while a
6466 * checkpoint proceeds, we always accumulate stats, even if
6467 * log_checkpoints is currently off.
6469 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
6470 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
6473 * Let smgr prepare for checkpoint; this has to happen outside the
6474 * critical section and before we determine the REDO pointer. Note that
6475 * smgr must not do anything that'd have to be undone if we decide no
6476 * checkpoint is needed.
6478 SyncPreCheckpoint();
6481 * Use a critical section to force system panic if we have trouble.
6483 START_CRIT_SECTION();
6485 if (shutdown)
6487 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6488 ControlFile->state = DB_SHUTDOWNING;
6489 UpdateControlFile();
6490 LWLockRelease(ControlFileLock);
6493 /* Begin filling in the checkpoint WAL record */
6494 MemSet(&checkPoint, 0, sizeof(checkPoint));
6495 checkPoint.time = (pg_time_t) time(NULL);
6498 * For Hot Standby, derive the oldestActiveXid before we fix the redo
6499 * pointer. This allows us to begin accumulating changes to assemble our
6500 * starting snapshot of locks and transactions.
6502 if (!shutdown && XLogStandbyInfoActive())
6503 checkPoint.oldestActiveXid = GetOldestActiveTransactionId();
6504 else
6505 checkPoint.oldestActiveXid = InvalidTransactionId;
6508 * Get location of last important record before acquiring insert locks (as
6509 * GetLastImportantRecPtr() also locks WAL locks).
6511 last_important_lsn = GetLastImportantRecPtr();
6514 * We must block concurrent insertions while examining insert state to
6515 * determine the checkpoint REDO pointer.
6517 WALInsertLockAcquireExclusive();
6518 curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
6521 * If this isn't a shutdown or forced checkpoint, and if there has been no
6522 * WAL activity requiring a checkpoint, skip it. The idea here is to
6523 * avoid inserting duplicate checkpoints when the system is idle.
6525 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
6526 CHECKPOINT_FORCE)) == 0)
6528 if (last_important_lsn == ControlFile->checkPoint)
6530 WALInsertLockRelease();
6531 END_CRIT_SECTION();
6532 ereport(DEBUG1,
6533 (errmsg_internal("checkpoint skipped because system is idle")));
6534 return;
6539 * An end-of-recovery checkpoint is created before anyone is allowed to
6540 * write WAL. To allow us to write the checkpoint record, temporarily
6541 * enable XLogInsertAllowed.
6543 if (flags & CHECKPOINT_END_OF_RECOVERY)
6544 oldXLogAllowed = LocalSetXLogInsertAllowed();
6546 checkPoint.ThisTimeLineID = XLogCtl->InsertTimeLineID;
6547 if (flags & CHECKPOINT_END_OF_RECOVERY)
6548 checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
6549 else
6550 checkPoint.PrevTimeLineID = checkPoint.ThisTimeLineID;
6552 checkPoint.fullPageWrites = Insert->fullPageWrites;
6555 * Compute new REDO record ptr = location of next XLOG record.
6557 * NB: this is NOT necessarily where the checkpoint record itself will be,
6558 * since other backends may insert more XLOG records while we're off doing
6559 * the buffer flush work. Those XLOG records are logically after the
6560 * checkpoint, even though physically before it. Got that?
6562 freespace = INSERT_FREESPACE(curInsert);
6563 if (freespace == 0)
6565 if (XLogSegmentOffset(curInsert, wal_segment_size) == 0)
6566 curInsert += SizeOfXLogLongPHD;
6567 else
6568 curInsert += SizeOfXLogShortPHD;
6570 checkPoint.redo = curInsert;
6573 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
6574 * must be done while holding all the insertion locks.
6576 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
6577 * pointing past where it really needs to point. This is okay; the only
6578 * consequence is that XLogInsert might back up whole buffers that it
6579 * didn't really need to. We can't postpone advancing RedoRecPtr because
6580 * XLogInserts that happen while we are dumping buffers must assume that
6581 * their buffer changes are not included in the checkpoint.
6583 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
6586 * Now we can release the WAL insertion locks, allowing other xacts to
6587 * proceed while we are flushing disk buffers.
6589 WALInsertLockRelease();
6591 /* Update the info_lck-protected copy of RedoRecPtr as well */
6592 SpinLockAcquire(&XLogCtl->info_lck);
6593 XLogCtl->RedoRecPtr = checkPoint.redo;
6594 SpinLockRelease(&XLogCtl->info_lck);
6597 * If enabled, log checkpoint start. We postpone this until now so as not
6598 * to log anything if we decided to skip the checkpoint.
6600 if (log_checkpoints)
6601 LogCheckpointStart(flags, false);
6603 /* Update the process title */
6604 update_checkpoint_display(flags, false, false);
6606 TRACE_POSTGRESQL_CHECKPOINT_START(flags);
6609 * Get the other info we need for the checkpoint record.
6611 * We don't need to save oldestClogXid in the checkpoint, it only matters
6612 * for the short period in which clog is being truncated, and if we crash
6613 * during that we'll redo the clog truncation and fix up oldestClogXid
6614 * there.
6616 LWLockAcquire(XidGenLock, LW_SHARED);
6617 checkPoint.nextXid = ShmemVariableCache->nextXid;
6618 checkPoint.oldestXid = ShmemVariableCache->oldestXid;
6619 checkPoint.oldestXidDB = ShmemVariableCache->oldestXidDB;
6620 LWLockRelease(XidGenLock);
6622 LWLockAcquire(CommitTsLock, LW_SHARED);
6623 checkPoint.oldestCommitTsXid = ShmemVariableCache->oldestCommitTsXid;
6624 checkPoint.newestCommitTsXid = ShmemVariableCache->newestCommitTsXid;
6625 LWLockRelease(CommitTsLock);
6627 LWLockAcquire(OidGenLock, LW_SHARED);
6628 checkPoint.nextOid = ShmemVariableCache->nextOid;
6629 if (!shutdown)
6630 checkPoint.nextOid += ShmemVariableCache->oidCount;
6631 LWLockRelease(OidGenLock);
6633 MultiXactGetCheckptMulti(shutdown,
6634 &checkPoint.nextMulti,
6635 &checkPoint.nextMultiOffset,
6636 &checkPoint.oldestMulti,
6637 &checkPoint.oldestMultiDB);
6640 * Having constructed the checkpoint record, ensure all shmem disk buffers
6641 * and commit-log buffers are flushed to disk.
6643 * This I/O could fail for various reasons. If so, we will fail to
6644 * complete the checkpoint, but there is no reason to force a system
6645 * panic. Accordingly, exit critical section while doing it.
6647 END_CRIT_SECTION();
6650 * In some cases there are groups of actions that must all occur on one
6651 * side or the other of a checkpoint record. Before flushing the
6652 * checkpoint record we must explicitly wait for any backend currently
6653 * performing those groups of actions.
6655 * One example is end of transaction, so we must wait for any transactions
6656 * that are currently in commit critical sections. If an xact inserted
6657 * its commit record into XLOG just before the REDO point, then a crash
6658 * restart from the REDO point would not replay that record, which means
6659 * that our flushing had better include the xact's update of pg_xact. So
6660 * we wait till he's out of his commit critical section before proceeding.
6661 * See notes in RecordTransactionCommit().
6663 * Because we've already released the insertion locks, this test is a bit
6664 * fuzzy: it is possible that we will wait for xacts we didn't really need
6665 * to wait for. But the delay should be short and it seems better to make
6666 * checkpoint take a bit longer than to hold off insertions longer than
6667 * necessary. (In fact, the whole reason we have this issue is that xact.c
6668 * does commit record XLOG insertion and clog update as two separate steps
6669 * protected by different locks, but again that seems best on grounds of
6670 * minimizing lock contention.)
6672 * A transaction that has not yet set delayChkptFlags when we look cannot
6673 * be at risk, since it has not inserted its commit record yet; and one
6674 * that's already cleared it is not at risk either, since it's done fixing
6675 * clog and we will correctly flush the update below. So we cannot miss
6676 * any xacts we need to wait for.
6678 vxids = GetVirtualXIDsDelayingChkpt(&nvxids, DELAY_CHKPT_START);
6679 if (nvxids > 0)
6683 pg_usleep(10000L); /* wait for 10 msec */
6684 } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids,
6685 DELAY_CHKPT_START));
6687 pfree(vxids);
6689 CheckPointGuts(checkPoint.redo, flags);
6691 vxids = GetVirtualXIDsDelayingChkpt(&nvxids, DELAY_CHKPT_COMPLETE);
6692 if (nvxids > 0)
6696 pg_usleep(10000L); /* wait for 10 msec */
6697 } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids,
6698 DELAY_CHKPT_COMPLETE));
6700 pfree(vxids);
6703 * Take a snapshot of running transactions and write this to WAL. This
6704 * allows us to reconstruct the state of running transactions during
6705 * archive recovery, if required. Skip, if this info disabled.
6707 * If we are shutting down, or Startup process is completing crash
6708 * recovery we don't need to write running xact data.
6710 if (!shutdown && XLogStandbyInfoActive())
6711 LogStandbySnapshot();
6713 START_CRIT_SECTION();
6716 * Now insert the checkpoint record into XLOG.
6718 XLogBeginInsert();
6719 XLogRegisterData((char *) (&checkPoint), sizeof(checkPoint));
6720 recptr = XLogInsert(RM_XLOG_ID,
6721 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
6722 XLOG_CHECKPOINT_ONLINE);
6724 XLogFlush(recptr);
6727 * We mustn't write any new WAL after a shutdown checkpoint, or it will be
6728 * overwritten at next startup. No-one should even try, this just allows
6729 * sanity-checking. In the case of an end-of-recovery checkpoint, we want
6730 * to just temporarily disable writing until the system has exited
6731 * recovery.
6733 if (shutdown)
6735 if (flags & CHECKPOINT_END_OF_RECOVERY)
6736 LocalXLogInsertAllowed = oldXLogAllowed;
6737 else
6738 LocalXLogInsertAllowed = 0; /* never again write WAL */
6742 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
6743 * = end of actual checkpoint record.
6745 if (shutdown && checkPoint.redo != ProcLastRecPtr)
6746 ereport(PANIC,
6747 (errmsg("concurrent write-ahead log activity while database system is shutting down")));
6750 * Remember the prior checkpoint's redo ptr for
6751 * UpdateCheckPointDistanceEstimate()
6753 PriorRedoPtr = ControlFile->checkPointCopy.redo;
6756 * Update the control file.
6758 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6759 if (shutdown)
6760 ControlFile->state = DB_SHUTDOWNED;
6761 ControlFile->checkPoint = ProcLastRecPtr;
6762 ControlFile->checkPointCopy = checkPoint;
6763 /* crash recovery should always recover to the end of WAL */
6764 ControlFile->minRecoveryPoint = InvalidXLogRecPtr;
6765 ControlFile->minRecoveryPointTLI = 0;
6768 * Persist unloggedLSN value. It's reset on crash recovery, so this goes
6769 * unused on non-shutdown checkpoints, but seems useful to store it always
6770 * for debugging purposes.
6772 SpinLockAcquire(&XLogCtl->ulsn_lck);
6773 ControlFile->unloggedLSN = XLogCtl->unloggedLSN;
6774 SpinLockRelease(&XLogCtl->ulsn_lck);
6776 UpdateControlFile();
6777 LWLockRelease(ControlFileLock);
6779 /* Update shared-memory copy of checkpoint XID/epoch */
6780 SpinLockAcquire(&XLogCtl->info_lck);
6781 XLogCtl->ckptFullXid = checkPoint.nextXid;
6782 SpinLockRelease(&XLogCtl->info_lck);
6785 * We are now done with critical updates; no need for system panic if we
6786 * have trouble while fooling with old log segments.
6788 END_CRIT_SECTION();
6791 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
6793 SyncPostCheckpoint();
6796 * Update the average distance between checkpoints if the prior checkpoint
6797 * exists.
6799 if (PriorRedoPtr != InvalidXLogRecPtr)
6800 UpdateCheckPointDistanceEstimate(RedoRecPtr - PriorRedoPtr);
6803 * Delete old log files, those no longer needed for last checkpoint to
6804 * prevent the disk holding the xlog from growing full.
6806 XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
6807 KeepLogSeg(recptr, &_logSegNo);
6808 if (InvalidateObsoleteReplicationSlots(_logSegNo))
6811 * Some slots have been invalidated; recalculate the old-segment
6812 * horizon, starting again from RedoRecPtr.
6814 XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
6815 KeepLogSeg(recptr, &_logSegNo);
6817 _logSegNo--;
6818 RemoveOldXlogFiles(_logSegNo, RedoRecPtr, recptr,
6819 checkPoint.ThisTimeLineID);
6822 * Make more log segments if needed. (Do this after recycling old log
6823 * segments, since that may supply some of the needed files.)
6825 if (!shutdown)
6826 PreallocXlogFiles(recptr, checkPoint.ThisTimeLineID);
6829 * Truncate pg_subtrans if possible. We can throw away all data before
6830 * the oldest XMIN of any running transaction. No future transaction will
6831 * attempt to reference any pg_subtrans entry older than that (see Asserts
6832 * in subtrans.c). During recovery, though, we mustn't do this because
6833 * StartupSUBTRANS hasn't been called yet.
6835 if (!RecoveryInProgress())
6836 TruncateSUBTRANS(GetOldestTransactionIdConsideredRunning());
6838 /* Real work is done; log and update stats. */
6839 LogCheckpointEnd(false);
6841 /* Reset the process title */
6842 update_checkpoint_display(flags, false, true);
6844 TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
6845 NBuffers,
6846 CheckpointStats.ckpt_segs_added,
6847 CheckpointStats.ckpt_segs_removed,
6848 CheckpointStats.ckpt_segs_recycled);
6852 * Mark the end of recovery in WAL though without running a full checkpoint.
6853 * We can expect that a restartpoint is likely to be in progress as we
6854 * do this, though we are unwilling to wait for it to complete.
6856 * CreateRestartPoint() allows for the case where recovery may end before
6857 * the restartpoint completes so there is no concern of concurrent behaviour.
6859 static void
6860 CreateEndOfRecoveryRecord(void)
6862 xl_end_of_recovery xlrec;
6863 XLogRecPtr recptr;
6865 /* sanity check */
6866 if (!RecoveryInProgress())
6867 elog(ERROR, "can only be used to end recovery");
6869 xlrec.end_time = GetCurrentTimestamp();
6871 WALInsertLockAcquireExclusive();
6872 xlrec.ThisTimeLineID = XLogCtl->InsertTimeLineID;
6873 xlrec.PrevTimeLineID = XLogCtl->PrevTimeLineID;
6874 WALInsertLockRelease();
6876 START_CRIT_SECTION();
6878 XLogBeginInsert();
6879 XLogRegisterData((char *) &xlrec, sizeof(xl_end_of_recovery));
6880 recptr = XLogInsert(RM_XLOG_ID, XLOG_END_OF_RECOVERY);
6882 XLogFlush(recptr);
6885 * Update the control file so that crash recovery can follow the timeline
6886 * changes to this point.
6888 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6889 ControlFile->minRecoveryPoint = recptr;
6890 ControlFile->minRecoveryPointTLI = xlrec.ThisTimeLineID;
6891 UpdateControlFile();
6892 LWLockRelease(ControlFileLock);
6894 END_CRIT_SECTION();
6898 * Write an OVERWRITE_CONTRECORD message.
6900 * When on WAL replay we expect a continuation record at the start of a page
6901 * that is not there, recovery ends and WAL writing resumes at that point.
6902 * But it's wrong to resume writing new WAL back at the start of the record
6903 * that was broken, because downstream consumers of that WAL (physical
6904 * replicas) are not prepared to "rewind". So the first action after
6905 * finishing replay of all valid WAL must be to write a record of this type
6906 * at the point where the contrecord was missing; to support xlogreader
6907 * detecting the special case, XLP_FIRST_IS_OVERWRITE_CONTRECORD is also added
6908 * to the page header where the record occurs. xlogreader has an ad-hoc
6909 * mechanism to report metadata about the broken record, which is what we
6910 * use here.
6912 * At replay time, XLP_FIRST_IS_OVERWRITE_CONTRECORD instructs xlogreader to
6913 * skip the record it was reading, and pass back the LSN of the skipped
6914 * record, so that its caller can verify (on "replay" of that record) that the
6915 * XLOG_OVERWRITE_CONTRECORD matches what was effectively overwritten.
6917 * 'aborted_lsn' is the beginning position of the record that was incomplete.
6918 * It is included in the WAL record. 'pagePtr' and 'newTLI' point to the
6919 * beginning of the XLOG page where the record is to be inserted. They must
6920 * match the current WAL insert position, they're passed here just so that we
6921 * can verify that.
6923 static XLogRecPtr
6924 CreateOverwriteContrecordRecord(XLogRecPtr aborted_lsn, XLogRecPtr pagePtr,
6925 TimeLineID newTLI)
6927 xl_overwrite_contrecord xlrec;
6928 XLogRecPtr recptr;
6929 XLogPageHeader pagehdr;
6930 XLogRecPtr startPos;
6932 /* sanity checks */
6933 if (!RecoveryInProgress())
6934 elog(ERROR, "can only be used at end of recovery");
6935 if (pagePtr % XLOG_BLCKSZ != 0)
6936 elog(ERROR, "invalid position for missing continuation record %X/%X",
6937 LSN_FORMAT_ARGS(pagePtr));
6939 /* The current WAL insert position should be right after the page header */
6940 startPos = pagePtr;
6941 if (XLogSegmentOffset(startPos, wal_segment_size) == 0)
6942 startPos += SizeOfXLogLongPHD;
6943 else
6944 startPos += SizeOfXLogShortPHD;
6945 recptr = GetXLogInsertRecPtr();
6946 if (recptr != startPos)
6947 elog(ERROR, "invalid WAL insert position %X/%X for OVERWRITE_CONTRECORD",
6948 LSN_FORMAT_ARGS(recptr));
6950 START_CRIT_SECTION();
6953 * Initialize the XLOG page header (by GetXLogBuffer), and set the
6954 * XLP_FIRST_IS_OVERWRITE_CONTRECORD flag.
6956 * No other backend is allowed to write WAL yet, so acquiring the WAL
6957 * insertion lock is just pro forma.
6959 WALInsertLockAcquire();
6960 pagehdr = (XLogPageHeader) GetXLogBuffer(pagePtr, newTLI);
6961 pagehdr->xlp_info |= XLP_FIRST_IS_OVERWRITE_CONTRECORD;
6962 WALInsertLockRelease();
6965 * Insert the XLOG_OVERWRITE_CONTRECORD record as the first record on the
6966 * page. We know it becomes the first record, because no other backend is
6967 * allowed to write WAL yet.
6969 XLogBeginInsert();
6970 xlrec.overwritten_lsn = aborted_lsn;
6971 xlrec.overwrite_time = GetCurrentTimestamp();
6972 XLogRegisterData((char *) &xlrec, sizeof(xl_overwrite_contrecord));
6973 recptr = XLogInsert(RM_XLOG_ID, XLOG_OVERWRITE_CONTRECORD);
6975 /* check that the record was inserted to the right place */
6976 if (ProcLastRecPtr != startPos)
6977 elog(ERROR, "OVERWRITE_CONTRECORD was inserted to unexpected position %X/%X",
6978 LSN_FORMAT_ARGS(ProcLastRecPtr));
6980 XLogFlush(recptr);
6982 END_CRIT_SECTION();
6984 return recptr;
6988 * Flush all data in shared memory to disk, and fsync
6990 * This is the common code shared between regular checkpoints and
6991 * recovery restartpoints.
6993 static void
6994 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
6996 CheckPointRelationMap();
6997 CheckPointReplicationSlots();
6998 CheckPointSnapBuild();
6999 CheckPointLogicalRewriteHeap();
7000 CheckPointReplicationOrigin();
7002 /* Write out all dirty data in SLRUs and the main buffer pool */
7003 TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START(flags);
7004 CheckpointStats.ckpt_write_t = GetCurrentTimestamp();
7005 CheckPointCLOG();
7006 CheckPointCommitTs();
7007 CheckPointSUBTRANS();
7008 CheckPointMultiXact();
7009 CheckPointPredicate();
7010 CheckPointBuffers(flags);
7012 /* Perform all queued up fsyncs */
7013 TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START();
7014 CheckpointStats.ckpt_sync_t = GetCurrentTimestamp();
7015 ProcessSyncRequests();
7016 CheckpointStats.ckpt_sync_end_t = GetCurrentTimestamp();
7017 TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE();
7019 /* We deliberately delay 2PC checkpointing as long as possible */
7020 CheckPointTwoPhase(checkPointRedo);
7024 * Save a checkpoint for recovery restart if appropriate
7026 * This function is called each time a checkpoint record is read from XLOG.
7027 * It must determine whether the checkpoint represents a safe restartpoint or
7028 * not. If so, the checkpoint record is stashed in shared memory so that
7029 * CreateRestartPoint can consult it. (Note that the latter function is
7030 * executed by the checkpointer, while this one will be executed by the
7031 * startup process.)
7033 static void
7034 RecoveryRestartPoint(const CheckPoint *checkPoint, XLogReaderState *record)
7037 * Also refrain from creating a restartpoint if we have seen any
7038 * references to non-existent pages. Restarting recovery from the
7039 * restartpoint would not see the references, so we would lose the
7040 * cross-check that the pages belonged to a relation that was dropped
7041 * later.
7043 if (XLogHaveInvalidPages())
7045 elog(trace_recovery(DEBUG2),
7046 "could not record restart point at %X/%X because there "
7047 "are unresolved references to invalid pages",
7048 LSN_FORMAT_ARGS(checkPoint->redo));
7049 return;
7053 * Copy the checkpoint record to shared memory, so that checkpointer can
7054 * work out the next time it wants to perform a restartpoint.
7056 SpinLockAcquire(&XLogCtl->info_lck);
7057 XLogCtl->lastCheckPointRecPtr = record->ReadRecPtr;
7058 XLogCtl->lastCheckPointEndPtr = record->EndRecPtr;
7059 XLogCtl->lastCheckPoint = *checkPoint;
7060 SpinLockRelease(&XLogCtl->info_lck);
7064 * Establish a restartpoint if possible.
7066 * This is similar to CreateCheckPoint, but is used during WAL recovery
7067 * to establish a point from which recovery can roll forward without
7068 * replaying the entire recovery log.
7070 * Returns true if a new restartpoint was established. We can only establish
7071 * a restartpoint if we have replayed a safe checkpoint record since last
7072 * restartpoint.
7074 bool
7075 CreateRestartPoint(int flags)
7077 XLogRecPtr lastCheckPointRecPtr;
7078 XLogRecPtr lastCheckPointEndPtr;
7079 CheckPoint lastCheckPoint;
7080 XLogRecPtr PriorRedoPtr;
7081 XLogRecPtr receivePtr;
7082 XLogRecPtr replayPtr;
7083 TimeLineID replayTLI;
7084 XLogRecPtr endptr;
7085 XLogSegNo _logSegNo;
7086 TimestampTz xtime;
7088 /* Concurrent checkpoint/restartpoint cannot happen */
7089 Assert(!IsUnderPostmaster || MyBackendType == B_CHECKPOINTER);
7091 /* Get a local copy of the last safe checkpoint record. */
7092 SpinLockAcquire(&XLogCtl->info_lck);
7093 lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
7094 lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
7095 lastCheckPoint = XLogCtl->lastCheckPoint;
7096 SpinLockRelease(&XLogCtl->info_lck);
7099 * Check that we're still in recovery mode. It's ok if we exit recovery
7100 * mode after this check, the restart point is valid anyway.
7102 if (!RecoveryInProgress())
7104 ereport(DEBUG2,
7105 (errmsg_internal("skipping restartpoint, recovery has already ended")));
7106 return false;
7110 * If the last checkpoint record we've replayed is already our last
7111 * restartpoint, we can't perform a new restart point. We still update
7112 * minRecoveryPoint in that case, so that if this is a shutdown restart
7113 * point, we won't start up earlier than before. That's not strictly
7114 * necessary, but when hot standby is enabled, it would be rather weird if
7115 * the database opened up for read-only connections at a point-in-time
7116 * before the last shutdown. Such time travel is still possible in case of
7117 * immediate shutdown, though.
7119 * We don't explicitly advance minRecoveryPoint when we do create a
7120 * restartpoint. It's assumed that flushing the buffers will do that as a
7121 * side-effect.
7123 if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
7124 lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
7126 ereport(DEBUG2,
7127 (errmsg_internal("skipping restartpoint, already performed at %X/%X",
7128 LSN_FORMAT_ARGS(lastCheckPoint.redo))));
7130 UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
7131 if (flags & CHECKPOINT_IS_SHUTDOWN)
7133 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7134 ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
7135 UpdateControlFile();
7136 LWLockRelease(ControlFileLock);
7138 return false;
7142 * Update the shared RedoRecPtr so that the startup process can calculate
7143 * the number of segments replayed since last restartpoint, and request a
7144 * restartpoint if it exceeds CheckPointSegments.
7146 * Like in CreateCheckPoint(), hold off insertions to update it, although
7147 * during recovery this is just pro forma, because no WAL insertions are
7148 * happening.
7150 WALInsertLockAcquireExclusive();
7151 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
7152 WALInsertLockRelease();
7154 /* Also update the info_lck-protected copy */
7155 SpinLockAcquire(&XLogCtl->info_lck);
7156 XLogCtl->RedoRecPtr = lastCheckPoint.redo;
7157 SpinLockRelease(&XLogCtl->info_lck);
7160 * Prepare to accumulate statistics.
7162 * Note: because it is possible for log_checkpoints to change while a
7163 * checkpoint proceeds, we always accumulate stats, even if
7164 * log_checkpoints is currently off.
7166 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
7167 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
7169 if (log_checkpoints)
7170 LogCheckpointStart(flags, true);
7172 /* Update the process title */
7173 update_checkpoint_display(flags, true, false);
7175 CheckPointGuts(lastCheckPoint.redo, flags);
7178 * Remember the prior checkpoint's redo ptr for
7179 * UpdateCheckPointDistanceEstimate()
7181 PriorRedoPtr = ControlFile->checkPointCopy.redo;
7184 * Update pg_control, using current time. Check that it still shows an
7185 * older checkpoint, else do nothing; this is a quick hack to make sure
7186 * nothing really bad happens if somehow we get here after the
7187 * end-of-recovery checkpoint.
7189 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7190 if (ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
7193 * Update the checkpoint information. We do this even if the cluster
7194 * does not show DB_IN_ARCHIVE_RECOVERY to match with the set of WAL
7195 * segments recycled below.
7197 ControlFile->checkPoint = lastCheckPointRecPtr;
7198 ControlFile->checkPointCopy = lastCheckPoint;
7201 * Ensure minRecoveryPoint is past the checkpoint record and update it
7202 * if the control file still shows DB_IN_ARCHIVE_RECOVERY. Normally,
7203 * this will have happened already while writing out dirty buffers,
7204 * but not necessarily - e.g. because no buffers were dirtied. We do
7205 * this because a backup performed in recovery uses minRecoveryPoint
7206 * to determine which WAL files must be included in the backup, and
7207 * the file (or files) containing the checkpoint record must be
7208 * included, at a minimum. Note that for an ordinary restart of
7209 * recovery there's no value in having the minimum recovery point any
7210 * earlier than this anyway, because redo will begin just after the
7211 * checkpoint record.
7213 if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
7215 if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
7217 ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
7218 ControlFile->minRecoveryPointTLI = lastCheckPoint.ThisTimeLineID;
7220 /* update local copy */
7221 LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
7222 LocalMinRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
7224 if (flags & CHECKPOINT_IS_SHUTDOWN)
7225 ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
7227 UpdateControlFile();
7229 LWLockRelease(ControlFileLock);
7232 * Update the average distance between checkpoints/restartpoints if the
7233 * prior checkpoint exists.
7235 if (PriorRedoPtr != InvalidXLogRecPtr)
7236 UpdateCheckPointDistanceEstimate(RedoRecPtr - PriorRedoPtr);
7239 * Delete old log files, those no longer needed for last restartpoint to
7240 * prevent the disk holding the xlog from growing full.
7242 XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
7245 * Retreat _logSegNo using the current end of xlog replayed or received,
7246 * whichever is later.
7248 receivePtr = GetWalRcvFlushRecPtr(NULL, NULL);
7249 replayPtr = GetXLogReplayRecPtr(&replayTLI);
7250 endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
7251 KeepLogSeg(endptr, &_logSegNo);
7252 if (InvalidateObsoleteReplicationSlots(_logSegNo))
7255 * Some slots have been invalidated; recalculate the old-segment
7256 * horizon, starting again from RedoRecPtr.
7258 XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
7259 KeepLogSeg(endptr, &_logSegNo);
7261 _logSegNo--;
7264 * Try to recycle segments on a useful timeline. If we've been promoted
7265 * since the beginning of this restartpoint, use the new timeline chosen
7266 * at end of recovery. If we're still in recovery, use the timeline we're
7267 * currently replaying.
7269 * There is no guarantee that the WAL segments will be useful on the
7270 * current timeline; if recovery proceeds to a new timeline right after
7271 * this, the pre-allocated WAL segments on this timeline will not be used,
7272 * and will go wasted until recycled on the next restartpoint. We'll live
7273 * with that.
7275 if (!RecoveryInProgress())
7276 replayTLI = XLogCtl->InsertTimeLineID;
7278 RemoveOldXlogFiles(_logSegNo, RedoRecPtr, endptr, replayTLI);
7281 * Make more log segments if needed. (Do this after recycling old log
7282 * segments, since that may supply some of the needed files.)
7284 PreallocXlogFiles(endptr, replayTLI);
7287 * Truncate pg_subtrans if possible. We can throw away all data before
7288 * the oldest XMIN of any running transaction. No future transaction will
7289 * attempt to reference any pg_subtrans entry older than that (see Asserts
7290 * in subtrans.c). When hot standby is disabled, though, we mustn't do
7291 * this because StartupSUBTRANS hasn't been called yet.
7293 if (EnableHotStandby)
7294 TruncateSUBTRANS(GetOldestTransactionIdConsideredRunning());
7296 /* Real work is done; log and update stats. */
7297 LogCheckpointEnd(true);
7299 /* Reset the process title */
7300 update_checkpoint_display(flags, true, true);
7302 xtime = GetLatestXTime();
7303 ereport((log_checkpoints ? LOG : DEBUG2),
7304 (errmsg("recovery restart point at %X/%X",
7305 LSN_FORMAT_ARGS(lastCheckPoint.redo)),
7306 xtime ? errdetail("Last completed transaction was at log time %s.",
7307 timestamptz_to_str(xtime)) : 0));
7310 * Finally, execute archive_cleanup_command, if any.
7312 if (archiveCleanupCommand && strcmp(archiveCleanupCommand, "") != 0)
7314 char lastRestartPointFname[MAXFNAMELEN];
7316 GetOldestRestartPointFileName(lastRestartPointFname);
7317 shell_archive_cleanup(lastRestartPointFname);
7320 return true;
7324 * Report availability of WAL for the given target LSN
7325 * (typically a slot's restart_lsn)
7327 * Returns one of the following enum values:
7329 * * WALAVAIL_RESERVED means targetLSN is available and it is in the range of
7330 * max_wal_size.
7332 * * WALAVAIL_EXTENDED means it is still available by preserving extra
7333 * segments beyond max_wal_size. If max_slot_wal_keep_size is smaller
7334 * than max_wal_size, this state is not returned.
7336 * * WALAVAIL_UNRESERVED means it is being lost and the next checkpoint will
7337 * remove reserved segments. The walsender using this slot may return to the
7338 * above.
7340 * * WALAVAIL_REMOVED means it has been removed. A replication stream on
7341 * a slot with this LSN cannot continue. (Any associated walsender
7342 * processes should have been terminated already.)
7344 * * WALAVAIL_INVALID_LSN means the slot hasn't been set to reserve WAL.
7346 WALAvailability
7347 GetWALAvailability(XLogRecPtr targetLSN)
7349 XLogRecPtr currpos; /* current write LSN */
7350 XLogSegNo currSeg; /* segid of currpos */
7351 XLogSegNo targetSeg; /* segid of targetLSN */
7352 XLogSegNo oldestSeg; /* actual oldest segid */
7353 XLogSegNo oldestSegMaxWalSize; /* oldest segid kept by max_wal_size */
7354 XLogSegNo oldestSlotSeg; /* oldest segid kept by slot */
7355 uint64 keepSegs;
7358 * slot does not reserve WAL. Either deactivated, or has never been active
7360 if (XLogRecPtrIsInvalid(targetLSN))
7361 return WALAVAIL_INVALID_LSN;
7364 * Calculate the oldest segment currently reserved by all slots,
7365 * considering wal_keep_size and max_slot_wal_keep_size. Initialize
7366 * oldestSlotSeg to the current segment.
7368 currpos = GetXLogWriteRecPtr();
7369 XLByteToSeg(currpos, oldestSlotSeg, wal_segment_size);
7370 KeepLogSeg(currpos, &oldestSlotSeg);
7373 * Find the oldest extant segment file. We get 1 until checkpoint removes
7374 * the first WAL segment file since startup, which causes the status being
7375 * wrong under certain abnormal conditions but that doesn't actually harm.
7377 oldestSeg = XLogGetLastRemovedSegno() + 1;
7379 /* calculate oldest segment by max_wal_size */
7380 XLByteToSeg(currpos, currSeg, wal_segment_size);
7381 keepSegs = ConvertToXSegs(max_wal_size_mb, wal_segment_size) + 1;
7383 if (currSeg > keepSegs)
7384 oldestSegMaxWalSize = currSeg - keepSegs;
7385 else
7386 oldestSegMaxWalSize = 1;
7388 /* the segment we care about */
7389 XLByteToSeg(targetLSN, targetSeg, wal_segment_size);
7392 * No point in returning reserved or extended status values if the
7393 * targetSeg is known to be lost.
7395 if (targetSeg >= oldestSlotSeg)
7397 /* show "reserved" when targetSeg is within max_wal_size */
7398 if (targetSeg >= oldestSegMaxWalSize)
7399 return WALAVAIL_RESERVED;
7401 /* being retained by slots exceeding max_wal_size */
7402 return WALAVAIL_EXTENDED;
7405 /* WAL segments are no longer retained but haven't been removed yet */
7406 if (targetSeg >= oldestSeg)
7407 return WALAVAIL_UNRESERVED;
7409 /* Definitely lost */
7410 return WALAVAIL_REMOVED;
7415 * Retreat *logSegNo to the last segment that we need to retain because of
7416 * either wal_keep_size or replication slots.
7418 * This is calculated by subtracting wal_keep_size from the given xlog
7419 * location, recptr and by making sure that that result is below the
7420 * requirement of replication slots. For the latter criterion we do consider
7421 * the effects of max_slot_wal_keep_size: reserve at most that much space back
7422 * from recptr.
7424 * Note about replication slots: if this function calculates a value
7425 * that's further ahead than what slots need reserved, then affected
7426 * slots need to be invalidated and this function invoked again.
7427 * XXX it might be a good idea to rewrite this function so that
7428 * invalidation is optionally done here, instead.
7430 static void
7431 KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
7433 XLogSegNo currSegNo;
7434 XLogSegNo segno;
7435 XLogRecPtr keep;
7437 XLByteToSeg(recptr, currSegNo, wal_segment_size);
7438 segno = currSegNo;
7441 * Calculate how many segments are kept by slots first, adjusting for
7442 * max_slot_wal_keep_size.
7444 keep = XLogGetReplicationSlotMinimumLSN();
7445 if (keep != InvalidXLogRecPtr)
7447 XLByteToSeg(keep, segno, wal_segment_size);
7449 /* Cap by max_slot_wal_keep_size ... */
7450 if (max_slot_wal_keep_size_mb >= 0)
7452 uint64 slot_keep_segs;
7454 slot_keep_segs =
7455 ConvertToXSegs(max_slot_wal_keep_size_mb, wal_segment_size);
7457 if (currSegNo - segno > slot_keep_segs)
7458 segno = currSegNo - slot_keep_segs;
7462 /* but, keep at least wal_keep_size if that's set */
7463 if (wal_keep_size_mb > 0)
7465 uint64 keep_segs;
7467 keep_segs = ConvertToXSegs(wal_keep_size_mb, wal_segment_size);
7468 if (currSegNo - segno < keep_segs)
7470 /* avoid underflow, don't go below 1 */
7471 if (currSegNo <= keep_segs)
7472 segno = 1;
7473 else
7474 segno = currSegNo - keep_segs;
7478 /* don't delete WAL segments newer than the calculated segment */
7479 if (segno < *logSegNo)
7480 *logSegNo = segno;
7484 * Write a NEXTOID log record
7486 void
7487 XLogPutNextOid(Oid nextOid)
7489 XLogBeginInsert();
7490 XLogRegisterData((char *) (&nextOid), sizeof(Oid));
7491 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID);
7494 * We need not flush the NEXTOID record immediately, because any of the
7495 * just-allocated OIDs could only reach disk as part of a tuple insert or
7496 * update that would have its own XLOG record that must follow the NEXTOID
7497 * record. Therefore, the standard buffer LSN interlock applied to those
7498 * records will ensure no such OID reaches disk before the NEXTOID record
7499 * does.
7501 * Note, however, that the above statement only covers state "within" the
7502 * database. When we use a generated OID as a file or directory name, we
7503 * are in a sense violating the basic WAL rule, because that filesystem
7504 * change may reach disk before the NEXTOID WAL record does. The impact
7505 * of this is that if a database crash occurs immediately afterward, we
7506 * might after restart re-generate the same OID and find that it conflicts
7507 * with the leftover file or directory. But since for safety's sake we
7508 * always loop until finding a nonconflicting filename, this poses no real
7509 * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
7514 * Write an XLOG SWITCH record.
7516 * Here we just blindly issue an XLogInsert request for the record.
7517 * All the magic happens inside XLogInsert.
7519 * The return value is either the end+1 address of the switch record,
7520 * or the end+1 address of the prior segment if we did not need to
7521 * write a switch record because we are already at segment start.
7523 XLogRecPtr
7524 RequestXLogSwitch(bool mark_unimportant)
7526 XLogRecPtr RecPtr;
7528 /* XLOG SWITCH has no data */
7529 XLogBeginInsert();
7531 if (mark_unimportant)
7532 XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
7533 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH);
7535 return RecPtr;
7539 * Write a RESTORE POINT record
7541 XLogRecPtr
7542 XLogRestorePoint(const char *rpName)
7544 XLogRecPtr RecPtr;
7545 xl_restore_point xlrec;
7547 xlrec.rp_time = GetCurrentTimestamp();
7548 strlcpy(xlrec.rp_name, rpName, MAXFNAMELEN);
7550 XLogBeginInsert();
7551 XLogRegisterData((char *) &xlrec, sizeof(xl_restore_point));
7553 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_RESTORE_POINT);
7555 ereport(LOG,
7556 (errmsg("restore point \"%s\" created at %X/%X",
7557 rpName, LSN_FORMAT_ARGS(RecPtr))));
7559 return RecPtr;
7563 * Check if any of the GUC parameters that are critical for hot standby
7564 * have changed, and update the value in pg_control file if necessary.
7566 static void
7567 XLogReportParameters(void)
7569 if (wal_level != ControlFile->wal_level ||
7570 wal_log_hints != ControlFile->wal_log_hints ||
7571 MaxConnections != ControlFile->MaxConnections ||
7572 max_worker_processes != ControlFile->max_worker_processes ||
7573 max_wal_senders != ControlFile->max_wal_senders ||
7574 max_prepared_xacts != ControlFile->max_prepared_xacts ||
7575 max_locks_per_xact != ControlFile->max_locks_per_xact ||
7576 track_commit_timestamp != ControlFile->track_commit_timestamp)
7579 * The change in number of backend slots doesn't need to be WAL-logged
7580 * if archiving is not enabled, as you can't start archive recovery
7581 * with wal_level=minimal anyway. We don't really care about the
7582 * values in pg_control either if wal_level=minimal, but seems better
7583 * to keep them up-to-date to avoid confusion.
7585 if (wal_level != ControlFile->wal_level || XLogIsNeeded())
7587 xl_parameter_change xlrec;
7588 XLogRecPtr recptr;
7590 xlrec.MaxConnections = MaxConnections;
7591 xlrec.max_worker_processes = max_worker_processes;
7592 xlrec.max_wal_senders = max_wal_senders;
7593 xlrec.max_prepared_xacts = max_prepared_xacts;
7594 xlrec.max_locks_per_xact = max_locks_per_xact;
7595 xlrec.wal_level = wal_level;
7596 xlrec.wal_log_hints = wal_log_hints;
7597 xlrec.track_commit_timestamp = track_commit_timestamp;
7599 XLogBeginInsert();
7600 XLogRegisterData((char *) &xlrec, sizeof(xlrec));
7602 recptr = XLogInsert(RM_XLOG_ID, XLOG_PARAMETER_CHANGE);
7603 XLogFlush(recptr);
7606 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7608 ControlFile->MaxConnections = MaxConnections;
7609 ControlFile->max_worker_processes = max_worker_processes;
7610 ControlFile->max_wal_senders = max_wal_senders;
7611 ControlFile->max_prepared_xacts = max_prepared_xacts;
7612 ControlFile->max_locks_per_xact = max_locks_per_xact;
7613 ControlFile->wal_level = wal_level;
7614 ControlFile->wal_log_hints = wal_log_hints;
7615 ControlFile->track_commit_timestamp = track_commit_timestamp;
7616 UpdateControlFile();
7618 LWLockRelease(ControlFileLock);
7623 * Update full_page_writes in shared memory, and write an
7624 * XLOG_FPW_CHANGE record if necessary.
7626 * Note: this function assumes there is no other process running
7627 * concurrently that could update it.
7629 void
7630 UpdateFullPageWrites(void)
7632 XLogCtlInsert *Insert = &XLogCtl->Insert;
7633 bool recoveryInProgress;
7636 * Do nothing if full_page_writes has not been changed.
7638 * It's safe to check the shared full_page_writes without the lock,
7639 * because we assume that there is no concurrently running process which
7640 * can update it.
7642 if (fullPageWrites == Insert->fullPageWrites)
7643 return;
7646 * Perform this outside critical section so that the WAL insert
7647 * initialization done by RecoveryInProgress() doesn't trigger an
7648 * assertion failure.
7650 recoveryInProgress = RecoveryInProgress();
7652 START_CRIT_SECTION();
7655 * It's always safe to take full page images, even when not strictly
7656 * required, but not the other round. So if we're setting full_page_writes
7657 * to true, first set it true and then write the WAL record. If we're
7658 * setting it to false, first write the WAL record and then set the global
7659 * flag.
7661 if (fullPageWrites)
7663 WALInsertLockAcquireExclusive();
7664 Insert->fullPageWrites = true;
7665 WALInsertLockRelease();
7669 * Write an XLOG_FPW_CHANGE record. This allows us to keep track of
7670 * full_page_writes during archive recovery, if required.
7672 if (XLogStandbyInfoActive() && !recoveryInProgress)
7674 XLogBeginInsert();
7675 XLogRegisterData((char *) (&fullPageWrites), sizeof(bool));
7677 XLogInsert(RM_XLOG_ID, XLOG_FPW_CHANGE);
7680 if (!fullPageWrites)
7682 WALInsertLockAcquireExclusive();
7683 Insert->fullPageWrites = false;
7684 WALInsertLockRelease();
7686 END_CRIT_SECTION();
7690 * XLOG resource manager's routines
7692 * Definitions of info values are in include/catalog/pg_control.h, though
7693 * not all record types are related to control file updates.
7695 * NOTE: Some XLOG record types that are directly related to WAL recovery
7696 * are handled in xlogrecovery_redo().
7698 void
7699 xlog_redo(XLogReaderState *record)
7701 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
7702 XLogRecPtr lsn = record->EndRecPtr;
7705 * In XLOG rmgr, backup blocks are only used by XLOG_FPI and
7706 * XLOG_FPI_FOR_HINT records.
7708 Assert(info == XLOG_FPI || info == XLOG_FPI_FOR_HINT ||
7709 !XLogRecHasAnyBlockRefs(record));
7711 if (info == XLOG_NEXTOID)
7713 Oid nextOid;
7716 * We used to try to take the maximum of ShmemVariableCache->nextOid
7717 * and the recorded nextOid, but that fails if the OID counter wraps
7718 * around. Since no OID allocation should be happening during replay
7719 * anyway, better to just believe the record exactly. We still take
7720 * OidGenLock while setting the variable, just in case.
7722 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
7723 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
7724 ShmemVariableCache->nextOid = nextOid;
7725 ShmemVariableCache->oidCount = 0;
7726 LWLockRelease(OidGenLock);
7728 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
7730 CheckPoint checkPoint;
7731 TimeLineID replayTLI;
7733 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
7734 /* In a SHUTDOWN checkpoint, believe the counters exactly */
7735 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
7736 ShmemVariableCache->nextXid = checkPoint.nextXid;
7737 LWLockRelease(XidGenLock);
7738 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
7739 ShmemVariableCache->nextOid = checkPoint.nextOid;
7740 ShmemVariableCache->oidCount = 0;
7741 LWLockRelease(OidGenLock);
7742 MultiXactSetNextMXact(checkPoint.nextMulti,
7743 checkPoint.nextMultiOffset);
7745 MultiXactAdvanceOldest(checkPoint.oldestMulti,
7746 checkPoint.oldestMultiDB);
7749 * No need to set oldestClogXid here as well; it'll be set when we
7750 * redo an xl_clog_truncate if it changed since initialization.
7752 SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
7755 * If we see a shutdown checkpoint while waiting for an end-of-backup
7756 * record, the backup was canceled and the end-of-backup record will
7757 * never arrive.
7759 if (ArchiveRecoveryRequested &&
7760 !XLogRecPtrIsInvalid(ControlFile->backupStartPoint) &&
7761 XLogRecPtrIsInvalid(ControlFile->backupEndPoint))
7762 ereport(PANIC,
7763 (errmsg("online backup was canceled, recovery cannot continue")));
7766 * If we see a shutdown checkpoint, we know that nothing was running
7767 * on the primary at this point. So fake-up an empty running-xacts
7768 * record and use that here and now. Recover additional standby state
7769 * for prepared transactions.
7771 if (standbyState >= STANDBY_INITIALIZED)
7773 TransactionId *xids;
7774 int nxids;
7775 TransactionId oldestActiveXID;
7776 TransactionId latestCompletedXid;
7777 RunningTransactionsData running;
7779 oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
7782 * Construct a RunningTransactions snapshot representing a shut
7783 * down server, with only prepared transactions still alive. We're
7784 * never overflowed at this point because all subxids are listed
7785 * with their parent prepared transactions.
7787 running.xcnt = nxids;
7788 running.subxcnt = 0;
7789 running.subxid_overflow = false;
7790 running.nextXid = XidFromFullTransactionId(checkPoint.nextXid);
7791 running.oldestRunningXid = oldestActiveXID;
7792 latestCompletedXid = XidFromFullTransactionId(checkPoint.nextXid);
7793 TransactionIdRetreat(latestCompletedXid);
7794 Assert(TransactionIdIsNormal(latestCompletedXid));
7795 running.latestCompletedXid = latestCompletedXid;
7796 running.xids = xids;
7798 ProcArrayApplyRecoveryInfo(&running);
7800 StandbyRecoverPreparedTransactions();
7803 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
7804 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7805 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
7806 LWLockRelease(ControlFileLock);
7808 /* Update shared-memory copy of checkpoint XID/epoch */
7809 SpinLockAcquire(&XLogCtl->info_lck);
7810 XLogCtl->ckptFullXid = checkPoint.nextXid;
7811 SpinLockRelease(&XLogCtl->info_lck);
7814 * We should've already switched to the new TLI before replaying this
7815 * record.
7817 (void) GetCurrentReplayRecPtr(&replayTLI);
7818 if (checkPoint.ThisTimeLineID != replayTLI)
7819 ereport(PANIC,
7820 (errmsg("unexpected timeline ID %u (should be %u) in shutdown checkpoint record",
7821 checkPoint.ThisTimeLineID, replayTLI)));
7823 RecoveryRestartPoint(&checkPoint, record);
7825 else if (info == XLOG_CHECKPOINT_ONLINE)
7827 CheckPoint checkPoint;
7828 TimeLineID replayTLI;
7830 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
7831 /* In an ONLINE checkpoint, treat the XID counter as a minimum */
7832 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
7833 if (FullTransactionIdPrecedes(ShmemVariableCache->nextXid,
7834 checkPoint.nextXid))
7835 ShmemVariableCache->nextXid = checkPoint.nextXid;
7836 LWLockRelease(XidGenLock);
7839 * We ignore the nextOid counter in an ONLINE checkpoint, preferring
7840 * to track OID assignment through XLOG_NEXTOID records. The nextOid
7841 * counter is from the start of the checkpoint and might well be stale
7842 * compared to later XLOG_NEXTOID records. We could try to take the
7843 * maximum of the nextOid counter and our latest value, but since
7844 * there's no particular guarantee about the speed with which the OID
7845 * counter wraps around, that's a risky thing to do. In any case,
7846 * users of the nextOid counter are required to avoid assignment of
7847 * duplicates, so that a somewhat out-of-date value should be safe.
7850 /* Handle multixact */
7851 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
7852 checkPoint.nextMultiOffset);
7855 * NB: This may perform multixact truncation when replaying WAL
7856 * generated by an older primary.
7858 MultiXactAdvanceOldest(checkPoint.oldestMulti,
7859 checkPoint.oldestMultiDB);
7860 if (TransactionIdPrecedes(ShmemVariableCache->oldestXid,
7861 checkPoint.oldestXid))
7862 SetTransactionIdLimit(checkPoint.oldestXid,
7863 checkPoint.oldestXidDB);
7864 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
7865 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7866 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
7867 LWLockRelease(ControlFileLock);
7869 /* Update shared-memory copy of checkpoint XID/epoch */
7870 SpinLockAcquire(&XLogCtl->info_lck);
7871 XLogCtl->ckptFullXid = checkPoint.nextXid;
7872 SpinLockRelease(&XLogCtl->info_lck);
7874 /* TLI should not change in an on-line checkpoint */
7875 (void) GetCurrentReplayRecPtr(&replayTLI);
7876 if (checkPoint.ThisTimeLineID != replayTLI)
7877 ereport(PANIC,
7878 (errmsg("unexpected timeline ID %u (should be %u) in online checkpoint record",
7879 checkPoint.ThisTimeLineID, replayTLI)));
7881 RecoveryRestartPoint(&checkPoint, record);
7883 else if (info == XLOG_OVERWRITE_CONTRECORD)
7885 /* nothing to do here, handled in xlogrecovery_redo() */
7887 else if (info == XLOG_END_OF_RECOVERY)
7889 xl_end_of_recovery xlrec;
7890 TimeLineID replayTLI;
7892 memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_end_of_recovery));
7895 * For Hot Standby, we could treat this like a Shutdown Checkpoint,
7896 * but this case is rarer and harder to test, so the benefit doesn't
7897 * outweigh the potential extra cost of maintenance.
7901 * We should've already switched to the new TLI before replaying this
7902 * record.
7904 (void) GetCurrentReplayRecPtr(&replayTLI);
7905 if (xlrec.ThisTimeLineID != replayTLI)
7906 ereport(PANIC,
7907 (errmsg("unexpected timeline ID %u (should be %u) in end-of-recovery record",
7908 xlrec.ThisTimeLineID, replayTLI)));
7910 else if (info == XLOG_NOOP)
7912 /* nothing to do here */
7914 else if (info == XLOG_SWITCH)
7916 /* nothing to do here */
7918 else if (info == XLOG_RESTORE_POINT)
7920 /* nothing to do here, handled in xlogrecovery.c */
7922 else if (info == XLOG_FPI || info == XLOG_FPI_FOR_HINT)
7925 * XLOG_FPI records contain nothing else but one or more block
7926 * references. Every block reference must include a full-page image
7927 * even if full_page_writes was disabled when the record was generated
7928 * - otherwise there would be no point in this record.
7930 * XLOG_FPI_FOR_HINT records are generated when a page needs to be
7931 * WAL-logged because of a hint bit update. They are only generated
7932 * when checksums and/or wal_log_hints are enabled. They may include
7933 * no full-page images if full_page_writes was disabled when they were
7934 * generated. In this case there is nothing to do here.
7936 * No recovery conflicts are generated by these generic records - if a
7937 * resource manager needs to generate conflicts, it has to define a
7938 * separate WAL record type and redo routine.
7940 for (uint8 block_id = 0; block_id <= XLogRecMaxBlockId(record); block_id++)
7942 Buffer buffer;
7944 if (!XLogRecHasBlockImage(record, block_id))
7946 if (info == XLOG_FPI)
7947 elog(ERROR, "XLOG_FPI record did not contain a full-page image");
7948 continue;
7951 if (XLogReadBufferForRedo(record, block_id, &buffer) != BLK_RESTORED)
7952 elog(ERROR, "unexpected XLogReadBufferForRedo result when restoring backup block");
7953 UnlockReleaseBuffer(buffer);
7956 else if (info == XLOG_BACKUP_END)
7958 /* nothing to do here, handled in xlogrecovery_redo() */
7960 else if (info == XLOG_PARAMETER_CHANGE)
7962 xl_parameter_change xlrec;
7964 /* Update our copy of the parameters in pg_control */
7965 memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_parameter_change));
7967 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7968 ControlFile->MaxConnections = xlrec.MaxConnections;
7969 ControlFile->max_worker_processes = xlrec.max_worker_processes;
7970 ControlFile->max_wal_senders = xlrec.max_wal_senders;
7971 ControlFile->max_prepared_xacts = xlrec.max_prepared_xacts;
7972 ControlFile->max_locks_per_xact = xlrec.max_locks_per_xact;
7973 ControlFile->wal_level = xlrec.wal_level;
7974 ControlFile->wal_log_hints = xlrec.wal_log_hints;
7977 * Update minRecoveryPoint to ensure that if recovery is aborted, we
7978 * recover back up to this point before allowing hot standby again.
7979 * This is important if the max_* settings are decreased, to ensure
7980 * you don't run queries against the WAL preceding the change. The
7981 * local copies cannot be updated as long as crash recovery is
7982 * happening and we expect all the WAL to be replayed.
7984 if (InArchiveRecovery)
7986 LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
7987 LocalMinRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
7989 if (LocalMinRecoveryPoint != InvalidXLogRecPtr && LocalMinRecoveryPoint < lsn)
7991 TimeLineID replayTLI;
7993 (void) GetCurrentReplayRecPtr(&replayTLI);
7994 ControlFile->minRecoveryPoint = lsn;
7995 ControlFile->minRecoveryPointTLI = replayTLI;
7998 CommitTsParameterChange(xlrec.track_commit_timestamp,
7999 ControlFile->track_commit_timestamp);
8000 ControlFile->track_commit_timestamp = xlrec.track_commit_timestamp;
8002 UpdateControlFile();
8003 LWLockRelease(ControlFileLock);
8005 /* Check to see if any parameter change gives a problem on recovery */
8006 CheckRequiredParameterValues();
8008 else if (info == XLOG_FPW_CHANGE)
8010 bool fpw;
8012 memcpy(&fpw, XLogRecGetData(record), sizeof(bool));
8015 * Update the LSN of the last replayed XLOG_FPW_CHANGE record so that
8016 * do_pg_backup_start() and do_pg_backup_stop() can check whether
8017 * full_page_writes has been disabled during online backup.
8019 if (!fpw)
8021 SpinLockAcquire(&XLogCtl->info_lck);
8022 if (XLogCtl->lastFpwDisableRecPtr < record->ReadRecPtr)
8023 XLogCtl->lastFpwDisableRecPtr = record->ReadRecPtr;
8024 SpinLockRelease(&XLogCtl->info_lck);
8027 /* Keep track of full_page_writes */
8028 lastFullPageWrites = fpw;
8033 * Return the (possible) sync flag used for opening a file, depending on the
8034 * value of the GUC wal_sync_method.
8036 static int
8037 get_sync_bit(int method)
8039 int o_direct_flag = 0;
8041 /* If fsync is disabled, never open in sync mode */
8042 if (!enableFsync)
8043 return 0;
8046 * Optimize writes by bypassing kernel cache with O_DIRECT when using
8047 * O_SYNC and O_DSYNC. But only if archiving and streaming are disabled,
8048 * otherwise the archive command or walsender process will read the WAL
8049 * soon after writing it, which is guaranteed to cause a physical read if
8050 * we bypassed the kernel cache. We also skip the
8051 * posix_fadvise(POSIX_FADV_DONTNEED) call in XLogFileClose() for the same
8052 * reason.
8054 * Never use O_DIRECT in walreceiver process for similar reasons; the WAL
8055 * written by walreceiver is normally read by the startup process soon
8056 * after it's written. Also, walreceiver performs unaligned writes, which
8057 * don't work with O_DIRECT, so it is required for correctness too.
8059 if (!XLogIsNeeded() && !AmWalReceiverProcess())
8060 o_direct_flag = PG_O_DIRECT;
8062 switch (method)
8065 * enum values for all sync options are defined even if they are
8066 * not supported on the current platform. But if not, they are
8067 * not included in the enum option array, and therefore will never
8068 * be seen here.
8070 case SYNC_METHOD_FSYNC:
8071 case SYNC_METHOD_FSYNC_WRITETHROUGH:
8072 case SYNC_METHOD_FDATASYNC:
8073 return 0;
8074 #ifdef O_SYNC
8075 case SYNC_METHOD_OPEN:
8076 return O_SYNC | o_direct_flag;
8077 #endif
8078 #ifdef O_DSYNC
8079 case SYNC_METHOD_OPEN_DSYNC:
8080 return O_DSYNC | o_direct_flag;
8081 #endif
8082 default:
8083 /* can't happen (unless we are out of sync with option array) */
8084 elog(ERROR, "unrecognized wal_sync_method: %d", method);
8085 return 0; /* silence warning */
8090 * GUC support
8092 void
8093 assign_xlog_sync_method(int new_sync_method, void *extra)
8095 if (sync_method != new_sync_method)
8098 * To ensure that no blocks escape unsynced, force an fsync on the
8099 * currently open log segment (if any). Also, if the open flag is
8100 * changing, close the log file so it will be reopened (with new flag
8101 * bit) at next use.
8103 if (openLogFile >= 0)
8105 pgstat_report_wait_start(WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN);
8106 if (pg_fsync(openLogFile) != 0)
8108 char xlogfname[MAXFNAMELEN];
8109 int save_errno;
8111 save_errno = errno;
8112 XLogFileName(xlogfname, openLogTLI, openLogSegNo,
8113 wal_segment_size);
8114 errno = save_errno;
8115 ereport(PANIC,
8116 (errcode_for_file_access(),
8117 errmsg("could not fsync file \"%s\": %m", xlogfname)));
8120 pgstat_report_wait_end();
8121 if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
8122 XLogFileClose();
8129 * Issue appropriate kind of fsync (if any) for an XLOG output file.
8131 * 'fd' is a file descriptor for the XLOG file to be fsync'd.
8132 * 'segno' is for error reporting purposes.
8134 void
8135 issue_xlog_fsync(int fd, XLogSegNo segno, TimeLineID tli)
8137 char *msg = NULL;
8138 instr_time start;
8140 Assert(tli != 0);
8143 * Quick exit if fsync is disabled or write() has already synced the WAL
8144 * file.
8146 if (!enableFsync ||
8147 sync_method == SYNC_METHOD_OPEN ||
8148 sync_method == SYNC_METHOD_OPEN_DSYNC)
8149 return;
8151 /* Measure I/O timing to sync the WAL file */
8152 if (track_wal_io_timing)
8153 INSTR_TIME_SET_CURRENT(start);
8155 pgstat_report_wait_start(WAIT_EVENT_WAL_SYNC);
8156 switch (sync_method)
8158 case SYNC_METHOD_FSYNC:
8159 if (pg_fsync_no_writethrough(fd) != 0)
8160 msg = _("could not fsync file \"%s\": %m");
8161 break;
8162 #ifdef HAVE_FSYNC_WRITETHROUGH
8163 case SYNC_METHOD_FSYNC_WRITETHROUGH:
8164 if (pg_fsync_writethrough(fd) != 0)
8165 msg = _("could not fsync write-through file \"%s\": %m");
8166 break;
8167 #endif
8168 case SYNC_METHOD_FDATASYNC:
8169 if (pg_fdatasync(fd) != 0)
8170 msg = _("could not fdatasync file \"%s\": %m");
8171 break;
8172 case SYNC_METHOD_OPEN:
8173 case SYNC_METHOD_OPEN_DSYNC:
8174 /* not reachable */
8175 Assert(false);
8176 break;
8177 default:
8178 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
8179 break;
8182 /* PANIC if failed to fsync */
8183 if (msg)
8185 char xlogfname[MAXFNAMELEN];
8186 int save_errno = errno;
8188 XLogFileName(xlogfname, tli, segno, wal_segment_size);
8189 errno = save_errno;
8190 ereport(PANIC,
8191 (errcode_for_file_access(),
8192 errmsg(msg, xlogfname)));
8195 pgstat_report_wait_end();
8198 * Increment the I/O timing and the number of times WAL files were synced.
8200 if (track_wal_io_timing)
8202 instr_time duration;
8204 INSTR_TIME_SET_CURRENT(duration);
8205 INSTR_TIME_SUBTRACT(duration, start);
8206 PendingWalStats.wal_sync_time += INSTR_TIME_GET_MICROSEC(duration);
8209 PendingWalStats.wal_sync++;
8213 * do_pg_backup_start is the workhorse of the user-visible pg_backup_start()
8214 * function. It creates the necessary starting checkpoint and constructs the
8215 * backup state and tablespace map.
8217 * Input parameters are "state" (the backup state), "fast" (if true, we do
8218 * the checkpoint in immediate mode to make it faster), and "tablespaces"
8219 * (if non-NULL, indicates a list of tablespaceinfo structs describing the
8220 * cluster's tablespaces.).
8222 * The tablespace map contents are appended to passed-in parameter
8223 * tablespace_map and the caller is responsible for including it in the backup
8224 * archive as 'tablespace_map'. The tablespace_map file is required mainly for
8225 * tar format in windows as native windows utilities are not able to create
8226 * symlinks while extracting files from tar. However for consistency and
8227 * platform-independence, we do it the same way everywhere.
8229 * It fills in "state" with the information required for the backup, such
8230 * as the minimum WAL location that must be present to restore from this
8231 * backup (starttli) and the corresponding timeline ID (starttli).
8233 * Every successfully started backup must be stopped by calling
8234 * do_pg_backup_stop() or do_pg_abort_backup(). There can be many
8235 * backups active at the same time.
8237 * It is the responsibility of the caller of this function to verify the
8238 * permissions of the calling user!
8240 void
8241 do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces,
8242 BackupState *state, StringInfo tblspcmapfile)
8244 bool backup_started_in_recovery;
8246 Assert(state != NULL);
8247 backup_started_in_recovery = RecoveryInProgress();
8250 * During recovery, we don't need to check WAL level. Because, if WAL
8251 * level is not sufficient, it's impossible to get here during recovery.
8253 if (!backup_started_in_recovery && !XLogIsNeeded())
8254 ereport(ERROR,
8255 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8256 errmsg("WAL level not sufficient for making an online backup"),
8257 errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
8259 if (strlen(backupidstr) > MAXPGPATH)
8260 ereport(ERROR,
8261 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8262 errmsg("backup label too long (max %d bytes)",
8263 MAXPGPATH)));
8265 memcpy(state->name, backupidstr, strlen(backupidstr));
8268 * Mark backup active in shared memory. We must do full-page WAL writes
8269 * during an on-line backup even if not doing so at other times, because
8270 * it's quite possible for the backup dump to obtain a "torn" (partially
8271 * written) copy of a database page if it reads the page concurrently with
8272 * our write to the same page. This can be fixed as long as the first
8273 * write to the page in the WAL sequence is a full-page write. Hence, we
8274 * increment runningBackups then force a CHECKPOINT, to ensure there are
8275 * no dirty pages in shared memory that might get dumped while the backup
8276 * is in progress without having a corresponding WAL record. (Once the
8277 * backup is complete, we need not force full-page writes anymore, since
8278 * we expect that any pages not modified during the backup interval must
8279 * have been correctly captured by the backup.)
8281 * Note that forcing full-page writes has no effect during an online
8282 * backup from the standby.
8284 * We must hold all the insertion locks to change the value of
8285 * runningBackups, to ensure adequate interlocking against
8286 * XLogInsertRecord().
8288 WALInsertLockAcquireExclusive();
8289 XLogCtl->Insert.runningBackups++;
8290 WALInsertLockRelease();
8293 * Ensure we decrement runningBackups if we fail below. NB -- for this to
8294 * work correctly, it is critical that sessionBackupState is only updated
8295 * after this block is over.
8297 PG_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, DatumGetBool(true));
8299 bool gotUniqueStartpoint = false;
8300 DIR *tblspcdir;
8301 struct dirent *de;
8302 tablespaceinfo *ti;
8303 int datadirpathlen;
8306 * Force an XLOG file switch before the checkpoint, to ensure that the
8307 * WAL segment the checkpoint is written to doesn't contain pages with
8308 * old timeline IDs. That would otherwise happen if you called
8309 * pg_backup_start() right after restoring from a PITR archive: the
8310 * first WAL segment containing the startup checkpoint has pages in
8311 * the beginning with the old timeline ID. That can cause trouble at
8312 * recovery: we won't have a history file covering the old timeline if
8313 * pg_wal directory was not included in the base backup and the WAL
8314 * archive was cleared too before starting the backup.
8316 * This also ensures that we have emitted a WAL page header that has
8317 * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
8318 * Therefore, if a WAL archiver (such as pglesslog) is trying to
8319 * compress out removable backup blocks, it won't remove any that
8320 * occur after this point.
8322 * During recovery, we skip forcing XLOG file switch, which means that
8323 * the backup taken during recovery is not available for the special
8324 * recovery case described above.
8326 if (!backup_started_in_recovery)
8327 RequestXLogSwitch(false);
8331 bool checkpointfpw;
8334 * Force a CHECKPOINT. Aside from being necessary to prevent torn
8335 * page problems, this guarantees that two successive backup runs
8336 * will have different checkpoint positions and hence different
8337 * history file names, even if nothing happened in between.
8339 * During recovery, establish a restartpoint if possible. We use
8340 * the last restartpoint as the backup starting checkpoint. This
8341 * means that two successive backup runs can have same checkpoint
8342 * positions.
8344 * Since the fact that we are executing do_pg_backup_start()
8345 * during recovery means that checkpointer is running, we can use
8346 * RequestCheckpoint() to establish a restartpoint.
8348 * We use CHECKPOINT_IMMEDIATE only if requested by user (via
8349 * passing fast = true). Otherwise this can take awhile.
8351 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT |
8352 (fast ? CHECKPOINT_IMMEDIATE : 0));
8355 * Now we need to fetch the checkpoint record location, and also
8356 * its REDO pointer. The oldest point in WAL that would be needed
8357 * to restore starting from the checkpoint is precisely the REDO
8358 * pointer.
8360 LWLockAcquire(ControlFileLock, LW_SHARED);
8361 state->checkpointloc = ControlFile->checkPoint;
8362 state->startpoint = ControlFile->checkPointCopy.redo;
8363 state->starttli = ControlFile->checkPointCopy.ThisTimeLineID;
8364 checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
8365 LWLockRelease(ControlFileLock);
8367 if (backup_started_in_recovery)
8369 XLogRecPtr recptr;
8372 * Check to see if all WAL replayed during online backup
8373 * (i.e., since last restartpoint used as backup starting
8374 * checkpoint) contain full-page writes.
8376 SpinLockAcquire(&XLogCtl->info_lck);
8377 recptr = XLogCtl->lastFpwDisableRecPtr;
8378 SpinLockRelease(&XLogCtl->info_lck);
8380 if (!checkpointfpw || state->startpoint <= recptr)
8381 ereport(ERROR,
8382 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8383 errmsg("WAL generated with full_page_writes=off was replayed "
8384 "since last restartpoint"),
8385 errhint("This means that the backup being taken on the standby "
8386 "is corrupt and should not be used. "
8387 "Enable full_page_writes and run CHECKPOINT on the primary, "
8388 "and then try an online backup again.")));
8391 * During recovery, since we don't use the end-of-backup WAL
8392 * record and don't write the backup history file, the
8393 * starting WAL location doesn't need to be unique. This means
8394 * that two base backups started at the same time might use
8395 * the same checkpoint as starting locations.
8397 gotUniqueStartpoint = true;
8401 * If two base backups are started at the same time (in WAL sender
8402 * processes), we need to make sure that they use different
8403 * checkpoints as starting locations, because we use the starting
8404 * WAL location as a unique identifier for the base backup in the
8405 * end-of-backup WAL record and when we write the backup history
8406 * file. Perhaps it would be better generate a separate unique ID
8407 * for each backup instead of forcing another checkpoint, but
8408 * taking a checkpoint right after another is not that expensive
8409 * either because only few buffers have been dirtied yet.
8411 WALInsertLockAcquireExclusive();
8412 if (XLogCtl->Insert.lastBackupStart < state->startpoint)
8414 XLogCtl->Insert.lastBackupStart = state->startpoint;
8415 gotUniqueStartpoint = true;
8417 WALInsertLockRelease();
8418 } while (!gotUniqueStartpoint);
8421 * Construct tablespace_map file.
8423 datadirpathlen = strlen(DataDir);
8425 /* Collect information about all tablespaces */
8426 tblspcdir = AllocateDir("pg_tblspc");
8427 while ((de = ReadDir(tblspcdir, "pg_tblspc")) != NULL)
8429 char fullpath[MAXPGPATH + 10];
8430 char linkpath[MAXPGPATH];
8431 char *relpath = NULL;
8432 int rllen;
8433 StringInfoData escapedpath;
8434 char *s;
8436 /* Skip anything that doesn't look like a tablespace */
8437 if (strspn(de->d_name, "0123456789") != strlen(de->d_name))
8438 continue;
8440 snprintf(fullpath, sizeof(fullpath), "pg_tblspc/%s", de->d_name);
8443 * Skip anything that isn't a symlink/junction. For testing only,
8444 * we sometimes use allow_in_place_tablespaces to create
8445 * directories directly under pg_tblspc, which would fail below.
8447 if (get_dirent_type(fullpath, de, false, ERROR) != PGFILETYPE_LNK)
8448 continue;
8450 rllen = readlink(fullpath, linkpath, sizeof(linkpath));
8451 if (rllen < 0)
8453 ereport(WARNING,
8454 (errmsg("could not read symbolic link \"%s\": %m",
8455 fullpath)));
8456 continue;
8458 else if (rllen >= sizeof(linkpath))
8460 ereport(WARNING,
8461 (errmsg("symbolic link \"%s\" target is too long",
8462 fullpath)));
8463 continue;
8465 linkpath[rllen] = '\0';
8468 * Build a backslash-escaped version of the link path to include
8469 * in the tablespace map file.
8471 initStringInfo(&escapedpath);
8472 for (s = linkpath; *s; s++)
8474 if (*s == '\n' || *s == '\r' || *s == '\\')
8475 appendStringInfoChar(&escapedpath, '\\');
8476 appendStringInfoChar(&escapedpath, *s);
8480 * Relpath holds the relative path of the tablespace directory
8481 * when it's located within PGDATA, or NULL if it's located
8482 * elsewhere.
8484 if (rllen > datadirpathlen &&
8485 strncmp(linkpath, DataDir, datadirpathlen) == 0 &&
8486 IS_DIR_SEP(linkpath[datadirpathlen]))
8487 relpath = linkpath + datadirpathlen + 1;
8489 ti = palloc(sizeof(tablespaceinfo));
8490 ti->oid = pstrdup(de->d_name);
8491 ti->path = pstrdup(linkpath);
8492 ti->rpath = relpath ? pstrdup(relpath) : NULL;
8493 ti->size = -1;
8495 if (tablespaces)
8496 *tablespaces = lappend(*tablespaces, ti);
8498 appendStringInfo(tblspcmapfile, "%s %s\n",
8499 ti->oid, escapedpath.data);
8501 pfree(escapedpath.data);
8503 FreeDir(tblspcdir);
8505 state->starttime = (pg_time_t) time(NULL);
8507 PG_END_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, DatumGetBool(true));
8509 state->started_in_recovery = backup_started_in_recovery;
8512 * Mark that the start phase has correctly finished for the backup.
8514 sessionBackupState = SESSION_BACKUP_RUNNING;
8518 * Utility routine to fetch the session-level status of a backup running.
8520 SessionBackupState
8521 get_backup_status(void)
8523 return sessionBackupState;
8527 * do_pg_backup_stop
8529 * Utility function called at the end of an online backup. It creates history
8530 * file (if required), resets sessionBackupState and so on. It can optionally
8531 * wait for WAL segments to be archived.
8533 * "state" is filled with the information necessary to restore from this
8534 * backup with its stop LSN (stoppoint), its timeline ID (stoptli), etc.
8536 * It is the responsibility of the caller of this function to verify the
8537 * permissions of the calling user!
8539 void
8540 do_pg_backup_stop(BackupState *state, bool waitforarchive)
8542 bool backup_stopped_in_recovery = false;
8543 char histfilepath[MAXPGPATH];
8544 char lastxlogfilename[MAXFNAMELEN];
8545 char histfilename[MAXFNAMELEN];
8546 XLogSegNo _logSegNo;
8547 FILE *fp;
8548 int seconds_before_warning;
8549 int waits = 0;
8550 bool reported_waiting = false;
8552 Assert(state != NULL);
8554 backup_stopped_in_recovery = RecoveryInProgress();
8557 * During recovery, we don't need to check WAL level. Because, if WAL
8558 * level is not sufficient, it's impossible to get here during recovery.
8560 if (!backup_stopped_in_recovery && !XLogIsNeeded())
8561 ereport(ERROR,
8562 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8563 errmsg("WAL level not sufficient for making an online backup"),
8564 errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
8567 * OK to update backup counter and session-level lock.
8569 * Note that CHECK_FOR_INTERRUPTS() must not occur while updating them,
8570 * otherwise they can be updated inconsistently, which might cause
8571 * do_pg_abort_backup() to fail.
8573 WALInsertLockAcquireExclusive();
8576 * It is expected that each do_pg_backup_start() call is matched by
8577 * exactly one do_pg_backup_stop() call.
8579 Assert(XLogCtl->Insert.runningBackups > 0);
8580 XLogCtl->Insert.runningBackups--;
8583 * Clean up session-level lock.
8585 * You might think that WALInsertLockRelease() can be called before
8586 * cleaning up session-level lock because session-level lock doesn't need
8587 * to be protected with WAL insertion lock. But since
8588 * CHECK_FOR_INTERRUPTS() can occur in it, session-level lock must be
8589 * cleaned up before it.
8591 sessionBackupState = SESSION_BACKUP_NONE;
8593 WALInsertLockRelease();
8596 * If we are taking an online backup from the standby, we confirm that the
8597 * standby has not been promoted during the backup.
8599 if (state->started_in_recovery && !backup_stopped_in_recovery)
8600 ereport(ERROR,
8601 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8602 errmsg("the standby was promoted during online backup"),
8603 errhint("This means that the backup being taken is corrupt "
8604 "and should not be used. "
8605 "Try taking another online backup.")));
8608 * During recovery, we don't write an end-of-backup record. We assume that
8609 * pg_control was backed up last and its minimum recovery point can be
8610 * available as the backup end location. Since we don't have an
8611 * end-of-backup record, we use the pg_control value to check whether
8612 * we've reached the end of backup when starting recovery from this
8613 * backup. We have no way of checking if pg_control wasn't backed up last
8614 * however.
8616 * We don't force a switch to new WAL file but it is still possible to
8617 * wait for all the required files to be archived if waitforarchive is
8618 * true. This is okay if we use the backup to start a standby and fetch
8619 * the missing WAL using streaming replication. But in the case of an
8620 * archive recovery, a user should set waitforarchive to true and wait for
8621 * them to be archived to ensure that all the required files are
8622 * available.
8624 * We return the current minimum recovery point as the backup end
8625 * location. Note that it can be greater than the exact backup end
8626 * location if the minimum recovery point is updated after the backup of
8627 * pg_control. This is harmless for current uses.
8629 * XXX currently a backup history file is for informational and debug
8630 * purposes only. It's not essential for an online backup. Furthermore,
8631 * even if it's created, it will not be archived during recovery because
8632 * an archiver is not invoked. So it doesn't seem worthwhile to write a
8633 * backup history file during recovery.
8635 if (backup_stopped_in_recovery)
8637 XLogRecPtr recptr;
8640 * Check to see if all WAL replayed during online backup contain
8641 * full-page writes.
8643 SpinLockAcquire(&XLogCtl->info_lck);
8644 recptr = XLogCtl->lastFpwDisableRecPtr;
8645 SpinLockRelease(&XLogCtl->info_lck);
8647 if (state->startpoint <= recptr)
8648 ereport(ERROR,
8649 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8650 errmsg("WAL generated with full_page_writes=off was replayed "
8651 "during online backup"),
8652 errhint("This means that the backup being taken on the standby "
8653 "is corrupt and should not be used. "
8654 "Enable full_page_writes and run CHECKPOINT on the primary, "
8655 "and then try an online backup again.")));
8658 LWLockAcquire(ControlFileLock, LW_SHARED);
8659 state->stoppoint = ControlFile->minRecoveryPoint;
8660 state->stoptli = ControlFile->minRecoveryPointTLI;
8661 LWLockRelease(ControlFileLock);
8663 else
8665 char *history_file;
8668 * Write the backup-end xlog record
8670 XLogBeginInsert();
8671 XLogRegisterData((char *) (&state->startpoint),
8672 sizeof(state->startpoint));
8673 state->stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END);
8676 * Given that we're not in recovery, InsertTimeLineID is set and can't
8677 * change, so we can read it without a lock.
8679 state->stoptli = XLogCtl->InsertTimeLineID;
8682 * Force a switch to a new xlog segment file, so that the backup is
8683 * valid as soon as archiver moves out the current segment file.
8685 RequestXLogSwitch(false);
8687 state->stoptime = (pg_time_t) time(NULL);
8690 * Write the backup history file
8692 XLByteToSeg(state->startpoint, _logSegNo, wal_segment_size);
8693 BackupHistoryFilePath(histfilepath, state->stoptli, _logSegNo,
8694 state->startpoint, wal_segment_size);
8695 fp = AllocateFile(histfilepath, "w");
8696 if (!fp)
8697 ereport(ERROR,
8698 (errcode_for_file_access(),
8699 errmsg("could not create file \"%s\": %m",
8700 histfilepath)));
8702 /* Build and save the contents of the backup history file */
8703 history_file = build_backup_content(state, true);
8704 fprintf(fp, "%s", history_file);
8705 pfree(history_file);
8707 if (fflush(fp) || ferror(fp) || FreeFile(fp))
8708 ereport(ERROR,
8709 (errcode_for_file_access(),
8710 errmsg("could not write file \"%s\": %m",
8711 histfilepath)));
8714 * Clean out any no-longer-needed history files. As a side effect,
8715 * this will post a .ready file for the newly created history file,
8716 * notifying the archiver that history file may be archived
8717 * immediately.
8719 CleanupBackupHistory();
8723 * If archiving is enabled, wait for all the required WAL files to be
8724 * archived before returning. If archiving isn't enabled, the required WAL
8725 * needs to be transported via streaming replication (hopefully with
8726 * wal_keep_size set high enough), or some more exotic mechanism like
8727 * polling and copying files from pg_wal with script. We have no knowledge
8728 * of those mechanisms, so it's up to the user to ensure that he gets all
8729 * the required WAL.
8731 * We wait until both the last WAL file filled during backup and the
8732 * history file have been archived, and assume that the alphabetic sorting
8733 * property of the WAL files ensures any earlier WAL files are safely
8734 * archived as well.
8736 * We wait forever, since archive_command is supposed to work and we
8737 * assume the admin wanted his backup to work completely. If you don't
8738 * wish to wait, then either waitforarchive should be passed in as false,
8739 * or you can set statement_timeout. Also, some notices are issued to
8740 * clue in anyone who might be doing this interactively.
8743 if (waitforarchive &&
8744 ((!backup_stopped_in_recovery && XLogArchivingActive()) ||
8745 (backup_stopped_in_recovery && XLogArchivingAlways())))
8747 XLByteToPrevSeg(state->stoppoint, _logSegNo, wal_segment_size);
8748 XLogFileName(lastxlogfilename, state->stoptli, _logSegNo,
8749 wal_segment_size);
8751 XLByteToSeg(state->startpoint, _logSegNo, wal_segment_size);
8752 BackupHistoryFileName(histfilename, state->stoptli, _logSegNo,
8753 state->startpoint, wal_segment_size);
8755 seconds_before_warning = 60;
8756 waits = 0;
8758 while (XLogArchiveIsBusy(lastxlogfilename) ||
8759 XLogArchiveIsBusy(histfilename))
8761 CHECK_FOR_INTERRUPTS();
8763 if (!reported_waiting && waits > 5)
8765 ereport(NOTICE,
8766 (errmsg("base backup done, waiting for required WAL segments to be archived")));
8767 reported_waiting = true;
8770 (void) WaitLatch(MyLatch,
8771 WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
8772 1000L,
8773 WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE);
8774 ResetLatch(MyLatch);
8776 if (++waits >= seconds_before_warning)
8778 seconds_before_warning *= 2; /* This wraps in >10 years... */
8779 ereport(WARNING,
8780 (errmsg("still waiting for all required WAL segments to be archived (%d seconds elapsed)",
8781 waits),
8782 errhint("Check that your archive_command is executing properly. "
8783 "You can safely cancel this backup, "
8784 "but the database backup will not be usable without all the WAL segments.")));
8788 ereport(NOTICE,
8789 (errmsg("all required WAL segments have been archived")));
8791 else if (waitforarchive)
8792 ereport(NOTICE,
8793 (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
8798 * do_pg_abort_backup: abort a running backup
8800 * This does just the most basic steps of do_pg_backup_stop(), by taking the
8801 * system out of backup mode, thus making it a lot more safe to call from
8802 * an error handler.
8804 * 'arg' indicates that it's being called during backup setup; so
8805 * sessionBackupState has not been modified yet, but runningBackups has
8806 * already been incremented. When it's false, then it's invoked as a
8807 * before_shmem_exit handler, and therefore we must not change state
8808 * unless sessionBackupState indicates that a backup is actually running.
8810 * NB: This gets used as a PG_ENSURE_ERROR_CLEANUP callback and
8811 * before_shmem_exit handler, hence the odd-looking signature.
8813 void
8814 do_pg_abort_backup(int code, Datum arg)
8816 bool during_backup_start = DatumGetBool(arg);
8818 /* If called during backup start, there shouldn't be one already running */
8819 Assert(!during_backup_start || sessionBackupState == SESSION_BACKUP_NONE);
8821 if (during_backup_start || sessionBackupState != SESSION_BACKUP_NONE)
8823 WALInsertLockAcquireExclusive();
8824 Assert(XLogCtl->Insert.runningBackups > 0);
8825 XLogCtl->Insert.runningBackups--;
8827 sessionBackupState = SESSION_BACKUP_NONE;
8828 WALInsertLockRelease();
8830 if (!during_backup_start)
8831 ereport(WARNING,
8832 errmsg("aborting backup due to backend exiting before pg_backup_stop was called"));
8837 * Register a handler that will warn about unterminated backups at end of
8838 * session, unless this has already been done.
8840 void
8841 register_persistent_abort_backup_handler(void)
8843 static bool already_done = false;
8845 if (already_done)
8846 return;
8847 before_shmem_exit(do_pg_abort_backup, DatumGetBool(false));
8848 already_done = true;
8852 * Get latest WAL insert pointer
8854 XLogRecPtr
8855 GetXLogInsertRecPtr(void)
8857 XLogCtlInsert *Insert = &XLogCtl->Insert;
8858 uint64 current_bytepos;
8860 SpinLockAcquire(&Insert->insertpos_lck);
8861 current_bytepos = Insert->CurrBytePos;
8862 SpinLockRelease(&Insert->insertpos_lck);
8864 return XLogBytePosToRecPtr(current_bytepos);
8868 * Get latest WAL write pointer
8870 XLogRecPtr
8871 GetXLogWriteRecPtr(void)
8873 SpinLockAcquire(&XLogCtl->info_lck);
8874 LogwrtResult = XLogCtl->LogwrtResult;
8875 SpinLockRelease(&XLogCtl->info_lck);
8877 return LogwrtResult.Write;
8881 * Returns the redo pointer of the last checkpoint or restartpoint. This is
8882 * the oldest point in WAL that we still need, if we have to restart recovery.
8884 void
8885 GetOldestRestartPoint(XLogRecPtr *oldrecptr, TimeLineID *oldtli)
8887 LWLockAcquire(ControlFileLock, LW_SHARED);
8888 *oldrecptr = ControlFile->checkPointCopy.redo;
8889 *oldtli = ControlFile->checkPointCopy.ThisTimeLineID;
8890 LWLockRelease(ControlFileLock);
8894 * Returns the WAL file name for the last checkpoint or restartpoint. This is
8895 * the oldest WAL file that we still need if we have to restart recovery.
8897 static void
8898 GetOldestRestartPointFileName(char *fname)
8900 XLogRecPtr restartRedoPtr;
8901 TimeLineID restartTli;
8902 XLogSegNo restartSegNo;
8904 GetOldestRestartPoint(&restartRedoPtr, &restartTli);
8905 XLByteToSeg(restartRedoPtr, restartSegNo, wal_segment_size);
8906 XLogFileName(fname, restartTli, restartSegNo, wal_segment_size);
8909 /* Thin wrapper around ShutdownWalRcv(). */
8910 void
8911 XLogShutdownWalRcv(void)
8913 ShutdownWalRcv();
8915 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8916 XLogCtl->InstallXLogFileSegmentActive = false;
8917 LWLockRelease(ControlFileLock);
8920 /* Enable WAL file recycling and preallocation. */
8921 void
8922 SetInstallXLogFileSegmentActive(void)
8924 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8925 XLogCtl->InstallXLogFileSegmentActive = true;
8926 LWLockRelease(ControlFileLock);
8929 bool
8930 IsInstallXLogFileSegmentActive(void)
8932 bool result;
8934 LWLockAcquire(ControlFileLock, LW_SHARED);
8935 result = XLogCtl->InstallXLogFileSegmentActive;
8936 LWLockRelease(ControlFileLock);
8938 return result;
8942 * Update the WalWriterSleeping flag.
8944 void
8945 SetWalWriterSleeping(bool sleeping)
8947 SpinLockAcquire(&XLogCtl->info_lck);
8948 XLogCtl->WalWriterSleeping = sleeping;
8949 SpinLockRelease(&XLogCtl->info_lck);