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