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