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