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