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