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