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