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