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