PostgreSQL Source Code  git master
xlog.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * xlog.c
4  * PostgreSQL write-ahead log manager
5  *
6  *
7  * Portions Copyright (c) 1996-2018, 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 that space, but we need to actually fill it.
1538  */
1539  if (isLogSwitch && XLogSegmentOffset(CurrPos, wal_segment_size) != 0)
1540  {
1541  /* An xlog-switch record doesn't contain any data besides the header */
1542  Assert(write_len == SizeOfXLogRecord);
1543 
1544  /* Assert that we did reserve the right amount of space */
1545  Assert(XLogSegmentOffset(EndPos, wal_segment_size) == 0);
1546 
1547  /* Use up all the remaining space on the current page */
1548  CurrPos += freespace;
1549 
1550  /*
1551  * Cause all remaining pages in the segment to be flushed, leaving the
1552  * XLog position where it should be, at the start of the next segment.
1553  * We do this one page at a time, to make sure we don't deadlock
1554  * against ourselves if wal_buffers < wal_segment_size.
1555  */
1556  while (CurrPos < EndPos)
1557  {
1558  /*
1559  * The minimal action to flush the page would be to call
1560  * WALInsertLockUpdateInsertingAt(CurrPos) followed by
1561  * AdvanceXLInsertBuffer(...). The page would be left initialized
1562  * mostly to zeros, except for the page header (always the short
1563  * variant, as this is never a segment's first page).
1564  *
1565  * The large vistas of zeros are good for compressibility, but the
1566  * headers interrupting them every XLOG_BLCKSZ (with values that
1567  * differ from page to page) are not. The effect varies with
1568  * compression tool, but bzip2 for instance compresses about an
1569  * order of magnitude worse if those headers are left in place.
1570  *
1571  * Rather than complicating AdvanceXLInsertBuffer itself (which is
1572  * called in heavily-loaded circumstances as well as this lightly-
1573  * loaded one) with variant behavior, we just use GetXLogBuffer
1574  * (which itself calls the two methods we need) to get the pointer
1575  * and zero most of the page. Then we just zero the page header.
1576  */
1577  currpos = GetXLogBuffer(CurrPos);
1578  MemSet(currpos, 0, SizeOfXLogShortPHD);
1579 
1580  CurrPos += XLOG_BLCKSZ;
1581  }
1582  }
1583  else
1584  {
1585  /* Align the end position, so that the next record starts aligned */
1586  CurrPos = MAXALIGN64(CurrPos);
1587  }
1588 
1589  if (CurrPos != EndPos)
1590  elog(PANIC, "space reserved for WAL record does not match what was written");
1591 }
1592 
1593 /*
1594  * Acquire a WAL insertion lock, for inserting to WAL.
1595  */
1596 static void
1598 {
1599  bool immed;
1600 
1601  /*
1602  * It doesn't matter which of the WAL insertion locks we acquire, so try
1603  * the one we used last time. If the system isn't particularly busy, it's
1604  * a good bet that it's still available, and it's good to have some
1605  * affinity to a particular lock so that you don't unnecessarily bounce
1606  * cache lines between processes when there's no contention.
1607  *
1608  * If this is the first time through in this backend, pick a lock
1609  * (semi-)randomly. This allows the locks to be used evenly if you have a
1610  * lot of very short connections.
1611  */
1612  static int lockToTry = -1;
1613 
1614  if (lockToTry == -1)
1615  lockToTry = MyProc->pgprocno % NUM_XLOGINSERT_LOCKS;
1616  MyLockNo = lockToTry;
1617 
1618  /*
1619  * The insertingAt value is initially set to 0, as we don't know our
1620  * insert location yet.
1621  */
1622  immed = LWLockAcquire(&WALInsertLocks[MyLockNo].l.lock, LW_EXCLUSIVE);
1623  if (!immed)
1624  {
1625  /*
1626  * If we couldn't get the lock immediately, try another lock next
1627  * time. On a system with more insertion locks than concurrent
1628  * inserters, this causes all the inserters to eventually migrate to a
1629  * lock that no-one else is using. On a system with more inserters
1630  * than locks, it still helps to distribute the inserters evenly
1631  * across the locks.
1632  */
1633  lockToTry = (lockToTry + 1) % NUM_XLOGINSERT_LOCKS;
1634  }
1635 }
1636 
1637 /*
1638  * Acquire all WAL insertion locks, to prevent other backends from inserting
1639  * to WAL.
1640  */
1641 static void
1643 {
1644  int i;
1645 
1646  /*
1647  * When holding all the locks, all but the last lock's insertingAt
1648  * indicator is set to 0xFFFFFFFFFFFFFFFF, which is higher than any real
1649  * XLogRecPtr value, to make sure that no-one blocks waiting on those.
1650  */
1651  for (i = 0; i < NUM_XLOGINSERT_LOCKS - 1; i++)
1652  {
1653  LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
1654  LWLockUpdateVar(&WALInsertLocks[i].l.lock,
1655  &WALInsertLocks[i].l.insertingAt,
1656  PG_UINT64_MAX);
1657  }
1658  /* Variable value reset to 0 at release */
1659  LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
1660 
1661  holdingAllLocks = true;
1662 }
1663 
1664 /*
1665  * Release our insertion lock (or locks, if we're holding them all).
1666  *
1667  * NB: Reset all variables to 0, so they cause LWLockWaitForVar to block the
1668  * next time the lock is acquired.
1669  */
1670 static void
1672 {
1673  if (holdingAllLocks)
1674  {
1675  int i;
1676 
1677  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1678  LWLockReleaseClearVar(&WALInsertLocks[i].l.lock,
1679  &WALInsertLocks[i].l.insertingAt,
1680  0);
1681 
1682  holdingAllLocks = false;
1683  }
1684  else
1685  {
1686  LWLockReleaseClearVar(&WALInsertLocks[MyLockNo].l.lock,
1687  &WALInsertLocks[MyLockNo].l.insertingAt,
1688  0);
1689  }
1690 }
1691 
1692 /*
1693  * Update our insertingAt value, to let others know that we've finished
1694  * inserting up to that point.
1695  */
1696 static void
1698 {
1699  if (holdingAllLocks)
1700  {
1701  /*
1702  * We use the last lock to mark our actual position, see comments in
1703  * WALInsertLockAcquireExclusive.
1704  */
1705  LWLockUpdateVar(&WALInsertLocks[NUM_XLOGINSERT_LOCKS - 1].l.lock,
1706  &WALInsertLocks[NUM_XLOGINSERT_LOCKS - 1].l.insertingAt,
1707  insertingAt);
1708  }
1709  else
1710  LWLockUpdateVar(&WALInsertLocks[MyLockNo].l.lock,
1711  &WALInsertLocks[MyLockNo].l.insertingAt,
1712  insertingAt);
1713 }
1714 
1715 /*
1716  * Wait for any WAL insertions < upto to finish.
1717  *
1718  * Returns the location of the oldest insertion that is still in-progress.
1719  * Any WAL prior to that point has been fully copied into WAL buffers, and
1720  * can be flushed out to disk. Because this waits for any insertions older
1721  * than 'upto' to finish, the return value is always >= 'upto'.
1722  *
1723  * Note: When you are about to write out WAL, you must call this function
1724  * *before* acquiring WALWriteLock, to avoid deadlocks. This function might
1725  * need to wait for an insertion to finish (or at least advance to next
1726  * uninitialized page), and the inserter might need to evict an old WAL buffer
1727  * to make room for a new one, which in turn requires WALWriteLock.
1728  */
1729 static XLogRecPtr
1731 {
1732  uint64 bytepos;
1733  XLogRecPtr reservedUpto;
1734  XLogRecPtr finishedUpto;
1735  XLogCtlInsert *Insert = &XLogCtl->Insert;
1736  int i;
1737 
1738  if (MyProc == NULL)
1739  elog(PANIC, "cannot wait without a PGPROC structure");
1740 
1741  /* Read the current insert position */
1742  SpinLockAcquire(&Insert->insertpos_lck);
1743  bytepos = Insert->CurrBytePos;
1744  SpinLockRelease(&Insert->insertpos_lck);
1745  reservedUpto = XLogBytePosToEndRecPtr(bytepos);
1746 
1747  /*
1748  * No-one should request to flush a piece of WAL that hasn't even been
1749  * reserved yet. However, it can happen if there is a block with a bogus
1750  * LSN on disk, for example. XLogFlush checks for that situation and
1751  * complains, but only after the flush. Here we just assume that to mean
1752  * that all WAL that has been reserved needs to be finished. In this
1753  * corner-case, the return value can be smaller than 'upto' argument.
1754  */
1755  if (upto > reservedUpto)
1756  {
1757  elog(LOG, "request to flush past end of generated WAL; request %X/%X, currpos %X/%X",
1758  (uint32) (upto >> 32), (uint32) upto,
1759  (uint32) (reservedUpto >> 32), (uint32) reservedUpto);
1760  upto = reservedUpto;
1761  }
1762 
1763  /*
1764  * Loop through all the locks, sleeping on any in-progress insert older
1765  * than 'upto'.
1766  *
1767  * finishedUpto is our return value, indicating the point upto which all
1768  * the WAL insertions have been finished. Initialize it to the head of
1769  * reserved WAL, and as we iterate through the insertion locks, back it
1770  * out for any insertion that's still in progress.
1771  */
1772  finishedUpto = reservedUpto;
1773  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1774  {
1775  XLogRecPtr insertingat = InvalidXLogRecPtr;
1776 
1777  do
1778  {
1779  /*
1780  * See if this insertion is in progress. LWLockWait will wait for
1781  * the lock to be released, or for the 'value' to be set by a
1782  * LWLockUpdateVar call. When a lock is initially acquired, its
1783  * value is 0 (InvalidXLogRecPtr), which means that we don't know
1784  * where it's inserting yet. We will have to wait for it. If
1785  * it's a small insertion, the record will most likely fit on the
1786  * same page and the inserter will release the lock without ever
1787  * calling LWLockUpdateVar. But if it has to sleep, it will
1788  * advertise the insertion point with LWLockUpdateVar before
1789  * sleeping.
1790  */
1791  if (LWLockWaitForVar(&WALInsertLocks[i].l.lock,
1792  &WALInsertLocks[i].l.insertingAt,
1793  insertingat, &insertingat))
1794  {
1795  /* the lock was free, so no insertion in progress */
1796  insertingat = InvalidXLogRecPtr;
1797  break;
1798  }
1799 
1800  /*
1801  * This insertion is still in progress. Have to wait, unless the
1802  * inserter has proceeded past 'upto'.
1803  */
1804  } while (insertingat < upto);
1805 
1806  if (insertingat != InvalidXLogRecPtr && insertingat < finishedUpto)
1807  finishedUpto = insertingat;
1808  }
1809  return finishedUpto;
1810 }
1811 
1812 /*
1813  * Get a pointer to the right location in the WAL buffer containing the
1814  * given XLogRecPtr.
1815  *
1816  * If the page is not initialized yet, it is initialized. That might require
1817  * evicting an old dirty buffer from the buffer cache, which means I/O.
1818  *
1819  * The caller must ensure that the page containing the requested location
1820  * isn't evicted yet, and won't be evicted. The way to ensure that is to
1821  * hold onto a WAL insertion lock with the insertingAt position set to
1822  * something <= ptr. GetXLogBuffer() will update insertingAt if it needs
1823  * to evict an old page from the buffer. (This means that once you call
1824  * GetXLogBuffer() with a given 'ptr', you must not access anything before
1825  * that point anymore, and must not call GetXLogBuffer() with an older 'ptr'
1826  * later, because older buffers might be recycled already)
1827  */
1828 static char *
1830 {
1831  int idx;
1832  XLogRecPtr endptr;
1833  static uint64 cachedPage = 0;
1834  static char *cachedPos = NULL;
1835  XLogRecPtr expectedEndPtr;
1836 
1837  /*
1838  * Fast path for the common case that we need to access again the same
1839  * page as last time.
1840  */
1841  if (ptr / XLOG_BLCKSZ == cachedPage)
1842  {
1843  Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1844  Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1845  return cachedPos + ptr % XLOG_BLCKSZ;
1846  }
1847 
1848  /*
1849  * The XLog buffer cache is organized so that a page is always loaded to a
1850  * particular buffer. That way we can easily calculate the buffer a given
1851  * page must be loaded into, from the XLogRecPtr alone.
1852  */
1853  idx = XLogRecPtrToBufIdx(ptr);
1854 
1855  /*
1856  * See what page is loaded in the buffer at the moment. It could be the
1857  * page we're looking for, or something older. It can't be anything newer
1858  * - that would imply the page we're looking for has already been written
1859  * out to disk and evicted, and the caller is responsible for making sure
1860  * that doesn't happen.
1861  *
1862  * However, we don't hold a lock while we read the value. If someone has
1863  * just initialized the page, it's possible that we get a "torn read" of
1864  * the XLogRecPtr if 64-bit fetches are not atomic on this platform. In
1865  * that case we will see a bogus value. That's ok, we'll grab the mapping
1866  * lock (in AdvanceXLInsertBuffer) and retry if we see anything else than
1867  * the page we're looking for. But it means that when we do this unlocked
1868  * read, we might see a value that appears to be ahead of the page we're
1869  * looking for. Don't PANIC on that, until we've verified the value while
1870  * holding the lock.
1871  */
1872  expectedEndPtr = ptr;
1873  expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
1874 
1875  endptr = XLogCtl->xlblocks[idx];
1876  if (expectedEndPtr != endptr)
1877  {
1878  XLogRecPtr initializedUpto;
1879 
1880  /*
1881  * Before calling AdvanceXLInsertBuffer(), which can block, let others
1882  * know how far we're finished with inserting the record.
1883  *
1884  * NB: If 'ptr' points to just after the page header, advertise a
1885  * position at the beginning of the page rather than 'ptr' itself. If
1886  * there are no other insertions running, someone might try to flush
1887  * up to our advertised location. If we advertised a position after
1888  * the page header, someone might try to flush the page header, even
1889  * though page might actually not be initialized yet. As the first
1890  * inserter on the page, we are effectively responsible for making
1891  * sure that it's initialized, before we let insertingAt to move past
1892  * the page header.
1893  */
1894  if (ptr % XLOG_BLCKSZ == SizeOfXLogShortPHD &&
1895  XLogSegmentOffset(ptr, wal_segment_size) > XLOG_BLCKSZ)
1896  initializedUpto = ptr - SizeOfXLogShortPHD;
1897  else if (ptr % XLOG_BLCKSZ == SizeOfXLogLongPHD &&
1898  XLogSegmentOffset(ptr, wal_segment_size) < XLOG_BLCKSZ)
1899  initializedUpto = ptr - SizeOfXLogLongPHD;
1900  else
1901  initializedUpto = ptr;
1902 
1903  WALInsertLockUpdateInsertingAt(initializedUpto);
1904 
1905  AdvanceXLInsertBuffer(ptr, false);
1906  endptr = XLogCtl->xlblocks[idx];
1907 
1908  if (expectedEndPtr != endptr)
1909  elog(PANIC, "could not find WAL buffer for %X/%X",
1910  (uint32) (ptr >> 32), (uint32) ptr);
1911  }
1912  else
1913  {
1914  /*
1915  * Make sure the initialization of the page is visible to us, and
1916  * won't arrive later to overwrite the WAL data we write on the page.
1917  */
1919  }
1920 
1921  /*
1922  * Found the buffer holding this page. Return a pointer to the right
1923  * offset within the page.
1924  */
1925  cachedPage = ptr / XLOG_BLCKSZ;
1926  cachedPos = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
1927 
1928  Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1929  Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1930 
1931  return cachedPos + ptr % XLOG_BLCKSZ;
1932 }
1933 
1934 /*
1935  * Converts a "usable byte position" to XLogRecPtr. A usable byte position
1936  * is the position starting from the beginning of WAL, excluding all WAL
1937  * page headers.
1938  */
1939 static XLogRecPtr
1940 XLogBytePosToRecPtr(uint64 bytepos)
1941 {
1942  uint64 fullsegs;
1943  uint64 fullpages;
1944  uint64 bytesleft;
1945  uint32 seg_offset;
1946  XLogRecPtr result;
1947 
1948  fullsegs = bytepos / UsableBytesInSegment;
1949  bytesleft = bytepos % UsableBytesInSegment;
1950 
1951  if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
1952  {
1953  /* fits on first page of segment */
1954  seg_offset = bytesleft + SizeOfXLogLongPHD;
1955  }
1956  else
1957  {
1958  /* account for the first page on segment with long header */
1959  seg_offset = XLOG_BLCKSZ;
1960  bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
1961 
1962  fullpages = bytesleft / UsableBytesInPage;
1963  bytesleft = bytesleft % UsableBytesInPage;
1964 
1965  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
1966  }
1967 
1968  XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, result, wal_segment_size);
1969 
1970  return result;
1971 }
1972 
1973 /*
1974  * Like XLogBytePosToRecPtr, but if the position is at a page boundary,
1975  * returns a pointer to the beginning of the page (ie. before page header),
1976  * not to where the first xlog record on that page would go to. This is used
1977  * when converting a pointer to the end of a record.
1978  */
1979 static XLogRecPtr
1980 XLogBytePosToEndRecPtr(uint64 bytepos)
1981 {
1982  uint64 fullsegs;
1983  uint64 fullpages;
1984  uint64 bytesleft;
1985  uint32 seg_offset;
1986  XLogRecPtr result;
1987 
1988  fullsegs = bytepos / UsableBytesInSegment;
1989  bytesleft = bytepos % UsableBytesInSegment;
1990 
1991  if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
1992  {
1993  /* fits on first page of segment */
1994  if (bytesleft == 0)
1995  seg_offset = 0;
1996  else
1997  seg_offset = bytesleft + SizeOfXLogLongPHD;
1998  }
1999  else
2000  {
2001  /* account for the first page on segment with long header */
2002  seg_offset = XLOG_BLCKSZ;
2003  bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2004 
2005  fullpages = bytesleft / UsableBytesInPage;
2006  bytesleft = bytesleft % UsableBytesInPage;
2007 
2008  if (bytesleft == 0)
2009  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
2010  else
2011  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2012  }
2013 
2014  XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, result, wal_segment_size);
2015 
2016  return result;
2017 }
2018 
2019 /*
2020  * Convert an XLogRecPtr to a "usable byte position".
2021  */
2022 static uint64
2024 {
2025  uint64 fullsegs;
2026  uint32 fullpages;
2027  uint32 offset;
2028  uint64 result;
2029 
2030  XLByteToSeg(ptr, fullsegs, wal_segment_size);
2031 
2032  fullpages = (XLogSegmentOffset(ptr, wal_segment_size)) / XLOG_BLCKSZ;
2033  offset = ptr % XLOG_BLCKSZ;
2034 
2035  if (fullpages == 0)
2036  {
2037  result = fullsegs * UsableBytesInSegment;
2038  if (offset > 0)
2039  {
2040  Assert(offset >= SizeOfXLogLongPHD);
2041  result += offset - SizeOfXLogLongPHD;
2042  }
2043  }
2044  else
2045  {
2046  result = fullsegs * UsableBytesInSegment +
2047  (XLOG_BLCKSZ - SizeOfXLogLongPHD) + /* account for first page */
2048  (fullpages - 1) * UsableBytesInPage; /* full pages */
2049  if (offset > 0)
2050  {
2051  Assert(offset >= SizeOfXLogShortPHD);
2052  result += offset - SizeOfXLogShortPHD;
2053  }
2054  }
2055 
2056  return result;
2057 }
2058 
2059 /*
2060  * Initialize XLOG buffers, writing out old buffers if they still contain
2061  * unwritten data, upto the page containing 'upto'. Or if 'opportunistic' is
2062  * true, initialize as many pages as we can without having to write out
2063  * unwritten data. Any new pages are initialized to zeros, with pages headers
2064  * initialized properly.
2065  */
2066 static void
2067 AdvanceXLInsertBuffer(XLogRecPtr upto, bool opportunistic)
2068 {
2069  XLogCtlInsert *Insert = &XLogCtl->Insert;
2070  int nextidx;
2071  XLogRecPtr OldPageRqstPtr;
2072  XLogwrtRqst WriteRqst;
2073  XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
2074  XLogRecPtr NewPageBeginPtr;
2075  XLogPageHeader NewPage;
2076  int npages = 0;
2077 
2078  LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2079 
2080  /*
2081  * Now that we have the lock, check if someone initialized the page
2082  * already.
2083  */
2084  while (upto >= XLogCtl->InitializedUpTo || opportunistic)
2085  {
2086  nextidx = XLogRecPtrToBufIdx(XLogCtl->InitializedUpTo);
2087 
2088  /*
2089  * Get ending-offset of the buffer page we need to replace (this may
2090  * be zero if the buffer hasn't been used yet). Fall through if it's
2091  * already written out.
2092  */
2093  OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
2094  if (LogwrtResult.Write < OldPageRqstPtr)
2095  {
2096  /*
2097  * Nope, got work to do. If we just want to pre-initialize as much
2098  * as we can without flushing, give up now.
2099  */
2100  if (opportunistic)
2101  break;
2102 
2103  /* Before waiting, get info_lck and update LogwrtResult */
2104  SpinLockAcquire(&XLogCtl->info_lck);
2105  if (XLogCtl->LogwrtRqst.Write < OldPageRqstPtr)
2106  XLogCtl->LogwrtRqst.Write = OldPageRqstPtr;
2107  LogwrtResult = XLogCtl->LogwrtResult;
2108  SpinLockRelease(&XLogCtl->info_lck);
2109 
2110  /*
2111  * Now that we have an up-to-date LogwrtResult value, see if we
2112  * still need to write it or if someone else already did.
2113  */
2114  if (LogwrtResult.Write < OldPageRqstPtr)
2115  {
2116  /*
2117  * Must acquire write lock. Release WALBufMappingLock first,
2118  * to make sure that all insertions that we need to wait for
2119  * can finish (up to this same position). Otherwise we risk
2120  * deadlock.
2121  */
2122  LWLockRelease(WALBufMappingLock);
2123 
2124  WaitXLogInsertionsToFinish(OldPageRqstPtr);
2125 
2126  LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2127 
2128  LogwrtResult = XLogCtl->LogwrtResult;
2129  if (LogwrtResult.Write >= OldPageRqstPtr)
2130  {
2131  /* OK, someone wrote it already */
2132  LWLockRelease(WALWriteLock);
2133  }
2134  else
2135  {
2136  /* Have to write it ourselves */
2137  TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2138  WriteRqst.Write = OldPageRqstPtr;
2139  WriteRqst.Flush = 0;
2140  XLogWrite(WriteRqst, false);
2141  LWLockRelease(WALWriteLock);
2142  TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
2143  }
2144  /* Re-acquire WALBufMappingLock and retry */
2145  LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2146  continue;
2147  }
2148  }
2149 
2150  /*
2151  * Now the next buffer slot is free and we can set it up to be the
2152  * next output page.
2153  */
2154  NewPageBeginPtr = XLogCtl->InitializedUpTo;
2155  NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2156 
2157  Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
2158 
2159  NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
2160 
2161  /*
2162  * Be sure to re-zero the buffer so that bytes beyond what we've
2163  * written will look like zeroes and not valid XLOG records...
2164  */
2165  MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
2166 
2167  /*
2168  * Fill the new page's header
2169  */
2170  NewPage->xlp_magic = XLOG_PAGE_MAGIC;
2171 
2172  /* NewPage->xlp_info = 0; */ /* done by memset */
2173  NewPage->xlp_tli = ThisTimeLineID;
2174  NewPage->xlp_pageaddr = NewPageBeginPtr;
2175 
2176  /* NewPage->xlp_rem_len = 0; */ /* done by memset */
2177 
2178  /*
2179  * If online backup is not in progress, mark the header to indicate
2180  * that WAL records beginning in this page have removable backup
2181  * blocks. This allows the WAL archiver to know whether it is safe to
2182  * compress archived WAL data by transforming full-block records into
2183  * the non-full-block format. It is sufficient to record this at the
2184  * page level because we force a page switch (in fact a segment
2185  * switch) when starting a backup, so the flag will be off before any
2186  * records can be written during the backup. At the end of a backup,
2187  * the last page will be marked as all unsafe when perhaps only part
2188  * is unsafe, but at worst the archiver would miss the opportunity to
2189  * compress a few records.
2190  */
2191  if (!Insert->forcePageWrites)
2192  NewPage->xlp_info |= XLP_BKP_REMOVABLE;
2193 
2194  /*
2195  * If first page of an XLOG segment file, make it a long header.
2196  */
2197  if ((XLogSegmentOffset(NewPage->xlp_pageaddr, wal_segment_size)) == 0)
2198  {
2199  XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
2200 
2201  NewLongPage->xlp_sysid = ControlFile->system_identifier;
2202  NewLongPage->xlp_seg_size = wal_segment_size;
2203  NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
2204  NewPage->xlp_info |= XLP_LONG_HEADER;
2205  }
2206 
2207  /*
2208  * Make sure the initialization of the page becomes visible to others
2209  * before the xlblocks update. GetXLogBuffer() reads xlblocks without
2210  * holding a lock.
2211  */
2212  pg_write_barrier();
2213 
2214  *((volatile XLogRecPtr *) &XLogCtl->xlblocks[nextidx]) = NewPageEndPtr;
2215 
2216  XLogCtl->InitializedUpTo = NewPageEndPtr;
2217 
2218  npages++;
2219  }
2220  LWLockRelease(WALBufMappingLock);
2221 
2222 #ifdef WAL_DEBUG
2223  if (XLOG_DEBUG && npages > 0)
2224  {
2225  elog(DEBUG1, "initialized %d pages, up to %X/%X",
2226  npages, (uint32) (NewPageEndPtr >> 32), (uint32) NewPageEndPtr);
2227  }
2228 #endif
2229 }
2230 
2231 /*
2232  * Calculate CheckPointSegments based on max_wal_size_mb and
2233  * checkpoint_completion_target.
2234  */
2235 static void
2237 {
2238  double target;
2239 
2240  /*-------
2241  * Calculate the distance at which to trigger a checkpoint, to avoid
2242  * exceeding max_wal_size_mb. This is based on two assumptions:
2243  *
2244  * a) we keep WAL for only one checkpoint cycle (prior to PG11 we kept
2245  * WAL for two checkpoint cycles to allow us to recover from the
2246  * secondary checkpoint if the first checkpoint failed, though we
2247  * only did this on the master anyway, not on standby. Keeping just
2248  * one checkpoint simplifies processing and reduces disk space in
2249  * many smaller databases.)
2250  * b) during checkpoint, we consume checkpoint_completion_target *
2251  * number of segments consumed between checkpoints.
2252  *-------
2253  */
2254  target = (double) ConvertToXSegs(max_wal_size_mb, wal_segment_size) /
2256 
2257  /* round down */
2258  CheckPointSegments = (int) target;
2259 
2260  if (CheckPointSegments < 1)
2261  CheckPointSegments = 1;
2262 }
2263 
2264 void
2265 assign_max_wal_size(int newval, void *extra)
2266 {
2269 }
2270 
2271 void
2273 {
2276 }
2277 
2278 /*
2279  * At a checkpoint, how many WAL segments to recycle as preallocated future
2280  * XLOG segments? Returns the highest segment that should be preallocated.
2281  */
2282 static XLogSegNo
2284 {
2285  XLogSegNo minSegNo;
2286  XLogSegNo maxSegNo;
2287  double distance;
2288  XLogSegNo recycleSegNo;
2289 
2290  /*
2291  * Calculate the segment numbers that min_wal_size_mb and max_wal_size_mb
2292  * correspond to. Always recycle enough segments to meet the minimum, and
2293  * remove enough segments to stay below the maximum.
2294  */
2295  minSegNo = PriorRedoPtr / wal_segment_size +
2297  maxSegNo = PriorRedoPtr / wal_segment_size +
2299 
2300  /*
2301  * Between those limits, recycle enough segments to get us through to the
2302  * estimated end of next checkpoint.
2303  *
2304  * To estimate where the next checkpoint will finish, assume that the
2305  * system runs steadily consuming CheckPointDistanceEstimate bytes between
2306  * every checkpoint.
2307  */
2309  /* add 10% for good measure. */
2310  distance *= 1.10;
2311 
2312  recycleSegNo = (XLogSegNo) ceil(((double) PriorRedoPtr + distance) /
2314 
2315  if (recycleSegNo < minSegNo)
2316  recycleSegNo = minSegNo;
2317  if (recycleSegNo > maxSegNo)
2318  recycleSegNo = maxSegNo;
2319 
2320  return recycleSegNo;
2321 }
2322 
2323 /*
2324  * Check whether we've consumed enough xlog space that a checkpoint is needed.
2325  *
2326  * new_segno indicates a log file that has just been filled up (or read
2327  * during recovery). We measure the distance from RedoRecPtr to new_segno
2328  * and see if that exceeds CheckPointSegments.
2329  *
2330  * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
2331  */
2332 static bool
2334 {
2335  XLogSegNo old_segno;
2336 
2338 
2339  if (new_segno >= old_segno + (uint64) (CheckPointSegments - 1))
2340  return true;
2341  return false;
2342 }
2343 
2344 /*
2345  * Write and/or fsync the log at least as far as WriteRqst indicates.
2346  *
2347  * If flexible == true, we don't have to write as far as WriteRqst, but
2348  * may stop at any convenient boundary (such as a cache or logfile boundary).
2349  * This option allows us to avoid uselessly issuing multiple writes when a
2350  * single one would do.
2351  *
2352  * Must be called with WALWriteLock held. WaitXLogInsertionsToFinish(WriteRqst)
2353  * must be called before grabbing the lock, to make sure the data is ready to
2354  * write.
2355  */
2356 static void
2357 XLogWrite(XLogwrtRqst WriteRqst, bool flexible)
2358 {
2359  bool ispartialpage;
2360  bool last_iteration;
2361  bool finishing_seg;
2362  bool use_existent;
2363  int curridx;
2364  int npages;
2365  int startidx;
2366  uint32 startoffset;
2367 
2368  /* We should always be inside a critical section here */
2369  Assert(CritSectionCount > 0);
2370 
2371  /*
2372  * Update local LogwrtResult (caller probably did this already, but...)
2373  */
2374  LogwrtResult = XLogCtl->LogwrtResult;
2375 
2376  /*
2377  * Since successive pages in the xlog cache are consecutively allocated,
2378  * we can usually gather multiple pages together and issue just one
2379  * write() call. npages is the number of pages we have determined can be
2380  * written together; startidx is the cache block index of the first one,
2381  * and startoffset is the file offset at which it should go. The latter
2382  * two variables are only valid when npages > 0, but we must initialize
2383  * all of them to keep the compiler quiet.
2384  */
2385  npages = 0;
2386  startidx = 0;
2387  startoffset = 0;
2388 
2389  /*
2390  * Within the loop, curridx is the cache block index of the page to
2391  * consider writing. Begin at the buffer containing the next unwritten
2392  * page, or last partially written page.
2393  */
2394  curridx = XLogRecPtrToBufIdx(LogwrtResult.Write);
2395 
2396  while (LogwrtResult.Write < WriteRqst.Write)
2397  {
2398  /*
2399  * Make sure we're not ahead of the insert process. This could happen
2400  * if we're passed a bogus WriteRqst.Write that is past the end of the
2401  * last page that's been initialized by AdvanceXLInsertBuffer.
2402  */
2403  XLogRecPtr EndPtr = XLogCtl->xlblocks[curridx];
2404 
2405  if (LogwrtResult.Write >= EndPtr)
2406  elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
2407  (uint32) (LogwrtResult.Write >> 32),
2408  (uint32) LogwrtResult.Write,
2409  (uint32) (EndPtr >> 32), (uint32) EndPtr);
2410 
2411  /* Advance LogwrtResult.Write to end of current buffer page */
2412  LogwrtResult.Write = EndPtr;
2413  ispartialpage = WriteRqst.Write < LogwrtResult.Write;
2414 
2415  if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
2417  {
2418  /*
2419  * Switch to new logfile segment. We cannot have any pending
2420  * pages here (since we dump what we have at segment end).
2421  */
2422  Assert(npages == 0);
2423  if (openLogFile >= 0)
2424  XLogFileClose();
2425  XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2427 
2428  /* create/use new log file */
2429  use_existent = true;
2430  openLogFile = XLogFileInit(openLogSegNo, &use_existent, true);
2431  openLogOff = 0;
2432  }
2433 
2434  /* Make sure we have the current logfile open */
2435  if (openLogFile < 0)
2436  {
2437  XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2440  openLogOff = 0;
2441  }
2442 
2443  /* Add current page to the set of pending pages-to-dump */
2444  if (npages == 0)
2445  {
2446  /* first of group */
2447  startidx = curridx;
2448  startoffset = XLogSegmentOffset(LogwrtResult.Write - XLOG_BLCKSZ,
2450  }
2451  npages++;
2452 
2453  /*
2454  * Dump the set if this will be the last loop iteration, or if we are
2455  * at the last page of the cache area (since the next page won't be
2456  * contiguous in memory), or if we are at the end of the logfile
2457  * segment.
2458  */
2459  last_iteration = WriteRqst.Write <= LogwrtResult.Write;
2460 
2461  finishing_seg = !ispartialpage &&
2462  (startoffset + npages * XLOG_BLCKSZ) >= wal_segment_size;
2463 
2464  if (last_iteration ||
2465  curridx == XLogCtl->XLogCacheBlck ||
2466  finishing_seg)
2467  {
2468  char *from;
2469  Size nbytes;
2470  Size nleft;
2471  int written;
2472 
2473  /* Need to seek in the file? */
2474  if (openLogOff != startoffset)
2475  {
2476  if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
2477  ereport(PANIC,
2479  errmsg("could not seek in log file %s to offset %u: %m",
2481  startoffset)));
2482  openLogOff = startoffset;
2483  }
2484 
2485  /* OK to write the page(s) */
2486  from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
2487  nbytes = npages * (Size) XLOG_BLCKSZ;
2488  nleft = nbytes;
2489  do
2490  {
2491  errno = 0;
2493  written = write(openLogFile, from, nleft);
2495  if (written <= 0)
2496  {
2497  if (errno == EINTR)
2498  continue;
2499  ereport(PANIC,
2501  errmsg("could not write to log file %s "
2502  "at offset %u, length %zu: %m",
2504  openLogOff, nbytes)));
2505  }
2506  nleft -= written;
2507  from += written;
2508  } while (nleft > 0);
2509 
2510  /* Update state for write */
2511  openLogOff += nbytes;
2512  npages = 0;
2513 
2514  /*
2515  * If we just wrote the whole last page of a logfile segment,
2516  * fsync the segment immediately. This avoids having to go back
2517  * and re-open prior segments when an fsync request comes along
2518  * later. Doing it here ensures that one and only one backend will
2519  * perform this fsync.
2520  *
2521  * This is also the right place to notify the Archiver that the
2522  * segment is ready to copy to archival storage, and to update the
2523  * timer for archive_timeout, and to signal for a checkpoint if
2524  * too many logfile segments have been used since the last
2525  * checkpoint.
2526  */
2527  if (finishing_seg)
2528  {
2530 
2531  /* signal that we need to wakeup walsenders later */
2533 
2534  LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
2535 
2536  if (XLogArchivingActive())
2538 
2539  XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
2540  XLogCtl->lastSegSwitchLSN = LogwrtResult.Flush;
2541 
2542  /*
2543  * Request a checkpoint if we've consumed too much xlog since
2544  * the last one. For speed, we first check using the local
2545  * copy of RedoRecPtr, which might be out of date; if it looks
2546  * like a checkpoint is needed, forcibly update RedoRecPtr and
2547  * recheck.
2548  */
2550  {
2551  (void) GetRedoRecPtr();
2554  }
2555  }
2556  }
2557 
2558  if (ispartialpage)
2559  {
2560  /* Only asked to write a partial page */
2561  LogwrtResult.Write = WriteRqst.Write;
2562  break;
2563  }
2564  curridx = NextBufIdx(curridx);
2565 
2566  /* If flexible, break out of loop as soon as we wrote something */
2567  if (flexible && npages == 0)
2568  break;
2569  }
2570 
2571  Assert(npages == 0);
2572 
2573  /*
2574  * If asked to flush, do so
2575  */
2576  if (LogwrtResult.Flush < WriteRqst.Flush &&
2577  LogwrtResult.Flush < LogwrtResult.Write)
2578 
2579  {
2580  /*
2581  * Could get here without iterating above loop, in which case we might
2582  * have no open file or the wrong one. However, we do not need to
2583  * fsync more than one file.
2584  */
2585  if (sync_method != SYNC_METHOD_OPEN &&
2587  {
2588  if (openLogFile >= 0 &&
2589  !XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
2591  XLogFileClose();
2592  if (openLogFile < 0)
2593  {
2594  XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2597  openLogOff = 0;
2598  }
2599 
2601  }
2602 
2603  /* signal that we need to wakeup walsenders later */
2605 
2606  LogwrtResult.Flush = LogwrtResult.Write;
2607  }
2608 
2609  /*
2610  * Update shared-memory status
2611  *
2612  * We make sure that the shared 'request' values do not fall behind the
2613  * 'result' values. This is not absolutely essential, but it saves some
2614  * code in a couple of places.
2615  */
2616  {
2617  SpinLockAcquire(&XLogCtl->info_lck);
2618  XLogCtl->LogwrtResult = LogwrtResult;
2619  if (XLogCtl->LogwrtRqst.Write < LogwrtResult.Write)
2620  XLogCtl->LogwrtRqst.Write = LogwrtResult.Write;
2621  if (XLogCtl->LogwrtRqst.Flush < LogwrtResult.Flush)
2622  XLogCtl->LogwrtRqst.Flush = LogwrtResult.Flush;
2623  SpinLockRelease(&XLogCtl->info_lck);
2624  }
2625 }
2626 
2627 /*
2628  * Record the LSN for an asynchronous transaction commit/abort
2629  * and nudge the WALWriter if there is work for it to do.
2630  * (This should not be called for synchronous commits.)
2631  */
2632 void
2634 {
2635  XLogRecPtr WriteRqstPtr = asyncXactLSN;
2636  bool sleeping;
2637 
2638  SpinLockAcquire(&XLogCtl->info_lck);
2639  LogwrtResult = XLogCtl->LogwrtResult;
2640  sleeping = XLogCtl->WalWriterSleeping;
2641  if (XLogCtl->asyncXactLSN < asyncXactLSN)
2642  XLogCtl->asyncXactLSN = asyncXactLSN;
2643  SpinLockRelease(&XLogCtl->info_lck);
2644 
2645  /*
2646  * If the WALWriter is sleeping, we should kick it to make it come out of
2647  * low-power mode. Otherwise, determine whether there's a full page of
2648  * WAL available to write.
2649  */
2650  if (!sleeping)
2651  {
2652  /* back off to last completed page boundary */
2653  WriteRqstPtr -= WriteRqstPtr % XLOG_BLCKSZ;
2654 
2655  /* if we have already flushed that far, we're done */
2656  if (WriteRqstPtr <= LogwrtResult.Flush)
2657  return;
2658  }
2659 
2660  /*
2661  * Nudge the WALWriter: it has a full page of WAL to write, or we want it
2662  * to come out of low-power mode so that this async commit will reach disk
2663  * within the expected amount of time.
2664  */
2667 }
2668 
2669 /*
2670  * Record the LSN up to which we can remove WAL because it's not required by
2671  * any replication slot.
2672  */
2673 void
2675 {
2676  SpinLockAcquire(&XLogCtl->info_lck);
2677  XLogCtl->replicationSlotMinLSN = lsn;
2678  SpinLockRelease(&XLogCtl->info_lck);
2679 }
2680 
2681 
2682 /*
2683  * Return the oldest LSN we must retain to satisfy the needs of some
2684  * replication slot.
2685  */
2686 static XLogRecPtr
2688 {
2689  XLogRecPtr retval;
2690 
2691  SpinLockAcquire(&XLogCtl->info_lck);
2692  retval = XLogCtl->replicationSlotMinLSN;
2693  SpinLockRelease(&XLogCtl->info_lck);
2694 
2695  return retval;
2696 }
2697 
2698 /*
2699  * Advance minRecoveryPoint in control file.
2700  *
2701  * If we crash during recovery, we must reach this point again before the
2702  * database is consistent.
2703  *
2704  * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
2705  * is only updated if it's not already greater than or equal to 'lsn'.
2706  */
2707 static void
2709 {
2710  /* Quick check using our local copy of the variable */
2711  if (!updateMinRecoveryPoint || (!force && lsn <= minRecoveryPoint))
2712  return;
2713 
2714  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2715 
2716  /* update local copy */
2717  minRecoveryPoint = ControlFile->minRecoveryPoint;
2719 
2720  /*
2721  * An invalid minRecoveryPoint means that we need to recover all the WAL,
2722  * i.e., we're doing crash recovery. We never modify the control file's
2723  * value in that case, so we can short-circuit future checks here too.
2724  */
2725  if (minRecoveryPoint == 0)
2726  updateMinRecoveryPoint = false;
2727  else if (force || minRecoveryPoint < lsn)
2728  {
2729  XLogRecPtr newMinRecoveryPoint;
2730  TimeLineID newMinRecoveryPointTLI;
2731 
2732  /*
2733  * To avoid having to update the control file too often, we update it
2734  * all the way to the last record being replayed, even though 'lsn'
2735  * would suffice for correctness. This also allows the 'force' case
2736  * to not need a valid 'lsn' value.
2737  *
2738  * Another important reason for doing it this way is that the passed
2739  * 'lsn' value could be bogus, i.e., past the end of available WAL, if
2740  * the caller got it from a corrupted heap page. Accepting such a
2741  * value as the min recovery point would prevent us from coming up at
2742  * all. Instead, we just log a warning and continue with recovery.
2743  * (See also the comments about corrupt LSNs in XLogFlush.)
2744  */
2745  SpinLockAcquire(&XLogCtl->info_lck);
2746  newMinRecoveryPoint = XLogCtl->replayEndRecPtr;
2747  newMinRecoveryPointTLI = XLogCtl->replayEndTLI;
2748  SpinLockRelease(&XLogCtl->info_lck);
2749 
2750  if (!force && newMinRecoveryPoint < lsn)
2751  elog(WARNING,
2752  "xlog min recovery request %X/%X is past current point %X/%X",
2753  (uint32) (lsn >> 32), (uint32) lsn,
2754  (uint32) (newMinRecoveryPoint >> 32),
2755  (uint32) newMinRecoveryPoint);
2756 
2757  /* update control file */
2758  if (ControlFile->minRecoveryPoint < newMinRecoveryPoint)
2759  {
2760  ControlFile->minRecoveryPoint = newMinRecoveryPoint;
2761  ControlFile->minRecoveryPointTLI = newMinRecoveryPointTLI;
2763  minRecoveryPoint = newMinRecoveryPoint;
2764  minRecoveryPointTLI = newMinRecoveryPointTLI;
2765 
2766  ereport(DEBUG2,
2767  (errmsg("updated min recovery point to %X/%X on timeline %u",
2768  (uint32) (minRecoveryPoint >> 32),
2770  newMinRecoveryPointTLI)));
2771  }
2772  }
2773  LWLockRelease(ControlFileLock);
2774 }
2775 
2776 /*
2777  * Ensure that all XLOG data through the given position is flushed to disk.
2778  *
2779  * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
2780  * already held, and we try to avoid acquiring it if possible.
2781  */
2782 void
2784 {
2785  XLogRecPtr WriteRqstPtr;
2786  XLogwrtRqst WriteRqst;
2787 
2788  /*
2789  * During REDO, we are reading not writing WAL. Therefore, instead of
2790  * trying to flush the WAL, we should update minRecoveryPoint instead. We
2791  * test XLogInsertAllowed(), not InRecovery, because we need checkpointer
2792  * to act this way too, and because when it tries to write the
2793  * end-of-recovery checkpoint, it should indeed flush.
2794  */
2795  if (!XLogInsertAllowed())
2796  {
2797  UpdateMinRecoveryPoint(record, false);
2798  return;
2799  }
2800 
2801  /* Quick exit if already known flushed */
2802  if (record <= LogwrtResult.Flush)
2803  return;
2804 
2805 #ifdef WAL_DEBUG
2806  if (XLOG_DEBUG)
2807  elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
2808  (uint32) (record >> 32), (uint32) record,
2809  (uint32) (LogwrtResult.Write >> 32), (uint32) LogwrtResult.Write,
2810  (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
2811 #endif
2812 
2814 
2815  /*
2816  * Since fsync is usually a horribly expensive operation, we try to
2817  * piggyback as much data as we can on each fsync: if we see any more data
2818  * entered into the xlog buffer, we'll write and fsync that too, so that
2819  * the final value of LogwrtResult.Flush is as large as possible. This
2820  * gives us some chance of avoiding another fsync immediately after.
2821  */
2822 
2823  /* initialize to given target; may increase below */
2824  WriteRqstPtr = record;
2825 
2826  /*
2827  * Now wait until we get the write lock, or someone else does the flush
2828  * for us.
2829  */
2830  for (;;)
2831  {
2832  XLogRecPtr insertpos;
2833 
2834  /* read LogwrtResult and update local state */
2835  SpinLockAcquire(&XLogCtl->info_lck);
2836  if (WriteRqstPtr < XLogCtl->LogwrtRqst.Write)
2837  WriteRqstPtr = XLogCtl->LogwrtRqst.Write;
2838  LogwrtResult = XLogCtl->LogwrtResult;
2839  SpinLockRelease(&XLogCtl->info_lck);
2840 
2841  /* done already? */
2842  if (record <= LogwrtResult.Flush)
2843  break;
2844 
2845  /*
2846  * Before actually performing the write, wait for all in-flight
2847  * insertions to the pages we're about to write to finish.
2848  */
2849  insertpos = WaitXLogInsertionsToFinish(WriteRqstPtr);
2850 
2851  /*
2852  * Try to get the write lock. If we can't get it immediately, wait
2853  * until it's released, and recheck if we still need to do the flush
2854  * or if the backend that held the lock did it for us already. This
2855  * helps to maintain a good rate of group committing when the system
2856  * is bottlenecked by the speed of fsyncing.
2857  */
2858  if (!LWLockAcquireOrWait(WALWriteLock, LW_EXCLUSIVE))
2859  {
2860  /*
2861  * The lock is now free, but we didn't acquire it yet. Before we
2862  * do, loop back to check if someone else flushed the record for
2863  * us already.
2864  */
2865  continue;
2866  }
2867 
2868  /* Got the lock; recheck whether request is satisfied */
2869  LogwrtResult = XLogCtl->LogwrtResult;
2870  if (record <= LogwrtResult.Flush)
2871  {
2872  LWLockRelease(WALWriteLock);
2873  break;
2874  }
2875 
2876  /*
2877  * Sleep before flush! By adding a delay here, we may give further
2878  * backends the opportunity to join the backlog of group commit
2879  * followers; this can significantly improve transaction throughput,
2880  * at the risk of increasing transaction latency.
2881  *
2882  * We do not sleep if enableFsync is not turned on, nor if there are
2883  * fewer than CommitSiblings other backends with active transactions.
2884  */
2885  if (CommitDelay > 0 && enableFsync &&
2887  {
2889 
2890  /*
2891  * Re-check how far we can now flush the WAL. It's generally not
2892  * safe to call WaitXLogInsertionsToFinish while holding
2893  * WALWriteLock, because an in-progress insertion might need to
2894  * also grab WALWriteLock to make progress. But we know that all
2895  * the insertions up to insertpos have already finished, because
2896  * that's what the earlier WaitXLogInsertionsToFinish() returned.
2897  * We're only calling it again to allow insertpos to be moved
2898  * further forward, not to actually wait for anyone.
2899  */
2900  insertpos = WaitXLogInsertionsToFinish(insertpos);
2901  }
2902 
2903  /* try to write/flush later additions to XLOG as well */
2904  WriteRqst.Write = insertpos;
2905  WriteRqst.Flush = insertpos;
2906 
2907  XLogWrite(WriteRqst, false);
2908 
2909  LWLockRelease(WALWriteLock);
2910  /* done */
2911  break;
2912  }
2913 
2914  END_CRIT_SECTION();
2915 
2916  /* wake up walsenders now that we've released heavily contended locks */
2918 
2919  /*
2920  * If we still haven't flushed to the request point then we have a
2921  * problem; most likely, the requested flush point is past end of XLOG.
2922  * This has been seen to occur when a disk page has a corrupted LSN.
2923  *
2924  * Formerly we treated this as a PANIC condition, but that hurts the
2925  * system's robustness rather than helping it: we do not want to take down
2926  * the whole system due to corruption on one data page. In particular, if
2927  * the bad page is encountered again during recovery then we would be
2928  * unable to restart the database at all! (This scenario actually
2929  * happened in the field several times with 7.1 releases.) As of 8.4, bad
2930  * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
2931  * the only time we can reach here during recovery is while flushing the
2932  * end-of-recovery checkpoint record, and we don't expect that to have a
2933  * bad LSN.
2934  *
2935  * Note that for calls from xact.c, the ERROR will be promoted to PANIC
2936  * since xact.c calls this routine inside a critical section. However,
2937  * calls from bufmgr.c are not within critical sections and so we will not
2938  * force a restart for a bad LSN on a data page.
2939  */
2940  if (LogwrtResult.Flush < record)
2941  elog(ERROR,
2942  "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
2943  (uint32) (record >> 32), (uint32) record,
2944  (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
2945 }
2946 
2947 /*
2948  * Write & flush xlog, but without specifying exactly where to.
2949  *
2950  * We normally write only completed blocks; but if there is nothing to do on
2951  * that basis, we check for unwritten async commits in the current incomplete
2952  * block, and write through the latest one of those. Thus, if async commits
2953  * are not being used, we will write complete blocks only.
2954  *
2955  * If, based on the above, there's anything to write we do so immediately. But
2956  * to avoid calling fsync, fdatasync et. al. at a rate that'd impact
2957  * concurrent IO, we only flush WAL every wal_writer_delay ms, or if there's
2958  * more than wal_writer_flush_after unflushed blocks.
2959  *
2960  * We can guarantee that async commits reach disk after at most three
2961  * wal_writer_delay cycles. (When flushing complete blocks, we allow XLogWrite
2962  * to write "flexibly", meaning it can stop at the end of the buffer ring;
2963  * this makes a difference only with very high load or long wal_writer_delay,
2964  * but imposes one extra cycle for the worst case for async commits.)
2965  *
2966  * This routine is invoked periodically by the background walwriter process.
2967  *
2968  * Returns true if there was any work to do, even if we skipped flushing due
2969  * to wal_writer_delay/wal_writer_flush_after.
2970  */
2971 bool
2973 {
2974  XLogwrtRqst WriteRqst;
2975  bool flexible = true;
2976  static TimestampTz lastflush;
2977  TimestampTz now;
2978  int flushbytes;
2979 
2980  /* XLOG doesn't need flushing during recovery */
2981  if (RecoveryInProgress())
2982  return false;
2983 
2984  /* read LogwrtResult and update local state */
2985  SpinLockAcquire(&XLogCtl->info_lck);
2986  LogwrtResult = XLogCtl->LogwrtResult;
2987  WriteRqst = XLogCtl->LogwrtRqst;
2988  SpinLockRelease(&XLogCtl->info_lck);
2989 
2990  /* back off to last completed page boundary */
2991  WriteRqst.Write -= WriteRqst.Write % XLOG_BLCKSZ;
2992 
2993  /* if we have already flushed that far, consider async commit records */
2994  if (WriteRqst.Write <= LogwrtResult.Flush)
2995  {
2996  SpinLockAcquire(&XLogCtl->info_lck);
2997  WriteRqst.Write = XLogCtl->asyncXactLSN;
2998  SpinLockRelease(&XLogCtl->info_lck);
2999  flexible = false; /* ensure it all gets written */
3000  }
3001 
3002  /*
3003  * If already known flushed, we're done. Just need to check if we are
3004  * holding an open file handle to a logfile that's no longer in use,
3005  * preventing the file from being deleted.
3006  */
3007  if (WriteRqst.Write <= LogwrtResult.Flush)
3008  {
3009  if (openLogFile >= 0)
3010  {
3011  if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
3013  {
3014  XLogFileClose();
3015  }
3016  }
3017  return false;
3018  }
3019 
3020  /*
3021  * Determine how far to flush WAL, based on the wal_writer_delay and
3022  * wal_writer_flush_after GUCs.
3023  */
3024  now = GetCurrentTimestamp();
3025  flushbytes =
3026  WriteRqst.Write / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
3027 
3028  if (WalWriterFlushAfter == 0 || lastflush == 0)
3029  {
3030  /* first call, or block based limits disabled */
3031  WriteRqst.Flush = WriteRqst.Write;
3032  lastflush = now;
3033  }
3034  else if (TimestampDifferenceExceeds(lastflush, now, WalWriterDelay))
3035  {
3036  /*
3037  * Flush the writes at least every WalWriteDelay ms. This is important
3038  * to bound the amount of time it takes for an asynchronous commit to
3039  * hit disk.
3040  */
3041  WriteRqst.Flush = WriteRqst.Write;
3042  lastflush = now;
3043  }
3044  else if (flushbytes >= WalWriterFlushAfter)
3045  {
3046  /* exceeded wal_writer_flush_after blocks, flush */
3047  WriteRqst.Flush = WriteRqst.Write;
3048  lastflush = now;
3049  }
3050  else
3051  {
3052  /* no flushing, this time round */
3053  WriteRqst.Flush = 0;
3054  }
3055 
3056 #ifdef WAL_DEBUG
3057  if (XLOG_DEBUG)
3058  elog(LOG, "xlog bg flush request write %X/%X; flush: %X/%X, current is write %X/%X; flush %X/%X",
3059  (uint32) (WriteRqst.Write >> 32), (uint32) WriteRqst.Write,
3060  (uint32) (WriteRqst.Flush >> 32), (uint32) WriteRqst.Flush,
3061  (uint32) (LogwrtResult.Write >> 32), (uint32) LogwrtResult.Write,
3062  (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush);
3063 #endif
3064 
3066 
3067  /* now wait for any in-progress insertions to finish and get write lock */
3068  WaitXLogInsertionsToFinish(WriteRqst.Write);
3069  LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
3070  LogwrtResult = XLogCtl->LogwrtResult;
3071  if (WriteRqst.Write > LogwrtResult.Write ||
3072  WriteRqst.Flush > LogwrtResult.Flush)
3073  {
3074  XLogWrite(WriteRqst, flexible);
3075  }
3076  LWLockRelease(WALWriteLock);
3077 
3078  END_CRIT_SECTION();
3079 
3080  /* wake up walsenders now that we've released heavily contended locks */
3082 
3083  /*
3084  * Great, done. To take some work off the critical path, try to initialize
3085  * as many of the no-longer-needed WAL buffers for future use as we can.
3086  */
3088 
3089  /*
3090  * If we determined that we need to write data, but somebody else
3091  * wrote/flushed already, it should be considered as being active, to
3092  * avoid hibernating too early.
3093  */
3094  return true;
3095 }
3096 
3097 /*
3098  * Test whether XLOG data has been flushed up to (at least) the given position.
3099  *
3100  * Returns true if a flush is still needed. (It may be that someone else
3101  * is already in process of flushing that far, however.)
3102  */
3103 bool
3105 {
3106  /*
3107  * During recovery, we don't flush WAL but update minRecoveryPoint
3108  * instead. So "needs flush" is taken to mean whether minRecoveryPoint
3109  * would need to be updated.
3110  */
3111  if (RecoveryInProgress())
3112  {
3113  /* Quick exit if already known updated */
3114  if (record <= minRecoveryPoint || !updateMinRecoveryPoint)
3115  return false;
3116 
3117  /*
3118  * Update local copy of minRecoveryPoint. But if the lock is busy,
3119  * just return a conservative guess.
3120  */
3121  if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
3122  return true;
3123  minRecoveryPoint = ControlFile->minRecoveryPoint;
3125  LWLockRelease(ControlFileLock);
3126 
3127  /*
3128  * An invalid minRecoveryPoint means that we need to recover all the
3129  * WAL, i.e., we're doing crash recovery. We never modify the control
3130  * file's value in that case, so we can short-circuit future checks
3131  * here too.
3132  */
3133  if (minRecoveryPoint == 0)
3134  updateMinRecoveryPoint = false;
3135 
3136  /* check again */
3137  if (record <= minRecoveryPoint || !updateMinRecoveryPoint)
3138  return false;
3139  else
3140  return true;
3141  }
3142 
3143  /* Quick exit if already known flushed */
3144  if (record <= LogwrtResult.Flush)
3145  return false;
3146 
3147  /* read LogwrtResult and update local state */
3148  SpinLockAcquire(&XLogCtl->info_lck);
3149  LogwrtResult = XLogCtl->LogwrtResult;
3150  SpinLockRelease(&XLogCtl->info_lck);
3151 
3152  /* check again */
3153  if (record <= LogwrtResult.Flush)
3154  return false;
3155 
3156  return true;
3157 }
3158 
3159 /*
3160  * Create a new XLOG file segment, or open a pre-existing one.
3161  *
3162  * log, seg: identify segment to be created/opened.
3163  *
3164  * *use_existent: if true, OK to use a pre-existing file (else, any
3165  * pre-existing file will be deleted). On return, true if a pre-existing
3166  * file was used.
3167  *
3168  * use_lock: if true, acquire ControlFileLock while moving file into
3169  * place. This should be true except during bootstrap log creation. The
3170  * caller must *not* hold the lock at call.
3171  *
3172  * Returns FD of opened file.
3173  *
3174  * Note: errors here are ERROR not PANIC because we might or might not be
3175  * inside a critical section (eg, during checkpoint there is no reason to
3176  * take down the system on failure). They will promote to PANIC if we are
3177  * in a critical section.
3178  */
3179 int
3180 XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
3181 {
3182  char path[MAXPGPATH];
3183  char tmppath[MAXPGPATH];
3184  char zbuffer_raw[XLOG_BLCKSZ + MAXIMUM_ALIGNOF];
3185  char *zbuffer;
3186  XLogSegNo installed_segno;
3187  XLogSegNo max_segno;
3188  int fd;
3189  int nbytes;
3190 
3191  XLogFilePath(path, ThisTimeLineID, logsegno, wal_segment_size);
3192 
3193  /*
3194  * Try to use existent file (checkpoint maker may have created it already)
3195  */
3196  if (*use_existent)
3197  {
3198  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
3199  if (fd < 0)
3200  {
3201  if (errno != ENOENT)
3202  ereport(ERROR,
3204  errmsg("could not open file \"%s\": %m", path)));
3205  }
3206  else
3207  return fd;
3208  }
3209 
3210  /*
3211  * Initialize an empty (all zeroes) segment. NOTE: it is possible that
3212  * another process is doing the same thing. If so, we will end up
3213  * pre-creating an extra log segment. That seems OK, and better than
3214  * holding the lock throughout this lengthy process.
3215  */
3216  elog(DEBUG2, "creating and filling new WAL file");
3217 
3218  snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3219 
3220  unlink(tmppath);
3221 
3222  /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3223  fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3224  if (fd < 0)
3225  ereport(ERROR,
3227  errmsg("could not create file \"%s\": %m", tmppath)));
3228 
3229  /*
3230  * Zero-fill the file. We have to do this the hard way to ensure that all
3231  * the file space has really been allocated --- on platforms that allow
3232  * "holes" in files, just seeking to the end doesn't allocate intermediate
3233  * space. This way, we know that we have all the space and (after the
3234  * fsync below) that all the indirect blocks are down on disk. Therefore,
3235  * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
3236  * log file.
3237  *
3238  * Note: ensure the buffer is reasonably well-aligned; this may save a few
3239  * cycles transferring data to the kernel.
3240  */
3241  zbuffer = (char *) MAXALIGN(zbuffer_raw);
3242  memset(zbuffer, 0, XLOG_BLCKSZ);
3243  for (nbytes = 0; nbytes < wal_segment_size; nbytes += XLOG_BLCKSZ)
3244  {
3245  errno = 0;
3247  if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
3248  {
3249  int save_errno = errno;
3250 
3251  /*
3252  * If we fail to make the file, delete it to release disk space
3253  */
3254  unlink(tmppath);
3255 
3256  close(fd);
3257 
3258  /* if write didn't set errno, assume problem is no disk space */
3259  errno = save_errno ? save_errno : ENOSPC;
3260 
3261  ereport(ERROR,
3263  errmsg("could not write to file \"%s\": %m", tmppath)));
3264  }
3266  }
3267 
3269  if (pg_fsync(fd) != 0)
3270  {
3271  close(fd);
3272  ereport(ERROR,
3274  errmsg("could not fsync file \"%s\": %m", tmppath)));
3275  }
3277 
3278  if (close(fd))
3279  ereport(ERROR,
3281  errmsg("could not close file \"%s\": %m", tmppath)));
3282 
3283  /*
3284  * Now move the segment into place with its final name.
3285  *
3286  * If caller didn't want to use a pre-existing file, get rid of any
3287  * pre-existing file. Otherwise, cope with possibility that someone else
3288  * has created the file while we were filling ours: if so, use ours to
3289  * pre-create a future log segment.
3290  */
3291  installed_segno = logsegno;
3292 
3293  /*
3294  * XXX: What should we use as max_segno? We used to use XLOGfileslop when
3295  * that was a constant, but that was always a bit dubious: normally, at a
3296  * checkpoint, XLOGfileslop was the offset from the checkpoint record, but
3297  * here, it was the offset from the insert location. We can't do the
3298  * normal XLOGfileslop calculation here because we don't have access to
3299  * the prior checkpoint's redo location. So somewhat arbitrarily, just use
3300  * CheckPointSegments.
3301  */
3302  max_segno = logsegno + CheckPointSegments;
3303  if (!InstallXLogFileSegment(&installed_segno, tmppath,
3304  *use_existent, max_segno,
3305  use_lock))
3306  {
3307  /*
3308  * No need for any more future segments, or InstallXLogFileSegment()
3309  * failed to rename the file into place. If the rename failed, opening
3310  * the file below will fail.
3311  */
3312  unlink(tmppath);
3313  }
3314 
3315  /* Set flag to tell caller there was no existent file */
3316  *use_existent = false;
3317 
3318  /* Now open original target segment (might not be file I just made) */
3319  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
3320  if (fd < 0)
3321  ereport(ERROR,
3323  errmsg("could not open file \"%s\": %m", path)));
3324 
3325  elog(DEBUG2, "done creating and filling new WAL file");
3326 
3327  return fd;
3328 }
3329 
3330 /*
3331  * Create a new XLOG file segment by copying a pre-existing one.
3332  *
3333  * destsegno: identify segment to be created.
3334  *
3335  * srcTLI, srcsegno: identify segment to be copied (could be from
3336  * a different timeline)
3337  *
3338  * upto: how much of the source file to copy (the rest is filled with
3339  * zeros)
3340  *
3341  * Currently this is only used during recovery, and so there are no locking
3342  * considerations. But we should be just as tense as XLogFileInit to avoid
3343  * emplacing a bogus file.
3344  */
3345 static void
3346 XLogFileCopy(XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno,
3347  int upto)
3348 {
3349  char path[MAXPGPATH];
3350  char tmppath[MAXPGPATH];
3351  char buffer[XLOG_BLCKSZ];
3352  int srcfd;
3353  int fd;
3354  int nbytes;
3355 
3356  /*
3357  * Open the source file
3358  */
3359  XLogFilePath(path, srcTLI, srcsegno, wal_segment_size);
3360  srcfd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3361  if (srcfd < 0)
3362  ereport(ERROR,
3364  errmsg("could not open file \"%s\": %m", path)));
3365 
3366  /*
3367  * Copy into a temp file name.
3368  */
3369  snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3370 
3371  unlink(tmppath);
3372 
3373  /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3374  fd = OpenTransientFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3375  if (fd < 0)
3376  ereport(ERROR,
3378  errmsg("could not create file \"%s\": %m", tmppath)));
3379 
3380  /*
3381  * Do the data copying.
3382  */
3383  for (nbytes = 0; nbytes < wal_segment_size; nbytes += sizeof(buffer))
3384  {
3385  int nread;
3386 
3387  nread = upto - nbytes;
3388 
3389  /*
3390  * The part that is not read from the source file is filled with
3391  * zeros.
3392  */
3393  if (nread < sizeof(buffer))
3394  memset(buffer, 0, sizeof(buffer));
3395 
3396  if (nread > 0)
3397  {
3398  if (nread > sizeof(buffer))
3399  nread = sizeof(buffer);
3400  errno = 0;
3402  if (read(srcfd, buffer, nread) != nread)
3403  {
3404  if (errno != 0)
3405  ereport(ERROR,
3407  errmsg("could not read file \"%s\": %m",
3408  path)));
3409  else
3410  ereport(ERROR,
3411  (errmsg("not enough data in file \"%s\"",
3412  path)));
3413  }
3415  }
3416  errno = 0;
3418  if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
3419  {
3420  int save_errno = errno;
3421 
3422  /*
3423  * If we fail to make the file, delete it to release disk space
3424  */
3425  unlink(tmppath);
3426  /* if write didn't set errno, assume problem is no disk space */
3427  errno = save_errno ? save_errno : ENOSPC;
3428 
3429  ereport(ERROR,
3431  errmsg("could not write to file \"%s\": %m", tmppath)));
3432  }
3434  }
3435 
3437  if (pg_fsync(fd) != 0)
3438  ereport(ERROR,
3440  errmsg("could not fsync file \"%s\": %m", tmppath)));
3442 
3443  if (CloseTransientFile(fd))
3444  ereport(ERROR,
3446  errmsg("could not close file \"%s\": %m", tmppath)));
3447 
3448  CloseTransientFile(srcfd);
3449 
3450  /*
3451  * Now move the segment into place with its final name.
3452  */
3453  if (!InstallXLogFileSegment(&destsegno, tmppath, false, 0, false))
3454  elog(ERROR, "InstallXLogFileSegment should not have failed");
3455 }
3456 
3457 /*
3458  * Install a new XLOG segment file as a current or future log segment.
3459  *
3460  * This is used both to install a newly-created segment (which has a temp
3461  * filename while it's being created) and to recycle an old segment.
3462  *
3463  * *segno: identify segment to install as (or first possible target).
3464  * When find_free is true, this is modified on return to indicate the
3465  * actual installation location or last segment searched.
3466  *
3467  * tmppath: initial name of file to install. It will be renamed into place.
3468  *
3469  * find_free: if true, install the new segment at the first empty segno
3470  * number at or after the passed numbers. If false, install the new segment
3471  * exactly where specified, deleting any existing segment file there.
3472  *
3473  * max_segno: maximum segment number to install the new file as. Fail if no
3474  * free slot is found between *segno and max_segno. (Ignored when find_free
3475  * is false.)
3476  *
3477  * use_lock: if true, acquire ControlFileLock while moving file into
3478  * place. This should be true except during bootstrap log creation. The
3479  * caller must *not* hold the lock at call.
3480  *
3481  * Returns true if the file was installed successfully. false indicates that
3482  * max_segno limit was exceeded, or an error occurred while renaming the
3483  * file into place.
3484  */
3485 static bool
3486 InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
3487  bool find_free, XLogSegNo max_segno,
3488  bool use_lock)
3489 {
3490  char path[MAXPGPATH];
3491  struct stat stat_buf;
3492 
3494 
3495  /*
3496  * We want to be sure that only one process does this at a time.
3497  */
3498  if (use_lock)
3499  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3500 
3501  if (!find_free)
3502  {
3503  /* Force installation: get rid of any pre-existing segment file */
3504  durable_unlink(path, DEBUG1);
3505  }
3506  else
3507  {
3508  /* Find a free slot to put it in */
3509  while (stat(path, &stat_buf) == 0)
3510  {
3511  if ((*segno) >= max_segno)
3512  {
3513  /* Failed to find a free slot within specified range */
3514  if (use_lock)
3515  LWLockRelease(ControlFileLock);
3516  return false;
3517  }
3518  (*segno)++;
3520  }
3521  }
3522 
3523  /*
3524  * Perform the rename using link if available, paranoidly trying to avoid
3525  * overwriting an existing file (there shouldn't be one).
3526  */
3527  if (durable_link_or_rename(tmppath, path, LOG) != 0)
3528  {
3529  if (use_lock)
3530  LWLockRelease(ControlFileLock);
3531  /* durable_link_or_rename already emitted log message */
3532  return false;
3533  }
3534 
3535  if (use_lock)
3536  LWLockRelease(ControlFileLock);
3537 
3538  return true;
3539 }
3540 
3541 /*
3542  * Open a pre-existing logfile segment for writing.
3543  */
3544 int
3546 {
3547  char path[MAXPGPATH];
3548  int fd;
3549 
3551 
3552  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method));
3553  if (fd < 0)
3554  ereport(PANIC,
3556  errmsg("could not open write-ahead log file \"%s\": %m", path)));
3557 
3558  return fd;
3559 }
3560 
3561 /*
3562  * Open a logfile segment for reading (during recovery).
3563  *
3564  * If source == XLOG_FROM_ARCHIVE, the segment is retrieved from archive.
3565  * Otherwise, it's assumed to be already available in pg_wal.
3566  */
3567 static int
3568 XLogFileRead(XLogSegNo segno, int emode, TimeLineID tli,
3569  int source, bool notfoundOk)
3570 {
3571  char xlogfname[MAXFNAMELEN];
3572  char activitymsg[MAXFNAMELEN + 16];
3573  char path[MAXPGPATH];
3574  int fd;
3575 
3576  XLogFileName(xlogfname, tli, segno, wal_segment_size);
3577 
3578  switch (source)
3579  {
3580  case XLOG_FROM_ARCHIVE:
3581  /* Report recovery progress in PS display */
3582  snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
3583  xlogfname);
3584  set_ps_display(activitymsg, false);
3585 
3586  restoredFromArchive = RestoreArchivedFile(path, xlogfname,
3587  "RECOVERYXLOG",
3589  InRedo);
3590  if (!restoredFromArchive)
3591  return -1;
3592  break;
3593 
3594  case XLOG_FROM_PG_WAL:
3595  case XLOG_FROM_STREAM:
3596  XLogFilePath(path, tli, segno, wal_segment_size);
3597  restoredFromArchive = false;
3598  break;
3599 
3600  default:
3601  elog(ERROR, "invalid XLogFileRead source %d", source);
3602  }
3603 
3604  /*
3605  * If the segment was fetched from archival storage, replace the existing
3606  * xlog segment (if any) with the archival version.
3607  */
3608  if (source == XLOG_FROM_ARCHIVE)
3609  {
3610  KeepFileRestoredFromArchive(path, xlogfname);
3611 
3612  /*
3613  * Set path to point at the new file in pg_wal.
3614  */
3615  snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
3616  }
3617 
3618  fd = BasicOpenFile(path, O_RDONLY | PG_BINARY);
3619  if (fd >= 0)
3620  {
3621  /* Success! */
3622  curFileTLI = tli;
3623 
3624  /* Report recovery progress in PS display */
3625  snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
3626  xlogfname);
3627  set_ps_display(activitymsg, false);
3628 
3629  /* Track source of data in assorted state variables */
3630  readSource = source;
3631  XLogReceiptSource = source;
3632  /* In FROM_STREAM case, caller tracks receipt time, not me */
3633  if (source != XLOG_FROM_STREAM)
3635 
3636  return fd;
3637  }
3638  if (errno != ENOENT || !notfoundOk) /* unexpected failure? */
3639  ereport(PANIC,
3641  errmsg("could not open file \"%s\": %m", path)));
3642  return -1;
3643 }
3644 
3645 /*
3646  * Open a logfile segment for reading (during recovery).
3647  *
3648  * This version searches for the segment with any TLI listed in expectedTLEs.
3649  */
3650 static int
3651 XLogFileReadAnyTLI(XLogSegNo segno, int emode, int source)
3652 {
3653  char path[MAXPGPATH];
3654  ListCell *cell;
3655  int fd;
3656  List *tles;
3657 
3658  /*
3659  * Loop looking for a suitable timeline ID: we might need to read any of
3660  * the timelines listed in expectedTLEs.
3661  *
3662  * We expect curFileTLI on entry to be the TLI of the preceding file in
3663  * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
3664  * to go backwards; this prevents us from picking up the wrong file when a
3665  * parent timeline extends to higher segment numbers than the child we
3666  * want to read.
3667  *
3668  * If we haven't read the timeline history file yet, read it now, so that
3669  * we know which TLIs to scan. We don't save the list in expectedTLEs,
3670  * however, unless we actually find a valid segment. That way if there is
3671  * neither a timeline history file nor a WAL segment in the archive, and
3672  * streaming replication is set up, we'll read the timeline history file
3673  * streamed from the master when we start streaming, instead of recovering
3674  * with a dummy history generated here.
3675  */
3676  if (expectedTLEs)
3677  tles = expectedTLEs;
3678  else
3680 
3681  foreach(cell, tles)
3682  {
3683  TimeLineID tli = ((TimeLineHistoryEntry *) lfirst(cell))->tli;
3684 
3685  if (tli < curFileTLI)
3686  break; /* don't bother looking at too-old TLIs */
3687 
3688  if (source == XLOG_FROM_ANY || source == XLOG_FROM_ARCHIVE)
3689  {
3690  fd = XLogFileRead(segno, emode, tli,
3691  XLOG_FROM_ARCHIVE, true);
3692  if (fd != -1)
3693  {
3694  elog(DEBUG1, "got WAL segment from archive");
3695  if (!expectedTLEs)
3696  expectedTLEs = tles;
3697  return fd;
3698  }
3699  }
3700 
3701  if (source == XLOG_FROM_ANY || source == XLOG_FROM_PG_WAL)
3702  {
3703  fd = XLogFileRead(segno, emode, tli,
3704  XLOG_FROM_PG_WAL, true);
3705  if (fd != -1)
3706  {
3707  if (!expectedTLEs)
3708  expectedTLEs = tles;
3709  return fd;
3710  }
3711  }
3712  }
3713 
3714  /* Couldn't find it. For simplicity, complain about front timeline */
3716  errno = ENOENT;
3717  ereport(emode,
3719  errmsg("could not open file \"%s\": %m", path)));
3720  return -1;
3721 }
3722 
3723 /*
3724  * Close the current logfile segment for writing.
3725  */
3726 static void
3728 {
3729  Assert(openLogFile >= 0);
3730 
3731  /*
3732  * WAL segment files will not be re-read in normal operation, so we advise
3733  * the OS to release any cached pages. But do not do so if WAL archiving
3734  * or streaming is active, because archiver and walsender process could
3735  * use the cache to read the WAL segment.
3736  */
3737 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3738  if (!XLogIsNeeded())
3739  (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3740 #endif
3741 
3742  if (close(openLogFile))
3743  ereport(PANIC,
3745  errmsg("could not close log file %s: %m",
3747  openLogFile = -1;
3748 }
3749 
3750 /*
3751  * Preallocate log files beyond the specified log endpoint.
3752  *
3753  * XXX this is currently extremely conservative, since it forces only one
3754  * future log segment to exist, and even that only if we are 75% done with
3755  * the current one. This is only appropriate for very low-WAL-volume systems.
3756  * High-volume systems will be OK once they've built up a sufficient set of
3757  * recycled log segments, but the startup transient is likely to include
3758  * a lot of segment creations by foreground processes, which is not so good.
3759  */
3760 static void
3762 {
3763  XLogSegNo _logSegNo;
3764  int lf;
3765  bool use_existent;
3766  uint64 offset;
3767 
3768  XLByteToPrevSeg(endptr, _logSegNo, wal_segment_size);
3769  offset = XLogSegmentOffset(endptr - 1, wal_segment_size);
3770  if (offset >= (uint32) (0.75 * wal_segment_size))
3771  {
3772  _logSegNo++;
3773  use_existent = true;
3774  lf = XLogFileInit(_logSegNo, &use_existent, true);
3775  close(lf);
3776  if (!use_existent)
3777  CheckpointStats.ckpt_segs_added++;
3778  }
3779 }
3780 
3781 /*
3782  * Throws an error if the given log segment has already been removed or
3783  * recycled. The caller should only pass a segment that it knows to have
3784  * existed while the server has been running, as this function always
3785  * succeeds if no WAL segments have been removed since startup.
3786  * 'tli' is only used in the error message.
3787  *
3788  * Note: this function guarantees to keep errno unchanged on return.
3789  * This supports callers that use this to possibly deliver a better
3790  * error message about a missing file, while still being able to throw
3791  * a normal file-access error afterwards, if this does return.
3792  */
3793 void
3795 {
3796  int save_errno = errno;
3797  XLogSegNo lastRemovedSegNo;
3798 
3799  SpinLockAcquire(&XLogCtl->info_lck);
3800  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3801  SpinLockRelease(&XLogCtl->info_lck);
3802 
3803  if (segno <= lastRemovedSegNo)
3804  {
3805  char filename[MAXFNAMELEN];
3806 
3807  XLogFileName(filename, tli, segno, wal_segment_size);
3808  errno = save_errno;
3809  ereport(ERROR,
3811  errmsg("requested WAL segment %s has already been removed",
3812  filename)));
3813  }
3814  errno = save_errno;
3815 }
3816 
3817 /*
3818  * Return the last WAL segment removed, or 0 if no segment has been removed
3819  * since startup.
3820  *
3821  * NB: the result can be out of date arbitrarily fast, the caller has to deal
3822  * with that.
3823  */
3824 XLogSegNo
3826 {
3827  XLogSegNo lastRemovedSegNo;
3828 
3829  SpinLockAcquire(&XLogCtl->info_lck);
3830  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3831  SpinLockRelease(&XLogCtl->info_lck);
3832 
3833  return lastRemovedSegNo;
3834 }
3835 
3836 /*
3837  * Update the last removed segno pointer in shared memory, to reflect
3838  * that the given XLOG file has been removed.
3839  */
3840 static void
3842 {
3843  uint32 tli;
3844  XLogSegNo segno;
3845 
3846  XLogFromFileName(filename, &tli, &segno, wal_segment_size);
3847 
3848  SpinLockAcquire(&XLogCtl->info_lck);
3849  if (segno > XLogCtl->lastRemovedSegNo)
3850  XLogCtl->lastRemovedSegNo = segno;
3851  SpinLockRelease(&XLogCtl->info_lck);
3852 }
3853 
3854 /*
3855  * Recycle or remove all log files older or equal to passed segno.
3856  *
3857  * endptr is current (or recent) end of xlog, and PriorRedoRecPtr is the
3858  * redo pointer of the previous checkpoint. These are used to determine
3859  * whether we want to recycle rather than delete no-longer-wanted log files.
3860  */
3861 static void
3863 {
3864  DIR *xldir;
3865  struct dirent *xlde;
3866  char lastoff[MAXFNAMELEN];
3867 
3868  /*
3869  * Construct a filename of the last segment to be kept. The timeline ID
3870  * doesn't matter, we ignore that in the comparison. (During recovery,
3871  * ThisTimeLineID isn't set, so we can't use that.)
3872  */
3873  XLogFileName(lastoff, 0, segno, wal_segment_size);
3874 
3875  elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
3876  lastoff);
3877 
3878  xldir = AllocateDir(XLOGDIR);
3879 
3880  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3881  {
3882  /* Ignore files that are not XLOG segments */
3883  if (!IsXLogFileName(xlde->d_name) &&
3884  !IsPartialXLogFileName(xlde->d_name))
3885  continue;
3886 
3887  /*
3888  * We ignore the timeline part of the XLOG segment identifiers in
3889  * deciding whether a segment is still needed. This ensures that we
3890  * won't prematurely remove a segment from a parent timeline. We could
3891  * probably be a little more proactive about removing segments of
3892  * non-parent timelines, but that would be a whole lot more
3893  * complicated.
3894  *
3895  * We use the alphanumeric sorting property of the filenames to decide
3896  * which ones are earlier than the lastoff segment.
3897  */
3898  if (strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
3899  {
3900  if (XLogArchiveCheckDone(xlde->d_name))
3901  {
3902  /* Update the last removed location in shared memory first */
3904 
3905  RemoveXlogFile(xlde->d_name, PriorRedoPtr, endptr);
3906  }
3907  }
3908  }
3909 
3910  FreeDir(xldir);
3911 }
3912 
3913 /*
3914  * Remove WAL files that are not part of the given timeline's history.
3915  *
3916  * This is called during recovery, whenever we switch to follow a new
3917  * timeline, and at the end of recovery when we create a new timeline. We
3918  * wouldn't otherwise care about extra WAL files lying in pg_wal, but they
3919  * might be leftover pre-allocated or recycled WAL segments on the old timeline
3920  * that we haven't used yet, and contain garbage. If we just leave them in
3921  * pg_wal, they will eventually be archived, and we can't let that happen.
3922  * Files that belong to our timeline history are valid, because we have
3923  * successfully replayed them, but from others we can't be sure.
3924  *
3925  * 'switchpoint' is the current point in WAL where we switch to new timeline,
3926  * and 'newTLI' is the new timeline we switch to.
3927  */
3928 static void
3930 {
3931  DIR *xldir;
3932  struct dirent *xlde;
3933  char switchseg[MAXFNAMELEN];
3934  XLogSegNo endLogSegNo;
3935 
3936  XLByteToPrevSeg(switchpoint, endLogSegNo, wal_segment_size);
3937 
3938  /*
3939  * Construct a filename of the last segment to be kept.
3940  */
3941  XLogFileName(switchseg, newTLI, endLogSegNo, wal_segment_size);
3942 
3943  elog(DEBUG2, "attempting to remove WAL segments newer than log file %s",
3944  switchseg);
3945 
3946  xldir = AllocateDir(XLOGDIR);
3947 
3948  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3949  {
3950  /* Ignore files that are not XLOG segments */
3951  if (!IsXLogFileName(xlde->d_name))
3952  continue;
3953 
3954  /*
3955  * Remove files that are on a timeline older than the new one we're
3956  * switching to, but with a segment number >= the first segment on the
3957  * new timeline.
3958  */
3959  if (strncmp(xlde->d_name, switchseg, 8) < 0 &&
3960  strcmp(xlde->d_name + 8, switchseg + 8) > 0)
3961  {
3962  /*
3963  * If the file has already been marked as .ready, however, don't
3964  * remove it yet. It should be OK to remove it - files that are
3965  * not part of our timeline history are not required for recovery
3966  * - but seems safer to let them be archived and removed later.
3967  */
3968  if (!XLogArchiveIsReady(xlde->d_name))
3969  RemoveXlogFile(xlde->d_name, InvalidXLogRecPtr, switchpoint);
3970  }
3971  }
3972 
3973  FreeDir(xldir);
3974 }
3975 
3976 /*
3977  * Recycle or remove a log file that's no longer needed.
3978  *
3979  * endptr is current (or recent) end of xlog, and PriorRedoRecPtr is the
3980  * redo pointer of the previous checkpoint. These are used to determine
3981  * whether we want to recycle rather than delete no-longer-wanted log files.
3982  * If PriorRedoRecPtr is not known, pass invalid, and the function will
3983  * recycle, somewhat arbitrarily, 10 future segments.
3984  */
3985 static void
3986 RemoveXlogFile(const char *segname, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
3987 {
3988  char path[MAXPGPATH];
3989 #ifdef WIN32
3990  char newpath[MAXPGPATH];
3991 #endif
3992  struct stat statbuf;
3993  XLogSegNo endlogSegNo;
3994  XLogSegNo recycleSegNo;
3995 
3996  /*
3997  * Initialize info about where to try to recycle to.
3998  */
3999  XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
4000  if (PriorRedoPtr == InvalidXLogRecPtr)
4001  recycleSegNo = endlogSegNo + 10;
4002  else
4003  recycleSegNo = XLOGfileslop(PriorRedoPtr);
4004 
4005  snprintf(path, MAXPGPATH, XLOGDIR "/%s", segname);
4006 
4007  /*
4008  * Before deleting the file, see if it can be recycled as a future log
4009  * segment. Only recycle normal files, pg_standby for example can create
4010  * symbolic links pointing to a separate archive directory.
4011  */
4012  if (endlogSegNo <= recycleSegNo &&
4013  lstat(path, &statbuf) == 0 && S_ISREG(statbuf.st_mode) &&
4014  InstallXLogFileSegment(&endlogSegNo, path,
4015  true, recycleSegNo, true))
4016  {
4017  ereport(DEBUG2,
4018  (errmsg("recycled write-ahead log file \"%s\"",
4019  segname)));
4020  CheckpointStats.ckpt_segs_recycled++;
4021  /* Needn't recheck that slot on future iterations */
4022  endlogSegNo++;
4023  }
4024  else
4025  {
4026  /* No need for any more future segments... */
4027  int rc;
4028 
4029  ereport(DEBUG2,
4030  (errmsg("removing write-ahead log file \"%s\"",
4031  segname)));
4032 
4033 #ifdef WIN32
4034 
4035  /*
4036  * On Windows, if another process (e.g another backend) holds the file
4037  * open in FILE_SHARE_DELETE mode, unlink will succeed, but the file
4038  * will still show up in directory listing until the last handle is
4039  * closed. To avoid confusing the lingering deleted file for a live
4040  * WAL file that needs to be archived, rename it before deleting it.
4041  *
4042  * If another process holds the file open without FILE_SHARE_DELETE
4043  * flag, rename will fail. We'll try again at the next checkpoint.
4044  */
4045  snprintf(newpath, MAXPGPATH, "%s.deleted", path);
4046  if (rename(path, newpath) != 0)
4047  {
4048  ereport(LOG,
4050  errmsg("could not rename old write-ahead log file \"%s\": %m",
4051  path)));
4052  return;
4053  }
4054  rc = durable_unlink(newpath, LOG);
4055 #else
4056  rc = durable_unlink(path, LOG);
4057 #endif
4058  if (rc != 0)
4059  {
4060  /* Message already logged by durable_unlink() */
4061  return;
4062  }
4063  CheckpointStats.ckpt_segs_removed++;
4064  }
4065 
4066  XLogArchiveCleanup(segname);
4067 }
4068 
4069 /*
4070  * Verify whether pg_wal and pg_wal/archive_status exist.
4071  * If the latter does not exist, recreate it.
4072  *
4073  * It is not the goal of this function to verify the contents of these
4074  * directories, but to help in cases where someone has performed a cluster
4075  * copy for PITR purposes but omitted pg_wal from the copy.
4076  *
4077  * We could also recreate pg_wal if it doesn't exist, but a deliberate
4078  * policy decision was made not to. It is fairly common for pg_wal to be
4079  * a symlink, and if that was the DBA's intent then automatically making a
4080  * plain directory would result in degraded performance with no notice.
4081  */
4082 static void
4084 {
4085  char path[MAXPGPATH];
4086  struct stat stat_buf;
4087 
4088  /* Check for pg_wal; if it doesn't exist, error out */
4089  if (stat(XLOGDIR, &stat_buf) != 0 ||
4090  !S_ISDIR(stat_buf.st_mode))
4091  ereport(FATAL,
4092  (errmsg("required WAL directory \"%s\" does not exist",
4093  XLOGDIR)));
4094 
4095  /* Check for archive_status */
4096  snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
4097  if (stat(path, &stat_buf) == 0)
4098  {
4099  /* Check for weird cases where it exists but isn't a directory */
4100  if (!S_ISDIR(stat_buf.st_mode))
4101  ereport(FATAL,
4102  (errmsg("required WAL directory \"%s\" does not exist",
4103  path)));
4104  }
4105  else
4106  {
4107  ereport(LOG,
4108  (errmsg("creating missing WAL directory \"%s\"", path)));
4109  if (MakePGDirectory(path) < 0)
4110  ereport(FATAL,
4111  (errmsg("could not create missing directory \"%s\": %m",
4112  path)));
4113  }
4114 }
4115 
4116 /*
4117  * Remove previous backup history files. This also retries creation of
4118  * .ready files for any backup history files for which XLogArchiveNotify
4119  * failed earlier.
4120  */
4121 static void
4123 {
4124  DIR *xldir;
4125  struct dirent *xlde;
4126  char path[MAXPGPATH + sizeof(XLOGDIR)];
4127 
4128  xldir = AllocateDir(XLOGDIR);
4129 
4130  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4131  {
4132  if (IsBackupHistoryFileName(xlde->d_name))
4133  {
4134  if (XLogArchiveCheckDone(xlde->d_name))
4135  {
4136  elog(DEBUG2, "removing WAL backup history file \"%s\"",
4137  xlde->d_name);
4138  snprintf(path, sizeof(path), XLOGDIR "/%s", xlde->d_name);
4139  unlink(path);
4140  XLogArchiveCleanup(xlde->d_name);
4141  }
4142  }
4143  }
4144 
4145  FreeDir(xldir);
4146 }
4147 
4148 /*
4149  * Attempt to read an XLOG record.
4150  *
4151  * If RecPtr is valid, try to read a record at that position. Otherwise
4152  * try to read a record just after the last one previously read.
4153  *
4154  * If no valid record is available, returns NULL, or fails if emode is PANIC.
4155  * (emode must be either PANIC, LOG). In standby mode, retries until a valid
4156  * record is available.
4157  *
4158  * The record is copied into readRecordBuf, so that on successful return,
4159  * the returned record pointer always points there.
4160  */
4161 static XLogRecord *
4162 ReadRecord(XLogReaderState *xlogreader, XLogRecPtr RecPtr, int emode,
4163  bool fetching_ckpt)
4164 {
4165  XLogRecord *record;
4166  XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
4167 
4168  /* Pass through parameters to XLogPageRead */
4169  private->fetching_ckpt = fetching_ckpt;
4170  private->emode = emode;
4171  private->randAccess = (RecPtr != InvalidXLogRecPtr);
4172 
4173  /* This is the first attempt to read this page. */
4174  lastSourceFailed = false;
4175 
4176  for (;;)
4177  {
4178  char *errormsg;
4179 
4180  record = XLogReadRecord(xlogreader, RecPtr, &errormsg);
4181  ReadRecPtr = xlogreader->ReadRecPtr;
4182  EndRecPtr = xlogreader->EndRecPtr;
4183  if (record == NULL)
4184  {
4185  if (readFile >= 0)
4186  {
4187  close(readFile);
4188  readFile = -1;
4189  }
4190 
4191  /*
4192  * We only end up here without a message when XLogPageRead()
4193  * failed - in that case we already logged something. In
4194  * StandbyMode that only happens if we have been triggered, so we
4195  * shouldn't loop anymore in that case.
4196  */
4197  if (errormsg)
4199  RecPtr ? RecPtr : EndRecPtr),
4200  (errmsg_internal("%s", errormsg) /* already translated */ ));
4201  }
4202 
4203  /*
4204  * Check page TLI is one of the expected values.
4205  */
4206  else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
4207  {
4208  char fname[MAXFNAMELEN];
4209  XLogSegNo segno;
4210  int32 offset;
4211 
4212  XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
4213  offset = XLogSegmentOffset(xlogreader->latestPagePtr,
4215  XLogFileName(fname, xlogreader->readPageTLI, segno,
4218  RecPtr ? RecPtr : EndRecPtr),
4219  (errmsg("unexpected timeline ID %u in log segment %s, offset %u",
4220  xlogreader->latestPageTLI,
4221  fname,
4222  offset)));
4223  record = NULL;
4224  }
4225 
4226  if (record)
4227  {
4228  /* Great, got a record */
4229  return record;
4230  }
4231  else
4232  {
4233  /* No valid record available from this source */
4234  lastSourceFailed = true;
4235 
4236  /*
4237  * If archive recovery was requested, but we were still doing
4238  * crash recovery, switch to archive recovery and retry using the
4239  * offline archive. We have now replayed all the valid WAL in
4240  * pg_wal, so we are presumably now consistent.
4241  *
4242  * We require that there's at least some valid WAL present in
4243  * pg_wal, however (!fetching_ckpt). We could recover using the
4244  * WAL from the archive, even if pg_wal is completely empty, but
4245  * we'd have no idea how far we'd have to replay to reach
4246  * consistency. So err on the safe side and give up.
4247  */
4249  !fetching_ckpt)
4250  {
4251  ereport(DEBUG1,
4252  (errmsg_internal("reached end of WAL in pg_wal, entering archive recovery")));
4253  InArchiveRecovery = true;
4255  StandbyMode = true;
4256 
4257  /* initialize minRecoveryPoint to this record */
4258  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
4259  ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4260  if (ControlFile->minRecoveryPoint < EndRecPtr)
4261  {
4262  ControlFile->minRecoveryPoint = EndRecPtr;
4263  ControlFile->minRecoveryPointTLI = ThisTimeLineID;
4264  }
4265  /* update local copy */
4266  minRecoveryPoint = ControlFile->minRecoveryPoint;
4268 
4270  LWLockRelease(ControlFileLock);
4271 
4273 
4274  /*
4275  * Before we retry, reset lastSourceFailed and currentSource
4276  * so that we will check the archive next.
4277  */
4278  lastSourceFailed = false;
4279  currentSource = 0;
4280 
4281  continue;
4282  }
4283 
4284  /* In standby mode, loop back to retry. Otherwise, give up. */
4286  continue;
4287  else
4288  return NULL;
4289  }
4290  }
4291 }
4292 
4293 /*
4294  * Scan for new timelines that might have appeared in the archive since we
4295  * started recovery.
4296  *
4297  * If there are any, the function changes recovery target TLI to the latest
4298  * one and returns 'true'.
4299  */
4300 static bool
4302 {
4303  List *newExpectedTLEs;
4304  bool found;
4305  ListCell *cell;
4306  TimeLineID newtarget;
4307  TimeLineID oldtarget = recoveryTargetTLI;
4308  TimeLineHistoryEntry *currentTle = NULL;
4309 
4311  if (newtarget == recoveryTargetTLI)
4312  {
4313  /* No new timelines found */
4314  return false;
4315  }
4316 
4317  /*
4318  * Determine the list of expected TLIs for the new TLI
4319  */
4320 
4321  newExpectedTLEs = readTimeLineHistory(newtarget);
4322 
4323  /*
4324  * If the current timeline is not part of the history of the new timeline,
4325  * we cannot proceed to it.
4326  */
4327  found = false;
4328  foreach(cell, newExpectedTLEs)
4329  {
4330  currentTle = (TimeLineHistoryEntry *) lfirst(cell);
4331 
4332  if (currentTle->tli == recoveryTargetTLI)
4333  {
4334  found = true;
4335  break;
4336  }
4337  }
4338  if (!found)
4339  {
4340  ereport(LOG,
4341  (errmsg("new timeline %u is not a child of database system timeline %u",
4342  newtarget,
4343  ThisTimeLineID)));
4344  return false;
4345  }
4346 
4347  /*
4348  * The current timeline was found in the history file, but check that the
4349  * next timeline was forked off from it *after* the current recovery
4350  * location.
4351  */
4352  if (currentTle->end < EndRecPtr)
4353  {
4354  ereport(LOG,
4355  (errmsg("new timeline %u forked off current database system timeline %u before current recovery point %X/%X",
4356  newtarget,
4358  (uint32) (EndRecPtr >> 32), (uint32) EndRecPtr)));
4359  return false;
4360  }
4361 
4362  /* The new timeline history seems valid. Switch target */
4363  recoveryTargetTLI = newtarget;
4364  list_free_deep(expectedTLEs);
4365  expectedTLEs = newExpectedTLEs;
4366 
4367  /*
4368  * As in StartupXLOG(), try to ensure we have all the history files
4369  * between the old target and new target in pg_wal.
4370  */
4371  restoreTimeLineHistoryFiles(oldtarget + 1, newtarget);
4372 
4373  ereport(LOG,
4374  (errmsg("new target timeline is %u",
4375  recoveryTargetTLI)));
4376 
4377  return true;
4378 }
4379 
4380 /*
4381  * I/O routines for pg_control
4382  *
4383  * *ControlFile is a buffer in shared memory that holds an image of the
4384  * contents of pg_control. WriteControlFile() initializes pg_control
4385  * given a preloaded buffer, ReadControlFile() loads the buffer from
4386  * the pg_control file (during postmaster or standalone-backend startup),
4387  * and UpdateControlFile() rewrites pg_control after we modify xlog state.
4388  *
4389  * For simplicity, WriteControlFile() initializes the fields of pg_control
4390  * that are related to checking backend/database compatibility, and
4391  * ReadControlFile() verifies they are correct. We could split out the
4392  * I/O and compatibility-check functions, but there seems no need currently.
4393  */
4394 static void
4396 {
4397  int fd;
4398  char buffer[PG_CONTROL_FILE_SIZE]; /* need not be aligned */
4399 
4400  /*
4401  * Ensure that the size of the pg_control data structure is sane. See the
4402  * comments for these symbols in pg_control.h.
4403  */
4405  "pg_control is too large for atomic disk writes");
4407  "sizeof(ControlFileData) exceeds PG_CONTROL_FILE_SIZE");
4408 
4409  /*
4410  * Initialize version and compatibility-check fields
4411  */
4412  ControlFile->pg_control_version = PG_CONTROL_VERSION;
4413  ControlFile->catalog_version_no = CATALOG_VERSION_NO;
4414 
4415  ControlFile->maxAlign = MAXIMUM_ALIGNOF;
4416  ControlFile->floatFormat = FLOATFORMAT_VALUE;
4417 
4418  ControlFile->blcksz = BLCKSZ;
4419  ControlFile->relseg_size = RELSEG_SIZE;
4420  ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4421  ControlFile->xlog_seg_size = wal_segment_size;
4422 
4423  ControlFile->nameDataLen = NAMEDATALEN;
4424  ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
4425 
4427  ControlFile->loblksize = LOBLKSIZE;
4428 
4429  ControlFile->float4ByVal = FLOAT4PASSBYVAL;
4430  ControlFile->float8ByVal = FLOAT8PASSBYVAL;
4431 
4432  /* Contents are protected with a CRC */
4433  INIT_CRC32C(ControlFile->crc);
4434  COMP_CRC32C(ControlFile->crc,
4435  (char *) ControlFile,
4436  offsetof(ControlFileData, crc));
4437  FIN_CRC32C(ControlFile->crc);
4438 
4439  /*
4440  * We write out PG_CONTROL_FILE_SIZE bytes into pg_control, zero-padding
4441  * the excess over sizeof(ControlFileData). This reduces the odds of
4442  * premature-EOF errors when reading pg_control. We'll still fail when we
4443  * check the contents of the file, but hopefully with a more specific
4444  * error than "couldn't read pg_control".
4445  */
4446  memset(buffer, 0, PG_CONTROL_FILE_SIZE);
4447  memcpy(buffer, ControlFile, sizeof(ControlFileData));
4448 
4450  O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
4451  if (fd < 0)
4452  ereport(PANIC,
4454  errmsg("could not create control file \"%s\": %m",
4455  XLOG_CONTROL_FILE)));
4456 
4457  errno = 0;
4459  if (write(fd, buffer, PG_CONTROL_FILE_SIZE) != PG_CONTROL_FILE_SIZE)
4460  {
4461  /* if write didn't set errno, assume problem is no disk space */
4462  if (errno == 0)
4463  errno = ENOSPC;
4464  ereport(PANIC,
4466  errmsg("could not write to control file: %m")));
4467  }
4469 
4471  if (pg_fsync(fd) != 0)
4472  ereport(PANIC,
4474  errmsg("could not fsync control file: %m")));
4476 
4477  if (close(fd))
4478  ereport(PANIC,
4480  errmsg("could not close control file: %m")));
4481 }
4482 
4483 static void
4485 {
4486  pg_crc32c crc;
4487  int fd;
4488  static char wal_segsz_str[20];
4489 
4490  /*
4491  * Read data...
4492  */
4494  O_RDWR | PG_BINARY);
4495  if (fd < 0)
4496  ereport(PANIC,
4498  errmsg("could not open control file \"%s\": %m",
4499  XLOG_CONTROL_FILE)));
4500 
4502  if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4503  ereport(PANIC,
4505  errmsg("could not read from control file: %m")));
4507 
4508  close(fd);
4509 
4510  /*
4511  * Check for expected pg_control format version. If this is wrong, the
4512  * CRC check will likely fail because we'll be checking the wrong number
4513  * of bytes. Complaining about wrong version will probably be more
4514  * enlightening than complaining about wrong CRC.
4515  */
4516 
4517  if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
4518  ereport(FATAL,
4519  (errmsg("database files are incompatible with server"),
4520  errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4521  " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4522  ControlFile->pg_control_version, ControlFile->pg_control_version,
4524  errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4525 
4526  if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
4527  ereport(FATAL,
4528  (errmsg("database files are incompatible with server"),
4529  errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4530  " but the server was compiled with PG_CONTROL_VERSION %d.",
4531  ControlFile->pg_control_version, PG_CONTROL_VERSION),
4532  errhint("It looks like you need to initdb.")));
4533 
4534  /* Now check the CRC. */
4535  INIT_CRC32C(crc);
4536  COMP_CRC32C(crc,
4537  (char *) ControlFile,
4538  offsetof(ControlFileData, crc));
4539  FIN_CRC32C(crc);
4540 
4541  if (!EQ_CRC32C(crc, ControlFile->crc))
4542  ereport(FATAL,
4543  (errmsg("incorrect checksum in control file")));
4544 
4545  /*
4546  * Do compatibility checking immediately. If the database isn't
4547  * compatible with the backend executable, we want to abort before we can
4548  * possibly do any damage.
4549  */
4550  if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
4551  ereport(FATAL,
4552  (errmsg("database files are incompatible with server"),
4553  errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
4554  " but the server was compiled with CATALOG_VERSION_NO %d.",
4555  ControlFile->catalog_version_no, CATALOG_VERSION_NO),
4556  errhint("It looks like you need to initdb.")));
4557  if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4558  ereport(FATAL,
4559  (errmsg("database files are incompatible with server"),
4560  errdetail("The database cluster was initialized with MAXALIGN %d,"
4561  " but the server was compiled with MAXALIGN %d.",
4562  ControlFile->maxAlign, MAXIMUM_ALIGNOF),
4563  errhint("It looks like you need to initdb.")));
4564  if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
4565  ereport(FATAL,
4566  (errmsg("database files are incompatible with server"),
4567  errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4568  errhint("It looks like you need to initdb.")));
4569  if (ControlFile->blcksz != BLCKSZ)
4570  ereport(FATAL,
4571  (errmsg("database files are incompatible with server"),
4572  errdetail("The database cluster was initialized with BLCKSZ %d,"
4573  " but the server was compiled with BLCKSZ %d.",
4574  ControlFile->blcksz, BLCKSZ),
4575  errhint("It looks like you need to recompile or initdb.")));
4576  if (ControlFile->relseg_size != RELSEG_SIZE)
4577  ereport(FATAL,
4578  (errmsg("database files are incompatible with server"),
4579  errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
4580  " but the server was compiled with RELSEG_SIZE %d.",
4581  ControlFile->relseg_size, RELSEG_SIZE),
4582  errhint("It looks like you need to recompile or initdb.")));
4583  if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4584  ereport(FATAL,
4585  (errmsg("database files are incompatible with server"),
4586  errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
4587  " but the server was compiled with XLOG_BLCKSZ %d.",
4588  ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4589  errhint("It looks like you need to recompile or initdb.")));
4590  if (ControlFile->nameDataLen != NAMEDATALEN)
4591  ereport(FATAL,
4592  (errmsg("database files are incompatible with server"),
4593  errdetail("The database cluster was initialized with NAMEDATALEN %d,"
4594  " but the server was compiled with NAMEDATALEN %d.",
4595  ControlFile->nameDataLen, NAMEDATALEN),
4596  errhint("It looks like you need to recompile or initdb.")));
4597  if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4598  ereport(FATAL,
4599  (errmsg("database files are incompatible with server"),
4600  errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
4601  " but the server was compiled with INDEX_MAX_KEYS %d.",
4602  ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
4603  errhint("It looks like you need to recompile or initdb.")));
4604  if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
4605  ereport(FATAL,
4606  (errmsg("database files are incompatible with server"),
4607  errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
4608  " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
4609  ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4610  errhint("It looks like you need to recompile or initdb.")));
4611  if (ControlFile->loblksize != LOBLKSIZE)
4612  ereport(FATAL,
4613  (errmsg("database files are incompatible with server"),
4614  errdetail("The database cluster was initialized with LOBLKSIZE %d,"
4615  " but the server was compiled with LOBLKSIZE %d.",
4616  ControlFile->loblksize, (int) LOBLKSIZE),
4617  errhint("It looks like you need to recompile or initdb.")));
4618 
4619 #ifdef USE_FLOAT4_BYVAL
4620  if (ControlFile->float4ByVal != true)
4621  ereport(FATAL,
4622  (errmsg("database files are incompatible with server"),
4623  errdetail("The database cluster was initialized without USE_FLOAT4_BYVAL"
4624  " but the server was compiled with USE_FLOAT4_BYVAL."),
4625  errhint("It looks like you need to recompile or initdb.")));
4626 #else
4627  if (ControlFile->float4ByVal != false)
4628  ereport(FATAL,
4629  (errmsg("database files are incompatible with server"),
4630  errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
4631  " but the server was compiled without USE_FLOAT4_BYVAL."),
4632  errhint("It looks like you need to recompile or initdb.")));
4633 #endif
4634 
4635 #ifdef USE_FLOAT8_BYVAL
4636  if (ControlFile->float8ByVal != true)
4637  ereport(FATAL,
4638  (errmsg("database files are incompatible with server"),
4639  errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4640  " but the server was compiled with USE_FLOAT8_BYVAL."),
4641  errhint("It looks like you need to recompile or initdb.")));
4642 #else
4643  if (ControlFile->float8ByVal != false)
4644  ereport(FATAL,
4645  (errmsg("database files are incompatible with server"),
4646  errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4647  " but the server was compiled without USE_FLOAT8_BYVAL."),
4648  errhint("It looks like you need to recompile or initdb.")));
4649 #endif
4650 
4651  wal_segment_size = ControlFile->xlog_seg_size;
4652 
4654  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4655  errmsg("WAL segment size must be a power of two between 1MB and 1GB, but the control file specifies %d bytes",
4656  wal_segment_size)));
4657 
4658  snprintf(wal_segsz_str, sizeof(wal_segsz_str), "%d", wal_segment_size);
4659  SetConfigOption("wal_segment_size", wal_segsz_str, PGC_INTERNAL,
4660  PGC_S_OVERRIDE);
4661 
4662  /* check and update variables dependent on wal_segment_size */
4664  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4665  errmsg("\"min_wal_size\" must be at least twice \"wal_segment_size\".")));
4666 
4668  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4669  errmsg("\"max_wal_size\" must be at least twice \"wal_segment_size\".")));
4670 
4672  (wal_segment_size / XLOG_BLCKSZ * UsableBytesInPage) -
4674 
4676 
4677  /* Make the initdb settings visible as GUC variables, too */
4678  SetConfigOption("data_checksums", DataChecksumsEnabled() ? "yes" : "no",
4680 }
4681 
4682 void
4684 {
4685  int fd;
4686 
4687  INIT_CRC32C(ControlFile->crc);
4688  COMP_CRC32C(ControlFile->crc,
4689  (char *) ControlFile,
4690  offsetof(ControlFileData, crc));
4691  FIN_CRC32C(ControlFile->crc);
4692 
4694  O_RDWR | PG_BINARY);
4695  if (fd < 0)
4696  ereport(PANIC,
4698  errmsg("could not open control file \"%s\": %m",
4699  XLOG_CONTROL_FILE)));
4700 
4701  errno = 0;
4703  if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4704  {
4705  /* if write didn't set errno, assume problem is no disk space */
4706  if (errno == 0)
4707  errno = ENOSPC;
4708  ereport(PANIC,
4710  errmsg("could not write to control file: %m")));
4711  }
4713 
4715  if (pg_fsync(fd) != 0)
4716  ereport(PANIC,
4718  errmsg("could not fsync control file: %m")));
4720 
4721  if (close(fd))
4722  ereport(PANIC,
4724  errmsg("could not close control file: %m")));
4725 }
4726 
4727 /*
4728  * Returns the unique system identifier from control file.
4729  */
4730 uint64
4732 {
4733  Assert(ControlFile != NULL);
4734  return ControlFile->system_identifier;
4735 }
4736 
4737 /*
4738  * Returns the random nonce from control file.
4739  */
4740 char *
4742 {
4743  Assert(ControlFile != NULL);
4744  return ControlFile->mock_authentication_nonce;
4745 }
4746 
4747 /*
4748  * Are checksums enabled for data pages?
4749  */
4750 bool
4752 {
4753  Assert(ControlFile != NULL);
4754  return (ControlFile->data_checksum_version > 0);
4755 }
4756 
4757 /*
4758  * Returns a fake LSN for unlogged relations.
4759  *
4760  * Each call generates an LSN that is greater than any previous value
4761  * returned. The current counter value is saved and restored across clean
4762  * shutdowns, but like unlogged relations, does not survive a crash. This can
4763  * be used in lieu of real LSN values returned by XLogInsert, if you need an
4764  * LSN-like increasing sequence of numbers without writing any WAL.
4765  */
4766 XLogRecPtr
4768 {
4769  XLogRecPtr nextUnloggedLSN;
4770 
4771  /* increment the unloggedLSN counter, need SpinLock */
4772  SpinLockAcquire(&XLogCtl->ulsn_lck);
4773  nextUnloggedLSN = XLogCtl->unloggedLSN++;
4774  SpinLockRelease(&XLogCtl->ulsn_lck);
4775 
4776  return nextUnloggedLSN;
4777 }
4778 
4779 /*
4780  * Auto-tune the number of XLOG buffers.
4781  *
4782  * The preferred setting for wal_buffers is about 3% of shared_buffers, with
4783  * a maximum of one XLOG segment (there is little reason to think that more
4784  * is helpful, at least so long as we force an fsync when switching log files)
4785  * and a minimum of 8 blocks (which was the default value prior to PostgreSQL
4786  * 9.1, when auto-tuning was added).
4787  *
4788  * This should not be called until NBuffers has received its final value.
4789  */
4790 static int
4792 {
4793  int xbuffers;
4794 
4795  xbuffers = NBuffers / 32;
4796  if (xbuffers > (wal_segment_size / XLOG_BLCKSZ))
4797  xbuffers = (wal_segment_size / XLOG_BLCKSZ);
4798  if (xbuffers < 8)
4799  xbuffers = 8;
4800  return xbuffers;
4801 }
4802 
4803 /*
4804  * GUC check_hook for wal_buffers
4805  */
4806 bool
4807 check_wal_buffers(int *newval, void **extra, GucSource source)
4808 {
4809  /*
4810  * -1 indicates a request for auto-tune.
4811  */
4812  if (*newval == -1)
4813  {
4814  /*
4815  * If we haven't yet changed the boot_val default of -1, just let it
4816  * be. We'll fix it when XLOGShmemSize is called.
4817  */
4818  if (XLOGbuffers == -1)
4819  return true;
4820 
4821  /* Otherwise, substitute the auto-tune value */
4822  *newval = XLOGChooseNumBuffers();
4823  }
4824 
4825  /*
4826  * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
4827  * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
4828  * the case, we just silently treat such values as a request for the
4829  * minimum. (We could throw an error instead, but that doesn't seem very
4830  * helpful.)
4831  */
4832  if (*newval < 4)
4833  *newval = 4;
4834 
4835  return true;
4836 }
4837 
4838 /*
4839  * Read the control file, set respective GUCs.
4840  *
4841  * This is to be called during startup, including a crash recovery cycle,
4842  * unless in bootstrap mode, where no control file yet exists. As there's no
4843  * usable shared memory yet (its sizing can depend on the contents of the
4844  * control file!), first store the contents in local memory. XLOGShmemInit()
4845  * will then copy it to shared memory later.
4846  *
4847  * reset just controls whether previous contents are to be expected (in the
4848  * reset case, there's a dangling pointer into old shared memory), or not.
4849  */
4850 void
4852 {
4853  Assert(reset || ControlFile == NULL);
4854  ControlFile = palloc(sizeof(ControlFileData));
4855  ReadControlFile();
4856 }
4857 
4858 /*
4859  * Initialization of shared memory for XLOG
4860  */
4861 Size
4863 {
4864  Size size;
4865 
4866  /*
4867  * If the value of wal_buffers is -1, use the preferred auto-tune value.
4868  * This isn't an amazingly clean place to do this, but we must wait till
4869  * NBuffers has received its final value, and must do it before using the
4870  * value of XLOGbuffers to do anything important.
4871  */
4872  if (XLOGbuffers == -1)
4873  {
4874  char buf[32];
4875 
4876  snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
4877  SetConfigOption("wal_buffers", buf, PGC_POSTMASTER, PGC_S_OVERRIDE);
4878  }
4879  Assert(XLOGbuffers > 0);
4880 
4881  /* XLogCtl */
4882  size = sizeof(XLogCtlData);
4883 
4884  /* WAL insertion locks, plus alignment */
4885  size = add_size(size, mul_size(sizeof(WALInsertLockPadded), NUM_XLOGINSERT_LOCKS + 1));
4886  /* xlblocks array */
4887  size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
4888  /* extra alignment padding for XLOG I/O buffers */
4889  size = add_size(size, XLOG_BLCKSZ);
4890  /* and the buffers themselves */
4891  size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4892 
4893  /*
4894  * Note: we don't count ControlFileData, it comes out of the "slop factor"
4895  * added by CreateSharedMemoryAndSemaphores. This lets us use this
4896  * routine again below to compute the actual allocation size.
4897  */
4898 
4899  return size;
4900 }
4901 
4902 void
4904 {
4905  bool foundCFile,
4906  foundXLog;
4907  char *allocptr;
4908  int i;
4909  ControlFileData *localControlFile;
4910 
4911 #ifdef WAL_DEBUG
4912 
4913  /*
4914  * Create a memory context for WAL debugging that's exempt from the normal
4915  * "no pallocs in critical section" rule. Yes, that can lead to a PANIC if
4916  * an allocation fails, but wal_debug is not for production use anyway.
4917  */
4918  if (walDebugCxt == NULL)
4919  {
4921  "WAL Debug",
4923  MemoryContextAllowInCriticalSection(walDebugCxt, true);
4924  }
4925 #endif
4926 
4927 
4928  XLogCtl = (XLogCtlData *)
4929  ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4930 
4931  localControlFile = ControlFile;
4932  ControlFile = (ControlFileData *)
4933  ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4934 
4935  if (foundCFile || foundXLog)
4936  {
4937  /* both should be present or neither */
4938  Assert(foundCFile && foundXLog);
4939 
4940  /* Initialize local copy of WALInsertLocks and register the tranche */
4941  WALInsertLocks = XLogCtl->Insert.WALInsertLocks;
4943  "wal_insert");
4944 
4945  if (localControlFile)
4946  pfree(localControlFile);
4947  return;
4948  }
4949  memset(XLogCtl, 0, sizeof(XLogCtlData));
4950 
4951  /*
4952  * Already have read control file locally, unless in bootstrap mode. Move
4953  * contents into shared memory.
4954  */
4955  if (localControlFile)
4956  {
4957  memcpy(ControlFile, localControlFile, sizeof(ControlFileData));
4958  pfree(localControlFile);
4959  }
4960 
4961  /*
4962  * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4963  * multiple of the alignment for same, so no extra alignment padding is
4964  * needed here.
4965  */
4966  allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4967  XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4968  memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4969  allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4970 
4971 
4972  /* WAL insertion locks. Ensure they're aligned to the full padded size */
4973  allocptr += sizeof(WALInsertLockPadded) -
4974  ((uintptr_t) allocptr) % sizeof(WALInsertLockPadded);
4975  WALInsertLocks = XLogCtl->Insert.WALInsertLocks =
4976  (WALInsertLockPadded *) allocptr;
4977  allocptr += sizeof(WALInsertLockPadded) * NUM_XLOGINSERT_LOCKS;
4978 
4980  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
4981  {
4982  LWLockInitialize(&WALInsertLocks[i].l.lock, LWTRANCHE_WAL_INSERT);
4983  WALInsertLocks[i].l.insertingAt = InvalidXLogRecPtr;
4984  WALInsertLocks[i].l.lastImportantAt = InvalidXLogRecPtr;
4985  }
4986 
4987  /*
4988  * Align the start of the page buffers to a full xlog block size boundary.
4989  * This simplifies some calculations in XLOG insertion. It is also
4990  * required for O_DIRECT.
4991  */
4992  allocptr = (char *) TYPEALIGN(XLOG_BLCKSZ, allocptr);
4993  XLogCtl->pages = allocptr;
4994  memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4995 
4996  /*
4997  * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4998  * in additional info.)
4999  */
5000  XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
5001  XLogCtl->SharedRecoveryInProgress = true;
5002  XLogCtl->SharedHotStandbyActive = false;
5003  XLogCtl->WalWriterSleeping = false;
5004 
5005  SpinLockInit(&XLogCtl->Insert.insertpos_lck);
5006  SpinLockInit(&XLogCtl->info_lck);
5007  SpinLockInit(&XLogCtl->ulsn_lck);
5009 }
5010 
5011 /*
5012  * This func must be called ONCE on system install. It creates pg_control
5013  * and the initial XLOG segment.
5014  */
5015 void
5017 {
5018  CheckPoint checkPoint;
5019  char *buffer;
5020  XLogPageHeader page;
5021  XLogLongPageHeader longpage;
5022  XLogRecord *record;
5023  char *recptr;
5024  bool use_existent;
5025  uint64 sysidentifier;
5026  char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
5027  struct timeval tv;
5028  pg_crc32c crc;
5029 
5030  /*
5031  * Select a hopefully-unique system identifier code for this installation.
5032  * We use the result of gettimeofday(), including the fractional seconds
5033  * field, as being about as unique as we can easily get. (Think not to
5034  * use random(), since it hasn't been seeded and there's no portable way
5035  * to seed it other than the system clock value...) The upper half of the
5036  * uint64 value is just the tv_sec part, while the lower half contains the
5037  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5038  * PID for a little extra uniqueness. A person knowing this encoding can
5039  * determine the initialization time of the installation, which could
5040  * perhaps be useful sometimes.
5041  */
5042  gettimeofday(&tv, NULL);
5043  sysidentifier = ((uint64) tv.tv_sec) << 32;
5044  sysidentifier |= ((uint64) tv.tv_usec) << 12;
5045  sysidentifier |= getpid() & 0xFFF;
5046 
5047  /*
5048  * Generate a random nonce. This is used for authentication requests that
5049  * will fail because the user does not exist. The nonce is used to create
5050  * a genuine-looking password challenge for the non-existent user, in lieu
5051  * of an actual stored password.
5052  */
5053  if (!pg_backend_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
5054  ereport(PANIC,
5055  (errcode(ERRCODE_INTERNAL_ERROR),
5056  errmsg("could not generate secret authorization token")));
5057 
5058  /* First timeline ID is always 1 */
5059  ThisTimeLineID = 1;
5060 
5061  /* page buffer must be aligned suitably for O_DIRECT */
5062  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5063  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5064  memset(page, 0, XLOG_BLCKSZ);
5065 
5066  /*
5067  * Set up information for the initial checkpoint record
5068  *
5069  * The initial checkpoint record is written to the beginning of the WAL
5070  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5071  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5072  */
5073  checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5074  checkPoint.ThisTimeLineID = ThisTimeLineID;
5075  checkPoint.PrevTimeLineID = ThisTimeLineID;
5076  checkPoint.fullPageWrites = fullPageWrites;
5077  checkPoint.nextXidEpoch = 0;
5078  checkPoint.nextXid = FirstNormalTransactionId;
5079  checkPoint.nextOid = FirstBootstrapObjectId;
5080  checkPoint.nextMulti = FirstMultiXactId;
5081  checkPoint.nextMultiOffset = 0;
5082  checkPoint.oldestXid = FirstNormalTransactionId;
5083  checkPoint.oldestXidDB = TemplateDbOid;
5084  checkPoint.oldestMulti = FirstMultiXactId;
5085  checkPoint.oldestMultiDB = TemplateDbOid;
5088  checkPoint.time = (pg_time_t) time(NULL);
5090 
5091  ShmemVariableCache->nextXid = checkPoint.nextXid;
5092  ShmemVariableCache->nextOid = checkPoint.nextOid;
5094  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5095  AdvanceOldestClogXid(checkPoint.oldestXid);
5096  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5097  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5099 
5100  /* Set up the XLOG page header */
5101  page->xlp_magic = XLOG_PAGE_MAGIC;
5102  page->xlp_info = XLP_LONG_HEADER;
5103  page->xlp_tli = ThisTimeLineID;
5105  longpage = (XLogLongPageHeader) page;
5106  longpage->xlp_sysid = sysidentifier;
5107  longpage->xlp_seg_size = wal_segment_size;
5108  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5109 
5110  /* Insert the initial checkpoint record */
5111  recptr = ((char *) page + SizeOfXLogLongPHD);
5112  record = (XLogRecord *) recptr;
5113  record->xl_prev = 0;
5114  record->xl_xid = InvalidTransactionId;
5115  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5117  record->xl_rmid = RM_XLOG_ID;
5118  recptr += SizeOfXLogRecord;
5119  /* fill the XLogRecordDataHeaderShort struct */
5120  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5121  *(recptr++) = sizeof(checkPoint);
5122  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5123  recptr += sizeof(checkPoint);
5124  Assert(recptr - (char *) record == record->xl_tot_len);
5125 
5126  INIT_CRC32C(crc);
5127  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5128  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5129  FIN_CRC32C(crc);
5130  record->xl_crc = crc;
5131 
5132  /* Create first XLOG segment file */
5133  use_existent = false;
5134  openLogFile = XLogFileInit(1, &use_existent, false);
5135 
5136  /* Write the first page with the initial record */
5137  errno = 0;
5139  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5140  {
5141  /* if write didn't set errno, assume problem is no disk space */
5142  if (errno == 0)
5143  errno = ENOSPC;
5144  ereport(PANIC,
5146  errmsg("could not write bootstrap write-ahead log file: %m")));
5147  }
5149 
5151  if (pg_fsync(openLogFile) != 0)
5152  ereport(PANIC,
5154  errmsg("could not fsync bootstrap write-ahead log file: %m")));
5156 
5157  if (close(openLogFile))
5158  ereport(PANIC,
5160  errmsg("could not close bootstrap write-ahead log file: %m")));
5161 
5162  openLogFile = -1;
5163 
5164  /* Now create pg_control */
5165 
5166  memset(ControlFile, 0, sizeof(ControlFileData));
5167  /* Initialize pg_control status fields */
5168  ControlFile->system_identifier = sysidentifier;
5169  memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
5170  ControlFile->state = DB_SHUTDOWNED;
5171  ControlFile->time = checkPoint.time;
5172  ControlFile->checkPoint = checkPoint.redo;
5173  ControlFile->checkPointCopy = checkPoint;
5174  ControlFile->unloggedLSN = 1;
5175 
5176  /* Set important parameter values for use when replaying WAL */
5177  ControlFile->MaxConnections = MaxConnections;
5179  ControlFile->max_prepared_xacts = max_prepared_xacts;
5180  ControlFile->max_locks_per_xact = max_locks_per_xact;
5181  ControlFile->wal_level = wal_level;
5182  ControlFile->wal_log_hints = wal_log_hints;
5185 
5186  /* some additional ControlFile fields are set in WriteControlFile() */
5187 
5188  WriteControlFile();
5189 
5190  /* Bootstrap the commit log, too */
5191  BootStrapCLOG();
5195 
5196  pfree(buffer);
5197 
5198  /*
5199  * Force control file to be read - in contrast to normal processing we'd
5200  * otherwise never run the checks and GUC related initializations therein.
5201  */
5202  ReadControlFile();
5203 }
5204 
5205 static char *
5207 {
5208  static char buf[128];
5209 
5210  pg_strftime(buf, sizeof(buf),
5211  "%Y-%m-%d %H:%M:%S %Z",
5212  pg_localtime(&tnow, log_timezone));
5213 
5214  return buf;
5215 }
5216 
5217 /*
5218  * See if there is a recovery command file (recovery.conf), and if so
5219  * read in parameters for archive recovery and XLOG streaming.
5220  *
5221  * The file is parsed using the main configuration parser.
5222  */
5223 static void
5225 {
5226  FILE *fd;
5227  TimeLineID rtli = 0;
5228  bool rtliGiven = false;
5229  ConfigVariable *item,
5230  *head = NULL,
5231  *tail = NULL;
5232  bool recoveryTargetActionSet = false;
5233 
5234 
5236  if (fd == NULL)
5237  {
5238  if (errno == ENOENT)
5239  return; /* not there, so no archive recovery */
5240  ereport(FATAL,
5242  errmsg("could not open recovery command file \"%s\": %m",
5244  }
5245 
5246  /*
5247  * Since we're asking ParseConfigFp() to report errors as FATAL, there's
5248  * no need to check the return value.
5249  */
5250  (void) ParseConfigFp(fd, RECOVERY_COMMAND_FILE, 0, FATAL, &head, &tail);
5251 
5252  FreeFile(fd);
5253 
5254  for (item = head; item; item = item->next)
5255  {
5256  if (strcmp(item->name, "restore_command") == 0)
5257  {
5259  ereport(DEBUG2,
5260  (errmsg_internal("restore_command = '%s'",
5262  }
5263  else if (strcmp(item->name, "recovery_end_command") == 0)
5264  {
5265  recoveryEndCommand = pstrdup(item->value);
5266  ereport(DEBUG2,
5267  (errmsg_internal("recovery_end_command = '%s'",
5268  recoveryEndCommand)));
5269  }
5270  else if (strcmp(item->name, "archive_cleanup_command") == 0)
5271  {
5273  ereport(DEBUG2,
5274  (errmsg_internal("archive_cleanup_command = '%s'",
5276  }
5277  else if (strcmp(item->name, "recovery_target_action") == 0)
5278  {
5279  if (strcmp(item->value, "pause") == 0)
5281  else if (strcmp(item->value, "promote") == 0)
5283  else if (strcmp(item->value, "shutdown") == 0)
5285  else
5286  ereport(ERROR,
5287  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5288  errmsg("invalid value for recovery parameter \"%s\": \"%s\"",
5289  "recovery_target_action",
5290  item->value),
5291  errhint("Valid values are \"pause\", \"promote\", and \"shutdown\".")));
5292 
5293  ereport(DEBUG2,
5294  (errmsg_internal("recovery_target_action = '%s'",
5295  item->value)));
5296 
5297  recoveryTargetActionSet = true;
5298  }
5299  else if (strcmp(item->name, "recovery_target_timeline") == 0)
5300  {
5301  rtliGiven = true;
5302  if (strcmp(item->value, "latest") == 0)
5303  rtli = 0;
5304  else
5305  {
5306  errno = 0;
5307  rtli = (TimeLineID) strtoul(item->value, NULL, 0);
5308  if (errno == EINVAL || errno == ERANGE)
5309  ereport(FATAL,
5310  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5311  errmsg("recovery_target_timeline is not a valid number: \"%s\"",
5312  item->value)));
5313  }
5314  if (rtli)
5315  ereport(DEBUG2,
5316  (errmsg_internal("recovery_target_timeline = %u", rtli)));
5317  else
5318  ereport(DEBUG2,
5319  (errmsg_internal("recovery_target_timeline = latest")));
5320  }
5321  else if (strcmp(item->name, "recovery_target_xid") == 0)
5322  {
5323  errno = 0;
5324  recoveryTargetXid = (TransactionId) strtoul(item->value, NULL, 0);
5325  if (errno == EINVAL || errno == ERANGE)
5326  ereport(FATAL,
5327  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5328  errmsg("recovery_target_xid is not a valid number: \"%s\"",
5329  item->value)));
5330  ereport(DEBUG2,
5331  (errmsg_internal("recovery_target_xid = %u",
5332  recoveryTargetXid)));
5334  }
5335  else if (strcmp(item->name, "recovery_target_time") == 0)
5336  {
5338 
5339  if (strcmp(item->value, "epoch") == 0 ||
5340  strcmp(item->value, "infinity") == 0 ||
5341  strcmp(item->value, "-infinity") == 0 ||
5342  strcmp(item->value, "now") == 0 ||
5343  strcmp(item->value, "today") == 0 ||
5344  strcmp(item->value, "tomorrow") == 0 ||
5345  strcmp(item->value, "yesterday") == 0)
5346  ereport(FATAL,
5347  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5348  errmsg("recovery_target_time is not a valid timestamp: \"%s\"",
5349  item->value)));
5350 
5351  /*
5352  * Convert the time string given by the user to TimestampTz form.
5353  */
5356  CStringGetDatum(item->value),
5358  Int32GetDatum(-1)));
5359  ereport(DEBUG2,
5360  (errmsg_internal("recovery_target_time = '%s'",
5362  }
5363  else if (strcmp(item->name, "recovery_target_name") == 0)
5364  {
5366 
5367  recoveryTargetName = pstrdup(item->value);
5368  if (strlen(recoveryTargetName) >= MAXFNAMELEN)
5369  ereport(FATAL,
5370  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5371  errmsg("recovery_target_name is too long (maximum %d characters)",
5372  MAXFNAMELEN - 1)));
5373 
5374  ereport(DEBUG2,
5375  (errmsg_internal("recovery_target_name = '%s'",
5376  recoveryTargetName)));
5377  }
5378  else if (strcmp(item->name, "recovery_target_lsn") == 0)
5379  {
5381 
5382  /*
5383  * Convert the LSN string given by the user to XLogRecPtr form.
5384  */
5387  CStringGetDatum(item->value),
5389  Int32GetDatum(-1)));
5390  ereport(DEBUG2,
5391  (errmsg_internal("recovery_target_lsn = '%X/%X'",
5392  (uint32) (recoveryTargetLSN >> 32),
5394  }
5395  else if (strcmp(item->name, "recovery_target") == 0)
5396  {
5397  if (strcmp(item->value, "immediate") == 0)
5399  else
5400  ereport(ERROR,
5401  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5402  errmsg("invalid value for recovery parameter \"%s\": \"%s\"",
5403  "recovery_target",
5404  item->value),
5405  errhint("The only allowed value is \"immediate\".")));
5406  ereport(DEBUG2,
5407  (errmsg_internal("recovery_target = '%s'",
5408  item->value)));
5409  }
5410  else if (strcmp(item->name, "recovery_target_inclusive") == 0)
5411  {
5412  /*
5413  * does nothing if a recovery_target is not also set
5414  */
5416  ereport(ERROR,
5417  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5418  errmsg("parameter \"%s\" requires a Boolean value",
5419  "recovery_target_inclusive")));
5420  ereport(DEBUG2,
5421  (errmsg_internal("recovery_target_inclusive = %s",
5422  item->value)));
5423  }
5424  else if (strcmp(item->name, "standby_mode") == 0)
5425  {
5426  if (!parse_bool(item->value, &StandbyModeRequested))
5427  ereport(ERROR,
5428  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5429  errmsg("parameter \"%s\" requires a Boolean value",
5430  "standby_mode")));
5431  ereport(DEBUG2,
5432  (errmsg_internal("standby_mode = '%s'", item->value)));
5433  }
5434  else if (strcmp(item->name, "primary_conninfo") == 0)
5435  {
5436  PrimaryConnInfo = pstrdup(item->value);
5437  ereport(DEBUG2,
5438  (errmsg_internal("primary_conninfo = '%s'",
5439  PrimaryConnInfo)));
5440  }
5441  else if (strcmp(item->name, "primary_slot_name") == 0)
5442  {
5444  PrimarySlotName = pstrdup(item->value);
5445  ereport(DEBUG2,
5446  (errmsg_internal("primary_slot_name = '%s'",
5447  PrimarySlotName)));
5448  }
5449  else if (strcmp(item->name, "trigger_file") == 0)
5450  {
5451  TriggerFile = pstrdup(item->value);
5452  ereport(DEBUG2,
5453  (errmsg_internal("trigger_file = '%s'",
5454  TriggerFile)));
5455  }
5456  else if (strcmp(item->name, "recovery_min_apply_delay") == 0)
5457  {
5458  const char *hintmsg;
5459 
5461  &hintmsg))
5462  ereport(ERROR,
5463  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5464  errmsg("parameter \"%s\" requires a temporal value",
5465  "recovery_min_apply_delay"),
5466  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5467  ereport(DEBUG2,
5468  (errmsg_internal("recovery_min_apply_delay = '%s'", item->value)));
5469  }
5470  else
5471  ereport(FATAL,
5472  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5473  errmsg("unrecognized recovery parameter \"%s\"",
5474  item->name)));
5475  }
5476 
5477  /*
5478  * Check for compulsory parameters
5479  */
5481  {
5482  if (PrimaryConnInfo == NULL && recoveryRestoreCommand == NULL)
5483  ereport(WARNING,
5484  (errmsg("recovery command file \"%s\" specified neither primary_conninfo nor restore_command",
5486  errhint("The database server will regularly poll the pg_wal subdirectory to check for files placed there.")));
5487  }
5488  else
5489  {
5490  if (recoveryRestoreCommand == NULL)
5491  ereport(FATAL,
5492  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5493  errmsg("recovery command file \"%s\" must specify restore_command when standby mode is not enabled",
5495  }
5496 
5497  /*
5498  * Override any inconsistent requests. Not that this is a change of
5499  * behaviour in 9.5; prior to this we simply ignored a request to pause if
5500  * hot_standby = off, which was surprising behaviour.
5501  */
5503  recoveryTargetActionSet &&
5506 
5507  /*
5508  * We don't support standby_mode in standalone backends; that requires
5509  * other processes such as the WAL receiver to be alive.
5510  */
5512  ereport(FATAL,
5513  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5514  errmsg("standby mode is not supported by single-user servers")));
5515 
5516  /* Enable fetching from archive recovery area */
5517  ArchiveRecoveryRequested = true;
5518 
5519  /*
5520  * If user specified recovery_target_timeline, validate it or compute the
5521  * "latest" value. We can't do this until after we've gotten the restore
5522  * command and set InArchiveRecovery, because we need to fetch timeline
5523  * history files from the archive.
5524  */
5525  if (rtliGiven)
5526  {
5527  if (rtli)
5528  {
5529  /* Timeline 1 does not have a history file, all else should */
5530  if (rtli != 1 && !existsTimeLineHistory(rtli))
5531  ereport(FATAL,
5532  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5533  errmsg("recovery target timeline %u does not exist",
5534  rtli)));
5535  recoveryTargetTLI = rtli;
5536  recoveryTargetIsLatest = false;
5537  }
5538  else
5539  {
5540  /* We start the "latest" search from pg_control's timeline */
5542  recoveryTargetIsLatest = true;
5543  }
5544  }
5545 
5546  FreeConfigVariables(head);
5547 }
5548 
5549 /*
5550  * Exit archive-recovery state
5551  */
5552 static void
5554 {
5555  char recoveryPath[MAXPGPATH];
5556  char xlogfname[MAXFNAMELEN];
5557  XLogSegNo endLogSegNo;
5558  XLogSegNo startLogSegNo;
5559 
5560  /* we always switch to a new timeline after archive recovery */
5561  Assert(endTLI != ThisTimeLineID);
5562 
5563  /*
5564  * We are no longer in archive recovery state.
5565  */
5566  InArchiveRecovery = false;
5567 
5568  /*
5569  * Update min recovery point one last time.
5570  */
5572 
5573  /*
5574  * If the ending log segment is still open, close it (to avoid problems on
5575  * Windows with trying to rename or delete an open file).
5576  */
5577  if (readFile >= 0)
5578  {
5579  close(readFile);
5580  readFile = -1;
5581  }
5582 
5583  /*
5584  * Calculate the last segment on the old timeline, and the first segment
5585  * on the new timeline. If the switch happens in the middle of a segment,
5586  * they are the same, but if the switch happens exactly at a segment
5587  * boundary, startLogSegNo will be endLogSegNo + 1.
5588  */
5589  XLByteToPrevSeg(endOfLog, endLogSegNo, wal_segment_size);
5590  XLByteToSeg(endOfLog, startLogSegNo, wal_segment_size);
5591 
5592  /*
5593  * Initialize the starting WAL segment for the new timeline. If the switch
5594  * happens in the middle of a segment, copy data from the last WAL segment
5595  * of the old timeline up to the switch point, to the starting WAL segment
5596  * on the new timeline.
5597  */
5598  if (endLogSegNo == startLogSegNo)
5599  {
5600  /*
5601  * Make a copy of the file on the new timeline.
5602  *
5603  * Writing WAL isn't allowed yet, so there are no locking
5604  * considerations. But we should be just as tense as XLogFileInit to
5605  * avoid emplacing a bogus file.
5606  */
5607  XLogFileCopy(endLogSegNo, endTLI, endLogSegNo,
5608  XLogSegmentOffset(endOfLog, wal_segment_size));
5609  }
5610  else
5611  {
5612  /*
5613  * The switch happened at a segment boundary, so just create the next
5614  * segment on the new timeline.
5615  */
5616  bool use_existent = true;
5617  int fd;
5618 
5619  fd = XLogFileInit(startLogSegNo, &use_existent, true);
5620 
5621  if (close(fd))
5622  ereport(ERROR,
5624  errmsg("could not close log file %s: %m",
5625  XLogFileNameP(ThisTimeLineID, startLogSegNo))));
5626  }
5627 
5628  /*
5629  * Let's just make real sure there are not .ready or .done flags posted
5630  * for the new segment.
5631  */
5632  XLogFileName(xlogfname, ThisTimeLineID, startLogSegNo, wal_segment_size);
5633  XLogArchiveCleanup(xlogfname);
5634 
5635  /*
5636  * Since there might be a partial WAL segment named RECOVERYXLOG, get rid
5637  * of it.
5638  */
5639  snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
5640  unlink(recoveryPath); /* ignore any error */
5641 
5642  /* Get rid of any remaining recovered timeline-history file, too */
5643  snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
5644  unlink(recoveryPath); /* ignore any error */
5645 
5646  /*
5647  * Rename the config file out of the way, so that we don't accidentally
5648  * re-enter archive recovery mode in a subsequent crash.
5649  */
5650  unlink(RECOVERY_COMMAND_DONE);
5652 
5653  ereport(LOG,
5654  (errmsg("archive recovery complete")));
5655 }
5656 
5657 /*
5658  * Extract timestamp from WAL record.
5659  *
5660  * If the record contains a timestamp, returns true, and saves the timestamp
5661  * in *recordXtime. If the record type has no timestamp, returns false.
5662  * Currently, only transaction commit/abort records and restore points contain
5663  * timestamps.
5664  */
5665 static bool
5667 {
5668  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
5669  uint8 xact_info = info & XLOG_XACT_OPMASK;
5670  uint8 rmid = XLogRecGetRmid(record);
5671 
5672  if (rmid == RM_XLOG_ID && info == XLOG_RESTORE_POINT)
5673  {
5674  *recordXtime = ((xl_restore_point *) XLogRecGetData(record))->rp_time;
5675  return true;
5676  }
5677  if (rmid == RM_XACT_ID && (xact_info == XLOG_XACT_COMMIT ||
5678  xact_info == XLOG_XACT_COMMIT_PREPARED))
5679  {
5680  *recordXtime = ((xl_xact_commit *) XLogRecGetData(record))->xact_time;
5681  return true;
5682  }
5683  if (rmid == RM_XACT_ID && (xact_info == XLOG_XACT_ABORT ||
5684  xact_info == XLOG_XACT_ABORT_PREPARED))
5685  {
5686  *recordXtime = ((xl_xact_abort *) XLogRecGetData(record))->xact_time;
5687  return true;
5688  }
5689  return false;
5690 }
5691 
5692 /*
5693  * For point-in-time recovery, this function decides whether we want to
5694  * stop applying the XLOG before the current record.
5695  *
5696  * Returns true if we are stopping, false otherwise. If stopping, some
5697  * information is saved in recoveryStopXid et al for use in annotating the
5698  * new timeline's history file.
5699  */
5700 static bool