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