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