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