PostgreSQL Source Code  git master
xlog.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * xlog.c
4  * PostgreSQL write-ahead log manager
5  *
6  *
7  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * src/backend/access/transam/xlog.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 
15 #include "postgres.h"
16 
17 #include <ctype.h>
18 #include <math.h>
19 #include <time.h>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <sys/time.h>
23 #include <unistd.h>
24 
25 #include "access/clog.h"
26 #include "access/commit_ts.h"
27 #include "access/heaptoast.h"
28 #include "access/multixact.h"
29 #include "access/rewriteheap.h"
30 #include "access/subtrans.h"
31 #include "access/timeline.h"
32 #include "access/transam.h"
33 #include "access/twophase.h"
34 #include "access/xact.h"
35 #include "access/xlog_internal.h"
36 #include "access/xlogarchive.h"
37 #include "access/xloginsert.h"
38 #include "access/xlogreader.h"
39 #include "access/xlogutils.h"
40 #include "catalog/catversion.h"
41 #include "catalog/pg_control.h"
42 #include "catalog/pg_database.h"
43 #include "commands/progress.h"
44 #include "commands/tablespace.h"
46 #include "executor/instrument.h"
47 #include "miscadmin.h"
48 #include "pg_trace.h"
49 #include "pgstat.h"
50 #include "port/atomics.h"
51 #include "port/pg_iovec.h"
52 #include "postmaster/bgwriter.h"
53 #include "postmaster/startup.h"
54 #include "postmaster/walwriter.h"
55 #include "replication/basebackup.h"
56 #include "replication/logical.h"
57 #include "replication/origin.h"
58 #include "replication/slot.h"
59 #include "replication/snapbuild.h"
61 #include "replication/walsender.h"
62 #include "storage/bufmgr.h"
63 #include "storage/fd.h"
64 #include "storage/ipc.h"
65 #include "storage/large_object.h"
66 #include "storage/latch.h"
67 #include "storage/pmsignal.h"
68 #include "storage/predicate.h"
69 #include "storage/proc.h"
70 #include "storage/procarray.h"
71 #include "storage/reinit.h"
72 #include "storage/smgr.h"
73 #include "storage/spin.h"
74 #include "storage/sync.h"
75 #include "utils/builtins.h"
76 #include "utils/guc.h"
77 #include "utils/memutils.h"
78 #include "utils/ps_status.h"
79 #include "utils/relmapper.h"
80 #include "utils/pg_rusage.h"
81 #include "utils/snapmgr.h"
82 #include "utils/timeout.h"
83 #include "utils/timestamp.h"
84 
86 
87 /* Unsupported old recovery command file names (relative to $PGDATA) */
88 #define RECOVERY_COMMAND_FILE "recovery.conf"
89 #define RECOVERY_COMMAND_DONE "recovery.done"
90 
91 /* timeline ID to be used when bootstrapping */
92 #define BootstrapTimeLineID 1
93 
94 /* User-settable parameters */
95 int max_wal_size_mb = 1024; /* 1 GB */
96 int min_wal_size_mb = 80; /* 80 MB */
98 int XLOGbuffers = -1;
101 char *XLogArchiveCommand = NULL;
102 bool EnableHotStandby = false;
103 bool fullPageWrites = true;
104 bool wal_log_hints = false;
108 bool wal_init_zero = true;
109 bool wal_recycle = true;
110 bool log_checkpoints = false;
113 int CommitDelay = 0; /* precommit delay in microseconds */
114 int CommitSiblings = 5; /* # concurrent xacts needed to sleep */
117 bool track_wal_io_timing = false;
118 
119 #ifdef WAL_DEBUG
120 bool XLOG_DEBUG = false;
121 #endif
122 
124 
125 /*
126  * Number of WAL insertion locks to use. A higher value allows more insertions
127  * to happen concurrently, but adds some CPU overhead to flushing the WAL,
128  * which needs to iterate all the locks.
129  */
130 #define NUM_XLOGINSERT_LOCKS 8
131 
132 /*
133  * Max distance from last checkpoint, before triggering a new xlog-based
134  * checkpoint.
135  */
137 
138 /* Estimated distance between checkpoints, in bytes */
139 static double CheckPointDistanceEstimate = 0;
140 static double PrevCheckPointDistance = 0;
141 
142 /*
143  * GUC support
144  */
145 const struct config_enum_entry sync_method_options[] = {
146  {"fsync", SYNC_METHOD_FSYNC, false},
147 #ifdef HAVE_FSYNC_WRITETHROUGH
148  {"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
149 #endif
150 #ifdef HAVE_FDATASYNC
151  {"fdatasync", SYNC_METHOD_FDATASYNC, false},
152 #endif
153 #ifdef OPEN_SYNC_FLAG
154  {"open_sync", SYNC_METHOD_OPEN, false},
155 #endif
156 #ifdef OPEN_DATASYNC_FLAG
157  {"open_datasync", SYNC_METHOD_OPEN_DSYNC, false},
158 #endif
159  {NULL, 0, false}
160 };
161 
162 
163 /*
164  * Although only "on", "off", and "always" are documented,
165  * we accept all the likely variants of "on" and "off".
166  */
167 const struct config_enum_entry archive_mode_options[] = {
168  {"always", ARCHIVE_MODE_ALWAYS, false},
169  {"on", ARCHIVE_MODE_ON, false},
170  {"off", ARCHIVE_MODE_OFF, false},
171  {"true", ARCHIVE_MODE_ON, true},
172  {"false", ARCHIVE_MODE_OFF, true},
173  {"yes", ARCHIVE_MODE_ON, true},
174  {"no", ARCHIVE_MODE_OFF, true},
175  {"1", ARCHIVE_MODE_ON, true},
176  {"0", ARCHIVE_MODE_OFF, true},
177  {NULL, 0, false}
178 };
179 
181  {"pause", RECOVERY_TARGET_ACTION_PAUSE, false},
182  {"promote", RECOVERY_TARGET_ACTION_PROMOTE, false},
183  {"shutdown", RECOVERY_TARGET_ACTION_SHUTDOWN, false},
184  {NULL, 0, false}
185 };
186 
187 /*
188  * Statistics for current checkpoint are collected in this global struct.
189  * Because only the checkpointer or a stand-alone backend can perform
190  * checkpoints, this will be unused in normal backends.
191  */
193 
194 /* Local copy of WalRcv->flushedUpto */
197 
198 /*
199  * abortedRecPtr is the start pointer of a broken record at end of WAL when
200  * recovery completes; missingContrecPtr is the location of the first
201  * contrecord that went missing. See CreateOverwriteContrecordRecord for
202  * details.
203  */
206 
207 /*
208  * During recovery, lastFullPageWrites keeps track of full_page_writes that
209  * the replayed WAL records indicate. It's initialized with full_page_writes
210  * that the recovery starting checkpoint record indicates, and then updated
211  * each time XLOG_FPW_CHANGE record is replayed.
212  */
213 static bool lastFullPageWrites;
214 
215 /*
216  * Local copy of the state tracked by SharedRecoveryState in shared memory,
217  * It is false if SharedRecoveryState is RECOVERY_STATE_DONE. True actually
218  * means "not known, need to check the shared state".
219  */
220 static bool LocalRecoveryInProgress = true;
221 
222 /*
223  * Local copy of SharedHotStandbyActive variable. False actually means "not
224  * known, need to check the shared state".
225  */
226 static bool LocalHotStandbyActive = false;
227 
228 /*
229  * Local copy of SharedPromoteIsTriggered variable. False actually means "not
230  * known, need to check the shared state".
231  */
232 static bool LocalPromoteIsTriggered = false;
233 
234 /*
235  * Local state for XLogInsertAllowed():
236  * 1: unconditionally allowed to insert XLOG
237  * 0: unconditionally not allowed to insert XLOG
238  * -1: must check RecoveryInProgress(); disallow until it is false
239  * Most processes start with -1 and transition to 1 after seeing that recovery
240  * is not in progress. But we can also force the value for special cases.
241  * The coding in XLogInsertAllowed() depends on the first two of these states
242  * being numerically the same as bool true and false.
243  */
244 static int LocalXLogInsertAllowed = -1;
245 
246 /*
247  * When ArchiveRecoveryRequested is set, archive recovery was requested,
248  * ie. signal files were present. When InArchiveRecovery is set, we are
249  * currently recovering using offline XLOG archives. These variables are only
250  * valid in the startup process.
251  *
252  * When ArchiveRecoveryRequested is true, but InArchiveRecovery is false, we're
253  * currently performing crash recovery using only XLOG files in pg_wal, but
254  * will switch to using offline XLOG archives as soon as we reach the end of
255  * WAL in pg_wal.
256 */
258 bool InArchiveRecovery = false;
259 
260 static bool standby_signal_file_found = false;
261 static bool recovery_signal_file_found = false;
262 
263 /* Buffers dedicated to consistency checks of size BLCKSZ */
264 static char *replay_image_masked = NULL;
265 static char *primary_image_masked = NULL;
266 
267 /* options formerly taken from recovery.conf for archive recovery */
269 char *recoveryEndCommand = NULL;
277 const char *recoveryTargetName;
280 
281 /* options formerly taken from recovery.conf for XLOG streaming */
282 bool StandbyModeRequested = false;
283 char *PrimaryConnInfo = NULL;
284 char *PrimarySlotName = NULL;
285 char *PromoteTriggerFile = NULL;
287 
288 /* are we currently in standby mode? */
289 bool StandbyMode = false;
290 
291 /*
292  * if recoveryStopsBefore/After returns true, it saves information of the stop
293  * point here
294  */
299 static bool recoveryStopAfter;
300 
301 /*
302  * recoveryTargetTimeLineGoal: what the user requested, if any
303  *
304  * recoveryTargetTLIRequested: numeric value of requested timeline, if constant
305  *
306  * recoveryTargetTLI: the currently understood target timeline; changes
307  *
308  * expectedTLEs: a list of TimeLineHistoryEntries for recoveryTargetTLI and the timelines of
309  * its known parents, newest first (so recoveryTargetTLI is always the
310  * first list member). Only these TLIs are expected to be seen in the WAL
311  * segments we read, and indeed only these TLIs will be considered as
312  * candidate WAL files to open at all.
313  *
314  * curFileTLI: the TLI appearing in the name of the current input WAL file.
315  * (This is not necessarily the same as the timeline from which we are
316  * replaying WAL, which StartupXLOG calls replayTLI, because we could be
317  * scanning data that was copied from an ancestor timeline when the current
318  * file was created.) During a sequential scan we do not allow this value
319  * to decrease.
320  */
326 
327 /*
328  * ProcLastRecPtr points to the start of the last XLOG record inserted by the
329  * current backend. It is updated for all inserts. XactLastRecEnd points to
330  * end+1 of the last record, and is reset when we end a top-level transaction,
331  * or start a new one; so it can be used to tell if the current transaction has
332  * created any XLOG records.
333  *
334  * While in parallel mode, this may not be fully up to date. When committing,
335  * a transaction can assume this covers all xlog records written either by the
336  * user backend or by any parallel worker which was present at any point during
337  * the transaction. But when aborting, or when still in parallel mode, other
338  * parallel backends may have written WAL records at later LSNs than the value
339  * stored here. The parallel leader advances its own copy, when necessary,
340  * in WaitForParallelWorkersToFinish.
341  */
345 
346 /*
347  * RedoRecPtr is this backend's local copy of the REDO record pointer
348  * (which is almost but not quite the same as a pointer to the most recent
349  * CHECKPOINT record). We update this from the shared-memory copy,
350  * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
351  * hold an insertion lock). See XLogInsertRecord for details. We are also
352  * allowed to update from XLogCtl->RedoRecPtr if we hold the info_lck;
353  * see GetRedoRecPtr. A freshly spawned backend obtains the value during
354  * InitXLOGAccess.
355  */
357 
358 /*
359  * doPageWrites is this backend's local copy of (forcePageWrites ||
360  * fullPageWrites). It is used together with RedoRecPtr to decide whether
361  * a full-page image of a page need to be taken.
362  */
363 static bool doPageWrites;
364 
365 /* Has the recovery code requested a walreceiver wakeup? */
367 
368 /*
369  * RedoStartLSN points to the checkpoint's REDO location which is specified
370  * in a backup label file, backup history file or control file. In standby
371  * mode, XLOG streaming usually starts from the position where an invalid
372  * record was found. But if we fail to read even the initial checkpoint
373  * record, we use the REDO location instead of the checkpoint location as
374  * the start position of XLOG streaming. Otherwise we would have to jump
375  * backwards to the REDO location after reading the checkpoint record,
376  * because the REDO record can precede the checkpoint record.
377  */
379 
380 /*----------
381  * Shared-memory data structures for XLOG control
382  *
383  * LogwrtRqst indicates a byte position that we need to write and/or fsync
384  * the log up to (all records before that point must be written or fsynced).
385  * LogwrtResult indicates the byte positions we have already written/fsynced.
386  * These structs are identical but are declared separately to indicate their
387  * slightly different functions.
388  *
389  * To read XLogCtl->LogwrtResult, you must hold either info_lck or
390  * WALWriteLock. To update it, you need to hold both locks. The point of
391  * this arrangement is that the value can be examined by code that already
392  * holds WALWriteLock without needing to grab info_lck as well. In addition
393  * to the shared variable, each backend has a private copy of LogwrtResult,
394  * which is updated when convenient.
395  *
396  * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
397  * (protected by info_lck), but we don't need to cache any copies of it.
398  *
399  * info_lck is only held long enough to read/update the protected variables,
400  * so it's a plain spinlock. The other locks are held longer (potentially
401  * over I/O operations), so we use LWLocks for them. These locks are:
402  *
403  * WALBufMappingLock: must be held to replace a page in the WAL buffer cache.
404  * It is only held while initializing and changing the mapping. If the
405  * contents of the buffer being replaced haven't been written yet, the mapping
406  * lock is released while the write is done, and reacquired afterwards.
407  *
408  * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
409  * XLogFlush).
410  *
411  * ControlFileLock: must be held to read/update control file or create
412  * new log file.
413  *
414  *----------
415  */
416 
417 typedef struct XLogwrtRqst
418 {
419  XLogRecPtr Write; /* last byte + 1 to write out */
420  XLogRecPtr Flush; /* last byte + 1 to flush */
422 
423 typedef struct XLogwrtResult
424 {
425  XLogRecPtr Write; /* last byte + 1 written out */
426  XLogRecPtr Flush; /* last byte + 1 flushed */
428 
429 /*
430  * Inserting to WAL is protected by a small fixed number of WAL insertion
431  * locks. To insert to the WAL, you must hold one of the locks - it doesn't
432  * matter which one. To lock out other concurrent insertions, you must hold
433  * of them. Each WAL insertion lock consists of a lightweight lock, plus an
434  * indicator of how far the insertion has progressed (insertingAt).
435  *
436  * The insertingAt values are read when a process wants to flush WAL from
437  * the in-memory buffers to disk, to check that all the insertions to the
438  * region the process is about to write out have finished. You could simply
439  * wait for all currently in-progress insertions to finish, but the
440  * insertingAt indicator allows you to ignore insertions to later in the WAL,
441  * so that you only wait for the insertions that are modifying the buffers
442  * you're about to write out.
443  *
444  * This isn't just an optimization. If all the WAL buffers are dirty, an
445  * inserter that's holding a WAL insert lock might need to evict an old WAL
446  * buffer, which requires flushing the WAL. If it's possible for an inserter
447  * to block on another inserter unnecessarily, deadlock can arise when two
448  * inserters holding a WAL insert lock wait for each other to finish their
449  * insertion.
450  *
451  * Small WAL records that don't cross a page boundary never update the value,
452  * the WAL record is just copied to the page and the lock is released. But
453  * to avoid the deadlock-scenario explained above, the indicator is always
454  * updated before sleeping while holding an insertion lock.
455  *
456  * lastImportantAt contains the LSN of the last important WAL record inserted
457  * using a given lock. This value is used to detect if there has been
458  * important WAL activity since the last time some action, like a checkpoint,
459  * was performed - allowing to not repeat the action if not. The LSN is
460  * updated for all insertions, unless the XLOG_MARK_UNIMPORTANT flag was
461  * set. lastImportantAt is never cleared, only overwritten by the LSN of newer
462  * records. Tracking the WAL activity directly in WALInsertLock has the
463  * advantage of not needing any additional locks to update the value.
464  */
465 typedef struct
466 {
470 } WALInsertLock;
471 
472 /*
473  * All the WAL insertion locks are allocated as an array in shared memory. We
474  * force the array stride to be a power of 2, which saves a few cycles in
475  * indexing, but more importantly also ensures that individual slots don't
476  * cross cache line boundaries. (Of course, we have to also ensure that the
477  * array start address is suitably aligned.)
478  */
479 typedef union WALInsertLockPadded
480 {
484 
485 /*
486  * State of an exclusive backup, necessary to control concurrent activities
487  * across sessions when working on exclusive backups.
488  *
489  * EXCLUSIVE_BACKUP_NONE means that there is no exclusive backup actually
490  * running, to be more precise pg_start_backup() is not being executed for
491  * an exclusive backup and there is no exclusive backup in progress.
492  * EXCLUSIVE_BACKUP_STARTING means that pg_start_backup() is starting an
493  * exclusive backup.
494  * EXCLUSIVE_BACKUP_IN_PROGRESS means that pg_start_backup() has finished
495  * running and an exclusive backup is in progress. pg_stop_backup() is
496  * needed to finish it.
497  * EXCLUSIVE_BACKUP_STOPPING means that pg_stop_backup() is stopping an
498  * exclusive backup.
499  */
501 {
507 
508 /*
509  * Session status of running backup, used for sanity checks in SQL-callable
510  * functions to start and stop backups.
511  */
513 
514 /*
515  * Shared state data for WAL insertion.
516  */
517 typedef struct XLogCtlInsert
518 {
519  slock_t insertpos_lck; /* protects CurrBytePos and PrevBytePos */
520 
521  /*
522  * CurrBytePos is the end of reserved WAL. The next record will be
523  * inserted at that position. PrevBytePos is the start position of the
524  * previously inserted (or rather, reserved) record - it is copied to the
525  * prev-link of the next record. These are stored as "usable byte
526  * positions" rather than XLogRecPtrs (see XLogBytePosToRecPtr()).
527  */
528  uint64 CurrBytePos;
529  uint64 PrevBytePos;
530 
531  /*
532  * Make sure the above heavily-contended spinlock and byte positions are
533  * on their own cache line. In particular, the RedoRecPtr and full page
534  * write variables below should be on a different cache line. They are
535  * read on every WAL insertion, but updated rarely, and we don't want
536  * those reads to steal the cache line containing Curr/PrevBytePos.
537  */
539 
540  /*
541  * fullPageWrites is the authoritative value used by all backends to
542  * determine whether to write full-page image to WAL. This shared value,
543  * instead of the process-local fullPageWrites, is required because, when
544  * full_page_writes is changed by SIGHUP, we must WAL-log it before it
545  * actually affects WAL-logging by backends. Checkpointer sets at startup
546  * or after SIGHUP.
547  *
548  * To read these fields, you must hold an insertion lock. To modify them,
549  * you must hold ALL the locks.
550  */
551  XLogRecPtr RedoRecPtr; /* current redo point for insertions */
552  bool forcePageWrites; /* forcing full-page writes for PITR? */
554 
555  /*
556  * exclusiveBackupState indicates the state of an exclusive backup (see
557  * comments of ExclusiveBackupState for more details). nonExclusiveBackups
558  * is a counter indicating the number of streaming base backups currently
559  * in progress. forcePageWrites is set to true when either of these is
560  * non-zero. lastBackupStart is the latest checkpoint redo location used
561  * as a starting point for an online backup.
562  */
566 
567  /*
568  * WAL insertion locks.
569  */
572 
573 /*
574  * Total shared-memory state for XLOG.
575  */
576 typedef struct XLogCtlData
577 {
579 
580  /* Protected by info_lck: */
582  XLogRecPtr RedoRecPtr; /* a recent copy of Insert->RedoRecPtr */
583  FullTransactionId ckptFullXid; /* nextXid of latest checkpoint */
584  XLogRecPtr asyncXactLSN; /* LSN of newest async commit/abort */
585  XLogRecPtr replicationSlotMinLSN; /* oldest LSN needed by any slot */
586 
587  XLogSegNo lastRemovedSegNo; /* latest removed/recycled XLOG segment */
588 
589  /* Fake LSN counter, for unlogged relations. Protected by ulsn_lck. */
592 
593  /* Time and LSN of last xlog segment switch. Protected by WALWriteLock. */
596 
597  /*
598  * Protected by info_lck and WALWriteLock (you must hold either lock to
599  * read it, but both to update)
600  */
602 
603  /*
604  * Latest initialized page in the cache (last byte position + 1).
605  *
606  * To change the identity of a buffer (and InitializedUpTo), you need to
607  * hold WALBufMappingLock. To change the identity of a buffer that's
608  * still dirty, the old page needs to be written out first, and for that
609  * you need WALWriteLock, and you need to ensure that there are no
610  * in-progress insertions to the page by calling
611  * WaitXLogInsertionsToFinish().
612  */
614 
615  /*
616  * These values do not change after startup, although the pointed-to pages
617  * and xlblocks values certainly do. xlblocks values are protected by
618  * WALBufMappingLock.
619  */
620  char *pages; /* buffers for unwritten XLOG pages */
621  XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
622  int XLogCacheBlck; /* highest allocated xlog buffer index */
623 
624  /*
625  * InsertTimeLineID is the timeline into which new WAL is being inserted
626  * and flushed. It is zero during recovery, and does not change once set.
627  *
628  * If we create a new timeline when the system was started up,
629  * PrevTimeLineID is the old timeline's ID that we forked off from.
630  * Otherwise it's equal to InsertTimeLineID.
631  */
634 
635  /*
636  * SharedRecoveryState indicates if we're still in crash or archive
637  * recovery. Protected by info_lck.
638  */
640 
641  /*
642  * SharedHotStandbyActive indicates if we allow hot standby queries to be
643  * run. Protected by info_lck.
644  */
646 
647  /*
648  * InstallXLogFileSegmentActive indicates whether the checkpointer should
649  * arrange for future segments by recycling and/or PreallocXlogFiles().
650  * Protected by ControlFileLock. Only the startup process changes it. If
651  * true, anyone can use InstallXLogFileSegment(). If false, the startup
652  * process owns the exclusive right to install segments, by reading from
653  * the archive and possibly replacing existing files.
654  */
656 
657  /*
658  * SharedPromoteIsTriggered indicates if a standby promotion has been
659  * triggered. Protected by info_lck.
660  */
662 
663  /*
664  * WalWriterSleeping indicates whether the WAL writer is currently in
665  * low-power mode (and hence should be nudged if an async commit occurs).
666  * Protected by info_lck.
667  */
669 
670  /*
671  * recoveryWakeupLatch is used to wake up the startup process to continue
672  * WAL replay, if it is waiting for WAL to arrive or failover trigger file
673  * to appear.
674  *
675  * Note that the startup process also uses another latch, its procLatch,
676  * to wait for recovery conflict. If we get rid of recoveryWakeupLatch for
677  * signaling the startup process in favor of using its procLatch, which
678  * comports better with possible generic signal handlers using that latch.
679  * But we should not do that because the startup process doesn't assume
680  * that it's waken up by walreceiver process or SIGHUP signal handler
681  * while it's waiting for recovery conflict. The separate latches,
682  * recoveryWakeupLatch and procLatch, should be used for inter-process
683  * communication for WAL replay and recovery conflict, respectively.
684  */
686 
687  /*
688  * During recovery, we keep a copy of the latest checkpoint record here.
689  * lastCheckPointRecPtr points to start of checkpoint record and
690  * lastCheckPointEndPtr points to end+1 of checkpoint record. Used by the
691  * checkpointer when it wants to create a restartpoint.
692  *
693  * Protected by info_lck.
694  */
698 
699  /*
700  * lastReplayedEndRecPtr points to end+1 of the last record successfully
701  * replayed. When we're currently replaying a record, ie. in a redo
702  * function, replayEndRecPtr points to the end+1 of the record being
703  * replayed, otherwise it's equal to lastReplayedEndRecPtr.
704  */
709  /* timestamp of last COMMIT/ABORT record replayed (or being replayed) */
711 
712  /*
713  * timestamp of when we started replaying the current chunk of WAL data,
714  * only relevant for replication or archive recovery
715  */
717  /* Recovery pause state */
720 
721  /*
722  * lastFpwDisableRecPtr points to the start of the last replayed
723  * XLOG_FPW_CHANGE record that instructs full_page_writes is disabled.
724  */
726 
727  slock_t info_lck; /* locks shared variables shown above */
729 
730 static XLogCtlData *XLogCtl = NULL;
731 
732 /* a private copy of XLogCtl->Insert.WALInsertLocks, for convenience */
734 
735 /*
736  * We maintain an image of pg_control in shared memory.
737  */
739 
740 /*
741  * Calculate the amount of space left on the page after 'endptr'. Beware
742  * multiple evaluation!
743  */
744 #define INSERT_FREESPACE(endptr) \
745  (((endptr) % XLOG_BLCKSZ == 0) ? 0 : (XLOG_BLCKSZ - (endptr) % XLOG_BLCKSZ))
746 
747 /* Macro to advance to next buffer index. */
748 #define NextBufIdx(idx) \
749  (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
750 
751 /*
752  * XLogRecPtrToBufIdx returns the index of the WAL buffer that holds, or
753  * would hold if it was in cache, the page containing 'recptr'.
754  */
755 #define XLogRecPtrToBufIdx(recptr) \
756  (((recptr) / XLOG_BLCKSZ) % (XLogCtl->XLogCacheBlck + 1))
757 
758 /*
759  * These are the number of bytes in a WAL page usable for WAL data.
760  */
761 #define UsableBytesInPage (XLOG_BLCKSZ - SizeOfXLogShortPHD)
762 
763 /*
764  * Convert values of GUCs measured in megabytes to equiv. segment count.
765  * Rounds down.
766  */
767 #define ConvertToXSegs(x, segsize) XLogMBVarToSegs((x), (segsize))
768 
769 /* The number of bytes in a WAL segment usable for WAL data. */
771 
772 /*
773  * Private, possibly out-of-date copy of shared LogwrtResult.
774  * See discussion above.
775  */
776 static XLogwrtResult LogwrtResult = {0, 0};
777 
778 /*
779  * Codes indicating where we got a WAL file from during recovery, or where
780  * to attempt to get one.
781  */
782 typedef enum
783 {
784  XLOG_FROM_ANY = 0, /* request to read WAL from any source */
785  XLOG_FROM_ARCHIVE, /* restored using restore_command */
786  XLOG_FROM_PG_WAL, /* existing file in pg_wal */
787  XLOG_FROM_STREAM /* streamed from primary */
789 
790 /* human-readable names for XLogSources, for debugging output */
791 static const char *const xlogSourceNames[] = {"any", "archive", "pg_wal", "stream"};
792 
793 /*
794  * openLogFile is -1 or a kernel FD for an open log file segment.
795  * openLogSegNo identifies the segment, and openLogTLI the corresponding TLI.
796  * These variables are only used to write the XLOG, and so will normally refer
797  * to the active segment.
798  *
799  * Note: call Reserve/ReleaseExternalFD to track consumption of this FD.
800  */
801 static int openLogFile = -1;
804 
805 /*
806  * These variables are used similarly to the ones above, but for reading
807  * the XLOG. readOff is the offset of the page just read, readLen
808  * indicates how much of it has been read into readBuf, and readSource
809  * indicates where we got the currently open file from.
810  * Note: we could use Reserve/ReleaseExternalFD to track consumption of
811  * this FD too; but it doesn't currently seem worthwhile, since the XLOG is
812  * not read by general-purpose sessions.
813  */
814 static int readFile = -1;
815 static XLogSegNo readSegNo = 0;
816 static uint32 readOff = 0;
817 static uint32 readLen = 0;
819 
820 /*
821  * Keeps track of which source we're currently reading from. This is
822  * different from readSource in that this is always set, even when we don't
823  * currently have a WAL file open. If lastSourceFailed is set, our last
824  * attempt to read from currentSource failed, and we should try another source
825  * next.
826  *
827  * pendingWalRcvRestart is set when a config change occurs that requires a
828  * walreceiver restart. This is only valid in XLOG_FROM_STREAM state.
829  */
831 static bool lastSourceFailed = false;
832 static bool pendingWalRcvRestart = false;
833 
834 typedef struct XLogPageReadPrivate
835 {
836  int emode;
837  bool fetching_ckpt; /* are we fetching a checkpoint record? */
841 
842 /*
843  * These variables track when we last obtained some WAL data to process,
844  * and where we got it from. (XLogReceiptSource is initially the same as
845  * readSource, but readSource gets reset to zero when we don't have data
846  * to process right now. It is also different from currentSource, which
847  * also changes when we try to read from a source and fail, while
848  * XLogReceiptSource tracks where we last successfully read some WAL.)
849  */
852 
853 /*
854  * Local copies of equivalent fields in the control file. When running
855  * crash recovery, minRecoveryPoint is set to InvalidXLogRecPtr as we
856  * expect to replay all the WAL available, and updateMinRecoveryPoint is
857  * switched to false to prevent any updates while replaying records.
858  * Those values are kept consistent as long as crash recovery runs.
859  */
862 static bool updateMinRecoveryPoint = true;
863 
864 /*
865  * Have we reached a consistent database state? In crash recovery, we have
866  * to replay all the WAL, so reachedConsistency is never set. During archive
867  * recovery, the database is consistent once minRecoveryPoint is reached.
868  */
869 bool reachedConsistency = false;
870 
871 static bool InRedo = false;
872 
873 /* For WALInsertLockAcquire/Release functions */
874 static int MyLockNo = 0;
875 static bool holdingAllLocks = false;
876 
877 #ifdef WAL_DEBUG
878 static MemoryContext walDebugCxt = NULL;
879 #endif
880 
881 static void readRecoverySignalFile(void);
882 static void validateRecoveryParameters(void);
883 static void exitArchiveRecovery(TimeLineID endTLI, XLogRecPtr endOfLog,
884  TimeLineID newTLI);
885 static void CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI,
886  XLogRecPtr EndOfLog,
887  TimeLineID newTLI);
888 static bool recoveryStopsBefore(XLogReaderState *record);
889 static bool recoveryStopsAfter(XLogReaderState *record);
890 static char *getRecoveryStopReason(void);
891 static void ConfirmRecoveryPaused(void);
892 static void recoveryPausesHere(bool endOfRecovery);
893 static bool recoveryApplyDelay(XLogReaderState *record);
894 static void SetLatestXTime(TimestampTz xtime);
895 static void SetCurrentChunkStartTime(TimestampTz xtime);
896 static void CheckRequiredParameterValues(void);
897 static void XLogReportParameters(void);
898 static void checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI,
899  TimeLineID prevTLI, TimeLineID replayTLI);
902 static int LocalSetXLogInsertAllowed(void);
903 static void CreateEndOfRecoveryRecord(void);
905 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
906 static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo);
908 
909 static void AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli,
910  bool opportunistic);
911 static bool XLogCheckpointNeeded(XLogSegNo new_segno);
912 static void XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible);
913 static bool InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
914  bool find_free, XLogSegNo max_segno,
915  TimeLineID tli);
916 static int XLogFileRead(XLogSegNo segno, int emode, TimeLineID tli,
917  XLogSource source, bool notfoundOk);
918 static int XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source);
919 static int XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
920  int reqLen, XLogRecPtr targetRecPtr, char *readBuf);
921 static bool WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
922  bool fetching_ckpt, XLogRecPtr tliRecPtr,
923  TimeLineID replayTLI,
924  XLogRecPtr replayLSN);
925 static void XLogShutdownWalRcv(void);
926 static int emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
927 static void XLogFileClose(void);
928 static void PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli);
929 static void RemoveTempXlogFiles(void);
930 static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr,
931  XLogRecPtr endptr, TimeLineID insertTLI);
932 static void RemoveXlogFile(const char *segname, XLogSegNo recycleSegNo,
933  XLogSegNo *endlogSegNo, TimeLineID insertTLI);
934 static void UpdateLastRemovedPtr(char *filename);
935 static void ValidateXLOGDirectoryStructure(void);
936 static void CleanupBackupHistory(void);
937 static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
939  int emode, bool fetching_ckpt,
940  TimeLineID replayTLI);
941 static void CheckRecoveryConsistency(void);
942 static bool PerformRecoveryXLogAction(void);
944  XLogRecPtr RecPtr, int whichChkpt, bool report,
945  TimeLineID replayTLI);
946 static bool rescanLatestTimeLine(TimeLineID replayTLI,
947  XLogRecPtr replayLSN);
948 static void InitControlFile(uint64 sysidentifier);
949 static void WriteControlFile(void);
950 static void ReadControlFile(void);
951 static char *str_time(pg_time_t tnow);
952 static void SetPromoteIsTriggered(void);
953 static bool CheckForStandbyTrigger(void);
954 
955 #ifdef WAL_DEBUG
956 static void xlog_outrec(StringInfo buf, XLogReaderState *record);
957 #endif
958 static void xlog_block_info(StringInfo buf, XLogReaderState *record);
959 static void xlog_outdesc(StringInfo buf, XLogReaderState *record);
960 static void pg_start_backup_callback(int code, Datum arg);
961 static void pg_stop_backup_callback(int code, Datum arg);
962 static bool read_backup_label(XLogRecPtr *checkPointLoc,
963  TimeLineID *backupLabelTLI,
964  bool *backupEndRequired, bool *backupFromStandby);
965 static bool read_tablespace_map(List **tablespaces);
966 
967 static void rm_redo_error_callback(void *arg);
968 static int get_sync_bit(int method);
969 
970 static void CopyXLogRecordToWAL(int write_len, bool isLogSwitch,
971  XLogRecData *rdata,
972  XLogRecPtr StartPos, XLogRecPtr EndPos,
973  TimeLineID tli);
974 static void ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos,
975  XLogRecPtr *EndPos, XLogRecPtr *PrevPtr);
976 static bool ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos,
977  XLogRecPtr *PrevPtr);
979 static char *GetXLogBuffer(XLogRecPtr ptr, TimeLineID tli);
980 static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos);
981 static XLogRecPtr XLogBytePosToEndRecPtr(uint64 bytepos);
982 static uint64 XLogRecPtrToBytePos(XLogRecPtr ptr);
983 static void checkXLogConsistency(XLogReaderState *record);
984 
985 static void WALInsertLockAcquire(void);
986 static void WALInsertLockAcquireExclusive(void);
987 static void WALInsertLockRelease(void);
988 static void WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt);
989 
990 /*
991  * Insert an XLOG record represented by an already-constructed chain of data
992  * chunks. This is a low-level routine; to construct the WAL record header
993  * and data, use the higher-level routines in xloginsert.c.
994  *
995  * If 'fpw_lsn' is valid, it is the oldest LSN among the pages that this
996  * WAL record applies to, that were not included in the record as full page
997  * images. If fpw_lsn <= RedoRecPtr, the function does not perform the
998  * insertion and returns InvalidXLogRecPtr. The caller can then recalculate
999  * which pages need a full-page image, and retry. If fpw_lsn is invalid, the
1000  * record is always inserted.
1001  *
1002  * 'flags' gives more in-depth control on the record being inserted. See
1003  * XLogSetRecordFlags() for details.
1004  *
1005  * 'topxid_included' tells whether the top-transaction id is logged along with
1006  * current subtransaction. See XLogRecordAssemble().
1007  *
1008  * The first XLogRecData in the chain must be for the record header, and its
1009  * data must be MAXALIGNed. XLogInsertRecord fills in the xl_prev and
1010  * xl_crc fields in the header, the rest of the header must already be filled
1011  * by the caller.
1012  *
1013  * Returns XLOG pointer to end of record (beginning of next record).
1014  * This can be used as LSN for data pages affected by the logged action.
1015  * (LSN is the XLOG point up to which the XLOG must be flushed to disk
1016  * before the data page can be written out. This implements the basic
1017  * WAL rule "write the log before the data".)
1018  */
1019 XLogRecPtr
1021  XLogRecPtr fpw_lsn,
1022  uint8 flags,
1023  int num_fpi,
1024  bool topxid_included)
1025 {
1027  pg_crc32c rdata_crc;
1028  bool inserted;
1029  XLogRecord *rechdr = (XLogRecord *) rdata->data;
1030  uint8 info = rechdr->xl_info & ~XLR_INFO_MASK;
1031  bool isLogSwitch = (rechdr->xl_rmid == RM_XLOG_ID &&
1032  info == XLOG_SWITCH);
1033  XLogRecPtr StartPos;
1034  XLogRecPtr EndPos;
1035  bool prevDoPageWrites = doPageWrites;
1036  TimeLineID insertTLI;
1037 
1038  /* we assume that all of the record header is in the first chunk */
1039  Assert(rdata->len >= SizeOfXLogRecord);
1040 
1041  /* cross-check on whether we should be here or not */
1042  if (!XLogInsertAllowed())
1043  elog(ERROR, "cannot make new WAL entries during recovery");
1044 
1045  /*
1046  * Given that we're not in recovery, InsertTimeLineID is set and can't
1047  * change, so we can read it without a lock.
1048  */
1049  insertTLI = XLogCtl->InsertTimeLineID;
1050 
1051  /*----------
1052  *
1053  * We have now done all the preparatory work we can without holding a
1054  * lock or modifying shared state. From here on, inserting the new WAL
1055  * record to the shared WAL buffer cache is a two-step process:
1056  *
1057  * 1. Reserve the right amount of space from the WAL. The current head of
1058  * reserved space is kept in Insert->CurrBytePos, and is protected by
1059  * insertpos_lck.
1060  *
1061  * 2. Copy the record to the reserved WAL space. This involves finding the
1062  * correct WAL buffer containing the reserved space, and copying the
1063  * record in place. This can be done concurrently in multiple processes.
1064  *
1065  * To keep track of which insertions are still in-progress, each concurrent
1066  * inserter acquires an insertion lock. In addition to just indicating that
1067  * an insertion is in progress, the lock tells others how far the inserter
1068  * has progressed. There is a small fixed number of insertion locks,
1069  * determined by NUM_XLOGINSERT_LOCKS. When an inserter crosses a page
1070  * boundary, it updates the value stored in the lock to the how far it has
1071  * inserted, to allow the previous buffer to be flushed.
1072  *
1073  * Holding onto an insertion lock also protects RedoRecPtr and
1074  * fullPageWrites from changing until the insertion is finished.
1075  *
1076  * Step 2 can usually be done completely in parallel. If the required WAL
1077  * page is not initialized yet, you have to grab WALBufMappingLock to
1078  * initialize it, but the WAL writer tries to do that ahead of insertions
1079  * to avoid that from happening in the critical path.
1080  *
1081  *----------
1082  */
1084  if (isLogSwitch)
1086  else
1088 
1089  /*
1090  * Check to see if my copy of RedoRecPtr is out of date. If so, may have
1091  * to go back and have the caller recompute everything. This can only
1092  * happen just after a checkpoint, so it's better to be slow in this case
1093  * and fast otherwise.
1094  *
1095  * Also check to see if fullPageWrites or forcePageWrites was just turned
1096  * on; if we weren't already doing full-page writes then go back and
1097  * recompute.
1098  *
1099  * If we aren't doing full-page writes then RedoRecPtr doesn't actually
1100  * affect the contents of the XLOG record, so we'll update our local copy
1101  * but not force a recomputation. (If doPageWrites was just turned off,
1102  * we could recompute the record without full pages, but we choose not to
1103  * bother.)
1104  */
1105  if (RedoRecPtr != Insert->RedoRecPtr)
1106  {
1107  Assert(RedoRecPtr < Insert->RedoRecPtr);
1108  RedoRecPtr = Insert->RedoRecPtr;
1109  }
1110  doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);
1111 
1112  if (doPageWrites &&
1113  (!prevDoPageWrites ||
1114  (fpw_lsn != InvalidXLogRecPtr && fpw_lsn <= RedoRecPtr)))
1115  {
1116  /*
1117  * Oops, some buffer now needs to be backed up that the caller didn't
1118  * back up. Start over.
1119  */
1121  END_CRIT_SECTION();
1122  return InvalidXLogRecPtr;
1123  }
1124 
1125  /*
1126  * Reserve space for the record in the WAL. This also sets the xl_prev
1127  * pointer.
1128  */
1129  if (isLogSwitch)
1130  inserted = ReserveXLogSwitch(&StartPos, &EndPos, &rechdr->xl_prev);
1131  else
1132  {
1133  ReserveXLogInsertLocation(rechdr->xl_tot_len, &StartPos, &EndPos,
1134  &rechdr->xl_prev);
1135  inserted = true;
1136  }
1137 
1138  if (inserted)
1139  {
1140  /*
1141  * Now that xl_prev has been filled in, calculate CRC of the record
1142  * header.
1143  */
1144  rdata_crc = rechdr->xl_crc;
1145  COMP_CRC32C(rdata_crc, rechdr, offsetof(XLogRecord, xl_crc));
1146  FIN_CRC32C(rdata_crc);
1147  rechdr->xl_crc = rdata_crc;
1148 
1149  /*
1150  * All the record data, including the header, is now ready to be
1151  * inserted. Copy the record in the space reserved.
1152  */
1153  CopyXLogRecordToWAL(rechdr->xl_tot_len, isLogSwitch, rdata,
1154  StartPos, EndPos, insertTLI);
1155 
1156  /*
1157  * Unless record is flagged as not important, update LSN of last
1158  * important record in the current slot. When holding all locks, just
1159  * update the first one.
1160  */
1161  if ((flags & XLOG_MARK_UNIMPORTANT) == 0)
1162  {
1163  int lockno = holdingAllLocks ? 0 : MyLockNo;
1164 
1165  WALInsertLocks[lockno].l.lastImportantAt = StartPos;
1166  }
1167  }
1168  else
1169  {
1170  /*
1171  * This was an xlog-switch record, but the current insert location was
1172  * already exactly at the beginning of a segment, so there was no need
1173  * to do anything.
1174  */
1175  }
1176 
1177  /*
1178  * Done! Let others know that we're finished.
1179  */
1181 
1182  END_CRIT_SECTION();
1183 
1185 
1186  /*
1187  * Mark top transaction id is logged (if needed) so that we should not try
1188  * to log it again with the next WAL record in the current subtransaction.
1189  */
1190  if (topxid_included)
1192 
1193  /*
1194  * Update shared LogwrtRqst.Write, if we crossed page boundary.
1195  */
1196  if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
1197  {
1199  /* advance global request to include new block(s) */
1200  if (XLogCtl->LogwrtRqst.Write < EndPos)
1201  XLogCtl->LogwrtRqst.Write = EndPos;
1202  /* update local result copy while I have the chance */
1205  }
1206 
1207  /*
1208  * If this was an XLOG_SWITCH record, flush the record and the empty
1209  * padding space that fills the rest of the segment, and perform
1210  * end-of-segment actions (eg, notifying archiver).
1211  */
1212  if (isLogSwitch)
1213  {
1214  TRACE_POSTGRESQL_WAL_SWITCH();
1215  XLogFlush(EndPos);
1216 
1217  /*
1218  * Even though we reserved the rest of the segment for us, which is
1219  * reflected in EndPos, we return a pointer to just the end of the
1220  * xlog-switch record.
1221  */
1222  if (inserted)
1223  {
1224  EndPos = StartPos + SizeOfXLogRecord;
1225  if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
1226  {
1227  uint64 offset = XLogSegmentOffset(EndPos, wal_segment_size);
1228 
1229  if (offset == EndPos % XLOG_BLCKSZ)
1230  EndPos += SizeOfXLogLongPHD;
1231  else
1232  EndPos += SizeOfXLogShortPHD;
1233  }
1234  }
1235  }
1236 
1237 #ifdef WAL_DEBUG
1238  if (XLOG_DEBUG)
1239  {
1240  static XLogReaderState *debug_reader = NULL;
1242  StringInfoData recordBuf;
1243  char *errormsg = NULL;
1244  MemoryContext oldCxt;
1245 
1246  oldCxt = MemoryContextSwitchTo(walDebugCxt);
1247 
1248  initStringInfo(&buf);
1249  appendStringInfo(&buf, "INSERT @ %X/%X: ", LSN_FORMAT_ARGS(EndPos));
1250 
1251  /*
1252  * We have to piece together the WAL record data from the XLogRecData
1253  * entries, so that we can pass it to the rm_desc function as one
1254  * contiguous chunk.
1255  */
1256  initStringInfo(&recordBuf);
1257  for (; rdata != NULL; rdata = rdata->next)
1258  appendBinaryStringInfo(&recordBuf, rdata->data, rdata->len);
1259 
1260  if (!debug_reader)
1261  debug_reader = XLogReaderAllocate(wal_segment_size, NULL,
1262  XL_ROUTINE(), NULL);
1263 
1264  if (!debug_reader)
1265  {
1266  appendStringInfoString(&buf, "error decoding record: out of memory while allocating a WAL reading processor");
1267  }
1268  else if (!DecodeXLogRecord(debug_reader, (XLogRecord *) recordBuf.data,
1269  &errormsg))
1270  {
1271  appendStringInfo(&buf, "error decoding record: %s",
1272  errormsg ? errormsg : "no error message");
1273  }
1274  else
1275  {
1276  appendStringInfoString(&buf, " - ");
1277  xlog_outdesc(&buf, debug_reader);
1278  }
1279  elog(LOG, "%s", buf.data);
1280 
1281  pfree(buf.data);
1282  pfree(recordBuf.data);
1283  MemoryContextSwitchTo(oldCxt);
1284  }
1285 #endif
1286 
1287  /*
1288  * Update our global variables
1289  */
1290  ProcLastRecPtr = StartPos;
1291  XactLastRecEnd = EndPos;
1292 
1293  /* Report WAL traffic to the instrumentation. */
1294  if (inserted)
1295  {
1296  pgWalUsage.wal_bytes += rechdr->xl_tot_len;
1298  pgWalUsage.wal_fpi += num_fpi;
1299  }
1300 
1301  return EndPos;
1302 }
1303 
1304 /*
1305  * Reserves the right amount of space for a record of given size from the WAL.
1306  * *StartPos is set to the beginning of the reserved section, *EndPos to
1307  * its end+1. *PrevPtr is set to the beginning of the previous record; it is
1308  * used to set the xl_prev of this record.
1309  *
1310  * This is the performance critical part of XLogInsert that must be serialized
1311  * across backends. The rest can happen mostly in parallel. Try to keep this
1312  * section as short as possible, insertpos_lck can be heavily contended on a
1313  * busy system.
1314  *
1315  * NB: The space calculation here must match the code in CopyXLogRecordToWAL,
1316  * where we actually copy the record to the reserved space.
1317  */
1318 static void
1319 ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos, XLogRecPtr *EndPos,
1320  XLogRecPtr *PrevPtr)
1321 {
1323  uint64 startbytepos;
1324  uint64 endbytepos;
1325  uint64 prevbytepos;
1326 
1327  size = MAXALIGN(size);
1328 
1329  /* All (non xlog-switch) records should contain data. */
1330  Assert(size > SizeOfXLogRecord);
1331 
1332  /*
1333  * The duration the spinlock needs to be held is minimized by minimizing
1334  * the calculations that have to be done while holding the lock. The
1335  * current tip of reserved WAL is kept in CurrBytePos, as a byte position
1336  * that only counts "usable" bytes in WAL, that is, it excludes all WAL
1337  * page headers. The mapping between "usable" byte positions and physical
1338  * positions (XLogRecPtrs) can be done outside the locked region, and
1339  * because the usable byte position doesn't include any headers, reserving
1340  * X bytes from WAL is almost as simple as "CurrBytePos += X".
1341  */
1342  SpinLockAcquire(&Insert->insertpos_lck);
1343 
1344  startbytepos = Insert->CurrBytePos;
1345  endbytepos = startbytepos + size;
1346  prevbytepos = Insert->PrevBytePos;
1347  Insert->CurrBytePos = endbytepos;
1348  Insert->PrevBytePos = startbytepos;
1349 
1350  SpinLockRelease(&Insert->insertpos_lck);
1351 
1352  *StartPos = XLogBytePosToRecPtr(startbytepos);
1353  *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1354  *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1355 
1356  /*
1357  * Check that the conversions between "usable byte positions" and
1358  * XLogRecPtrs work consistently in both directions.
1359  */
1360  Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1361  Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1362  Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1363 }
1364 
1365 /*
1366  * Like ReserveXLogInsertLocation(), but for an xlog-switch record.
1367  *
1368  * A log-switch record is handled slightly differently. The rest of the
1369  * segment will be reserved for this insertion, as indicated by the returned
1370  * *EndPos value. However, if we are already at the beginning of the current
1371  * segment, *StartPos and *EndPos are set to the current location without
1372  * reserving any space, and the function returns false.
1373 */
1374 static bool
1375 ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
1376 {
1378  uint64 startbytepos;
1379  uint64 endbytepos;
1380  uint64 prevbytepos;
1382  XLogRecPtr ptr;
1383  uint32 segleft;
1384 
1385  /*
1386  * These calculations are a bit heavy-weight to be done while holding a
1387  * spinlock, but since we're holding all the WAL insertion locks, there
1388  * are no other inserters competing for it. GetXLogInsertRecPtr() does
1389  * compete for it, but that's not called very frequently.
1390  */
1391  SpinLockAcquire(&Insert->insertpos_lck);
1392 
1393  startbytepos = Insert->CurrBytePos;
1394 
1395  ptr = XLogBytePosToEndRecPtr(startbytepos);
1396  if (XLogSegmentOffset(ptr, wal_segment_size) == 0)
1397  {
1398  SpinLockRelease(&Insert->insertpos_lck);
1399  *EndPos = *StartPos = ptr;
1400  return false;
1401  }
1402 
1403  endbytepos = startbytepos + size;
1404  prevbytepos = Insert->PrevBytePos;
1405 
1406  *StartPos = XLogBytePosToRecPtr(startbytepos);
1407  *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1408 
1409  segleft = wal_segment_size - XLogSegmentOffset(*EndPos, wal_segment_size);
1410  if (segleft != wal_segment_size)
1411  {
1412  /* consume the rest of the segment */
1413  *EndPos += segleft;
1414  endbytepos = XLogRecPtrToBytePos(*EndPos);
1415  }
1416  Insert->CurrBytePos = endbytepos;
1417  Insert->PrevBytePos = startbytepos;
1418 
1419  SpinLockRelease(&Insert->insertpos_lck);
1420 
1421  *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1422 
1423  Assert(XLogSegmentOffset(*EndPos, wal_segment_size) == 0);
1424  Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1425  Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1426  Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1427 
1428  return true;
1429 }
1430 
1431 /*
1432  * Checks whether the current buffer page and backup page stored in the
1433  * WAL record are consistent or not. Before comparing the two pages, a
1434  * masking can be applied to the pages to ignore certain areas like hint bits,
1435  * unused space between pd_lower and pd_upper among other things. This
1436  * function should be called once WAL replay has been completed for a
1437  * given record.
1438  */
1439 static void
1441 {
1442  RmgrId rmid = XLogRecGetRmid(record);
1443  RelFileNode rnode;
1444  ForkNumber forknum;
1445  BlockNumber blkno;
1446  int block_id;
1447 
1448  /* Records with no backup blocks have no need for consistency checks. */
1449  if (!XLogRecHasAnyBlockRefs(record))
1450  return;
1451 
1452  Assert((XLogRecGetInfo(record) & XLR_CHECK_CONSISTENCY) != 0);
1453 
1454  for (block_id = 0; block_id <= record->max_block_id; block_id++)
1455  {
1456  Buffer buf;
1457  Page page;
1458 
1459  if (!XLogRecGetBlockTag(record, block_id, &rnode, &forknum, &blkno))
1460  {
1461  /*
1462  * WAL record doesn't contain a block reference with the given id.
1463  * Do nothing.
1464  */
1465  continue;
1466  }
1467 
1468  Assert(XLogRecHasBlockImage(record, block_id));
1469 
1470  if (XLogRecBlockImageApply(record, block_id))
1471  {
1472  /*
1473  * WAL record has already applied the page, so bypass the
1474  * consistency check as that would result in comparing the full
1475  * page stored in the record with itself.
1476  */
1477  continue;
1478  }
1479 
1480  /*
1481  * Read the contents from the current buffer and store it in a
1482  * temporary page.
1483  */
1484  buf = XLogReadBufferExtended(rnode, forknum, blkno,
1486  if (!BufferIsValid(buf))
1487  continue;
1488 
1490  page = BufferGetPage(buf);
1491 
1492  /*
1493  * Take a copy of the local page where WAL has been applied to have a
1494  * comparison base before masking it...
1495  */
1496  memcpy(replay_image_masked, page, BLCKSZ);
1497 
1498  /* No need for this page anymore now that a copy is in. */
1500 
1501  /*
1502  * If the block LSN is already ahead of this WAL record, we can't
1503  * expect contents to match. This can happen if recovery is
1504  * restarted.
1505  */
1506  if (PageGetLSN(replay_image_masked) > record->EndRecPtr)
1507  continue;
1508 
1509  /*
1510  * Read the contents from the backup copy, stored in WAL record and
1511  * store it in a temporary page. There is no need to allocate a new
1512  * page here, a local buffer is fine to hold its contents and a mask
1513  * can be directly applied on it.
1514  */
1515  if (!RestoreBlockImage(record, block_id, primary_image_masked))
1516  elog(ERROR, "failed to restore block image");
1517 
1518  /*
1519  * If masking function is defined, mask both the primary and replay
1520  * images
1521  */
1522  if (RmgrTable[rmid].rm_mask != NULL)
1523  {
1524  RmgrTable[rmid].rm_mask(replay_image_masked, blkno);
1525  RmgrTable[rmid].rm_mask(primary_image_masked, blkno);
1526  }
1527 
1528  /* Time to compare the primary and replay images. */
1529  if (memcmp(replay_image_masked, primary_image_masked, BLCKSZ) != 0)
1530  {
1531  elog(FATAL,
1532  "inconsistent page found, rel %u/%u/%u, forknum %u, blkno %u",
1533  rnode.spcNode, rnode.dbNode, rnode.relNode,
1534  forknum, blkno);
1535  }
1536  }
1537 }
1538 
1539 /*
1540  * Subroutine of XLogInsertRecord. Copies a WAL record to an already-reserved
1541  * area in the WAL.
1542  */
1543 static void
1544 CopyXLogRecordToWAL(int write_len, bool isLogSwitch, XLogRecData *rdata,
1545  XLogRecPtr StartPos, XLogRecPtr EndPos, TimeLineID tli)
1546 {
1547  char *currpos;
1548  int freespace;
1549  int written;
1550  XLogRecPtr CurrPos;
1551  XLogPageHeader pagehdr;
1552 
1553  /*
1554  * Get a pointer to the right place in the right WAL buffer to start
1555  * inserting to.
1556  */
1557  CurrPos = StartPos;
1558  currpos = GetXLogBuffer(CurrPos, tli);
1559  freespace = INSERT_FREESPACE(CurrPos);
1560 
1561  /*
1562  * there should be enough space for at least the first field (xl_tot_len)
1563  * on this page.
1564  */
1565  Assert(freespace >= sizeof(uint32));
1566 
1567  /* Copy record data */
1568  written = 0;
1569  while (rdata != NULL)
1570  {
1571  char *rdata_data = rdata->data;
1572  int rdata_len = rdata->len;
1573 
1574  while (rdata_len > freespace)
1575  {
1576  /*
1577  * Write what fits on this page, and continue on the next page.
1578  */
1579  Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || freespace == 0);
1580  memcpy(currpos, rdata_data, freespace);
1581  rdata_data += freespace;
1582  rdata_len -= freespace;
1583  written += freespace;
1584  CurrPos += freespace;
1585 
1586  /*
1587  * Get pointer to beginning of next page, and set the xlp_rem_len
1588  * in the page header. Set XLP_FIRST_IS_CONTRECORD.
1589  *
1590  * It's safe to set the contrecord flag and xlp_rem_len without a
1591  * lock on the page. All the other flags were already set when the
1592  * page was initialized, in AdvanceXLInsertBuffer, and we're the
1593  * only backend that needs to set the contrecord flag.
1594  */
1595  currpos = GetXLogBuffer(CurrPos, tli);
1596  pagehdr = (XLogPageHeader) currpos;
1597  pagehdr->xlp_rem_len = write_len - written;
1598  pagehdr->xlp_info |= XLP_FIRST_IS_CONTRECORD;
1599 
1600  /* skip over the page header */
1601  if (XLogSegmentOffset(CurrPos, wal_segment_size) == 0)
1602  {
1603  CurrPos += SizeOfXLogLongPHD;
1604  currpos += SizeOfXLogLongPHD;
1605  }
1606  else
1607  {
1608  CurrPos += SizeOfXLogShortPHD;
1609  currpos += SizeOfXLogShortPHD;
1610  }
1611  freespace = INSERT_FREESPACE(CurrPos);
1612  }
1613 
1614  Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || rdata_len == 0);
1615  memcpy(currpos, rdata_data, rdata_len);
1616  currpos += rdata_len;
1617  CurrPos += rdata_len;
1618  freespace -= rdata_len;
1619  written += rdata_len;
1620 
1621  rdata = rdata->next;
1622  }
1623  Assert(written == write_len);
1624 
1625  /*
1626  * If this was an xlog-switch, it's not enough to write the switch record,
1627  * we also have to consume all the remaining space in the WAL segment. We
1628  * have already reserved that space, but we need to actually fill it.
1629  */
1630  if (isLogSwitch && XLogSegmentOffset(CurrPos, wal_segment_size) != 0)
1631  {
1632  /* An xlog-switch record doesn't contain any data besides the header */
1633  Assert(write_len == SizeOfXLogRecord);
1634 
1635  /* Assert that we did reserve the right amount of space */
1636  Assert(XLogSegmentOffset(EndPos, wal_segment_size) == 0);
1637 
1638  /* Use up all the remaining space on the current page */
1639  CurrPos += freespace;
1640 
1641  /*
1642  * Cause all remaining pages in the segment to be flushed, leaving the
1643  * XLog position where it should be, at the start of the next segment.
1644  * We do this one page at a time, to make sure we don't deadlock
1645  * against ourselves if wal_buffers < wal_segment_size.
1646  */
1647  while (CurrPos < EndPos)
1648  {
1649  /*
1650  * The minimal action to flush the page would be to call
1651  * WALInsertLockUpdateInsertingAt(CurrPos) followed by
1652  * AdvanceXLInsertBuffer(...). The page would be left initialized
1653  * mostly to zeros, except for the page header (always the short
1654  * variant, as this is never a segment's first page).
1655  *
1656  * The large vistas of zeros are good for compressibility, but the
1657  * headers interrupting them every XLOG_BLCKSZ (with values that
1658  * differ from page to page) are not. The effect varies with
1659  * compression tool, but bzip2 for instance compresses about an
1660  * order of magnitude worse if those headers are left in place.
1661  *
1662  * Rather than complicating AdvanceXLInsertBuffer itself (which is
1663  * called in heavily-loaded circumstances as well as this lightly-
1664  * loaded one) with variant behavior, we just use GetXLogBuffer
1665  * (which itself calls the two methods we need) to get the pointer
1666  * and zero most of the page. Then we just zero the page header.
1667  */
1668  currpos = GetXLogBuffer(CurrPos, tli);
1669  MemSet(currpos, 0, SizeOfXLogShortPHD);
1670 
1671  CurrPos += XLOG_BLCKSZ;
1672  }
1673  }
1674  else
1675  {
1676  /* Align the end position, so that the next record starts aligned */
1677  CurrPos = MAXALIGN64(CurrPos);
1678  }
1679 
1680  if (CurrPos != EndPos)
1681  elog(PANIC, "space reserved for WAL record does not match what was written");
1682 }
1683 
1684 /*
1685  * Acquire a WAL insertion lock, for inserting to WAL.
1686  */
1687 static void
1689 {
1690  bool immed;
1691 
1692  /*
1693  * It doesn't matter which of the WAL insertion locks we acquire, so try
1694  * the one we used last time. If the system isn't particularly busy, it's
1695  * a good bet that it's still available, and it's good to have some
1696  * affinity to a particular lock so that you don't unnecessarily bounce
1697  * cache lines between processes when there's no contention.
1698  *
1699  * If this is the first time through in this backend, pick a lock
1700  * (semi-)randomly. This allows the locks to be used evenly if you have a
1701  * lot of very short connections.
1702  */
1703  static int lockToTry = -1;
1704 
1705  if (lockToTry == -1)
1706  lockToTry = MyProc->pgprocno % NUM_XLOGINSERT_LOCKS;
1707  MyLockNo = lockToTry;
1708 
1709  /*
1710  * The insertingAt value is initially set to 0, as we don't know our
1711  * insert location yet.
1712  */
1714  if (!immed)
1715  {
1716  /*
1717  * If we couldn't get the lock immediately, try another lock next
1718  * time. On a system with more insertion locks than concurrent
1719  * inserters, this causes all the inserters to eventually migrate to a
1720  * lock that no-one else is using. On a system with more inserters
1721  * than locks, it still helps to distribute the inserters evenly
1722  * across the locks.
1723  */
1724  lockToTry = (lockToTry + 1) % NUM_XLOGINSERT_LOCKS;
1725  }
1726 }
1727 
1728 /*
1729  * Acquire all WAL insertion locks, to prevent other backends from inserting
1730  * to WAL.
1731  */
1732 static void
1734 {
1735  int i;
1736 
1737  /*
1738  * When holding all the locks, all but the last lock's insertingAt
1739  * indicator is set to 0xFFFFFFFFFFFFFFFF, which is higher than any real
1740  * XLogRecPtr value, to make sure that no-one blocks waiting on those.
1741  */
1742  for (i = 0; i < NUM_XLOGINSERT_LOCKS - 1; i++)
1743  {
1745  LWLockUpdateVar(&WALInsertLocks[i].l.lock,
1747  PG_UINT64_MAX);
1748  }
1749  /* Variable value reset to 0 at release */
1751 
1752  holdingAllLocks = true;
1753 }
1754 
1755 /*
1756  * Release our insertion lock (or locks, if we're holding them all).
1757  *
1758  * NB: Reset all variables to 0, so they cause LWLockWaitForVar to block the
1759  * next time the lock is acquired.
1760  */
1761 static void
1763 {
1764  if (holdingAllLocks)
1765  {
1766  int i;
1767 
1768  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1771  0);
1772 
1773  holdingAllLocks = false;
1774  }
1775  else
1776  {
1779  0);
1780  }
1781 }
1782 
1783 /*
1784  * Update our insertingAt value, to let others know that we've finished
1785  * inserting up to that point.
1786  */
1787 static void
1789 {
1790  if (holdingAllLocks)
1791  {
1792  /*
1793  * We use the last lock to mark our actual position, see comments in
1794  * WALInsertLockAcquireExclusive.
1795  */
1798  insertingAt);
1799  }
1800  else
1803  insertingAt);
1804 }
1805 
1806 /*
1807  * Wait for any WAL insertions < upto to finish.
1808  *
1809  * Returns the location of the oldest insertion that is still in-progress.
1810  * Any WAL prior to that point has been fully copied into WAL buffers, and
1811  * can be flushed out to disk. Because this waits for any insertions older
1812  * than 'upto' to finish, the return value is always >= 'upto'.
1813  *
1814  * Note: When you are about to write out WAL, you must call this function
1815  * *before* acquiring WALWriteLock, to avoid deadlocks. This function might
1816  * need to wait for an insertion to finish (or at least advance to next
1817  * uninitialized page), and the inserter might need to evict an old WAL buffer
1818  * to make room for a new one, which in turn requires WALWriteLock.
1819  */
1820 static XLogRecPtr
1822 {
1823  uint64 bytepos;
1824  XLogRecPtr reservedUpto;
1825  XLogRecPtr finishedUpto;
1827  int i;
1828 
1829  if (MyProc == NULL)
1830  elog(PANIC, "cannot wait without a PGPROC structure");
1831 
1832  /* Read the current insert position */
1833  SpinLockAcquire(&Insert->insertpos_lck);
1834  bytepos = Insert->CurrBytePos;
1835  SpinLockRelease(&Insert->insertpos_lck);
1836  reservedUpto = XLogBytePosToEndRecPtr(bytepos);
1837 
1838  /*
1839  * No-one should request to flush a piece of WAL that hasn't even been
1840  * reserved yet. However, it can happen if there is a block with a bogus
1841  * LSN on disk, for example. XLogFlush checks for that situation and
1842  * complains, but only after the flush. Here we just assume that to mean
1843  * that all WAL that has been reserved needs to be finished. In this
1844  * corner-case, the return value can be smaller than 'upto' argument.
1845  */
1846  if (upto > reservedUpto)
1847  {
1848  ereport(LOG,
1849  (errmsg("request to flush past end of generated WAL; request %X/%X, current position %X/%X",
1850  LSN_FORMAT_ARGS(upto), LSN_FORMAT_ARGS(reservedUpto))));
1851  upto = reservedUpto;
1852  }
1853 
1854  /*
1855  * Loop through all the locks, sleeping on any in-progress insert older
1856  * than 'upto'.
1857  *
1858  * finishedUpto is our return value, indicating the point upto which all
1859  * the WAL insertions have been finished. Initialize it to the head of
1860  * reserved WAL, and as we iterate through the insertion locks, back it
1861  * out for any insertion that's still in progress.
1862  */
1863  finishedUpto = reservedUpto;
1864  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1865  {
1866  XLogRecPtr insertingat = InvalidXLogRecPtr;
1867 
1868  do
1869  {
1870  /*
1871  * See if this insertion is in progress. LWLockWaitForVar will
1872  * wait for the lock to be released, or for the 'value' to be set
1873  * by a LWLockUpdateVar call. When a lock is initially acquired,
1874  * its value is 0 (InvalidXLogRecPtr), which means that we don't
1875  * know where it's inserting yet. We will have to wait for it. If
1876  * it's a small insertion, the record will most likely fit on the
1877  * same page and the inserter will release the lock without ever
1878  * calling LWLockUpdateVar. But if it has to sleep, it will
1879  * advertise the insertion point with LWLockUpdateVar before
1880  * sleeping.
1881  */
1882  if (LWLockWaitForVar(&WALInsertLocks[i].l.lock,
1884  insertingat, &insertingat))
1885  {
1886  /* the lock was free, so no insertion in progress */
1887  insertingat = InvalidXLogRecPtr;
1888  break;
1889  }
1890 
1891  /*
1892  * This insertion is still in progress. Have to wait, unless the
1893  * inserter has proceeded past 'upto'.
1894  */
1895  } while (insertingat < upto);
1896 
1897  if (insertingat != InvalidXLogRecPtr && insertingat < finishedUpto)
1898  finishedUpto = insertingat;
1899  }
1900  return finishedUpto;
1901 }
1902 
1903 /*
1904  * Get a pointer to the right location in the WAL buffer containing the
1905  * given XLogRecPtr.
1906  *
1907  * If the page is not initialized yet, it is initialized. That might require
1908  * evicting an old dirty buffer from the buffer cache, which means I/O.
1909  *
1910  * The caller must ensure that the page containing the requested location
1911  * isn't evicted yet, and won't be evicted. The way to ensure that is to
1912  * hold onto a WAL insertion lock with the insertingAt position set to
1913  * something <= ptr. GetXLogBuffer() will update insertingAt if it needs
1914  * to evict an old page from the buffer. (This means that once you call
1915  * GetXLogBuffer() with a given 'ptr', you must not access anything before
1916  * that point anymore, and must not call GetXLogBuffer() with an older 'ptr'
1917  * later, because older buffers might be recycled already)
1918  */
1919 static char *
1921 {
1922  int idx;
1923  XLogRecPtr endptr;
1924  static uint64 cachedPage = 0;
1925  static char *cachedPos = NULL;
1926  XLogRecPtr expectedEndPtr;
1927 
1928  /*
1929  * Fast path for the common case that we need to access again the same
1930  * page as last time.
1931  */
1932  if (ptr / XLOG_BLCKSZ == cachedPage)
1933  {
1934  Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1935  Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1936  return cachedPos + ptr % XLOG_BLCKSZ;
1937  }
1938 
1939  /*
1940  * The XLog buffer cache is organized so that a page is always loaded to a
1941  * particular buffer. That way we can easily calculate the buffer a given
1942  * page must be loaded into, from the XLogRecPtr alone.
1943  */
1944  idx = XLogRecPtrToBufIdx(ptr);
1945 
1946  /*
1947  * See what page is loaded in the buffer at the moment. It could be the
1948  * page we're looking for, or something older. It can't be anything newer
1949  * - that would imply the page we're looking for has already been written
1950  * out to disk and evicted, and the caller is responsible for making sure
1951  * that doesn't happen.
1952  *
1953  * However, we don't hold a lock while we read the value. If someone has
1954  * just initialized the page, it's possible that we get a "torn read" of
1955  * the XLogRecPtr if 64-bit fetches are not atomic on this platform. In
1956  * that case we will see a bogus value. That's ok, we'll grab the mapping
1957  * lock (in AdvanceXLInsertBuffer) and retry if we see anything else than
1958  * the page we're looking for. But it means that when we do this unlocked
1959  * read, we might see a value that appears to be ahead of the page we're
1960  * looking for. Don't PANIC on that, until we've verified the value while
1961  * holding the lock.
1962  */
1963  expectedEndPtr = ptr;
1964  expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
1965 
1966  endptr = XLogCtl->xlblocks[idx];
1967  if (expectedEndPtr != endptr)
1968  {
1969  XLogRecPtr initializedUpto;
1970 
1971  /*
1972  * Before calling AdvanceXLInsertBuffer(), which can block, let others
1973  * know how far we're finished with inserting the record.
1974  *
1975  * NB: If 'ptr' points to just after the page header, advertise a
1976  * position at the beginning of the page rather than 'ptr' itself. If
1977  * there are no other insertions running, someone might try to flush
1978  * up to our advertised location. If we advertised a position after
1979  * the page header, someone might try to flush the page header, even
1980  * though page might actually not be initialized yet. As the first
1981  * inserter on the page, we are effectively responsible for making
1982  * sure that it's initialized, before we let insertingAt to move past
1983  * the page header.
1984  */
1985  if (ptr % XLOG_BLCKSZ == SizeOfXLogShortPHD &&
1986  XLogSegmentOffset(ptr, wal_segment_size) > XLOG_BLCKSZ)
1987  initializedUpto = ptr - SizeOfXLogShortPHD;
1988  else if (ptr % XLOG_BLCKSZ == SizeOfXLogLongPHD &&
1989  XLogSegmentOffset(ptr, wal_segment_size) < XLOG_BLCKSZ)
1990  initializedUpto = ptr - SizeOfXLogLongPHD;
1991  else
1992  initializedUpto = ptr;
1993 
1994  WALInsertLockUpdateInsertingAt(initializedUpto);
1995 
1996  AdvanceXLInsertBuffer(ptr, tli, false);
1997  endptr = XLogCtl->xlblocks[idx];
1998 
1999  if (expectedEndPtr != endptr)
2000  elog(PANIC, "could not find WAL buffer for %X/%X",
2001  LSN_FORMAT_ARGS(ptr));
2002  }
2003  else
2004  {
2005  /*
2006  * Make sure the initialization of the page is visible to us, and
2007  * won't arrive later to overwrite the WAL data we write on the page.
2008  */
2010  }
2011 
2012  /*
2013  * Found the buffer holding this page. Return a pointer to the right
2014  * offset within the page.
2015  */
2016  cachedPage = ptr / XLOG_BLCKSZ;
2017  cachedPos = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
2018 
2019  Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
2020  Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
2021 
2022  return cachedPos + ptr % XLOG_BLCKSZ;
2023 }
2024 
2025 /*
2026  * Converts a "usable byte position" to XLogRecPtr. A usable byte position
2027  * is the position starting from the beginning of WAL, excluding all WAL
2028  * page headers.
2029  */
2030 static XLogRecPtr
2031 XLogBytePosToRecPtr(uint64 bytepos)
2032 {
2033  uint64 fullsegs;
2034  uint64 fullpages;
2035  uint64 bytesleft;
2036  uint32 seg_offset;
2037  XLogRecPtr result;
2038 
2039  fullsegs = bytepos / UsableBytesInSegment;
2040  bytesleft = bytepos % UsableBytesInSegment;
2041 
2042  if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
2043  {
2044  /* fits on first page of segment */
2045  seg_offset = bytesleft + SizeOfXLogLongPHD;
2046  }
2047  else
2048  {
2049  /* account for the first page on segment with long header */
2050  seg_offset = XLOG_BLCKSZ;
2051  bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2052 
2053  fullpages = bytesleft / UsableBytesInPage;
2054  bytesleft = bytesleft % UsableBytesInPage;
2055 
2056  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2057  }
2058 
2059  XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
2060 
2061  return result;
2062 }
2063 
2064 /*
2065  * Like XLogBytePosToRecPtr, but if the position is at a page boundary,
2066  * returns a pointer to the beginning of the page (ie. before page header),
2067  * not to where the first xlog record on that page would go to. This is used
2068  * when converting a pointer to the end of a record.
2069  */
2070 static XLogRecPtr
2071 XLogBytePosToEndRecPtr(uint64 bytepos)
2072 {
2073  uint64 fullsegs;
2074  uint64 fullpages;
2075  uint64 bytesleft;
2076  uint32 seg_offset;
2077  XLogRecPtr result;
2078 
2079  fullsegs = bytepos / UsableBytesInSegment;
2080  bytesleft = bytepos % UsableBytesInSegment;
2081 
2082  if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
2083  {
2084  /* fits on first page of segment */
2085  if (bytesleft == 0)
2086  seg_offset = 0;
2087  else
2088  seg_offset = bytesleft + SizeOfXLogLongPHD;
2089  }
2090  else
2091  {
2092  /* account for the first page on segment with long header */
2093  seg_offset = XLOG_BLCKSZ;
2094  bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2095 
2096  fullpages = bytesleft / UsableBytesInPage;
2097  bytesleft = bytesleft % UsableBytesInPage;
2098 
2099  if (bytesleft == 0)
2100  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
2101  else
2102  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2103  }
2104 
2105  XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
2106 
2107  return result;
2108 }
2109 
2110 /*
2111  * Convert an XLogRecPtr to a "usable byte position".
2112  */
2113 static uint64
2115 {
2116  uint64 fullsegs;
2117  uint32 fullpages;
2118  uint32 offset;
2119  uint64 result;
2120 
2121  XLByteToSeg(ptr, fullsegs, wal_segment_size);
2122 
2123  fullpages = (XLogSegmentOffset(ptr, wal_segment_size)) / XLOG_BLCKSZ;
2124  offset = ptr % XLOG_BLCKSZ;
2125 
2126  if (fullpages == 0)
2127  {
2128  result = fullsegs * UsableBytesInSegment;
2129  if (offset > 0)
2130  {
2131  Assert(offset >= SizeOfXLogLongPHD);
2132  result += offset - SizeOfXLogLongPHD;
2133  }
2134  }
2135  else
2136  {
2137  result = fullsegs * UsableBytesInSegment +
2138  (XLOG_BLCKSZ - SizeOfXLogLongPHD) + /* account for first page */
2139  (fullpages - 1) * UsableBytesInPage; /* full pages */
2140  if (offset > 0)
2141  {
2142  Assert(offset >= SizeOfXLogShortPHD);
2143  result += offset - SizeOfXLogShortPHD;
2144  }
2145  }
2146 
2147  return result;
2148 }
2149 
2150 /*
2151  * Initialize XLOG buffers, writing out old buffers if they still contain
2152  * unwritten data, upto the page containing 'upto'. Or if 'opportunistic' is
2153  * true, initialize as many pages as we can without having to write out
2154  * unwritten data. Any new pages are initialized to zeros, with pages headers
2155  * initialized properly.
2156  */
2157 static void
2158 AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli, bool opportunistic)
2159 {
2161  int nextidx;
2162  XLogRecPtr OldPageRqstPtr;
2163  XLogwrtRqst WriteRqst;
2164  XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
2165  XLogRecPtr NewPageBeginPtr;
2166  XLogPageHeader NewPage;
2167  int npages = 0;
2168 
2169  LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2170 
2171  /*
2172  * Now that we have the lock, check if someone initialized the page
2173  * already.
2174  */
2175  while (upto >= XLogCtl->InitializedUpTo || opportunistic)
2176  {
2178 
2179  /*
2180  * Get ending-offset of the buffer page we need to replace (this may
2181  * be zero if the buffer hasn't been used yet). Fall through if it's
2182  * already written out.
2183  */
2184  OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
2185  if (LogwrtResult.Write < OldPageRqstPtr)
2186  {
2187  /*
2188  * Nope, got work to do. If we just want to pre-initialize as much
2189  * as we can without flushing, give up now.
2190  */
2191  if (opportunistic)
2192  break;
2193 
2194  /* Before waiting, get info_lck and update LogwrtResult */
2196  if (XLogCtl->LogwrtRqst.Write < OldPageRqstPtr)
2197  XLogCtl->LogwrtRqst.Write = OldPageRqstPtr;
2200 
2201  /*
2202  * Now that we have an up-to-date LogwrtResult value, see if we
2203  * still need to write it or if someone else already did.
2204  */
2205  if (LogwrtResult.Write < OldPageRqstPtr)
2206  {
2207  /*
2208  * Must acquire write lock. Release WALBufMappingLock first,
2209  * to make sure that all insertions that we need to wait for
2210  * can finish (up to this same position). Otherwise we risk
2211  * deadlock.
2212  */
2213  LWLockRelease(WALBufMappingLock);
2214 
2215  WaitXLogInsertionsToFinish(OldPageRqstPtr);
2216 
2217  LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2218 
2220  if (LogwrtResult.Write >= OldPageRqstPtr)
2221  {
2222  /* OK, someone wrote it already */
2223  LWLockRelease(WALWriteLock);
2224  }
2225  else
2226  {
2227  /* Have to write it ourselves */
2228  TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2229  WriteRqst.Write = OldPageRqstPtr;
2230  WriteRqst.Flush = 0;
2231  XLogWrite(WriteRqst, tli, false);
2232  LWLockRelease(WALWriteLock);
2234  TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
2235  }
2236  /* Re-acquire WALBufMappingLock and retry */
2237  LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2238  continue;
2239  }
2240  }
2241 
2242  /*
2243  * Now the next buffer slot is free and we can set it up to be the
2244  * next output page.
2245  */
2246  NewPageBeginPtr = XLogCtl->InitializedUpTo;
2247  NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2248 
2249  Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
2250 
2251  NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
2252 
2253  /*
2254  * Be sure to re-zero the buffer so that bytes beyond what we've
2255  * written will look like zeroes and not valid XLOG records...
2256  */
2257  MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
2258 
2259  /*
2260  * Fill the new page's header
2261  */
2262  NewPage->xlp_magic = XLOG_PAGE_MAGIC;
2263 
2264  /* NewPage->xlp_info = 0; */ /* done by memset */
2265  NewPage->xlp_tli = tli;
2266  NewPage->xlp_pageaddr = NewPageBeginPtr;
2267 
2268  /* NewPage->xlp_rem_len = 0; */ /* done by memset */
2269 
2270  /*
2271  * If online backup is not in progress, mark the header to indicate
2272  * that WAL records beginning in this page have removable backup
2273  * blocks. This allows the WAL archiver to know whether it is safe to
2274  * compress archived WAL data by transforming full-block records into
2275  * the non-full-block format. It is sufficient to record this at the
2276  * page level because we force a page switch (in fact a segment
2277  * switch) when starting a backup, so the flag will be off before any
2278  * records can be written during the backup. At the end of a backup,
2279  * the last page will be marked as all unsafe when perhaps only part
2280  * is unsafe, but at worst the archiver would miss the opportunity to
2281  * compress a few records.
2282  */
2283  if (!Insert->forcePageWrites)
2284  NewPage->xlp_info |= XLP_BKP_REMOVABLE;
2285 
2286  /*
2287  * If a record was found to be broken at the end of recovery, and
2288  * we're going to write on the page where its first contrecord was
2289  * lost, set the XLP_FIRST_IS_OVERWRITE_CONTRECORD flag on the page
2290  * header. See CreateOverwriteContrecordRecord().
2291  */
2292  if (missingContrecPtr == NewPageBeginPtr)
2293  {
2294  NewPage->xlp_info |= XLP_FIRST_IS_OVERWRITE_CONTRECORD;
2296  }
2297 
2298  /*
2299  * If first page of an XLOG segment file, make it a long header.
2300  */
2301  if ((XLogSegmentOffset(NewPage->xlp_pageaddr, wal_segment_size)) == 0)
2302  {
2303  XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
2304 
2305  NewLongPage->xlp_sysid = ControlFile->system_identifier;
2306  NewLongPage->xlp_seg_size = wal_segment_size;
2307  NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
2308  NewPage->xlp_info |= XLP_LONG_HEADER;
2309  }
2310 
2311  /*
2312  * Make sure the initialization of the page becomes visible to others
2313  * before the xlblocks update. GetXLogBuffer() reads xlblocks without
2314  * holding a lock.
2315  */
2316  pg_write_barrier();
2317 
2318  *((volatile XLogRecPtr *) &XLogCtl->xlblocks[nextidx]) = NewPageEndPtr;
2319 
2320  XLogCtl->InitializedUpTo = NewPageEndPtr;
2321 
2322  npages++;
2323  }
2324  LWLockRelease(WALBufMappingLock);
2325 
2326 #ifdef WAL_DEBUG
2327  if (XLOG_DEBUG && npages > 0)
2328  {
2329  elog(DEBUG1, "initialized %d pages, up to %X/%X",
2330  npages, LSN_FORMAT_ARGS(NewPageEndPtr));
2331  }
2332 #endif
2333 }
2334 
2335 /*
2336  * Calculate CheckPointSegments based on max_wal_size_mb and
2337  * checkpoint_completion_target.
2338  */
2339 static void
2341 {
2342  double target;
2343 
2344  /*-------
2345  * Calculate the distance at which to trigger a checkpoint, to avoid
2346  * exceeding max_wal_size_mb. This is based on two assumptions:
2347  *
2348  * a) we keep WAL for only one checkpoint cycle (prior to PG11 we kept
2349  * WAL for two checkpoint cycles to allow us to recover from the
2350  * secondary checkpoint if the first checkpoint failed, though we
2351  * only did this on the primary anyway, not on standby. Keeping just
2352  * one checkpoint simplifies processing and reduces disk space in
2353  * many smaller databases.)
2354  * b) during checkpoint, we consume checkpoint_completion_target *
2355  * number of segments consumed between checkpoints.
2356  *-------
2357  */
2358  target = (double) ConvertToXSegs(max_wal_size_mb, wal_segment_size) /
2360 
2361  /* round down */
2362  CheckPointSegments = (int) target;
2363 
2364  if (CheckPointSegments < 1)
2365  CheckPointSegments = 1;
2366 }
2367 
2368 void
2369 assign_max_wal_size(int newval, void *extra)
2370 {
2373 }
2374 
2375 void
2377 {
2380 }
2381 
2382 /*
2383  * At a checkpoint, how many WAL segments to recycle as preallocated future
2384  * XLOG segments? Returns the highest segment that should be preallocated.
2385  */
2386 static XLogSegNo
2388 {
2389  XLogSegNo minSegNo;
2390  XLogSegNo maxSegNo;
2391  double distance;
2392  XLogSegNo recycleSegNo;
2393 
2394  /*
2395  * Calculate the segment numbers that min_wal_size_mb and max_wal_size_mb
2396  * correspond to. Always recycle enough segments to meet the minimum, and
2397  * remove enough segments to stay below the maximum.
2398  */
2399  minSegNo = lastredoptr / wal_segment_size +
2401  maxSegNo = lastredoptr / wal_segment_size +
2403 
2404  /*
2405  * Between those limits, recycle enough segments to get us through to the
2406  * estimated end of next checkpoint.
2407  *
2408  * To estimate where the next checkpoint will finish, assume that the
2409  * system runs steadily consuming CheckPointDistanceEstimate bytes between
2410  * every checkpoint.
2411  */
2413  /* add 10% for good measure. */
2414  distance *= 1.10;
2415 
2416  recycleSegNo = (XLogSegNo) ceil(((double) lastredoptr + distance) /
2418 
2419  if (recycleSegNo < minSegNo)
2420  recycleSegNo = minSegNo;
2421  if (recycleSegNo > maxSegNo)
2422  recycleSegNo = maxSegNo;
2423 
2424  return recycleSegNo;
2425 }
2426 
2427 /*
2428  * Check whether we've consumed enough xlog space that a checkpoint is needed.
2429  *
2430  * new_segno indicates a log file that has just been filled up (or read
2431  * during recovery). We measure the distance from RedoRecPtr to new_segno
2432  * and see if that exceeds CheckPointSegments.
2433  *
2434  * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
2435  */
2436 static bool
2438 {
2439  XLogSegNo old_segno;
2440 
2442 
2443  if (new_segno >= old_segno + (uint64) (CheckPointSegments - 1))
2444  return true;
2445  return false;
2446 }
2447 
2448 /*
2449  * Write and/or fsync the log at least as far as WriteRqst indicates.
2450  *
2451  * If flexible == true, we don't have to write as far as WriteRqst, but
2452  * may stop at any convenient boundary (such as a cache or logfile boundary).
2453  * This option allows us to avoid uselessly issuing multiple writes when a
2454  * single one would do.
2455  *
2456  * Must be called with WALWriteLock held. WaitXLogInsertionsToFinish(WriteRqst)
2457  * must be called before grabbing the lock, to make sure the data is ready to
2458  * write.
2459  */
2460 static void
2461 XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible)
2462 {
2463  bool ispartialpage;
2464  bool last_iteration;
2465  bool finishing_seg;
2466  int curridx;
2467  int npages;
2468  int startidx;
2469  uint32 startoffset;
2470 
2471  /* We should always be inside a critical section here */
2472  Assert(CritSectionCount > 0);
2473 
2474  /*
2475  * Update local LogwrtResult (caller probably did this already, but...)
2476  */
2478 
2479  /*
2480  * Since successive pages in the xlog cache are consecutively allocated,
2481  * we can usually gather multiple pages together and issue just one
2482  * write() call. npages is the number of pages we have determined can be
2483  * written together; startidx is the cache block index of the first one,
2484  * and startoffset is the file offset at which it should go. The latter
2485  * two variables are only valid when npages > 0, but we must initialize
2486  * all of them to keep the compiler quiet.
2487  */
2488  npages = 0;
2489  startidx = 0;
2490  startoffset = 0;
2491 
2492  /*
2493  * Within the loop, curridx is the cache block index of the page to
2494  * consider writing. Begin at the buffer containing the next unwritten
2495  * page, or last partially written page.
2496  */
2498 
2499  while (LogwrtResult.Write < WriteRqst.Write)
2500  {
2501  /*
2502  * Make sure we're not ahead of the insert process. This could happen
2503  * if we're passed a bogus WriteRqst.Write that is past the end of the
2504  * last page that's been initialized by AdvanceXLInsertBuffer.
2505  */
2506  XLogRecPtr EndPtr = XLogCtl->xlblocks[curridx];
2507 
2508  if (LogwrtResult.Write >= EndPtr)
2509  elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
2511  LSN_FORMAT_ARGS(EndPtr));
2512 
2513  /* Advance LogwrtResult.Write to end of current buffer page */
2514  LogwrtResult.Write = EndPtr;
2515  ispartialpage = WriteRqst.Write < LogwrtResult.Write;
2516 
2519  {
2520  /*
2521  * Switch to new logfile segment. We cannot have any pending
2522  * pages here (since we dump what we have at segment end).
2523  */
2524  Assert(npages == 0);
2525  if (openLogFile >= 0)
2526  XLogFileClose();
2529  openLogTLI = tli;
2530 
2531  /* create/use new log file */
2534  }
2535 
2536  /* Make sure we have the current logfile open */
2537  if (openLogFile < 0)
2538  {
2541  openLogTLI = tli;
2544  }
2545 
2546  /* Add current page to the set of pending pages-to-dump */
2547  if (npages == 0)
2548  {
2549  /* first of group */
2550  startidx = curridx;
2551  startoffset = XLogSegmentOffset(LogwrtResult.Write - XLOG_BLCKSZ,
2553  }
2554  npages++;
2555 
2556  /*
2557  * Dump the set if this will be the last loop iteration, or if we are
2558  * at the last page of the cache area (since the next page won't be
2559  * contiguous in memory), or if we are at the end of the logfile
2560  * segment.
2561  */
2562  last_iteration = WriteRqst.Write <= LogwrtResult.Write;
2563 
2564  finishing_seg = !ispartialpage &&
2565  (startoffset + npages * XLOG_BLCKSZ) >= wal_segment_size;
2566 
2567  if (last_iteration ||
2568  curridx == XLogCtl->XLogCacheBlck ||
2569  finishing_seg)
2570  {
2571  char *from;
2572  Size nbytes;
2573  Size nleft;
2574  int written;
2575  instr_time start;
2576 
2577  /* OK to write the page(s) */
2578  from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
2579  nbytes = npages * (Size) XLOG_BLCKSZ;
2580  nleft = nbytes;
2581  do
2582  {
2583  errno = 0;
2584 
2585  /* Measure I/O timing to write WAL data */
2586  if (track_wal_io_timing)
2587  INSTR_TIME_SET_CURRENT(start);
2588 
2590  written = pg_pwrite(openLogFile, from, nleft, startoffset);
2592 
2593  /*
2594  * Increment the I/O timing and the number of times WAL data
2595  * were written out to disk.
2596  */
2597  if (track_wal_io_timing)
2598  {
2600 
2602  INSTR_TIME_SUBTRACT(duration, start);
2604  }
2605 
2607 
2608  if (written <= 0)
2609  {
2610  char xlogfname[MAXFNAMELEN];
2611  int save_errno;
2612 
2613  if (errno == EINTR)
2614  continue;
2615 
2616  save_errno = errno;
2617  XLogFileName(xlogfname, tli, openLogSegNo,
2619  errno = save_errno;
2620  ereport(PANIC,
2622  errmsg("could not write to log file %s "
2623  "at offset %u, length %zu: %m",
2624  xlogfname, startoffset, nleft)));
2625  }
2626  nleft -= written;
2627  from += written;
2628  startoffset += written;
2629  } while (nleft > 0);
2630 
2631  npages = 0;
2632 
2633  /*
2634  * If we just wrote the whole last page of a logfile segment,
2635  * fsync the segment immediately. This avoids having to go back
2636  * and re-open prior segments when an fsync request comes along
2637  * later. Doing it here ensures that one and only one backend will
2638  * perform this fsync.
2639  *
2640  * This is also the right place to notify the Archiver that the
2641  * segment is ready to copy to archival storage, and to update the
2642  * timer for archive_timeout, and to signal for a checkpoint if
2643  * too many logfile segments have been used since the last
2644  * checkpoint.
2645  */
2646  if (finishing_seg)
2647  {
2649 
2650  /* signal that we need to wakeup walsenders later */
2652 
2653  LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
2654 
2655  if (XLogArchivingActive())
2657 
2658  XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
2660 
2661  /*
2662  * Request a checkpoint if we've consumed too much xlog since
2663  * the last one. For speed, we first check using the local
2664  * copy of RedoRecPtr, which might be out of date; if it looks
2665  * like a checkpoint is needed, forcibly update RedoRecPtr and
2666  * recheck.
2667  */
2669  {
2670  (void) GetRedoRecPtr();
2673  }
2674  }
2675  }
2676 
2677  if (ispartialpage)
2678  {
2679  /* Only asked to write a partial page */
2680  LogwrtResult.Write = WriteRqst.Write;
2681  break;
2682  }
2683  curridx = NextBufIdx(curridx);
2684 
2685  /* If flexible, break out of loop as soon as we wrote something */
2686  if (flexible && npages == 0)
2687  break;
2688  }
2689 
2690  Assert(npages == 0);
2691 
2692  /*
2693  * If asked to flush, do so
2694  */
2695  if (LogwrtResult.Flush < WriteRqst.Flush &&
2697 
2698  {
2699  /*
2700  * Could get here without iterating above loop, in which case we might
2701  * have no open file or the wrong one. However, we do not need to
2702  * fsync more than one file.
2703  */
2704  if (sync_method != SYNC_METHOD_OPEN &&
2706  {
2707  if (openLogFile >= 0 &&
2710  XLogFileClose();
2711  if (openLogFile < 0)
2712  {
2715  openLogTLI = tli;
2718  }
2719 
2721  }
2722 
2723  /* signal that we need to wakeup walsenders later */
2725 
2727  }
2728 
2729  /*
2730  * Update shared-memory status
2731  *
2732  * We make sure that the shared 'request' values do not fall behind the
2733  * 'result' values. This is not absolutely essential, but it saves some
2734  * code in a couple of places.
2735  */
2736  {
2744  }
2745 }
2746 
2747 /*
2748  * Record the LSN for an asynchronous transaction commit/abort
2749  * and nudge the WALWriter if there is work for it to do.
2750  * (This should not be called for synchronous commits.)
2751  */
2752 void
2754 {
2755  XLogRecPtr WriteRqstPtr = asyncXactLSN;
2756  bool sleeping;
2757 
2760  sleeping = XLogCtl->WalWriterSleeping;
2761  if (XLogCtl->asyncXactLSN < asyncXactLSN)
2762  XLogCtl->asyncXactLSN = asyncXactLSN;
2764 
2765  /*
2766  * If the WALWriter is sleeping, we should kick it to make it come out of
2767  * low-power mode. Otherwise, determine whether there's a full page of
2768  * WAL available to write.
2769  */
2770  if (!sleeping)
2771  {
2772  /* back off to last completed page boundary */
2773  WriteRqstPtr -= WriteRqstPtr % XLOG_BLCKSZ;
2774 
2775  /* if we have already flushed that far, we're done */
2776  if (WriteRqstPtr <= LogwrtResult.Flush)
2777  return;
2778  }
2779 
2780  /*
2781  * Nudge the WALWriter: it has a full page of WAL to write, or we want it
2782  * to come out of low-power mode so that this async commit will reach disk
2783  * within the expected amount of time.
2784  */
2787 }
2788 
2789 /*
2790  * Record the LSN up to which we can remove WAL because it's not required by
2791  * any replication slot.
2792  */
2793 void
2795 {
2799 }
2800 
2801 
2802 /*
2803  * Return the oldest LSN we must retain to satisfy the needs of some
2804  * replication slot.
2805  */
2806 static XLogRecPtr
2808 {
2809  XLogRecPtr retval;
2810 
2812  retval = XLogCtl->replicationSlotMinLSN;
2814 
2815  return retval;
2816 }
2817 
2818 /*
2819  * Advance minRecoveryPoint in control file.
2820  *
2821  * If we crash during recovery, we must reach this point again before the
2822  * database is consistent.
2823  *
2824  * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
2825  * is only updated if it's not already greater than or equal to 'lsn'.
2826  */
2827 static void
2829 {
2830  /* Quick check using our local copy of the variable */
2831  if (!updateMinRecoveryPoint || (!force && lsn <= minRecoveryPoint))
2832  return;
2833 
2834  /*
2835  * An invalid minRecoveryPoint means that we need to recover all the WAL,
2836  * i.e., we're doing crash recovery. We never modify the control file's
2837  * value in that case, so we can short-circuit future checks here too. The
2838  * local values of minRecoveryPoint and minRecoveryPointTLI should not be
2839  * updated until crash recovery finishes. We only do this for the startup
2840  * process as it should not update its own reference of minRecoveryPoint
2841  * until it has finished crash recovery to make sure that all WAL
2842  * available is replayed in this case. This also saves from extra locks
2843  * taken on the control file from the startup process.
2844  */
2846  {
2847  updateMinRecoveryPoint = false;
2848  return;
2849  }
2850 
2851  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2852 
2853  /* update local copy */
2856 
2858  updateMinRecoveryPoint = false;
2859  else if (force || minRecoveryPoint < lsn)
2860  {
2861  XLogRecPtr newMinRecoveryPoint;
2862  TimeLineID newMinRecoveryPointTLI;
2863 
2864  /*
2865  * To avoid having to update the control file too often, we update it
2866  * all the way to the last record being replayed, even though 'lsn'
2867  * would suffice for correctness. This also allows the 'force' case
2868  * to not need a valid 'lsn' value.
2869  *
2870  * Another important reason for doing it this way is that the passed
2871  * 'lsn' value could be bogus, i.e., past the end of available WAL, if
2872  * the caller got it from a corrupted heap page. Accepting such a
2873  * value as the min recovery point would prevent us from coming up at
2874  * all. Instead, we just log a warning and continue with recovery.
2875  * (See also the comments about corrupt LSNs in XLogFlush.)
2876  */
2878  newMinRecoveryPoint = XLogCtl->replayEndRecPtr;
2879  newMinRecoveryPointTLI = XLogCtl->replayEndTLI;
2881 
2882  if (!force && newMinRecoveryPoint < lsn)
2883  elog(WARNING,
2884  "xlog min recovery request %X/%X is past current point %X/%X",
2885  LSN_FORMAT_ARGS(lsn), LSN_FORMAT_ARGS(newMinRecoveryPoint));
2886 
2887  /* update control file */
2888  if (ControlFile->minRecoveryPoint < newMinRecoveryPoint)
2889  {
2890  ControlFile->minRecoveryPoint = newMinRecoveryPoint;
2891  ControlFile->minRecoveryPointTLI = newMinRecoveryPointTLI;
2893  minRecoveryPoint = newMinRecoveryPoint;
2894  minRecoveryPointTLI = newMinRecoveryPointTLI;
2895 
2896  ereport(DEBUG2,
2897  (errmsg_internal("updated min recovery point to %X/%X on timeline %u",
2899  newMinRecoveryPointTLI)));
2900  }
2901  }
2902  LWLockRelease(ControlFileLock);
2903 }
2904 
2905 /*
2906  * Ensure that all XLOG data through the given position is flushed to disk.
2907  *
2908  * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
2909  * already held, and we try to avoid acquiring it if possible.
2910  */
2911 void
2913 {
2914  XLogRecPtr WriteRqstPtr;
2915  XLogwrtRqst WriteRqst;
2916  TimeLineID insertTLI = XLogCtl->InsertTimeLineID;
2917 
2918  /*
2919  * During REDO, we are reading not writing WAL. Therefore, instead of
2920  * trying to flush the WAL, we should update minRecoveryPoint instead. We
2921  * test XLogInsertAllowed(), not InRecovery, because we need checkpointer
2922  * to act this way too, and because when it tries to write the
2923  * end-of-recovery checkpoint, it should indeed flush.
2924  */
2925  if (!XLogInsertAllowed())
2926  {
2927  UpdateMinRecoveryPoint(record, false);
2928  return;
2929  }
2930 
2931  /* Quick exit if already known flushed */
2932  if (record <= LogwrtResult.Flush)
2933  return;
2934 
2935 #ifdef WAL_DEBUG
2936  if (XLOG_DEBUG)
2937  elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
2938  LSN_FORMAT_ARGS(record),
2941 #endif
2942 
2944 
2945  /*
2946  * Since fsync is usually a horribly expensive operation, we try to
2947  * piggyback as much data as we can on each fsync: if we see any more data
2948  * entered into the xlog buffer, we'll write and fsync that too, so that
2949  * the final value of LogwrtResult.Flush is as large as possible. This
2950  * gives us some chance of avoiding another fsync immediately after.
2951  */
2952 
2953  /* initialize to given target; may increase below */
2954  WriteRqstPtr = record;
2955 
2956  /*
2957  * Now wait until we get the write lock, or someone else does the flush
2958  * for us.
2959  */
2960  for (;;)
2961  {
2962  XLogRecPtr insertpos;
2963 
2964  /* read LogwrtResult and update local state */
2966  if (WriteRqstPtr < XLogCtl->LogwrtRqst.Write)
2967  WriteRqstPtr = XLogCtl->LogwrtRqst.Write;
2970 
2971  /* done already? */
2972  if (record <= LogwrtResult.Flush)
2973  break;
2974 
2975  /*
2976  * Before actually performing the write, wait for all in-flight
2977  * insertions to the pages we're about to write to finish.
2978  */
2979  insertpos = WaitXLogInsertionsToFinish(WriteRqstPtr);
2980 
2981  /*
2982  * Try to get the write lock. If we can't get it immediately, wait
2983  * until it's released, and recheck if we still need to do the flush
2984  * or if the backend that held the lock did it for us already. This
2985  * helps to maintain a good rate of group committing when the system
2986  * is bottlenecked by the speed of fsyncing.
2987  */
2988  if (!LWLockAcquireOrWait(WALWriteLock, LW_EXCLUSIVE))
2989  {
2990  /*
2991  * The lock is now free, but we didn't acquire it yet. Before we
2992  * do, loop back to check if someone else flushed the record for
2993  * us already.
2994  */
2995  continue;
2996  }
2997 
2998  /* Got the lock; recheck whether request is satisfied */
3000  if (record <= LogwrtResult.Flush)
3001  {
3002  LWLockRelease(WALWriteLock);
3003  break;
3004  }
3005 
3006  /*
3007  * Sleep before flush! By adding a delay here, we may give further
3008  * backends the opportunity to join the backlog of group commit
3009  * followers; this can significantly improve transaction throughput,
3010  * at the risk of increasing transaction latency.
3011  *
3012  * We do not sleep if enableFsync is not turned on, nor if there are
3013  * fewer than CommitSiblings other backends with active transactions.
3014  */
3015  if (CommitDelay > 0 && enableFsync &&
3017  {
3019 
3020  /*
3021  * Re-check how far we can now flush the WAL. It's generally not
3022  * safe to call WaitXLogInsertionsToFinish while holding
3023  * WALWriteLock, because an in-progress insertion might need to
3024  * also grab WALWriteLock to make progress. But we know that all
3025  * the insertions up to insertpos have already finished, because
3026  * that's what the earlier WaitXLogInsertionsToFinish() returned.
3027  * We're only calling it again to allow insertpos to be moved
3028  * further forward, not to actually wait for anyone.
3029  */
3030  insertpos = WaitXLogInsertionsToFinish(insertpos);
3031  }
3032 
3033  /* try to write/flush later additions to XLOG as well */
3034  WriteRqst.Write = insertpos;
3035  WriteRqst.Flush = insertpos;
3036 
3037  XLogWrite(WriteRqst, insertTLI, false);
3038 
3039  LWLockRelease(WALWriteLock);
3040  /* done */
3041  break;
3042  }
3043 
3044  END_CRIT_SECTION();
3045 
3046  /* wake up walsenders now that we've released heavily contended locks */
3048 
3049  /*
3050  * If we still haven't flushed to the request point then we have a
3051  * problem; most likely, the requested flush point is past end of XLOG.
3052  * This has been seen to occur when a disk page has a corrupted LSN.
3053  *
3054  * Formerly we treated this as a PANIC condition, but that hurts the
3055  * system's robustness rather than helping it: we do not want to take down
3056  * the whole system due to corruption on one data page. In particular, if
3057  * the bad page is encountered again during recovery then we would be
3058  * unable to restart the database at all! (This scenario actually
3059  * happened in the field several times with 7.1 releases.) As of 8.4, bad
3060  * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
3061  * the only time we can reach here during recovery is while flushing the
3062  * end-of-recovery checkpoint record, and we don't expect that to have a
3063  * bad LSN.
3064  *
3065  * Note that for calls from xact.c, the ERROR will be promoted to PANIC
3066  * since xact.c calls this routine inside a critical section. However,
3067  * calls from bufmgr.c are not within critical sections and so we will not
3068  * force a restart for a bad LSN on a data page.
3069  */
3070  if (LogwrtResult.Flush < record)
3071  elog(ERROR,
3072  "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
3073  LSN_FORMAT_ARGS(record),
3075 }
3076 
3077 /*
3078  * Write & flush xlog, but without specifying exactly where to.
3079  *
3080  * We normally write only completed blocks; but if there is nothing to do on
3081  * that basis, we check for unwritten async commits in the current incomplete
3082  * block, and write through the latest one of those. Thus, if async commits
3083  * are not being used, we will write complete blocks only.
3084  *
3085  * If, based on the above, there's anything to write we do so immediately. But
3086  * to avoid calling fsync, fdatasync et. al. at a rate that'd impact
3087  * concurrent IO, we only flush WAL every wal_writer_delay ms, or if there's
3088  * more than wal_writer_flush_after unflushed blocks.
3089  *
3090  * We can guarantee that async commits reach disk after at most three
3091  * wal_writer_delay cycles. (When flushing complete blocks, we allow XLogWrite
3092  * to write "flexibly", meaning it can stop at the end of the buffer ring;
3093  * this makes a difference only with very high load or long wal_writer_delay,
3094  * but imposes one extra cycle for the worst case for async commits.)
3095  *
3096  * This routine is invoked periodically by the background walwriter process.
3097  *
3098  * Returns true if there was any work to do, even if we skipped flushing due
3099  * to wal_writer_delay/wal_writer_flush_after.
3100  */
3101 bool
3103 {
3104  XLogwrtRqst WriteRqst;
3105  bool flexible = true;
3106  static TimestampTz lastflush;
3107  TimestampTz now;
3108  int flushbytes;
3109  TimeLineID insertTLI;
3110 
3111  /* XLOG doesn't need flushing during recovery */
3112  if (RecoveryInProgress())
3113  return false;
3114 
3115  /*
3116  * Since we're not in recovery, InsertTimeLineID is set and can't change,
3117  * so we can read it without a lock.
3118  */
3119  insertTLI = XLogCtl->InsertTimeLineID;
3120 
3121  /* read LogwrtResult and update local state */
3124  WriteRqst = XLogCtl->LogwrtRqst;
3126 
3127  /* back off to last completed page boundary */
3128  WriteRqst.Write -= WriteRqst.Write % XLOG_BLCKSZ;
3129 
3130  /* if we have already flushed that far, consider async commit records */
3131  if (WriteRqst.Write <= LogwrtResult.Flush)
3132  {
3134  WriteRqst.Write = XLogCtl->asyncXactLSN;
3136  flexible = false; /* ensure it all gets written */
3137  }
3138 
3139  /*
3140  * If already known flushed, we're done. Just need to check if we are
3141  * holding an open file handle to a logfile that's no longer in use,
3142  * preventing the file from being deleted.
3143  */
3144  if (WriteRqst.Write <= LogwrtResult.Flush)
3145  {
3146  if (openLogFile >= 0)
3147  {
3150  {
3151  XLogFileClose();
3152  }
3153  }
3154  return false;
3155  }
3156 
3157  /*
3158  * Determine how far to flush WAL, based on the wal_writer_delay and
3159  * wal_writer_flush_after GUCs.
3160  */
3162  flushbytes =
3163  WriteRqst.Write / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
3164 
3165  if (WalWriterFlushAfter == 0 || lastflush == 0)
3166  {
3167  /* first call, or block based limits disabled */
3168  WriteRqst.Flush = WriteRqst.Write;
3169  lastflush = now;
3170  }
3171  else if (TimestampDifferenceExceeds(lastflush, now, WalWriterDelay))
3172  {
3173  /*
3174  * Flush the writes at least every WalWriterDelay ms. This is
3175  * important to bound the amount of time it takes for an asynchronous
3176  * commit to hit disk.
3177  */
3178  WriteRqst.Flush = WriteRqst.Write;
3179  lastflush = now;
3180  }
3181  else if (flushbytes >= WalWriterFlushAfter)
3182  {
3183  /* exceeded wal_writer_flush_after blocks, flush */
3184  WriteRqst.Flush = WriteRqst.Write;
3185  lastflush = now;
3186  }
3187  else
3188  {
3189  /* no flushing, this time round */
3190  WriteRqst.Flush = 0;
3191  }
3192 
3193 #ifdef WAL_DEBUG
3194  if (XLOG_DEBUG)
3195  elog(LOG, "xlog bg flush request write %X/%X; flush: %X/%X, current is write %X/%X; flush %X/%X",
3196  LSN_FORMAT_ARGS(WriteRqst.Write),
3197  LSN_FORMAT_ARGS(WriteRqst.Flush),
3200 #endif
3201 
3203 
3204  /* now wait for any in-progress insertions to finish and get write lock */
3205  WaitXLogInsertionsToFinish(WriteRqst.Write);
3206  LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
3208  if (WriteRqst.Write > LogwrtResult.Write ||
3209  WriteRqst.Flush > LogwrtResult.Flush)
3210  {
3211  XLogWrite(WriteRqst, insertTLI, flexible);
3212  }
3213  LWLockRelease(WALWriteLock);
3214 
3215  END_CRIT_SECTION();
3216 
3217  /* wake up walsenders now that we've released heavily contended locks */
3219 
3220  /*
3221  * Great, done. To take some work off the critical path, try to initialize
3222  * as many of the no-longer-needed WAL buffers for future use as we can.
3223  */
3224  AdvanceXLInsertBuffer(InvalidXLogRecPtr, insertTLI, true);
3225 
3226  /*
3227  * If we determined that we need to write data, but somebody else
3228  * wrote/flushed already, it should be considered as being active, to
3229  * avoid hibernating too early.
3230  */
3231  return true;
3232 }
3233 
3234 /*
3235  * Test whether XLOG data has been flushed up to (at least) the given position.
3236  *
3237  * Returns true if a flush is still needed. (It may be that someone else
3238  * is already in process of flushing that far, however.)
3239  */
3240 bool
3242 {
3243  /*
3244  * During recovery, we don't flush WAL but update minRecoveryPoint
3245  * instead. So "needs flush" is taken to mean whether minRecoveryPoint
3246  * would need to be updated.
3247  */
3248  if (RecoveryInProgress())
3249  {
3250  /*
3251  * An invalid minRecoveryPoint means that we need to recover all the
3252  * WAL, i.e., we're doing crash recovery. We never modify the control
3253  * file's value in that case, so we can short-circuit future checks
3254  * here too. This triggers a quick exit path for the startup process,
3255  * which cannot update its local copy of minRecoveryPoint as long as
3256  * it has not replayed all WAL available when doing crash recovery.
3257  */
3259  updateMinRecoveryPoint = false;
3260 
3261  /* Quick exit if already known to be updated or cannot be updated */
3262  if (record <= minRecoveryPoint || !updateMinRecoveryPoint)
3263  return false;
3264 
3265  /*
3266  * Update local copy of minRecoveryPoint. But if the lock is busy,
3267  * just return a conservative guess.
3268  */
3269  if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
3270  return true;
3273  LWLockRelease(ControlFileLock);
3274 
3275  /*
3276  * Check minRecoveryPoint for any other process than the startup
3277  * process doing crash recovery, which should not update the control
3278  * file value if crash recovery is still running.
3279  */
3281  updateMinRecoveryPoint = false;
3282 
3283  /* check again */
3284  if (record <= minRecoveryPoint || !updateMinRecoveryPoint)
3285  return false;
3286  else
3287  return true;
3288  }
3289 
3290  /* Quick exit if already known flushed */
3291  if (record <= LogwrtResult.Flush)
3292  return false;
3293 
3294  /* read LogwrtResult and update local state */
3298 
3299  /* check again */
3300  if (record <= LogwrtResult.Flush)
3301  return false;
3302 
3303  return true;
3304 }
3305 
3306 /*
3307  * Try to make a given XLOG file segment exist.
3308  *
3309  * logsegno: identify segment.
3310  *
3311  * *added: on return, true if this call raised the number of extant segments.
3312  *
3313  * path: on return, this char[MAXPGPATH] has the path to the logsegno file.
3314  *
3315  * Returns -1 or FD of opened file. A -1 here is not an error; a caller
3316  * wanting an open segment should attempt to open "path", which usually will
3317  * succeed. (This is weird, but it's efficient for the callers.)
3318  */
3319 static int
3321  bool *added, char *path)
3322 {
3323  char tmppath[MAXPGPATH];
3324  PGAlignedXLogBlock zbuffer;
3325  XLogSegNo installed_segno;
3326  XLogSegNo max_segno;
3327  int fd;
3328  int save_errno;
3329 
3330  Assert(logtli != 0);
3331 
3332  XLogFilePath(path, logtli, logsegno, wal_segment_size);
3333 
3334  /*
3335  * Try to use existent file (checkpoint maker may have created it already)
3336  */
3337  *added = false;
3338  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
3339  if (fd < 0)
3340  {
3341  if (errno != ENOENT)
3342  ereport(ERROR,
3344  errmsg("could not open file \"%s\": %m", path)));
3345  }
3346  else
3347  return fd;
3348 
3349  /*
3350  * Initialize an empty (all zeroes) segment. NOTE: it is possible that
3351  * another process is doing the same thing. If so, we will end up
3352  * pre-creating an extra log segment. That seems OK, and better than
3353  * holding the lock throughout this lengthy process.
3354  */
3355  elog(DEBUG2, "creating and filling new WAL file");
3356 
3357  snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3358 
3359  unlink(tmppath);
3360 
3361  /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3362  fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3363  if (fd < 0)
3364  ereport(ERROR,
3366  errmsg("could not create file \"%s\": %m", tmppath)));
3367 
3368  memset(zbuffer.data, 0, XLOG_BLCKSZ);
3369 
3371  save_errno = 0;
3372  if (wal_init_zero)
3373  {
3374  struct iovec iov[PG_IOV_MAX];
3375  int blocks;
3376 
3377  /*
3378  * Zero-fill the file. With this setting, we do this the hard way to
3379  * ensure that all the file space has really been allocated. On
3380  * platforms that allow "holes" in files, just seeking to the end
3381  * doesn't allocate intermediate space. This way, we know that we
3382  * have all the space and (after the fsync below) that all the
3383  * indirect blocks are down on disk. Therefore, fdatasync(2) or
3384  * O_DSYNC will be sufficient to sync future writes to the log file.
3385  */
3386 
3387  /* Prepare to write out a lot of copies of our zero buffer at once. */
3388  for (int i = 0; i < lengthof(iov); ++i)
3389  {
3390  iov[i].iov_base = zbuffer.data;
3391  iov[i].iov_len = XLOG_BLCKSZ;
3392  }
3393 
3394  /* Loop, writing as many blocks as we can for each system call. */
3395  blocks = wal_segment_size / XLOG_BLCKSZ;
3396  for (int i = 0; i < blocks;)
3397  {
3398  int iovcnt = Min(blocks - i, lengthof(iov));
3399  off_t offset = i * XLOG_BLCKSZ;
3400 
3401  if (pg_pwritev_with_retry(fd, iov, iovcnt, offset) < 0)
3402  {
3403  save_errno = errno;
3404  break;
3405  }
3406 
3407  i += iovcnt;
3408  }
3409  }
3410  else
3411  {
3412  /*
3413  * Otherwise, seeking to the end and writing a solitary byte is
3414  * enough.
3415  */
3416  errno = 0;
3417  if (pg_pwrite(fd, zbuffer.data, 1, wal_segment_size - 1) != 1)
3418  {
3419  /* if write didn't set errno, assume no disk space */
3420  save_errno = errno ? errno : ENOSPC;
3421  }
3422  }
3424 
3425  if (save_errno)
3426  {
3427  /*
3428  * If we fail to make the file, delete it to release disk space
3429  */
3430  unlink(tmppath);
3431 
3432  close(fd);
3433 
3434  errno = save_errno;
3435 
3436  ereport(ERROR,
3438  errmsg("could not write to file \"%s\": %m", tmppath)));
3439  }
3440 
3442  if (pg_fsync(fd) != 0)
3443  {
3444  int save_errno = errno;
3445 
3446  close(fd);
3447  errno = save_errno;
3448  ereport(ERROR,
3450  errmsg("could not fsync file \"%s\": %m", tmppath)));
3451  }
3453 
3454  if (close(fd) != 0)
3455  ereport(ERROR,
3457  errmsg("could not close file \"%s\": %m", tmppath)));
3458 
3459  /*
3460  * Now move the segment into place with its final name. Cope with
3461  * possibility that someone else has created the file while we were
3462  * filling ours: if so, use ours to pre-create a future log segment.
3463  */
3464  installed_segno = logsegno;
3465 
3466  /*
3467  * XXX: What should we use as max_segno? We used to use XLOGfileslop when
3468  * that was a constant, but that was always a bit dubious: normally, at a
3469  * checkpoint, XLOGfileslop was the offset from the checkpoint record, but
3470  * here, it was the offset from the insert location. We can't do the
3471  * normal XLOGfileslop calculation here because we don't have access to
3472  * the prior checkpoint's redo location. So somewhat arbitrarily, just use
3473  * CheckPointSegments.
3474  */
3475  max_segno = logsegno + CheckPointSegments;
3476  if (InstallXLogFileSegment(&installed_segno, tmppath, true, max_segno,
3477  logtli))
3478  {
3479  *added = true;
3480  elog(DEBUG2, "done creating and filling new WAL file");
3481  }
3482  else
3483  {
3484  /*
3485  * No need for any more future segments, or InstallXLogFileSegment()
3486  * failed to rename the file into place. If the rename failed, a
3487  * caller opening the file may fail.
3488  */
3489  unlink(tmppath);
3490  elog(DEBUG2, "abandoned new WAL file");
3491  }
3492 
3493  return -1;
3494 }
3495 
3496 /*
3497  * Create a new XLOG file segment, or open a pre-existing one.
3498  *
3499  * logsegno: identify segment to be created/opened.
3500  *
3501  * Returns FD of opened file.
3502  *
3503  * Note: errors here are ERROR not PANIC because we might or might not be
3504  * inside a critical section (eg, during checkpoint there is no reason to
3505  * take down the system on failure). They will promote to PANIC if we are
3506  * in a critical section.
3507  */
3508 int
3510 {
3511  bool ignore_added;
3512  char path[MAXPGPATH];
3513  int fd;
3514 
3515  Assert(logtli != 0);
3516 
3517  fd = XLogFileInitInternal(logsegno, logtli, &ignore_added, path);
3518  if (fd >= 0)
3519  return fd;
3520 
3521  /* Now open original target segment (might not be file I just made) */
3522  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
3523  if (fd < 0)
3524  ereport(ERROR,
3526  errmsg("could not open file \"%s\": %m", path)));
3527  return fd;
3528 }
3529 
3530 /*
3531  * Create a new XLOG file segment by copying a pre-existing one.
3532  *
3533  * destsegno: identify segment to be created.
3534  *
3535  * srcTLI, srcsegno: identify segment to be copied (could be from
3536  * a different timeline)
3537  *
3538  * upto: how much of the source file to copy (the rest is filled with
3539  * zeros)
3540  *
3541  * Currently this is only used during recovery, and so there are no locking
3542  * considerations. But we should be just as tense as XLogFileInit to avoid
3543  * emplacing a bogus file.
3544  */
3545 static void
3546 XLogFileCopy(TimeLineID destTLI, XLogSegNo destsegno,
3547  TimeLineID srcTLI, XLogSegNo srcsegno,
3548  int upto)
3549 {
3550  char path[MAXPGPATH];
3551  char tmppath[MAXPGPATH];
3552  PGAlignedXLogBlock buffer;
3553  int srcfd;
3554  int fd;
3555  int nbytes;
3556 
3557  /*
3558  * Open the source file
3559  */
3560  XLogFilePath(path, srcTLI, srcsegno, wal_segment_size);
3561  srcfd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3562  if (srcfd < 0)
3563  ereport(ERROR,
3565  errmsg("could not open file \"%s\": %m", path)));
3566 
3567  /*
3568  * Copy into a temp file name.
3569  */
3570  snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3571 
3572  unlink(tmppath);
3573 
3574  /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3575  fd = OpenTransientFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3576  if (fd < 0)
3577  ereport(ERROR,
3579  errmsg("could not create file \"%s\": %m", tmppath)));
3580 
3581  /*
3582  * Do the data copying.
3583  */
3584  for (nbytes = 0; nbytes < wal_segment_size; nbytes += sizeof(buffer))
3585  {
3586  int nread;
3587 
3588  nread = upto - nbytes;
3589 
3590  /*
3591  * The part that is not read from the source file is filled with
3592  * zeros.
3593  */
3594  if (nread < sizeof(buffer))
3595  memset(buffer.data, 0, sizeof(buffer));
3596 
3597  if (nread > 0)
3598  {
3599  int r;
3600 
3601  if (nread > sizeof(buffer))
3602  nread = sizeof(buffer);
3604  r = read(srcfd, buffer.data, nread);
3605  if (r != nread)
3606  {
3607  if (r < 0)
3608  ereport(ERROR,
3610  errmsg("could not read file \"%s\": %m",
3611  path)));
3612  else
3613  ereport(ERROR,
3615  errmsg("could not read file \"%s\": read %d of %zu",
3616  path, r, (Size) nread)));
3617  }
3619  }
3620  errno = 0;
3622  if ((int) write(fd, buffer.data, sizeof(buffer)) != (int) sizeof(buffer))
3623  {
3624  int save_errno = errno;
3625 
3626  /*
3627  * If we fail to make the file, delete it to release disk space
3628  */
3629  unlink(tmppath);
3630  /* if write didn't set errno, assume problem is no disk space */
3631  errno = save_errno ? save_errno : ENOSPC;
3632 
3633  ereport(ERROR,
3635  errmsg("could not write to file \"%s\": %m", tmppath)));
3636  }
3638  }
3639 
3641  if (pg_fsync(fd) != 0)
3644  errmsg("could not fsync file \"%s\": %m", tmppath)));
3646 
3647  if (CloseTransientFile(fd) != 0)
3648  ereport(ERROR,
3650  errmsg("could not close file \"%s\": %m", tmppath)));
3651 
3652  if (CloseTransientFile(srcfd) != 0)
3653  ereport(ERROR,
3655  errmsg("could not close file \"%s\": %m", path)));
3656 
3657  /*
3658  * Now move the segment into place with its final name.
3659  */
3660  if (!InstallXLogFileSegment(&destsegno, tmppath, false, 0, destTLI))
3661  elog(ERROR, "InstallXLogFileSegment should not have failed");
3662 }
3663 
3664 /*
3665  * Install a new XLOG segment file as a current or future log segment.
3666  *
3667  * This is used both to install a newly-created segment (which has a temp
3668  * filename while it's being created) and to recycle an old segment.
3669  *
3670  * *segno: identify segment to install as (or first possible target).
3671  * When find_free is true, this is modified on return to indicate the
3672  * actual installation location or last segment searched.
3673  *
3674  * tmppath: initial name of file to install. It will be renamed into place.
3675  *
3676  * find_free: if true, install the new segment at the first empty segno
3677  * number at or after the passed numbers. If false, install the new segment
3678  * exactly where specified, deleting any existing segment file there.
3679  *
3680  * max_segno: maximum segment number to install the new file as. Fail if no
3681  * free slot is found between *segno and max_segno. (Ignored when find_free
3682  * is false.)
3683  *
3684  * tli: The timeline on which the new segment should be installed.
3685  *
3686  * Returns true if the file was installed successfully. false indicates that
3687  * max_segno limit was exceeded, the startup process has disabled this
3688  * function for now, or an error occurred while renaming the file into place.
3689  */
3690 static bool
3691 InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
3692  bool find_free, XLogSegNo max_segno, TimeLineID tli)
3693 {
3694  char path[MAXPGPATH];
3695  struct stat stat_buf;
3696 
3697  Assert(tli != 0);
3698 
3699  XLogFilePath(path, tli, *segno, wal_segment_size);
3700 
3701  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3703  {
3704  LWLockRelease(ControlFileLock);
3705  return false;
3706  }
3707 
3708  if (!find_free)
3709  {
3710  /* Force installation: get rid of any pre-existing segment file */
3711  durable_unlink(path, DEBUG1);
3712  }
3713  else
3714  {
3715  /* Find a free slot to put it in */
3716  while (stat(path, &stat_buf) == 0)
3717  {
3718  if ((*segno) >= max_segno)
3719  {
3720  /* Failed to find a free slot within specified range */
3721  LWLockRelease(ControlFileLock);
3722  return false;
3723  }
3724  (*segno)++;
3725  XLogFilePath(path, tli, *segno, wal_segment_size);
3726  }
3727  }
3728 
3729  /*
3730  * Perform the rename using link if available, paranoidly trying to avoid
3731  * overwriting an existing file (there shouldn't be one).
3732  */
3733  if (durable_rename_excl(tmppath, path, LOG) != 0)
3734  {
3735  LWLockRelease(ControlFileLock);
3736  /* durable_rename_excl already emitted log message */
3737  return false;
3738  }
3739 
3740  LWLockRelease(ControlFileLock);
3741 
3742  return true;
3743 }
3744 
3745 /*
3746  * Open a pre-existing logfile segment for writing.
3747  */
3748 int
3750 {
3751  char path[MAXPGPATH];
3752  int fd;
3753 
3754  XLogFilePath(path, tli, segno, wal_segment_size);
3755 
3756  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
3757  if (fd < 0)
3758  ereport(PANIC,
3760  errmsg("could not open file \"%s\": %m", path)));
3761 
3762  return fd;
3763 }
3764 
3765 /*
3766  * Open a logfile segment for reading (during recovery).
3767  *
3768  * If source == XLOG_FROM_ARCHIVE, the segment is retrieved from archive.
3769  * Otherwise, it's assumed to be already available in pg_wal.
3770  */
3771 static int
3772 XLogFileRead(XLogSegNo segno, int emode, TimeLineID tli,
3773  XLogSource source, bool notfoundOk)
3774 {
3775  char xlogfname[MAXFNAMELEN];
3776  char activitymsg[MAXFNAMELEN + 16];
3777  char path[MAXPGPATH];
3778  int fd;
3779 
3780  XLogFileName(xlogfname, tli, segno, wal_segment_size);
3781 
3782  switch (source)
3783  {
3784  case XLOG_FROM_ARCHIVE:
3785  /* Report recovery progress in PS display */
3786  snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
3787  xlogfname);
3788  set_ps_display(activitymsg);
3789 
3790  if (!RestoreArchivedFile(path, xlogfname,
3791  "RECOVERYXLOG",
3793  InRedo))
3794  return -1;
3795  break;
3796 
3797  case XLOG_FROM_PG_WAL:
3798  case XLOG_FROM_STREAM:
3799  XLogFilePath(path, tli, segno, wal_segment_size);
3800  break;
3801 
3802  default:
3803  elog(ERROR, "invalid XLogFileRead source %d", source);
3804  }
3805 
3806  /*
3807  * If the segment was fetched from archival storage, replace the existing
3808  * xlog segment (if any) with the archival version.
3809  */
3810  if (source == XLOG_FROM_ARCHIVE)
3811  {
3813  KeepFileRestoredFromArchive(path, xlogfname);
3814 
3815  /*
3816  * Set path to point at the new file in pg_wal.
3817  */
3818  snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
3819  }
3820 
3821  fd = BasicOpenFile(path, O_RDONLY | PG_BINARY);
3822  if (fd >= 0)
3823  {
3824  /* Success! */
3825  curFileTLI = tli;
3826 
3827  /* Report recovery progress in PS display */
3828  snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
3829  xlogfname);
3830  set_ps_display(activitymsg);
3831 
3832  /* Track source of data in assorted state variables */
3833  readSource = source;
3835  /* In FROM_STREAM case, caller tracks receipt time, not me */
3836  if (source != XLOG_FROM_STREAM)
3838 
3839  return fd;
3840  }
3841  if (errno != ENOENT || !notfoundOk) /* unexpected failure? */
3842  ereport(PANIC,
3844  errmsg("could not open file \"%s\": %m", path)));
3845  return -1;
3846 }
3847 
3848 /*
3849  * Open a logfile segment for reading (during recovery).
3850  *
3851  * This version searches for the segment with any TLI listed in expectedTLEs.
3852  */
3853 static int
3855 {
3856  char path[MAXPGPATH];
3857  ListCell *cell;
3858  int fd;
3859  List *tles;
3860 
3861  /*
3862  * Loop looking for a suitable timeline ID: we might need to read any of
3863  * the timelines listed in expectedTLEs.
3864  *
3865  * We expect curFileTLI on entry to be the TLI of the preceding file in
3866  * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
3867  * to go backwards; this prevents us from picking up the wrong file when a
3868  * parent timeline extends to higher segment numbers than the child we
3869  * want to read.
3870  *
3871  * If we haven't read the timeline history file yet, read it now, so that
3872  * we know which TLIs to scan. We don't save the list in expectedTLEs,
3873  * however, unless we actually find a valid segment. That way if there is
3874  * neither a timeline history file nor a WAL segment in the archive, and
3875  * streaming replication is set up, we'll read the timeline history file
3876  * streamed from the primary when we start streaming, instead of
3877  * recovering with a dummy history generated here.
3878  */
3879  if (expectedTLEs)
3880  tles = expectedTLEs;
3881  else
3883 
3884  foreach(cell, tles)
3885  {
3887  TimeLineID tli = hent->tli;
3888 
3889  if (tli < curFileTLI)
3890  break; /* don't bother looking at too-old TLIs */
3891 
3892  /*
3893  * Skip scanning the timeline ID that the logfile segment to read
3894  * doesn't belong to
3895  */
3896  if (hent->begin != InvalidXLogRecPtr)
3897  {
3898  XLogSegNo beginseg = 0;
3899 
3900  XLByteToSeg(hent->begin, beginseg, wal_segment_size);
3901 
3902  /*
3903  * The logfile segment that doesn't belong to the timeline is
3904  * older or newer than the segment that the timeline started or
3905  * ended at, respectively. It's sufficient to check only the
3906  * starting segment of the timeline here. Since the timelines are
3907  * scanned in descending order in this loop, any segments newer
3908  * than the ending segment should belong to newer timeline and
3909  * have already been read before. So it's not necessary to check
3910  * the ending segment of the timeline here.
3911  */
3912  if (segno < beginseg)
3913  continue;
3914  }
3915 
3917  {
3918  fd = XLogFileRead(segno, emode, tli,
3919  XLOG_FROM_ARCHIVE, true);
3920  if (fd != -1)
3921  {
3922  elog(DEBUG1, "got WAL segment from archive");
3923  if (!expectedTLEs)
3924  expectedTLEs = tles;
3925  return fd;
3926  }
3927  }
3928 
3930  {
3931  fd = XLogFileRead(segno, emode, tli,
3932  XLOG_FROM_PG_WAL, true);
3933  if (fd != -1)
3934  {
3935  if (!expectedTLEs)
3936  expectedTLEs = tles;
3937  return fd;
3938  }
3939  }
3940  }
3941 
3942  /* Couldn't find it. For simplicity, complain about front timeline */
3944  errno = ENOENT;
3945  ereport(emode,
3947  errmsg("could not open file \"%s\": %m", path)));
3948  return -1;
3949 }
3950 
3951 /*
3952  * Close the current logfile segment for writing.
3953  */
3954 static void
3956 {
3957  Assert(openLogFile >= 0);
3958 
3959  /*
3960  * WAL segment files will not be re-read in normal operation, so we advise
3961  * the OS to release any cached pages. But do not do so if WAL archiving
3962  * or streaming is active, because archiver and walsender process could
3963  * use the cache to read the WAL segment.
3964  */
3965 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3966  if (!XLogIsNeeded())
3967  (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3968 #endif
3969 
3970  if (close(openLogFile) != 0)
3971  {
3972  char xlogfname[MAXFNAMELEN];
3973  int save_errno = errno;
3974 
3976  errno = save_errno;
3977  ereport(PANIC,
3979  errmsg("could not close file \"%s\": %m", xlogfname)));
3980  }
3981 
3982  openLogFile = -1;
3984 }
3985 
3986 /*
3987  * Preallocate log files beyond the specified log endpoint.
3988  *
3989  * XXX this is currently extremely conservative, since it forces only one
3990  * future log segment to exist, and even that only if we are 75% done with
3991  * the current one. This is only appropriate for very low-WAL-volume systems.
3992  * High-volume systems will be OK once they've built up a sufficient set of
3993  * recycled log segments, but the startup transient is likely to include
3994  * a lot of segment creations by foreground processes, which is not so good.
3995  *
3996  * XLogFileInitInternal() can ereport(ERROR). All known causes indicate big
3997  * trouble; for example, a full filesystem is one cause. The checkpoint WAL
3998  * and/or ControlFile updates already completed. If a RequestCheckpoint()
3999  * initiated the present checkpoint and an ERROR ends this function, the
4000  * command that called RequestCheckpoint() fails. That's not ideal, but it's
4001  * not worth contorting more functions to use caller-specified elevel values.
4002  * (With or without RequestCheckpoint(), an ERROR forestalls some inessential
4003  * reporting and resource reclamation.)
4004  */
4005 static void
4007 {
4008  XLogSegNo _logSegNo;
4009  int lf;
4010  bool added;
4011  char path[MAXPGPATH];
4012  uint64 offset;
4013 
4015  return; /* unlocked check says no */
4016 
4017  XLByteToPrevSeg(endptr, _logSegNo, wal_segment_size);
4018  offset = XLogSegmentOffset(endptr - 1, wal_segment_size);
4019  if (offset >= (uint32) (0.75 * wal_segment_size))
4020  {
4021  _logSegNo++;
4022  lf = XLogFileInitInternal(_logSegNo, tli, &added, path);
4023  if (lf >= 0)
4024  close(lf);
4025  if (added)
4027  }
4028 }
4029 
4030 /*
4031  * Throws an error if the given log segment has already been removed or
4032  * recycled. The caller should only pass a segment that it knows to have
4033  * existed while the server has been running, as this function always
4034  * succeeds if no WAL segments have been removed since startup.
4035  * 'tli' is only used in the error message.
4036  *
4037  * Note: this function guarantees to keep errno unchanged on return.
4038  * This supports callers that use this to possibly deliver a better
4039  * error message about a missing file, while still being able to throw
4040  * a normal file-access error afterwards, if this does return.
4041  */
4042 void
4044 {
4045  int save_errno = errno;
4046  XLogSegNo lastRemovedSegNo;
4047 
4049  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
4051 
4052  if (segno <= lastRemovedSegNo)
4053  {
4054  char filename[MAXFNAMELEN];
4055 
4056  XLogFileName(filename, tli, segno, wal_segment_size);
4057  errno = save_errno;
4058  ereport(ERROR,
4060  errmsg("requested WAL segment %s has already been removed",
4061  filename)));
4062  }
4063  errno = save_errno;
4064 }
4065 
4066 /*
4067  * Return the last WAL segment removed, or 0 if no segment has been removed
4068  * since startup.
4069  *
4070  * NB: the result can be out of date arbitrarily fast, the caller has to deal
4071  * with that.
4072  */
4073 XLogSegNo
4075 {
4076  XLogSegNo lastRemovedSegNo;
4077 
4079  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
4081 
4082  return lastRemovedSegNo;
4083 }
4084 
4085 
4086 /*
4087  * Update the last removed segno pointer in shared memory, to reflect that the
4088  * given XLOG file has been removed.
4089  */
4090 static void
4092 {
4093  uint32 tli;
4094  XLogSegNo segno;
4095 
4096  XLogFromFileName(filename, &tli, &segno, wal_segment_size);
4097 
4099  if (segno > XLogCtl->lastRemovedSegNo)
4100  XLogCtl->lastRemovedSegNo = segno;
4102 }
4103 
4104 /*
4105  * Remove all temporary log files in pg_wal
4106  *
4107  * This is called at the beginning of recovery after a previous crash,
4108  * at a point where no other processes write fresh WAL data.
4109  */
4110 static void
4112 {
4113  DIR *xldir;
4114  struct dirent *xlde;
4115 
4116  elog(DEBUG2, "removing all temporary WAL segments");
4117 
4118  xldir = AllocateDir(XLOGDIR);
4119  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4120  {
4121  char path[MAXPGPATH];
4122 
4123  if (strncmp(xlde->d_name, "xlogtemp.", 9) != 0)
4124  continue;
4125 
4126  snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
4127  unlink(path);
4128  elog(DEBUG2, "removed temporary WAL segment \"%s\"", path);
4129  }
4130  FreeDir(xldir);
4131 }
4132 
4133 /*
4134  * Recycle or remove all log files older or equal to passed segno.
4135  *
4136  * endptr is current (or recent) end of xlog, and lastredoptr is the
4137  * redo pointer of the last checkpoint. These are used to determine
4138  * whether we want to recycle rather than delete no-longer-wanted log files.
4139  *
4140  * insertTLI is the current timeline for XLOG insertion. Any recycled
4141  * segments should be reused for this timeline.
4142  */
4143 static void
4145  TimeLineID insertTLI)
4146 {
4147  DIR *xldir;
4148  struct dirent *xlde;
4149  char lastoff[MAXFNAMELEN];
4150  XLogSegNo endlogSegNo;
4151  XLogSegNo recycleSegNo;
4152 
4153  /* Initialize info about where to try to recycle to */
4154  XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
4155  recycleSegNo = XLOGfileslop(lastredoptr);
4156 
4157  /*
4158  * Construct a filename of the last segment to be kept. The timeline ID
4159  * doesn't matter, we ignore that in the comparison. (During recovery,
4160  * InsertTimeLineID isn't set, so we can't use that.)
4161  */
4162  XLogFileName(lastoff, 0, segno, wal_segment_size);
4163 
4164  elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
4165  lastoff);
4166 
4167  xldir = AllocateDir(XLOGDIR);
4168 
4169  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4170  {
4171  /* Ignore files that are not XLOG segments */
4172  if (!IsXLogFileName(xlde->d_name) &&
4173  !IsPartialXLogFileName(xlde->d_name))
4174  continue;
4175 
4176  /*
4177  * We ignore the timeline part of the XLOG segment identifiers in
4178  * deciding whether a segment is still needed. This ensures that we
4179  * won't prematurely remove a segment from a parent timeline. We could
4180  * probably be a little more proactive about removing segments of
4181  * non-parent timelines, but that would be a whole lot more
4182  * complicated.
4183  *
4184  * We use the alphanumeric sorting property of the filenames to decide
4185  * which ones are earlier than the lastoff segment.
4186  */
4187  if (strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
4188  {
4189  if (XLogArchiveCheckDone(xlde->d_name))
4190  {
4191  /* Update the last removed location in shared memory first */
4193 
4194  RemoveXlogFile(xlde->d_name, recycleSegNo, &endlogSegNo,
4195  insertTLI);
4196  }
4197  }
4198  }
4199 
4200  FreeDir(xldir);
4201 }
4202 
4203 /*
4204  * Remove WAL files that are not part of the given timeline's history.
4205  *
4206  * This is called during recovery, whenever we switch to follow a new
4207  * timeline, and at the end of recovery when we create a new timeline. We
4208  * wouldn't otherwise care about extra WAL files lying in pg_wal, but they
4209  * might be leftover pre-allocated or recycled WAL segments on the old timeline
4210  * that we haven't used yet, and contain garbage. If we just leave them in
4211  * pg_wal, they will eventually be archived, and we can't let that happen.
4212  * Files that belong to our timeline history are valid, because we have
4213  * successfully replayed them, but from others we can't be sure.
4214  *
4215  * 'switchpoint' is the current point in WAL where we switch to new timeline,
4216  * and 'newTLI' is the new timeline we switch to.
4217  */
4218 static void
4220 {
4221  DIR *xldir;
4222  struct dirent *xlde;
4223  char switchseg[MAXFNAMELEN];
4224  XLogSegNo endLogSegNo;
4225  XLogSegNo switchLogSegNo;
4226  XLogSegNo recycleSegNo;
4227 
4228  /*
4229  * Initialize info about where to begin the work. This will recycle,
4230  * somewhat arbitrarily, 10 future segments.
4231  */
4232  XLByteToPrevSeg(switchpoint, switchLogSegNo, wal_segment_size);
4233  XLByteToSeg(switchpoint, endLogSegNo, wal_segment_size);
4234  recycleSegNo = endLogSegNo + 10;
4235 
4236  /*
4237  * Construct a filename of the last segment to be kept.
4238  */
4239  XLogFileName(switchseg, newTLI, switchLogSegNo, wal_segment_size);
4240 
4241  elog(DEBUG2, "attempting to remove WAL segments newer than log file %s",
4242  switchseg);
4243 
4244  xldir = AllocateDir(XLOGDIR);
4245 
4246  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4247  {
4248  /* Ignore files that are not XLOG segments */
4249  if (!IsXLogFileName(xlde->d_name))
4250  continue;
4251 
4252  /*
4253  * Remove files that are on a timeline older than the new one we're
4254  * switching to, but with a segment number >= the first segment on the
4255  * new timeline.
4256  */
4257  if (strncmp(xlde->d_name, switchseg, 8) < 0 &&
4258  strcmp(xlde->d_name + 8, switchseg + 8) > 0)
4259  {
4260  /*
4261  * If the file has already been marked as .ready, however, don't
4262  * remove it yet. It should be OK to remove it - files that are
4263  * not part of our timeline history are not required for recovery
4264  * - but seems safer to let them be archived and removed later.
4265  */
4266  if (!XLogArchiveIsReady(xlde->d_name))
4267  RemoveXlogFile(xlde->d_name, recycleSegNo, &endLogSegNo,
4268  newTLI);
4269  }
4270  }
4271 
4272  FreeDir(xldir);
4273 }
4274 
4275 /*
4276  * Recycle or remove a log file that's no longer needed.
4277  *
4278  * segname is the name of the segment to recycle or remove. recycleSegNo
4279  * is the segment number to recycle up to. endlogSegNo is the segment
4280  * number of the current (or recent) end of WAL.
4281  *
4282  * endlogSegNo gets incremented if the segment is recycled so as it is not
4283  * checked again with future callers of this function.
4284  *
4285  * insertTLI is the current timeline for XLOG insertion. Any recycled segments
4286  * should be used for this timeline.
4287  */
4288 static void
4289 RemoveXlogFile(const char *segname, XLogSegNo recycleSegNo,
4290  XLogSegNo *endlogSegNo, TimeLineID insertTLI)
4291 {
4292  char path[MAXPGPATH];
4293 #ifdef WIN32
4294  char newpath[MAXPGPATH];
4295 #endif
4296  struct stat statbuf;
4297 
4298  snprintf(path, MAXPGPATH, XLOGDIR "/%s", segname);
4299 
4300  /*
4301  * Before deleting the file, see if it can be recycled as a future log
4302  * segment. Only recycle normal files, because we don't want to recycle
4303  * symbolic links pointing to a separate archive directory.
4304  */
4305  if (wal_recycle &&
4306  *endlogSegNo <= recycleSegNo &&
4307  XLogCtl->InstallXLogFileSegmentActive && /* callee rechecks this */
4308  lstat(path, &statbuf) == 0 && S_ISREG(statbuf.st_mode) &&
4309  InstallXLogFileSegment(endlogSegNo, path,
4310  true, recycleSegNo, insertTLI))
4311  {
4312  ereport(DEBUG2,
4313  (errmsg_internal("recycled write-ahead log file \"%s\"",
4314  segname)));
4316  /* Needn't recheck that slot on future iterations */
4317  (*endlogSegNo)++;
4318  }
4319  else
4320  {
4321  /* No need for any more future segments, or recycling failed ... */
4322  int rc;
4323 
4324  ereport(DEBUG2,
4325  (errmsg_internal("removing write-ahead log file \"%s\"",
4326  segname)));
4327 
4328 #ifdef WIN32
4329 
4330  /*
4331  * On Windows, if another process (e.g another backend) holds the file
4332  * open in FILE_SHARE_DELETE mode, unlink will succeed, but the file
4333  * will still show up in directory listing until the last handle is
4334  * closed. To avoid confusing the lingering deleted file for a live
4335  * WAL file that needs to be archived, rename it before deleting it.
4336  *
4337  * If another process holds the file open without FILE_SHARE_DELETE
4338  * flag, rename will fail. We'll try again at the next checkpoint.
4339  */
4340  snprintf(newpath, MAXPGPATH, "%s.deleted", path);
4341  if (rename(path, newpath) != 0)
4342  {
4343  ereport(LOG,
4345  errmsg("could not rename file \"%s\": %m",
4346  path)));
4347  return;
4348  }
4349  rc = durable_unlink(newpath, LOG);
4350 #else
4351  rc = durable_unlink(path, LOG);
4352 #endif
4353  if (rc != 0)
4354  {
4355  /* Message already logged by durable_unlink() */
4356  return;
4357  }
4359  }
4360 
4361  XLogArchiveCleanup(segname);
4362 }
4363 
4364 /*
4365  * Verify whether pg_wal and pg_wal/archive_status exist.
4366  * If the latter does not exist, recreate it.
4367  *
4368  * It is not the goal of this function to verify the contents of these
4369  * directories, but to help in cases where someone has performed a cluster
4370  * copy for PITR purposes but omitted pg_wal from the copy.
4371  *
4372  * We could also recreate pg_wal if it doesn't exist, but a deliberate
4373  * policy decision was made not to. It is fairly common for pg_wal to be
4374  * a symlink, and if that was the DBA's intent then automatically making a
4375  * plain directory would result in degraded performance with no notice.
4376  */
4377 static void
4379 {
4380  char path[MAXPGPATH];
4381  struct stat stat_buf;
4382 
4383  /* Check for pg_wal; if it doesn't exist, error out */
4384  if (stat(XLOGDIR, &stat_buf) != 0 ||
4385  !S_ISDIR(stat_buf.st_mode))
4386  ereport(FATAL,
4387  (errmsg("required WAL directory \"%s\" does not exist",
4388  XLOGDIR)));
4389 
4390  /* Check for archive_status */
4391  snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
4392  if (stat(path, &stat_buf) == 0)
4393  {
4394  /* Check for weird cases where it exists but isn't a directory */
4395  if (!S_ISDIR(stat_buf.st_mode))
4396  ereport(FATAL,
4397  (errmsg("required WAL directory \"%s\" does not exist",
4398  path)));
4399  }
4400  else
4401  {
4402  ereport(LOG,
4403  (errmsg("creating missing WAL directory \"%s\"", path)));
4404  if (MakePGDirectory(path) < 0)
4405  ereport(FATAL,
4406  (errmsg("could not create missing directory \"%s\": %m",
4407  path)));
4408  }
4409 }
4410 
4411 /*
4412  * Remove previous backup history files. This also retries creation of
4413  * .ready files for any backup history files for which XLogArchiveNotify
4414  * failed earlier.
4415  */
4416 static void
4418 {
4419  DIR *xldir;
4420  struct dirent *xlde;
4421  char path[MAXPGPATH + sizeof(XLOGDIR)];
4422 
4423  xldir = AllocateDir(XLOGDIR);
4424 
4425  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4426  {
4427  if (IsBackupHistoryFileName(xlde->d_name))
4428  {
4429  if (XLogArchiveCheckDone(xlde->d_name))
4430  {
4431  elog(DEBUG2, "removing WAL backup history file \"%s\"",
4432  xlde->d_name);
4433  snprintf(path, sizeof(path), XLOGDIR "/%s", xlde->d_name);
4434  unlink(path);
4435  XLogArchiveCleanup(xlde->d_name);
4436  }
4437  }
4438  }
4439 
4440  FreeDir(xldir);
4441 }
4442 
4443 /*
4444  * Attempt to read the next XLOG record.
4445  *
4446  * Before first call, the reader needs to be positioned to the first record
4447  * by calling XLogBeginRead().
4448  *
4449  * If no valid record is available, returns NULL, or fails if emode is PANIC.
4450  * (emode must be either PANIC, LOG). In standby mode, retries until a valid
4451  * record is available.
4452  */
4453 static XLogRecord *
4455  bool fetching_ckpt, TimeLineID replayTLI)
4456 {
4457  XLogRecord *record;
4459 
4460  /* Pass through parameters to XLogPageRead */
4461  private->fetching_ckpt = fetching_ckpt;
4462  private->emode = emode;
4463  private->randAccess = (xlogreader->ReadRecPtr == InvalidXLogRecPtr);
4464  private->replayTLI = replayTLI;
4465 
4466  /* This is the first attempt to read this page. */
4467  lastSourceFailed = false;
4468 
4469  for (;;)
4470  {
4471  char *errormsg;
4472 
4473  record = XLogReadRecord(xlogreader, &errormsg);
4474  if (record == NULL)
4475  {
4476  /*
4477  * When not in standby mode we find that WAL ends in an incomplete
4478  * record, keep track of that record. After recovery is done,
4479  * we'll write a record to indicate downstream WAL readers that
4480  * that portion is to be ignored.
4481  */
4482  if (!StandbyMode &&
4484  {
4487  }
4488 
4489  if (readFile >= 0)
4490  {
4491  close(readFile);
4492  readFile = -1;
4493  }
4494 
4495  /*
4496  * We only end up here without a message when XLogPageRead()
4497  * failed - in that case we already logged something. In
4498  * StandbyMode that only happens if we have been triggered, so we
4499  * shouldn't loop anymore in that case.
4500  */
4501  if (errormsg)
4503  (errmsg_internal("%s", errormsg) /* already translated */ ));
4504  }
4505 
4506  /*
4507  * Check page TLI is one of the expected values.
4508  */
4510  {
4511  char fname[MAXFNAMELEN];
4512  XLogSegNo segno;
4513  int32 offset;
4514 
4518  XLogFileName(fname, xlogreader->seg.ws_tli, segno,
4521  (errmsg("unexpected timeline ID %u in log segment %s, offset %u",
4523  fname,
4524  offset)));
4525  record = NULL;
4526  }
4527 
4528  if (record)
4529  {
4530  /* Great, got a record */
4531  return record;
4532  }
4533  else
4534  {
4535  /* No valid record available from this source */
4536  lastSourceFailed = true;
4537 
4538  /*
4539  * If archive recovery was requested, but we were still doing
4540  * crash recovery, switch to archive recovery and retry using the
4541  * offline archive. We have now replayed all the valid WAL in
4542  * pg_wal, so we are presumably now consistent.
4543  *
4544  * We require that there's at least some valid WAL present in
4545  * pg_wal, however (!fetching_ckpt). We could recover using the
4546  * WAL from the archive, even if pg_wal is completely empty, but
4547  * we'd have no idea how far we'd have to replay to reach
4548  * consistency. So err on the safe side and give up.
4549  */
4551  !fetching_ckpt)
4552  {
4553  ereport(DEBUG1,
4554  (errmsg_internal("reached end of WAL in pg_wal, entering archive recovery")));
4555  InArchiveRecovery = true;
4557  StandbyMode = true;
4558 
4559  /* initialize minRecoveryPoint to this record */
4560  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
4563  {
4565  ControlFile->minRecoveryPointTLI = replayTLI;
4566  }
4567  /* update local copy */
4570 
4571  /*
4572  * The startup process can update its local copy of
4573  * minRecoveryPoint from this point.
4574  */
4575  updateMinRecoveryPoint = true;
4576 
4578 
4579  /*
4580  * We update SharedRecoveryState while holding the lock on
4581  * ControlFileLock so both states are consistent in shared
4582  * memory.
4583  */
4587 
4588  LWLockRelease(ControlFileLock);
4589 
4591 
4592  /*
4593  * Before we retry, reset lastSourceFailed and currentSource
4594  * so that we will check the archive next.
4595  */
4596  lastSourceFailed = false;
4598 
4599  continue;
4600  }
4601 
4602  /* In standby mode, loop back to retry. Otherwise, give up. */
4604  continue;
4605  else
4606  return NULL;
4607  }
4608  }
4609 }
4610 
4611 /*
4612  * Scan for new timelines that might have appeared in the archive since we
4613  * started recovery.
4614  *
4615  * If there are any, the function changes recovery target TLI to the latest
4616  * one and returns 'true'.
4617  */
4618 static bool
4620 {
4621  List *newExpectedTLEs;
4622  bool found;
4623  ListCell *cell;
4624  TimeLineID newtarget;
4625  TimeLineID oldtarget = recoveryTargetTLI;
4626  TimeLineHistoryEntry *currentTle = NULL;
4627 
4629  if (newtarget == recoveryTargetTLI)
4630  {
4631  /* No new timelines found */
4632  return false;
4633  }
4634 
4635  /*
4636  * Determine the list of expected TLIs for the new TLI
4637  */
4638 
4639  newExpectedTLEs = readTimeLineHistory(newtarget);
4640 
4641  /*
4642  * If the current timeline is not part of the history of the new timeline,
4643  * we cannot proceed to it.
4644  */
4645  found = false;
4646  foreach(cell, newExpectedTLEs)
4647  {
4648  currentTle = (TimeLineHistoryEntry *) lfirst(cell);
4649 
4650  if (currentTle->tli == recoveryTargetTLI)
4651  {
4652  found = true;
4653  break;
4654  }
4655  }
4656  if (!found)
4657  {
4658  ereport(LOG,
4659  (errmsg("new timeline %u is not a child of database system timeline %u",
4660  newtarget,
4661  replayTLI)));
4662  return false;
4663  }
4664 
4665  /*
4666  * The current timeline was found in the history file, but check that the
4667  * next timeline was forked off from it *after* the current recovery
4668  * location.
4669  */
4670  if (currentTle->end < replayLSN)
4671  {
4672  ereport(LOG,
4673  (errmsg("new timeline %u forked off current database system timeline %u before current recovery point %X/%X",
4674  newtarget,
4675  replayTLI,
4676  LSN_FORMAT_ARGS(replayLSN))));
4677  return false;
4678  }
4679 
4680  /* The new timeline history seems valid. Switch target */
4681  recoveryTargetTLI = newtarget;
4683  expectedTLEs = newExpectedTLEs;
4684 
4685  /*
4686  * As in StartupXLOG(), try to ensure we have all the history files
4687  * between the old target and new target in pg_wal.
4688  */
4689  restoreTimeLineHistoryFiles(oldtarget + 1, newtarget);
4690 
4691  ereport(LOG,
4692  (errmsg("new target timeline is %u",
4693  recoveryTargetTLI)));
4694 
4695  return true;
4696 }
4697 
4698 /*
4699  * I/O routines for pg_control
4700  *
4701  * *ControlFile is a buffer in shared memory that holds an image of the
4702  * contents of pg_control. WriteControlFile() initializes pg_control
4703  * given a preloaded buffer, ReadControlFile() loads the buffer from
4704  * the pg_control file (during postmaster or standalone-backend startup),
4705  * and UpdateControlFile() rewrites pg_control after we modify xlog state.
4706  * InitControlFile() fills the buffer with initial values.
4707  *
4708  * For simplicity, WriteControlFile() initializes the fields of pg_control
4709  * that are related to checking backend/database compatibility, and
4710  * ReadControlFile() verifies they are correct. We could split out the
4711  * I/O and compatibility-check functions, but there seems no need currently.
4712  */
4713 
4714 static void
4715 InitControlFile(uint64 sysidentifier)
4716 {
4717  char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
4718 
4719  /*
4720  * Generate a random nonce. This is used for authentication requests that
4721  * will fail because the user does not exist. The nonce is used to create
4722  * a genuine-looking password challenge for the non-existent user, in lieu
4723  * of an actual stored password.
4724  */
4725  if (!pg_strong_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
4726  ereport(PANIC,
4727  (errcode(ERRCODE_INTERNAL_ERROR),
4728  errmsg("could not generate secret authorization token")));
4729 
4730  memset(ControlFile, 0, sizeof(ControlFileData));
4731  /* Initialize pg_control status fields */
4732  ControlFile->system_identifier = sysidentifier;
4733  memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
4736 
4737  /* Set important parameter values for use when replaying WAL */
4747 }
4748 
4749 static void
4751 {
4752  int fd;
4753  char buffer[PG_CONTROL_FILE_SIZE]; /* need not be aligned */
4754 
4755  /*
4756  * Ensure that the size of the pg_control data structure is sane. See the
4757  * comments for these symbols in pg_control.h.
4758  */
4760  "pg_control is too large for atomic disk writes");
4762  "sizeof(ControlFileData) exceeds PG_CONTROL_FILE_SIZE");
4763 
4764  /*
4765  * Initialize version and compatibility-check fields
4766  */
4769 
4770  ControlFile->maxAlign = MAXIMUM_ALIGNOF;
4772 
4773  ControlFile->blcksz = BLCKSZ;
4774  ControlFile->relseg_size = RELSEG_SIZE;
4775  ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4777 
4780 
4783 
4785 
4786  /* Contents are protected with a CRC */
4789  (char *) ControlFile,
4792 
4793  /*
4794  * We write out PG_CONTROL_FILE_SIZE bytes into pg_control, zero-padding
4795  * the excess over sizeof(ControlFileData). This reduces the odds of
4796  * premature-EOF errors when reading pg_control. We'll still fail when we
4797  * check the contents of the file, but hopefully with a more specific
4798  * error than "couldn't read pg_control".
4799  */
4800  memset(buffer, 0, PG_CONTROL_FILE_SIZE);
4801  memcpy(buffer, ControlFile, sizeof(ControlFileData));
4802 
4804  O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
4805  if (fd < 0)
4806  ereport(PANIC,
4808  errmsg("could not create file \"%s\": %m",
4809  XLOG_CONTROL_FILE)));
4810 
4811  errno = 0;
4814  {
4815  /* if write didn't set errno, assume problem is no disk space */
4816  if (errno == 0)
4817  errno = ENOSPC;
4818  ereport(PANIC,
4820  errmsg("could not write to file \"%s\": %m",
4821  XLOG_CONTROL_FILE)));
4822  }
4824 
4826  if (pg_fsync(fd) != 0)
4827  ereport(PANIC,
4829  errmsg("could not fsync file \"%s\": %m",
4830  XLOG_CONTROL_FILE)));
4832 
4833  if (close(fd) != 0)
4834  ereport(PANIC,
4836  errmsg("could not close file \"%s\": %m",
4837  XLOG_CONTROL_FILE)));
4838 }
4839 
4840 static void
4842 {
4843  pg_crc32c crc;
4844  int fd;
4845  static char wal_segsz_str[20];
4846  int r;
4847 
4848  /*
4849  * Read data...
4850  */
4852  O_RDWR | PG_BINARY);
4853  if (fd < 0)
4854  ereport(PANIC,
4856  errmsg("could not open file \"%s\": %m",
4857  XLOG_CONTROL_FILE)));
4858 
4860  r = read(fd, ControlFile, sizeof(ControlFileData));
4861  if (r != sizeof(ControlFileData))
4862  {
4863  if (r < 0)
4864  ereport(PANIC,
4866  errmsg("could not read file \"%s\": %m",
4867  XLOG_CONTROL_FILE)));
4868  else
4869  ereport(PANIC,
4871  errmsg("could not read file \"%s\": read %d of %zu",
4872  XLOG_CONTROL_FILE, r, sizeof(ControlFileData))));
4873  }
4875 
4876  close(fd);
4877 
4878  /*
4879  * Check for expected pg_control format version. If this is wrong, the
4880  * CRC check will likely fail because we'll be checking the wrong number
4881  * of bytes. Complaining about wrong version will probably be more
4882  * enlightening than complaining about wrong CRC.
4883  */
4884 
4886  ereport(FATAL,
4887  (errmsg("database files are incompatible with server"),
4888  errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4889  " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4892  errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4893 
4895  ereport(FATAL,
4896  (errmsg("database files are incompatible with server"),
4897  errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4898  " but the server was compiled with PG_CONTROL_VERSION %d.",
4900  errhint("It looks like you need to initdb.")));
4901 
4902  /* Now check the CRC. */
4903  INIT_CRC32C(crc);
4904  COMP_CRC32C(crc,
4905  (char *) ControlFile,
4907  FIN_CRC32C(crc);
4908 
4909  if (!EQ_CRC32C(crc, ControlFile->crc))
4910  ereport(FATAL,
4911  (errmsg("incorrect checksum in control file")));
4912 
4913  /*
4914  * Do compatibility checking immediately. If the database isn't
4915  * compatible with the backend executable, we want to abort before we can
4916  * possibly do any damage.
4917  */
4919  ereport(FATAL,
4920  (errmsg("database files are incompatible with server"),
4921  errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
4922  " but the server was compiled with CATALOG_VERSION_NO %d.",
4924  errhint("It looks like you need to initdb.")));
4925  if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4926  ereport(FATAL,
4927  (errmsg("database files are incompatible with server"),
4928  errdetail("The database cluster was initialized with MAXALIGN %d,"
4929  " but the server was compiled with MAXALIGN %d.",
4930  ControlFile->maxAlign, MAXIMUM_ALIGNOF),
4931  errhint("It looks like you need to initdb.")));
4933  ereport(FATAL,
4934  (errmsg("database files are incompatible with server"),
4935  errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4936  errhint("It looks like you need to initdb.")));
4937  if (ControlFile->blcksz != BLCKSZ)
4938  ereport(FATAL,
4939  (errmsg("database files are incompatible with server"),
4940  errdetail("The database cluster was initialized with BLCKSZ %d,"
4941  " but the server was compiled with BLCKSZ %d.",
4942  ControlFile->blcksz, BLCKSZ),
4943  errhint("It looks like you need to recompile or initdb.")));
4944  if (ControlFile->relseg_size != RELSEG_SIZE)
4945  ereport(FATAL,
4946  (errmsg("database files are incompatible with server"),
4947  errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
4948  " but the server was compiled with RELSEG_SIZE %d.",
4949  ControlFile->relseg_size, RELSEG_SIZE),
4950  errhint("It looks like you need to recompile or initdb.")));
4951  if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4952  ereport(FATAL,
4953  (errmsg("database files are incompatible with server"),
4954  errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
4955  " but the server was compiled with XLOG_BLCKSZ %d.",
4956  ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4957  errhint("It looks like you need to recompile or initdb.")));
4959  ereport(FATAL,
4960  (errmsg("database files are incompatible with server"),
4961  errdetail("The database cluster was initialized with NAMEDATALEN %d,"
4962  " but the server was compiled with NAMEDATALEN %d.",
4964  errhint("It looks like you need to recompile or initdb.")));
4966  ereport(FATAL,
4967  (errmsg("database files are incompatible with server"),
4968  errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
4969  " but the server was compiled with INDEX_MAX_KEYS %d.",
4971  errhint("It looks like you need to recompile or initdb.")));
4973  ereport(FATAL,
4974  (errmsg("database files are incompatible with server"),
4975  errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
4976  " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
4978  errhint("It looks like you need to recompile or initdb.")));
4980  ereport(FATAL,
4981  (errmsg("database files are incompatible with server"),
4982  errdetail("The database cluster was initialized with LOBLKSIZE %d,"
4983  " but the server was compiled with LOBLKSIZE %d.",
4984  ControlFile->loblksize, (int) LOBLKSIZE),
4985  errhint("It looks like you need to recompile or initdb.")));
4986 
4987 #ifdef USE_FLOAT8_BYVAL
4988  if (ControlFile->float8ByVal != true)
4989  ereport(FATAL,
4990  (errmsg("database files are incompatible with server"),
4991  errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4992  " but the server was compiled with USE_FLOAT8_BYVAL."),
4993  errhint("It looks like you need to recompile or initdb.")));
4994 #else
4995  if (ControlFile->float8ByVal != false)
4996  ereport(FATAL,
4997  (errmsg("database files are incompatible with server"),
4998  errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4999  " but the server was compiled without USE_FLOAT8_BYVAL."),
5000  errhint("It looks like you need to recompile or initdb.")));
5001 #endif
5002 
5004 
5006  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5007  errmsg_plural("WAL segment size must be a power of two between 1 MB and 1 GB, but the control file specifies %d byte",
5008  "WAL segment size must be a power of two between 1 MB and 1 GB, but the control file specifies %d bytes",
5010  wal_segment_size)));
5011 
5012  snprintf(wal_segsz_str, sizeof(wal_segsz_str), "%d", wal_segment_size);
5013  SetConfigOption("wal_segment_size", wal_segsz_str, PGC_INTERNAL,
5014  PGC_S_OVERRIDE);
5015 
5016  /* check and update variables dependent on wal_segment_size */
5018  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5019  errmsg("\"min_wal_size\" must be at least twice \"wal_segment_size\"")));
5020 
5022  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5023  errmsg("\"max_wal_size\" must be at least twice \"wal_segment_size\"")));
5024 
5026  (wal_segment_size / XLOG_BLCKSZ * UsableBytesInPage) -
5028 
5030 
5031  /* Make the initdb settings visible as GUC variables, too */
5032  SetConfigOption("data_checksums", DataChecksumsEnabled() ? "yes" : "no",
5034 }
5035 
5036 /*
5037  * Utility wrapper to update the control file. Note that the control
5038  * file gets flushed.
5039  */
5040 void
5042 {
5044 }
5045 
5046 /*
5047  * Returns the unique system identifier from control file.
5048  */
5049 uint64
5051 {
5052  Assert(ControlFile != NULL);
5054 }
5055 
5056 /*
5057  * Returns the random nonce from control file.
5058  */
5059 char *
5061 {
5062  Assert(ControlFile != NULL);
5064 }
5065 
5066 /*
5067  * Are checksums enabled for data pages?
5068  */
5069 bool
5071 {
5072  Assert(ControlFile != NULL);
5073  return (ControlFile->data_checksum_version > 0);
5074 }
5075 
5076 /*
5077  * Returns a fake LSN for unlogged relations.
5078  *
5079  * Each call generates an LSN that is greater than any previous value
5080  * returned. The current counter value is saved and restored across clean
5081  * shutdowns, but like unlogged relations, does not survive a crash. This can
5082  * be used in lieu of real LSN values returned by XLogInsert, if you need an
5083  * LSN-like increasing sequence of numbers without writing any WAL.
5084  */
5085 XLogRecPtr
5087 {
5088  XLogRecPtr nextUnloggedLSN;
5089 
5090  /* increment the unloggedLSN counter, need SpinLock */
5092  nextUnloggedLSN = XLogCtl->unloggedLSN++;
5094 
5095  return nextUnloggedLSN;
5096 }
5097 
5098 /*
5099  * Auto-tune the number of XLOG buffers.
5100  *
5101  * The preferred setting for wal_buffers is about 3% of shared_buffers, with
5102  * a maximum of one XLOG segment (there is little reason to think that more
5103  * is helpful, at least so long as we force an fsync when switching log files)
5104  * and a minimum of 8 blocks (which was the default value prior to PostgreSQL
5105  * 9.1, when auto-tuning was added).
5106  *
5107  * This should not be called until NBuffers has received its final value.
5108  */
5109 static int
5111 {
5112  int xbuffers;
5113 
5114  xbuffers = NBuffers / 32;
5115  if (xbuffers > (wal_segment_size / XLOG_BLCKSZ))
5116  xbuffers = (wal_segment_size / XLOG_BLCKSZ);
5117  if (xbuffers < 8)
5118  xbuffers = 8;
5119  return xbuffers;
5120 }
5121 
5122 /*
5123  * GUC check_hook for wal_buffers
5124  */
5125 bool
5127 {
5128  /*
5129  * -1 indicates a request for auto-tune.
5130  */
5131  if (*newval == -1)
5132  {
5133  /*
5134  * If we haven't yet changed the boot_val default of -1, just let it
5135  * be. We'll fix it when XLOGShmemSize is called.
5136  */
5137  if (XLOGbuffers == -1)
5138  return true;
5139 
5140  /* Otherwise, substitute the auto-tune value */
5142  }
5143 
5144  /*
5145  * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
5146  * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
5147  * the case, we just silently treat such values as a request for the
5148  * minimum. (We could throw an error instead, but that doesn't seem very
5149  * helpful.)
5150  */
5151  if (*newval < 4)
5152  *newval = 4;
5153 
5154  return true;
5155 }
5156 
5157 /*
5158  * Read the control file, set respective GUCs.
5159  *
5160  * This is to be called during startup, including a crash recovery cycle,
5161  * unless in bootstrap mode, where no control file yet exists. As there's no
5162  * usable shared memory yet (its sizing can depend on the contents of the
5163  * control file!), first store the contents in local memory. XLOGShmemInit()
5164  * will then copy it to shared memory later.
5165  *
5166  * reset just controls whether previous contents are to be expected (in the
5167  * reset case, there's a dangling pointer into old shared memory), or not.
5168  */
5169 void
5171 {
5172  Assert(reset || ControlFile == NULL);
5173  ControlFile = palloc(sizeof(ControlFileData));
5174  ReadControlFile();
5175 }
5176 
5177 /*
5178  * Initialization of shared memory for XLOG
5179  */
5180 Size
5182 {
5183  Size size;
5184 
5185  /*
5186  * If the value of wal_buffers is -1, use the preferred auto-tune value.
5187  * This isn't an amazingly clean place to do this, but we must wait till
5188  * NBuffers has received its final value, and must do it before using the
5189  * value of XLOGbuffers to do anything important.
5190  */
5191  if (XLOGbuffers == -1)
5192  {
5193  char buf[32];
5194 
5195  snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
5197  }
5198  Assert(XLOGbuffers > 0);
5199 
5200  /* XLogCtl */
5201  size = sizeof(XLogCtlData);
5202 
5203  /* WAL insertion locks, plus alignment */
5204  size = add_size(size, mul_size(sizeof(WALInsertLockPadded), NUM_XLOGINSERT_LOCKS + 1));
5205  /* xlblocks array */
5206  size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
5207  /* extra alignment padding for XLOG I/O buffers */
5208  size = add_size(size, XLOG_BLCKSZ);
5209  /* and the buffers themselves */
5210  size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
5211 
5212  /*
5213  * Note: we don't count ControlFileData, it comes out of the "slop factor"
5214  * added by CreateSharedMemoryAndSemaphores. This lets us use this
5215  * routine again below to compute the actual allocation size.
5216  */
5217 
5218  return size;
5219 }
5220 
5221 void
5223 {
5224  bool foundCFile,
5225  foundXLog;
5226  char *allocptr;
5227  int i;
5228  ControlFileData *localControlFile;
5229 
5230 #ifdef WAL_DEBUG
5231 
5232  /*
5233  * Create a memory context for WAL debugging that's exempt from the normal
5234  * "no pallocs in critical section" rule. Yes, that can lead to a PANIC if
5235  * an allocation fails, but wal_debug is not for production use anyway.
5236  */
5237  if (walDebugCxt == NULL)
5238  {
5240  "WAL Debug",
5242  MemoryContextAllowInCriticalSection(walDebugCxt, true);
5243  }
5244 #endif
5245 
5246 
5247  XLogCtl = (XLogCtlData *)
5248  ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
5249 
5250  localControlFile = ControlFile;
5252  ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
5253 
5254  if (foundCFile || foundXLog)
5255  {
5256  /* both should be present or neither */
5257  Assert(foundCFile && foundXLog);
5258 
5259  /* Initialize local copy of WALInsertLocks */
5261 
5262  if (localControlFile)
5263  pfree(localControlFile);
5264  return;
5265  }
5266  memset(XLogCtl, 0, sizeof(XLogCtlData));
5267 
5268  /*
5269  * Already have read control file locally, unless in bootstrap mode. Move
5270  * contents into shared memory.
5271  */
5272  if (localControlFile)
5273  {
5274  memcpy(ControlFile, localControlFile, sizeof(ControlFileData));
5275  pfree(localControlFile);
5276  }
5277 
5278  /*
5279  * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
5280  * multiple of the alignment for same, so no extra alignment padding is
5281  * needed here.
5282  */
5283  allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
5284  XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
5285  memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
5286  allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
5287 
5288 
5289  /* WAL insertion locks. Ensure they're aligned to the full padded size */
5290  allocptr += sizeof(WALInsertLockPadded) -
5291  ((uintptr_t) allocptr) % sizeof(WALInsertLockPadded);
5293  (WALInsertLockPadded *) allocptr;
5294  allocptr += sizeof(WALInsertLockPadded) * NUM_XLOGINSERT_LOCKS;
5295 
5296  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
5297  {
5301  }
5302 
5303  /*
5304  * Align the start of the page buffers to a full xlog block size boundary.
5305  * This simplifies some calculations in XLOG insertion. It is also
5306  * required for O_DIRECT.
5307  */
5308  allocptr = (char *) TYPEALIGN(XLOG_BLCKSZ, allocptr);
5309  XLogCtl->pages = allocptr;
5310  memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
5311 
5312  /*
5313  * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
5314  * in additional info.)
5315  */
5321  XLogCtl->WalWriterSleeping = false;
5322 
5328 }
5329 
5330 /*
5331  * This func must be called ONCE on system install. It creates pg_control
5332  * and the initial XLOG segment.
5333  */
5334 void
5336 {
5337  CheckPoint checkPoint;
5338  char *buffer;
5339  XLogPageHeader page;
5340  XLogLongPageHeader longpage;
5341  XLogRecord *record;
5342  char *recptr;
5343  uint64 sysidentifier;
5344  struct timeval tv;
5345  pg_crc32c crc;
5346 
5347  /* allow ordinary WAL segment creation, like StartupXLOG() would */
5348  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5350  LWLockRelease(ControlFileLock);
5351 
5352  /*
5353  * Select a hopefully-unique system identifier code for this installation.
5354  * We use the result of gettimeofday(), including the fractional seconds
5355  * field, as being about as unique as we can easily get. (Think not to
5356  * use random(), since it hasn't been seeded and there's no portable way
5357  * to seed it other than the system clock value...) The upper half of the
5358  * uint64 value is just the tv_sec part, while the lower half contains the
5359  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5360  * PID for a little extra uniqueness. A person knowing this encoding can
5361  * determine the initialization time of the installation, which could
5362  * perhaps be useful sometimes.
5363  */
5364  gettimeofday(&tv, NULL);
5365  sysidentifier = ((uint64) tv.tv_sec) << 32;
5366  sysidentifier |= ((uint64) tv.tv_usec) << 12;
5367  sysidentifier |= getpid() & 0xFFF;
5368 
5369  /* page buffer must be aligned suitably for O_DIRECT */
5370  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5371  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5372  memset(page, 0, XLOG_BLCKSZ);
5373 
5374  /*
5375  * Set up information for the initial checkpoint record
5376  *
5377  * The initial checkpoint record is written to the beginning of the WAL
5378  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5379  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5380  */
5381  checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5382  checkPoint.ThisTimeLineID = BootstrapTimeLineID;
5383  checkPoint.PrevTimeLineID = BootstrapTimeLineID;
5384  checkPoint.fullPageWrites = fullPageWrites;
5385  checkPoint.nextXid =
5387  checkPoint.nextOid = FirstGenbkiObjectId;
5388  checkPoint.nextMulti = FirstMultiXactId;
5389  checkPoint.nextMultiOffset = 0;
5390  checkPoint.oldestXid = FirstNormalTransactionId;
5391  checkPoint.oldestXidDB = TemplateDbOid;
5392  checkPoint.oldestMulti = FirstMultiXactId;
5393  checkPoint.oldestMultiDB = TemplateDbOid;
5396  checkPoint.time = (pg_time_t) time(NULL);
5398 
5399  ShmemVariableCache->nextXid = checkPoint.nextXid;
5400  ShmemVariableCache->nextOid = checkPoint.nextOid;
5402  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5403  AdvanceOldestClogXid(checkPoint.oldestXid);
5404  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5405  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5407 
5408  /* Set up the XLOG page header */
5409  page->xlp_magic = XLOG_PAGE_MAGIC;
5410  page->xlp_info = XLP_LONG_HEADER;
5411  page->xlp_tli = BootstrapTimeLineID;
5413  longpage = (XLogLongPageHeader) page;
5414  longpage->xlp_sysid = sysidentifier;
5415  longpage->xlp_seg_size = wal_segment_size;
5416  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5417 
5418  /* Insert the initial checkpoint record */
5419  recptr = ((char *) page + SizeOfXLogLongPHD);
5420  record = (XLogRecord *) recptr;
5421  record->xl_prev = 0;
5422  record->xl_xid = InvalidTransactionId;
5423  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5425  record->xl_rmid = RM_XLOG_ID;
5426  recptr += SizeOfXLogRecord;
5427  /* fill the XLogRecordDataHeaderShort struct */
5428  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5429  *(recptr++) = sizeof(checkPoint);
5430  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5431  recptr += sizeof(checkPoint);
5432  Assert(recptr - (char *) record == record->xl_tot_len);
5433 
5434  INIT_CRC32C(crc);
5435  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5436  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5437  FIN_CRC32C(crc);
5438  record->xl_crc = crc;
5439 
5440  /* Create first XLOG segment file */
5443 
5444  /*
5445  * We needn't bother with Reserve/ReleaseExternalFD here, since we'll
5446  * close the file again in a moment.
5447  */
5448 
5449  /* Write the first page with the initial record */
5450  errno = 0;
5452  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5453  {
5454  /* if write didn't set errno, assume problem is no disk space */
5455  if (errno == 0)
5456  errno = ENOSPC;
5457  ereport(PANIC,
5459  errmsg("could not write bootstrap write-ahead log file: %m")));
5460  }
5462 
5464  if (pg_fsync(openLogFile) != 0)
5465  ereport(PANIC,
5467  errmsg("could not fsync bootstrap write-ahead log file: %m")));
5469 
5470  if (close(openLogFile) != 0)
5471  ereport(PANIC,
5473  errmsg("could not close bootstrap write-ahead log file: %m")));
5474 
5475  openLogFile = -1;
5476 
5477  /* Now create pg_control */
5478  InitControlFile(sysidentifier);
5479  ControlFile->time = checkPoint.time;
5480  ControlFile->checkPoint = checkPoint.redo;
5481  ControlFile->checkPointCopy = checkPoint;
5482 
5483  /* some additional ControlFile fields are set in WriteControlFile() */
5484  WriteControlFile();
5485 
5486  /* Bootstrap the commit log, too */
5487  BootStrapCLOG();
5491 
5492  pfree(buffer);
5493 
5494  /*
5495  * Force control file to be read - in contrast to normal processing we'd
5496  * otherwise never run the checks and GUC related initializations therein.
5497  */
5498  ReadControlFile();
5499 }
5500 
5501 static char *
5503 {
5504  static char buf[128];
5505 
5506  pg_strftime(buf, sizeof(buf),
5507  "%Y-%m-%d %H:%M:%S %Z",
5508  pg_localtime(&tnow, log_timezone));
5509 
5510  return buf;
5511 }
5512 
5513 /*
5514  * See if there are any recovery signal files and if so, set state for
5515  * recovery.
5516  *
5517  * See if there is a recovery command file (recovery.conf), and if so
5518  * throw an ERROR since as of PG12 we no longer recognize that.
5519  */
5520 static void
5522 {
5523  struct stat stat_buf;
5524 
5526