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  * The Write-Ahead Log (WAL) functionality is split into several source
7  * files, in addition to this one:
8  *
9  * xloginsert.c - Functions for constructing WAL records
10  * xlogrecovery.c - WAL recovery and standby code
11  * xlogreader.c - Facility for reading WAL files and parsing WAL records
12  * xlogutils.c - Helper functions for WAL redo routines
13  *
14  * This file contains functions for coordinating database startup and
15  * checkpointing, and managing the write-ahead log buffers when the
16  * system is running.
17  *
18  * StartupXLOG() is the main entry point of the startup process. It
19  * coordinates database startup, performing WAL recovery, and the
20  * transition from WAL recovery into normal operations.
21  *
22  * XLogInsertRecord() inserts a WAL record into the WAL buffers. Most
23  * callers should not call this directly, but use the functions in
24  * xloginsert.c to construct the WAL record. XLogFlush() can be used
25  * to force the WAL to disk.
26  *
27  * In addition to those, there are many other functions for interrogating
28  * the current system state, and for starting/stopping backups.
29  *
30  *
31  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
32  * Portions Copyright (c) 1994, Regents of the University of California
33  *
34  * src/backend/access/transam/xlog.c
35  *
36  *-------------------------------------------------------------------------
37  */
38 
39 #include "postgres.h"
40 
41 #include <ctype.h>
42 #include <math.h>
43 #include <time.h>
44 #include <fcntl.h>
45 #include <sys/stat.h>
46 #include <sys/time.h>
47 #include <unistd.h>
48 
49 #include "access/clog.h"
50 #include "access/commit_ts.h"
51 #include "access/heaptoast.h"
52 #include "access/multixact.h"
53 #include "access/rewriteheap.h"
54 #include "access/subtrans.h"
55 #include "access/timeline.h"
56 #include "access/transam.h"
57 #include "access/twophase.h"
58 #include "access/xact.h"
59 #include "access/xlog_internal.h"
60 #include "access/xlogarchive.h"
61 #include "access/xloginsert.h"
62 #include "access/xlogreader.h"
63 #include "access/xlogrecovery.h"
64 #include "access/xlogutils.h"
65 #include "backup/basebackup.h"
66 #include "catalog/catversion.h"
67 #include "catalog/pg_control.h"
68 #include "catalog/pg_database.h"
69 #include "commands/waitlsn.h"
71 #include "common/file_utils.h"
72 #include "executor/instrument.h"
73 #include "miscadmin.h"
74 #include "pg_trace.h"
75 #include "pgstat.h"
76 #include "port/atomics.h"
77 #include "port/pg_iovec.h"
78 #include "postmaster/bgwriter.h"
79 #include "postmaster/startup.h"
81 #include "postmaster/walwriter.h"
82 #include "replication/origin.h"
83 #include "replication/slot.h"
84 #include "replication/snapbuild.h"
86 #include "replication/walsender.h"
87 #include "storage/bufmgr.h"
88 #include "storage/fd.h"
89 #include "storage/ipc.h"
90 #include "storage/large_object.h"
91 #include "storage/latch.h"
92 #include "storage/predicate.h"
93 #include "storage/proc.h"
94 #include "storage/procarray.h"
95 #include "storage/reinit.h"
96 #include "storage/spin.h"
97 #include "storage/sync.h"
98 #include "utils/guc_hooks.h"
99 #include "utils/guc_tables.h"
100 #include "utils/injection_point.h"
101 #include "utils/memutils.h"
102 #include "utils/ps_status.h"
103 #include "utils/relmapper.h"
104 #include "utils/snapmgr.h"
105 #include "utils/timeout.h"
106 #include "utils/timestamp.h"
107 #include "utils/varlena.h"
108 
109 /* timeline ID to be used when bootstrapping */
110 #define BootstrapTimeLineID 1
111 
112 /* User-settable parameters */
113 int max_wal_size_mb = 1024; /* 1 GB */
114 int min_wal_size_mb = 80; /* 80 MB */
116 int XLOGbuffers = -1;
119 char *XLogArchiveCommand = NULL;
120 bool EnableHotStandby = false;
121 bool fullPageWrites = true;
122 bool wal_log_hints = false;
126 bool wal_init_zero = true;
127 bool wal_recycle = true;
128 bool log_checkpoints = true;
131 int CommitDelay = 0; /* precommit delay in microseconds */
132 int CommitSiblings = 5; /* # concurrent xacts needed to sleep */
135 int wal_decode_buffer_size = 512 * 1024;
136 bool track_wal_io_timing = false;
137 
138 #ifdef WAL_DEBUG
139 bool XLOG_DEBUG = false;
140 #endif
141 
143 
144 /*
145  * Number of WAL insertion locks to use. A higher value allows more insertions
146  * to happen concurrently, but adds some CPU overhead to flushing the WAL,
147  * which needs to iterate all the locks.
148  */
149 #define NUM_XLOGINSERT_LOCKS 8
150 
151 /*
152  * Max distance from last checkpoint, before triggering a new xlog-based
153  * checkpoint.
154  */
156 
157 /* Estimated distance between checkpoints, in bytes */
158 static double CheckPointDistanceEstimate = 0;
159 static double PrevCheckPointDistance = 0;
160 
161 /*
162  * Track whether there were any deferred checks for custom resource managers
163  * specified in wal_consistency_checking.
164  */
166 
167 /*
168  * GUC support
169  */
171  {"fsync", WAL_SYNC_METHOD_FSYNC, false},
172 #ifdef HAVE_FSYNC_WRITETHROUGH
173  {"fsync_writethrough", WAL_SYNC_METHOD_FSYNC_WRITETHROUGH, false},
174 #endif
175  {"fdatasync", WAL_SYNC_METHOD_FDATASYNC, false},
176 #ifdef O_SYNC
177  {"open_sync", WAL_SYNC_METHOD_OPEN, false},
178 #endif
179 #ifdef O_DSYNC
180  {"open_datasync", WAL_SYNC_METHOD_OPEN_DSYNC, false},
181 #endif
182  {NULL, 0, false}
183 };
184 
185 
186 /*
187  * Although only "on", "off", and "always" are documented,
188  * we accept all the likely variants of "on" and "off".
189  */
190 const struct config_enum_entry archive_mode_options[] = {
191  {"always", ARCHIVE_MODE_ALWAYS, false},
192  {"on", ARCHIVE_MODE_ON, false},
193  {"off", ARCHIVE_MODE_OFF, false},
194  {"true", ARCHIVE_MODE_ON, true},
195  {"false", ARCHIVE_MODE_OFF, true},
196  {"yes", ARCHIVE_MODE_ON, true},
197  {"no", ARCHIVE_MODE_OFF, true},
198  {"1", ARCHIVE_MODE_ON, true},
199  {"0", ARCHIVE_MODE_OFF, true},
200  {NULL, 0, false}
201 };
202 
203 /*
204  * Statistics for current checkpoint are collected in this global struct.
205  * Because only the checkpointer or a stand-alone backend can perform
206  * checkpoints, this will be unused in normal backends.
207  */
209 
210 /*
211  * During recovery, lastFullPageWrites keeps track of full_page_writes that
212  * the replayed WAL records indicate. It's initialized with full_page_writes
213  * that the recovery starting checkpoint record indicates, and then updated
214  * each time XLOG_FPW_CHANGE record is replayed.
215  */
216 static bool lastFullPageWrites;
217 
218 /*
219  * Local copy of the state tracked by SharedRecoveryState in shared memory,
220  * It is false if SharedRecoveryState is RECOVERY_STATE_DONE. True actually
221  * means "not known, need to check the shared state".
222  */
223 static bool LocalRecoveryInProgress = true;
224 
225 /*
226  * Local state for XLogInsertAllowed():
227  * 1: unconditionally allowed to insert XLOG
228  * 0: unconditionally not allowed to insert XLOG
229  * -1: must check RecoveryInProgress(); disallow until it is false
230  * Most processes start with -1 and transition to 1 after seeing that recovery
231  * is not in progress. But we can also force the value for special cases.
232  * The coding in XLogInsertAllowed() depends on the first two of these states
233  * being numerically the same as bool true and false.
234  */
235 static int LocalXLogInsertAllowed = -1;
236 
237 /*
238  * ProcLastRecPtr points to the start of the last XLOG record inserted by the
239  * current backend. It is updated for all inserts. XactLastRecEnd points to
240  * end+1 of the last record, and is reset when we end a top-level transaction,
241  * or start a new one; so it can be used to tell if the current transaction has
242  * created any XLOG records.
243  *
244  * While in parallel mode, this may not be fully up to date. When committing,
245  * a transaction can assume this covers all xlog records written either by the
246  * user backend or by any parallel worker which was present at any point during
247  * the transaction. But when aborting, or when still in parallel mode, other
248  * parallel backends may have written WAL records at later LSNs than the value
249  * stored here. The parallel leader advances its own copy, when necessary,
250  * in WaitForParallelWorkersToFinish.
251  */
255 
256 /*
257  * RedoRecPtr is this backend's local copy of the REDO record pointer
258  * (which is almost but not quite the same as a pointer to the most recent
259  * CHECKPOINT record). We update this from the shared-memory copy,
260  * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
261  * hold an insertion lock). See XLogInsertRecord for details. We are also
262  * allowed to update from XLogCtl->RedoRecPtr if we hold the info_lck;
263  * see GetRedoRecPtr.
264  *
265  * NB: Code that uses this variable must be prepared not only for the
266  * possibility that it may be arbitrarily out of date, but also for the
267  * possibility that it might be set to InvalidXLogRecPtr. We used to
268  * initialize it as a side effect of the first call to RecoveryInProgress(),
269  * which meant that most code that might use it could assume that it had a
270  * real if perhaps stale value. That's no longer the case.
271  */
273 
274 /*
275  * doPageWrites is this backend's local copy of (fullPageWrites ||
276  * runningBackups > 0). It is used together with RedoRecPtr to decide whether
277  * a full-page image of a page need to be taken.
278  *
279  * NB: Initially this is false, and there's no guarantee that it will be
280  * initialized to any other value before it is first used. Any code that
281  * makes use of it must recheck the value after obtaining a WALInsertLock,
282  * and respond appropriately if it turns out that the previous value wasn't
283  * accurate.
284  */
285 static bool doPageWrites;
286 
287 /*----------
288  * Shared-memory data structures for XLOG control
289  *
290  * LogwrtRqst indicates a byte position that we need to write and/or fsync
291  * the log up to (all records before that point must be written or fsynced).
292  * The positions already written/fsynced are maintained in logWriteResult
293  * and logFlushResult using atomic access.
294  * In addition to the shared variable, each backend has a private copy of
295  * both in LogwrtResult, which is updated when convenient.
296  *
297  * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
298  * (protected by info_lck), but we don't need to cache any copies of it.
299  *
300  * info_lck is only held long enough to read/update the protected variables,
301  * so it's a plain spinlock. The other locks are held longer (potentially
302  * over I/O operations), so we use LWLocks for them. These locks are:
303  *
304  * WALBufMappingLock: must be held to replace a page in the WAL buffer cache.
305  * It is only held while initializing and changing the mapping. If the
306  * contents of the buffer being replaced haven't been written yet, the mapping
307  * lock is released while the write is done, and reacquired afterwards.
308  *
309  * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
310  * XLogFlush).
311  *
312  * ControlFileLock: must be held to read/update control file or create
313  * new log file.
314  *
315  *----------
316  */
317 
318 typedef struct XLogwrtRqst
319 {
320  XLogRecPtr Write; /* last byte + 1 to write out */
321  XLogRecPtr Flush; /* last byte + 1 to flush */
323 
324 typedef struct XLogwrtResult
325 {
326  XLogRecPtr Write; /* last byte + 1 written out */
327  XLogRecPtr Flush; /* last byte + 1 flushed */
329 
330 /*
331  * Inserting to WAL is protected by a small fixed number of WAL insertion
332  * locks. To insert to the WAL, you must hold one of the locks - it doesn't
333  * matter which one. To lock out other concurrent insertions, you must hold
334  * of them. Each WAL insertion lock consists of a lightweight lock, plus an
335  * indicator of how far the insertion has progressed (insertingAt).
336  *
337  * The insertingAt values are read when a process wants to flush WAL from
338  * the in-memory buffers to disk, to check that all the insertions to the
339  * region the process is about to write out have finished. You could simply
340  * wait for all currently in-progress insertions to finish, but the
341  * insertingAt indicator allows you to ignore insertions to later in the WAL,
342  * so that you only wait for the insertions that are modifying the buffers
343  * you're about to write out.
344  *
345  * This isn't just an optimization. If all the WAL buffers are dirty, an
346  * inserter that's holding a WAL insert lock might need to evict an old WAL
347  * buffer, which requires flushing the WAL. If it's possible for an inserter
348  * to block on another inserter unnecessarily, deadlock can arise when two
349  * inserters holding a WAL insert lock wait for each other to finish their
350  * insertion.
351  *
352  * Small WAL records that don't cross a page boundary never update the value,
353  * the WAL record is just copied to the page and the lock is released. But
354  * to avoid the deadlock-scenario explained above, the indicator is always
355  * updated before sleeping while holding an insertion lock.
356  *
357  * lastImportantAt contains the LSN of the last important WAL record inserted
358  * using a given lock. This value is used to detect if there has been
359  * important WAL activity since the last time some action, like a checkpoint,
360  * was performed - allowing to not repeat the action if not. The LSN is
361  * updated for all insertions, unless the XLOG_MARK_UNIMPORTANT flag was
362  * set. lastImportantAt is never cleared, only overwritten by the LSN of newer
363  * records. Tracking the WAL activity directly in WALInsertLock has the
364  * advantage of not needing any additional locks to update the value.
365  */
366 typedef struct
367 {
371 } WALInsertLock;
372 
373 /*
374  * All the WAL insertion locks are allocated as an array in shared memory. We
375  * force the array stride to be a power of 2, which saves a few cycles in
376  * indexing, but more importantly also ensures that individual slots don't
377  * cross cache line boundaries. (Of course, we have to also ensure that the
378  * array start address is suitably aligned.)
379  */
380 typedef union WALInsertLockPadded
381 {
385 
386 /*
387  * Session status of running backup, used for sanity checks in SQL-callable
388  * functions to start and stop backups.
389  */
391 
392 /*
393  * Shared state data for WAL insertion.
394  */
395 typedef struct XLogCtlInsert
396 {
397  slock_t insertpos_lck; /* protects CurrBytePos and PrevBytePos */
398 
399  /*
400  * CurrBytePos is the end of reserved WAL. The next record will be
401  * inserted at that position. PrevBytePos is the start position of the
402  * previously inserted (or rather, reserved) record - it is copied to the
403  * prev-link of the next record. These are stored as "usable byte
404  * positions" rather than XLogRecPtrs (see XLogBytePosToRecPtr()).
405  */
406  uint64 CurrBytePos;
407  uint64 PrevBytePos;
408 
409  /*
410  * Make sure the above heavily-contended spinlock and byte positions are
411  * on their own cache line. In particular, the RedoRecPtr and full page
412  * write variables below should be on a different cache line. They are
413  * read on every WAL insertion, but updated rarely, and we don't want
414  * those reads to steal the cache line containing Curr/PrevBytePos.
415  */
417 
418  /*
419  * fullPageWrites is the authoritative value used by all backends to
420  * determine whether to write full-page image to WAL. This shared value,
421  * instead of the process-local fullPageWrites, is required because, when
422  * full_page_writes is changed by SIGHUP, we must WAL-log it before it
423  * actually affects WAL-logging by backends. Checkpointer sets at startup
424  * or after SIGHUP.
425  *
426  * To read these fields, you must hold an insertion lock. To modify them,
427  * you must hold ALL the locks.
428  */
429  XLogRecPtr RedoRecPtr; /* current redo point for insertions */
431 
432  /*
433  * runningBackups is a counter indicating the number of backups currently
434  * in progress. lastBackupStart is the latest checkpoint redo location
435  * used as a starting point for an online backup.
436  */
439 
440  /*
441  * WAL insertion locks.
442  */
445 
446 /*
447  * Total shared-memory state for XLOG.
448  */
449 typedef struct XLogCtlData
450 {
452 
453  /* Protected by info_lck: */
455  XLogRecPtr RedoRecPtr; /* a recent copy of Insert->RedoRecPtr */
456  FullTransactionId ckptFullXid; /* nextXid of latest checkpoint */
457  XLogRecPtr asyncXactLSN; /* LSN of newest async commit/abort */
458  XLogRecPtr replicationSlotMinLSN; /* oldest LSN needed by any slot */
459 
460  XLogSegNo lastRemovedSegNo; /* latest removed/recycled XLOG segment */
461 
462  /* Fake LSN counter, for unlogged relations. */
464 
465  /* Time and LSN of last xlog segment switch. Protected by WALWriteLock. */
468 
469  /* These are accessed using atomics -- info_lck not needed */
470  pg_atomic_uint64 logInsertResult; /* last byte + 1 inserted to buffers */
471  pg_atomic_uint64 logWriteResult; /* last byte + 1 written out */
472  pg_atomic_uint64 logFlushResult; /* last byte + 1 flushed */
473 
474  /*
475  * Latest initialized page in the cache (last byte position + 1).
476  *
477  * To change the identity of a buffer (and InitializedUpTo), you need to
478  * hold WALBufMappingLock. To change the identity of a buffer that's
479  * still dirty, the old page needs to be written out first, and for that
480  * you need WALWriteLock, and you need to ensure that there are no
481  * in-progress insertions to the page by calling
482  * WaitXLogInsertionsToFinish().
483  */
485 
486  /*
487  * These values do not change after startup, although the pointed-to pages
488  * and xlblocks values certainly do. xlblocks values are protected by
489  * WALBufMappingLock.
490  */
491  char *pages; /* buffers for unwritten XLOG pages */
492  pg_atomic_uint64 *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
493  int XLogCacheBlck; /* highest allocated xlog buffer index */
494 
495  /*
496  * InsertTimeLineID is the timeline into which new WAL is being inserted
497  * and flushed. It is zero during recovery, and does not change once set.
498  *
499  * If we create a new timeline when the system was started up,
500  * PrevTimeLineID is the old timeline's ID that we forked off from.
501  * Otherwise it's equal to InsertTimeLineID.
502  *
503  * We set these fields while holding info_lck. Most that reads these
504  * values knows that recovery is no longer in progress and so can safely
505  * read the value without a lock, but code that could be run either during
506  * or after recovery can take info_lck while reading these values.
507  */
510 
511  /*
512  * SharedRecoveryState indicates if we're still in crash or archive
513  * recovery. Protected by info_lck.
514  */
516 
517  /*
518  * InstallXLogFileSegmentActive indicates whether the checkpointer should
519  * arrange for future segments by recycling and/or PreallocXlogFiles().
520  * Protected by ControlFileLock. Only the startup process changes it. If
521  * true, anyone can use InstallXLogFileSegment(). If false, the startup
522  * process owns the exclusive right to install segments, by reading from
523  * the archive and possibly replacing existing files.
524  */
526 
527  /*
528  * WalWriterSleeping indicates whether the WAL writer is currently in
529  * low-power mode (and hence should be nudged if an async commit occurs).
530  * Protected by info_lck.
531  */
533 
534  /*
535  * During recovery, we keep a copy of the latest checkpoint record here.
536  * lastCheckPointRecPtr points to start of checkpoint record and
537  * lastCheckPointEndPtr points to end+1 of checkpoint record. Used by the
538  * checkpointer when it wants to create a restartpoint.
539  *
540  * Protected by info_lck.
541  */
545 
546  /*
547  * lastFpwDisableRecPtr points to the start of the last replayed
548  * XLOG_FPW_CHANGE record that instructs full_page_writes is disabled.
549  */
551 
552  slock_t info_lck; /* locks shared variables shown above */
554 
555 /*
556  * Classification of XLogRecordInsert operations.
557  */
558 typedef enum
559 {
564 
565 static XLogCtlData *XLogCtl = NULL;
566 
567 /* a private copy of XLogCtl->Insert.WALInsertLocks, for convenience */
569 
570 /*
571  * We maintain an image of pg_control in shared memory.
572  */
574 
575 /*
576  * Calculate the amount of space left on the page after 'endptr'. Beware
577  * multiple evaluation!
578  */
579 #define INSERT_FREESPACE(endptr) \
580  (((endptr) % XLOG_BLCKSZ == 0) ? 0 : (XLOG_BLCKSZ - (endptr) % XLOG_BLCKSZ))
581 
582 /* Macro to advance to next buffer index. */
583 #define NextBufIdx(idx) \
584  (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
585 
586 /*
587  * XLogRecPtrToBufIdx returns the index of the WAL buffer that holds, or
588  * would hold if it was in cache, the page containing 'recptr'.
589  */
590 #define XLogRecPtrToBufIdx(recptr) \
591  (((recptr) / XLOG_BLCKSZ) % (XLogCtl->XLogCacheBlck + 1))
592 
593 /*
594  * These are the number of bytes in a WAL page usable for WAL data.
595  */
596 #define UsableBytesInPage (XLOG_BLCKSZ - SizeOfXLogShortPHD)
597 
598 /*
599  * Convert values of GUCs measured in megabytes to equiv. segment count.
600  * Rounds down.
601  */
602 #define ConvertToXSegs(x, segsize) XLogMBVarToSegs((x), (segsize))
603 
604 /* The number of bytes in a WAL segment usable for WAL data. */
606 
607 /*
608  * Private, possibly out-of-date copy of shared LogwrtResult.
609  * See discussion above.
610  */
611 static XLogwrtResult LogwrtResult = {0, 0};
612 
613 /*
614  * Update local copy of shared XLogCtl->log{Write,Flush}Result
615  *
616  * It's critical that Flush always trails Write, so the order of the reads is
617  * important, as is the barrier. See also XLogWrite.
618  */
619 #define RefreshXLogWriteResult(_target) \
620  do { \
621  _target.Flush = pg_atomic_read_u64(&XLogCtl->logFlushResult); \
622  pg_read_barrier(); \
623  _target.Write = pg_atomic_read_u64(&XLogCtl->logWriteResult); \
624  } while (0)
625 
626 /*
627  * openLogFile is -1 or a kernel FD for an open log file segment.
628  * openLogSegNo identifies the segment, and openLogTLI the corresponding TLI.
629  * These variables are only used to write the XLOG, and so will normally refer
630  * to the active segment.
631  *
632  * Note: call Reserve/ReleaseExternalFD to track consumption of this FD.
633  */
634 static int openLogFile = -1;
637 
638 /*
639  * Local copies of equivalent fields in the control file. When running
640  * crash recovery, LocalMinRecoveryPoint is set to InvalidXLogRecPtr as we
641  * expect to replay all the WAL available, and updateMinRecoveryPoint is
642  * switched to false to prevent any updates while replaying records.
643  * Those values are kept consistent as long as crash recovery runs.
644  */
647 static bool updateMinRecoveryPoint = true;
648 
649 /* For WALInsertLockAcquire/Release functions */
650 static int MyLockNo = 0;
651 static bool holdingAllLocks = false;
652 
653 #ifdef WAL_DEBUG
654 static MemoryContext walDebugCxt = NULL;
655 #endif
656 
657 static void CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI,
658  XLogRecPtr EndOfLog,
659  TimeLineID newTLI);
660 static void CheckRequiredParameterValues(void);
661 static void XLogReportParameters(void);
662 static int LocalSetXLogInsertAllowed(void);
663 static void CreateEndOfRecoveryRecord(void);
665  XLogRecPtr pagePtr,
666  TimeLineID newTLI);
667 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
668 static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo);
670 
671 static void AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli,
672  bool opportunistic);
673 static void XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible);
674 static bool InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
675  bool find_free, XLogSegNo max_segno,
676  TimeLineID tli);
677 static void XLogFileClose(void);
678 static void PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli);
679 static void RemoveTempXlogFiles(void);
680 static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr,
681  XLogRecPtr endptr, TimeLineID insertTLI);
682 static void RemoveXlogFile(const struct dirent *segment_de,
683  XLogSegNo recycleSegNo, XLogSegNo *endlogSegNo,
684  TimeLineID insertTLI);
685 static void UpdateLastRemovedPtr(char *filename);
686 static void ValidateXLOGDirectoryStructure(void);
687 static void CleanupBackupHistory(void);
688 static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
689 static bool PerformRecoveryXLogAction(void);
690 static void InitControlFile(uint64 sysidentifier, uint32 data_checksum_version);
691 static void WriteControlFile(void);
692 static void ReadControlFile(void);
693 static void UpdateControlFile(void);
694 static char *str_time(pg_time_t tnow);
695 
696 static int get_sync_bit(int method);
697 
698 static void CopyXLogRecordToWAL(int write_len, bool isLogSwitch,
699  XLogRecData *rdata,
700  XLogRecPtr StartPos, XLogRecPtr EndPos,
701  TimeLineID tli);
702 static void ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos,
703  XLogRecPtr *EndPos, XLogRecPtr *PrevPtr);
704 static bool ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos,
705  XLogRecPtr *PrevPtr);
707 static char *GetXLogBuffer(XLogRecPtr ptr, TimeLineID tli);
708 static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos);
709 static XLogRecPtr XLogBytePosToEndRecPtr(uint64 bytepos);
710 static uint64 XLogRecPtrToBytePos(XLogRecPtr ptr);
711 
712 static void WALInsertLockAcquire(void);
713 static void WALInsertLockAcquireExclusive(void);
714 static void WALInsertLockRelease(void);
715 static void WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt);
716 
717 /*
718  * Insert an XLOG record represented by an already-constructed chain of data
719  * chunks. This is a low-level routine; to construct the WAL record header
720  * and data, use the higher-level routines in xloginsert.c.
721  *
722  * If 'fpw_lsn' is valid, it is the oldest LSN among the pages that this
723  * WAL record applies to, that were not included in the record as full page
724  * images. If fpw_lsn <= RedoRecPtr, the function does not perform the
725  * insertion and returns InvalidXLogRecPtr. The caller can then recalculate
726  * which pages need a full-page image, and retry. If fpw_lsn is invalid, the
727  * record is always inserted.
728  *
729  * 'flags' gives more in-depth control on the record being inserted. See
730  * XLogSetRecordFlags() for details.
731  *
732  * 'topxid_included' tells whether the top-transaction id is logged along with
733  * current subtransaction. See XLogRecordAssemble().
734  *
735  * The first XLogRecData in the chain must be for the record header, and its
736  * data must be MAXALIGNed. XLogInsertRecord fills in the xl_prev and
737  * xl_crc fields in the header, the rest of the header must already be filled
738  * by the caller.
739  *
740  * Returns XLOG pointer to end of record (beginning of next record).
741  * This can be used as LSN for data pages affected by the logged action.
742  * (LSN is the XLOG point up to which the XLOG must be flushed to disk
743  * before the data page can be written out. This implements the basic
744  * WAL rule "write the log before the data".)
745  */
748  XLogRecPtr fpw_lsn,
749  uint8 flags,
750  int num_fpi,
751  bool topxid_included)
752 {
754  pg_crc32c rdata_crc;
755  bool inserted;
756  XLogRecord *rechdr = (XLogRecord *) rdata->data;
757  uint8 info = rechdr->xl_info & ~XLR_INFO_MASK;
759  XLogRecPtr StartPos;
760  XLogRecPtr EndPos;
761  bool prevDoPageWrites = doPageWrites;
762  TimeLineID insertTLI;
763 
764  /* Does this record type require special handling? */
765  if (unlikely(rechdr->xl_rmid == RM_XLOG_ID))
766  {
767  if (info == XLOG_SWITCH)
768  class = WALINSERT_SPECIAL_SWITCH;
769  else if (info == XLOG_CHECKPOINT_REDO)
771  }
772 
773  /* we assume that all of the record header is in the first chunk */
774  Assert(rdata->len >= SizeOfXLogRecord);
775 
776  /* cross-check on whether we should be here or not */
777  if (!XLogInsertAllowed())
778  elog(ERROR, "cannot make new WAL entries during recovery");
779 
780  /*
781  * Given that we're not in recovery, InsertTimeLineID is set and can't
782  * change, so we can read it without a lock.
783  */
784  insertTLI = XLogCtl->InsertTimeLineID;
785 
786  /*----------
787  *
788  * We have now done all the preparatory work we can without holding a
789  * lock or modifying shared state. From here on, inserting the new WAL
790  * record to the shared WAL buffer cache is a two-step process:
791  *
792  * 1. Reserve the right amount of space from the WAL. The current head of
793  * reserved space is kept in Insert->CurrBytePos, and is protected by
794  * insertpos_lck.
795  *
796  * 2. Copy the record to the reserved WAL space. This involves finding the
797  * correct WAL buffer containing the reserved space, and copying the
798  * record in place. This can be done concurrently in multiple processes.
799  *
800  * To keep track of which insertions are still in-progress, each concurrent
801  * inserter acquires an insertion lock. In addition to just indicating that
802  * an insertion is in progress, the lock tells others how far the inserter
803  * has progressed. There is a small fixed number of insertion locks,
804  * determined by NUM_XLOGINSERT_LOCKS. When an inserter crosses a page
805  * boundary, it updates the value stored in the lock to the how far it has
806  * inserted, to allow the previous buffer to be flushed.
807  *
808  * Holding onto an insertion lock also protects RedoRecPtr and
809  * fullPageWrites from changing until the insertion is finished.
810  *
811  * Step 2 can usually be done completely in parallel. If the required WAL
812  * page is not initialized yet, you have to grab WALBufMappingLock to
813  * initialize it, but the WAL writer tries to do that ahead of insertions
814  * to avoid that from happening in the critical path.
815  *
816  *----------
817  */
819 
820  if (likely(class == WALINSERT_NORMAL))
821  {
823 
824  /*
825  * Check to see if my copy of RedoRecPtr is out of date. If so, may
826  * have to go back and have the caller recompute everything. This can
827  * only happen just after a checkpoint, so it's better to be slow in
828  * this case and fast otherwise.
829  *
830  * Also check to see if fullPageWrites was just turned on or there's a
831  * running backup (which forces full-page writes); if we weren't
832  * already doing full-page writes then go back and recompute.
833  *
834  * If we aren't doing full-page writes then RedoRecPtr doesn't
835  * actually affect the contents of the XLOG record, so we'll update
836  * our local copy but not force a recomputation. (If doPageWrites was
837  * just turned off, we could recompute the record without full pages,
838  * but we choose not to bother.)
839  */
840  if (RedoRecPtr != Insert->RedoRecPtr)
841  {
842  Assert(RedoRecPtr < Insert->RedoRecPtr);
843  RedoRecPtr = Insert->RedoRecPtr;
844  }
845  doPageWrites = (Insert->fullPageWrites || Insert->runningBackups > 0);
846 
847  if (doPageWrites &&
848  (!prevDoPageWrites ||
849  (fpw_lsn != InvalidXLogRecPtr && fpw_lsn <= RedoRecPtr)))
850  {
851  /*
852  * Oops, some buffer now needs to be backed up that the caller
853  * didn't back up. Start over.
854  */
857  return InvalidXLogRecPtr;
858  }
859 
860  /*
861  * Reserve space for the record in the WAL. This also sets the xl_prev
862  * pointer.
863  */
864  ReserveXLogInsertLocation(rechdr->xl_tot_len, &StartPos, &EndPos,
865  &rechdr->xl_prev);
866 
867  /* Normal records are always inserted. */
868  inserted = true;
869  }
870  else if (class == WALINSERT_SPECIAL_SWITCH)
871  {
872  /*
873  * In order to insert an XLOG_SWITCH record, we need to hold all of
874  * the WAL insertion locks, not just one, so that no one else can
875  * begin inserting a record until we've figured out how much space
876  * remains in the current WAL segment and claimed all of it.
877  *
878  * Nonetheless, this case is simpler than the normal cases handled
879  * below, which must check for changes in doPageWrites and RedoRecPtr.
880  * Those checks are only needed for records that can contain buffer
881  * references, and an XLOG_SWITCH record never does.
882  */
883  Assert(fpw_lsn == InvalidXLogRecPtr);
885  inserted = ReserveXLogSwitch(&StartPos, &EndPos, &rechdr->xl_prev);
886  }
887  else
888  {
890 
891  /*
892  * We need to update both the local and shared copies of RedoRecPtr,
893  * which means that we need to hold all the WAL insertion locks.
894  * However, there can't be any buffer references, so as above, we need
895  * not check RedoRecPtr before inserting the record; we just need to
896  * update it afterwards.
897  */
898  Assert(fpw_lsn == InvalidXLogRecPtr);
900  ReserveXLogInsertLocation(rechdr->xl_tot_len, &StartPos, &EndPos,
901  &rechdr->xl_prev);
902  RedoRecPtr = Insert->RedoRecPtr = StartPos;
903  inserted = true;
904  }
905 
906  if (inserted)
907  {
908  /*
909  * Now that xl_prev has been filled in, calculate CRC of the record
910  * header.
911  */
912  rdata_crc = rechdr->xl_crc;
913  COMP_CRC32C(rdata_crc, rechdr, offsetof(XLogRecord, xl_crc));
914  FIN_CRC32C(rdata_crc);
915  rechdr->xl_crc = rdata_crc;
916 
917  /*
918  * All the record data, including the header, is now ready to be
919  * inserted. Copy the record in the space reserved.
920  */
922  class == WALINSERT_SPECIAL_SWITCH, rdata,
923  StartPos, EndPos, insertTLI);
924 
925  /*
926  * Unless record is flagged as not important, update LSN of last
927  * important record in the current slot. When holding all locks, just
928  * update the first one.
929  */
930  if ((flags & XLOG_MARK_UNIMPORTANT) == 0)
931  {
932  int lockno = holdingAllLocks ? 0 : MyLockNo;
933 
934  WALInsertLocks[lockno].l.lastImportantAt = StartPos;
935  }
936  }
937  else
938  {
939  /*
940  * This was an xlog-switch record, but the current insert location was
941  * already exactly at the beginning of a segment, so there was no need
942  * to do anything.
943  */
944  }
945 
946  /*
947  * Done! Let others know that we're finished.
948  */
950 
952 
954 
955  /*
956  * Mark top transaction id is logged (if needed) so that we should not try
957  * to log it again with the next WAL record in the current subtransaction.
958  */
959  if (topxid_included)
961 
962  /*
963  * Update shared LogwrtRqst.Write, if we crossed page boundary.
964  */
965  if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
966  {
968  /* advance global request to include new block(s) */
969  if (XLogCtl->LogwrtRqst.Write < EndPos)
970  XLogCtl->LogwrtRqst.Write = EndPos;
973  }
974 
975  /*
976  * If this was an XLOG_SWITCH record, flush the record and the empty
977  * padding space that fills the rest of the segment, and perform
978  * end-of-segment actions (eg, notifying archiver).
979  */
980  if (class == WALINSERT_SPECIAL_SWITCH)
981  {
982  TRACE_POSTGRESQL_WAL_SWITCH();
983  XLogFlush(EndPos);
984 
985  /*
986  * Even though we reserved the rest of the segment for us, which is
987  * reflected in EndPos, we return a pointer to just the end of the
988  * xlog-switch record.
989  */
990  if (inserted)
991  {
992  EndPos = StartPos + SizeOfXLogRecord;
993  if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
994  {
995  uint64 offset = XLogSegmentOffset(EndPos, wal_segment_size);
996 
997  if (offset == EndPos % XLOG_BLCKSZ)
998  EndPos += SizeOfXLogLongPHD;
999  else
1000  EndPos += SizeOfXLogShortPHD;
1001  }
1002  }
1003  }
1004 
1005 #ifdef WAL_DEBUG
1006  if (XLOG_DEBUG)
1007  {
1008  static XLogReaderState *debug_reader = NULL;
1009  XLogRecord *record;
1010  DecodedXLogRecord *decoded;
1012  StringInfoData recordBuf;
1013  char *errormsg = NULL;
1014  MemoryContext oldCxt;
1015 
1016  oldCxt = MemoryContextSwitchTo(walDebugCxt);
1017 
1018  initStringInfo(&buf);
1019  appendStringInfo(&buf, "INSERT @ %X/%X: ", LSN_FORMAT_ARGS(EndPos));
1020 
1021  /*
1022  * We have to piece together the WAL record data from the XLogRecData
1023  * entries, so that we can pass it to the rm_desc function as one
1024  * contiguous chunk.
1025  */
1026  initStringInfo(&recordBuf);
1027  for (; rdata != NULL; rdata = rdata->next)
1028  appendBinaryStringInfo(&recordBuf, rdata->data, rdata->len);
1029 
1030  /* We also need temporary space to decode the record. */
1031  record = (XLogRecord *) recordBuf.data;
1032  decoded = (DecodedXLogRecord *)
1034 
1035  if (!debug_reader)
1036  debug_reader = XLogReaderAllocate(wal_segment_size, NULL,
1037  XL_ROUTINE(.page_read = NULL,
1038  .segment_open = NULL,
1039  .segment_close = NULL),
1040  NULL);
1041  if (!debug_reader)
1042  {
1043  appendStringInfoString(&buf, "error decoding record: out of memory while allocating a WAL reading processor");
1044  }
1045  else if (!DecodeXLogRecord(debug_reader,
1046  decoded,
1047  record,
1048  EndPos,
1049  &errormsg))
1050  {
1051  appendStringInfo(&buf, "error decoding record: %s",
1052  errormsg ? errormsg : "no error message");
1053  }
1054  else
1055  {
1056  appendStringInfoString(&buf, " - ");
1057 
1058  debug_reader->record = decoded;
1059  xlog_outdesc(&buf, debug_reader);
1060  debug_reader->record = NULL;
1061  }
1062  elog(LOG, "%s", buf.data);
1063 
1064  pfree(decoded);
1065  pfree(buf.data);
1066  pfree(recordBuf.data);
1067  MemoryContextSwitchTo(oldCxt);
1068  }
1069 #endif
1070 
1071  /*
1072  * Update our global variables
1073  */
1074  ProcLastRecPtr = StartPos;
1075  XactLastRecEnd = EndPos;
1076 
1077  /* Report WAL traffic to the instrumentation. */
1078  if (inserted)
1079  {
1080  pgWalUsage.wal_bytes += rechdr->xl_tot_len;
1082  pgWalUsage.wal_fpi += num_fpi;
1083  }
1084 
1085  return EndPos;
1086 }
1087 
1088 /*
1089  * Reserves the right amount of space for a record of given size from the WAL.
1090  * *StartPos is set to the beginning of the reserved section, *EndPos to
1091  * its end+1. *PrevPtr is set to the beginning of the previous record; it is
1092  * used to set the xl_prev of this record.
1093  *
1094  * This is the performance critical part of XLogInsert that must be serialized
1095  * across backends. The rest can happen mostly in parallel. Try to keep this
1096  * section as short as possible, insertpos_lck can be heavily contended on a
1097  * busy system.
1098  *
1099  * NB: The space calculation here must match the code in CopyXLogRecordToWAL,
1100  * where we actually copy the record to the reserved space.
1101  *
1102  * NB: Testing shows that XLogInsertRecord runs faster if this code is inlined;
1103  * however, because there are two call sites, the compiler is reluctant to
1104  * inline. We use pg_attribute_always_inline here to try to convince it.
1105  */
1106 static pg_attribute_always_inline void
1108  XLogRecPtr *PrevPtr)
1109 {
1111  uint64 startbytepos;
1112  uint64 endbytepos;
1113  uint64 prevbytepos;
1114 
1115  size = MAXALIGN(size);
1116 
1117  /* All (non xlog-switch) records should contain data. */
1119 
1120  /*
1121  * The duration the spinlock needs to be held is minimized by minimizing
1122  * the calculations that have to be done while holding the lock. The
1123  * current tip of reserved WAL is kept in CurrBytePos, as a byte position
1124  * that only counts "usable" bytes in WAL, that is, it excludes all WAL
1125  * page headers. The mapping between "usable" byte positions and physical
1126  * positions (XLogRecPtrs) can be done outside the locked region, and
1127  * because the usable byte position doesn't include any headers, reserving
1128  * X bytes from WAL is almost as simple as "CurrBytePos += X".
1129  */
1130  SpinLockAcquire(&Insert->insertpos_lck);
1131 
1132  startbytepos = Insert->CurrBytePos;
1133  endbytepos = startbytepos + size;
1134  prevbytepos = Insert->PrevBytePos;
1135  Insert->CurrBytePos = endbytepos;
1136  Insert->PrevBytePos = startbytepos;
1137 
1138  SpinLockRelease(&Insert->insertpos_lck);
1139 
1140  *StartPos = XLogBytePosToRecPtr(startbytepos);
1141  *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1142  *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1143 
1144  /*
1145  * Check that the conversions between "usable byte positions" and
1146  * XLogRecPtrs work consistently in both directions.
1147  */
1148  Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1149  Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1150  Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1151 }
1152 
1153 /*
1154  * Like ReserveXLogInsertLocation(), but for an xlog-switch record.
1155  *
1156  * A log-switch record is handled slightly differently. The rest of the
1157  * segment will be reserved for this insertion, as indicated by the returned
1158  * *EndPos value. However, if we are already at the beginning of the current
1159  * segment, *StartPos and *EndPos are set to the current location without
1160  * reserving any space, and the function returns false.
1161 */
1162 static bool
1163 ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
1164 {
1166  uint64 startbytepos;
1167  uint64 endbytepos;
1168  uint64 prevbytepos;
1170  XLogRecPtr ptr;
1171  uint32 segleft;
1172 
1173  /*
1174  * These calculations are a bit heavy-weight to be done while holding a
1175  * spinlock, but since we're holding all the WAL insertion locks, there
1176  * are no other inserters competing for it. GetXLogInsertRecPtr() does
1177  * compete for it, but that's not called very frequently.
1178  */
1179  SpinLockAcquire(&Insert->insertpos_lck);
1180 
1181  startbytepos = Insert->CurrBytePos;
1182 
1183  ptr = XLogBytePosToEndRecPtr(startbytepos);
1184  if (XLogSegmentOffset(ptr, wal_segment_size) == 0)
1185  {
1186  SpinLockRelease(&Insert->insertpos_lck);
1187  *EndPos = *StartPos = ptr;
1188  return false;
1189  }
1190 
1191  endbytepos = startbytepos + size;
1192  prevbytepos = Insert->PrevBytePos;
1193 
1194  *StartPos = XLogBytePosToRecPtr(startbytepos);
1195  *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1196 
1197  segleft = wal_segment_size - XLogSegmentOffset(*EndPos, wal_segment_size);
1198  if (segleft != wal_segment_size)
1199  {
1200  /* consume the rest of the segment */
1201  *EndPos += segleft;
1202  endbytepos = XLogRecPtrToBytePos(*EndPos);
1203  }
1204  Insert->CurrBytePos = endbytepos;
1205  Insert->PrevBytePos = startbytepos;
1206 
1207  SpinLockRelease(&Insert->insertpos_lck);
1208 
1209  *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1210 
1211  Assert(XLogSegmentOffset(*EndPos, wal_segment_size) == 0);
1212  Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1213  Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1214  Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1215 
1216  return true;
1217 }
1218 
1219 /*
1220  * Subroutine of XLogInsertRecord. Copies a WAL record to an already-reserved
1221  * area in the WAL.
1222  */
1223 static void
1224 CopyXLogRecordToWAL(int write_len, bool isLogSwitch, XLogRecData *rdata,
1225  XLogRecPtr StartPos, XLogRecPtr EndPos, TimeLineID tli)
1226 {
1227  char *currpos;
1228  int freespace;
1229  int written;
1230  XLogRecPtr CurrPos;
1231  XLogPageHeader pagehdr;
1232 
1233  /*
1234  * Get a pointer to the right place in the right WAL buffer to start
1235  * inserting to.
1236  */
1237  CurrPos = StartPos;
1238  currpos = GetXLogBuffer(CurrPos, tli);
1239  freespace = INSERT_FREESPACE(CurrPos);
1240 
1241  /*
1242  * there should be enough space for at least the first field (xl_tot_len)
1243  * on this page.
1244  */
1245  Assert(freespace >= sizeof(uint32));
1246 
1247  /* Copy record data */
1248  written = 0;
1249  while (rdata != NULL)
1250  {
1251  const char *rdata_data = rdata->data;
1252  int rdata_len = rdata->len;
1253 
1254  while (rdata_len > freespace)
1255  {
1256  /*
1257  * Write what fits on this page, and continue on the next page.
1258  */
1259  Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || freespace == 0);
1260  memcpy(currpos, rdata_data, freespace);
1261  rdata_data += freespace;
1262  rdata_len -= freespace;
1263  written += freespace;
1264  CurrPos += freespace;
1265 
1266  /*
1267  * Get pointer to beginning of next page, and set the xlp_rem_len
1268  * in the page header. Set XLP_FIRST_IS_CONTRECORD.
1269  *
1270  * It's safe to set the contrecord flag and xlp_rem_len without a
1271  * lock on the page. All the other flags were already set when the
1272  * page was initialized, in AdvanceXLInsertBuffer, and we're the
1273  * only backend that needs to set the contrecord flag.
1274  */
1275  currpos = GetXLogBuffer(CurrPos, tli);
1276  pagehdr = (XLogPageHeader) currpos;
1277  pagehdr->xlp_rem_len = write_len - written;
1278  pagehdr->xlp_info |= XLP_FIRST_IS_CONTRECORD;
1279 
1280  /* skip over the page header */
1281  if (XLogSegmentOffset(CurrPos, wal_segment_size) == 0)
1282  {
1283  CurrPos += SizeOfXLogLongPHD;
1284  currpos += SizeOfXLogLongPHD;
1285  }
1286  else
1287  {
1288  CurrPos += SizeOfXLogShortPHD;
1289  currpos += SizeOfXLogShortPHD;
1290  }
1291  freespace = INSERT_FREESPACE(CurrPos);
1292  }
1293 
1294  Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || rdata_len == 0);
1295  memcpy(currpos, rdata_data, rdata_len);
1296  currpos += rdata_len;
1297  CurrPos += rdata_len;
1298  freespace -= rdata_len;
1299  written += rdata_len;
1300 
1301  rdata = rdata->next;
1302  }
1303  Assert(written == write_len);
1304 
1305  /*
1306  * If this was an xlog-switch, it's not enough to write the switch record,
1307  * we also have to consume all the remaining space in the WAL segment. We
1308  * have already reserved that space, but we need to actually fill it.
1309  */
1310  if (isLogSwitch && XLogSegmentOffset(CurrPos, wal_segment_size) != 0)
1311  {
1312  /* An xlog-switch record doesn't contain any data besides the header */
1313  Assert(write_len == SizeOfXLogRecord);
1314 
1315  /* Assert that we did reserve the right amount of space */
1316  Assert(XLogSegmentOffset(EndPos, wal_segment_size) == 0);
1317 
1318  /* Use up all the remaining space on the current page */
1319  CurrPos += freespace;
1320 
1321  /*
1322  * Cause all remaining pages in the segment to be flushed, leaving the
1323  * XLog position where it should be, at the start of the next segment.
1324  * We do this one page at a time, to make sure we don't deadlock
1325  * against ourselves if wal_buffers < wal_segment_size.
1326  */
1327  while (CurrPos < EndPos)
1328  {
1329  /*
1330  * The minimal action to flush the page would be to call
1331  * WALInsertLockUpdateInsertingAt(CurrPos) followed by
1332  * AdvanceXLInsertBuffer(...). The page would be left initialized
1333  * mostly to zeros, except for the page header (always the short
1334  * variant, as this is never a segment's first page).
1335  *
1336  * The large vistas of zeros are good for compressibility, but the
1337  * headers interrupting them every XLOG_BLCKSZ (with values that
1338  * differ from page to page) are not. The effect varies with
1339  * compression tool, but bzip2 for instance compresses about an
1340  * order of magnitude worse if those headers are left in place.
1341  *
1342  * Rather than complicating AdvanceXLInsertBuffer itself (which is
1343  * called in heavily-loaded circumstances as well as this lightly-
1344  * loaded one) with variant behavior, we just use GetXLogBuffer
1345  * (which itself calls the two methods we need) to get the pointer
1346  * and zero most of the page. Then we just zero the page header.
1347  */
1348  currpos = GetXLogBuffer(CurrPos, tli);
1349  MemSet(currpos, 0, SizeOfXLogShortPHD);
1350 
1351  CurrPos += XLOG_BLCKSZ;
1352  }
1353  }
1354  else
1355  {
1356  /* Align the end position, so that the next record starts aligned */
1357  CurrPos = MAXALIGN64(CurrPos);
1358  }
1359 
1360  if (CurrPos != EndPos)
1361  ereport(PANIC,
1363  errmsg_internal("space reserved for WAL record does not match what was written"));
1364 }
1365 
1366 /*
1367  * Acquire a WAL insertion lock, for inserting to WAL.
1368  */
1369 static void
1371 {
1372  bool immed;
1373 
1374  /*
1375  * It doesn't matter which of the WAL insertion locks we acquire, so try
1376  * the one we used last time. If the system isn't particularly busy, it's
1377  * a good bet that it's still available, and it's good to have some
1378  * affinity to a particular lock so that you don't unnecessarily bounce
1379  * cache lines between processes when there's no contention.
1380  *
1381  * If this is the first time through in this backend, pick a lock
1382  * (semi-)randomly. This allows the locks to be used evenly if you have a
1383  * lot of very short connections.
1384  */
1385  static int lockToTry = -1;
1386 
1387  if (lockToTry == -1)
1388  lockToTry = MyProcNumber % NUM_XLOGINSERT_LOCKS;
1389  MyLockNo = lockToTry;
1390 
1391  /*
1392  * The insertingAt value is initially set to 0, as we don't know our
1393  * insert location yet.
1394  */
1396  if (!immed)
1397  {
1398  /*
1399  * If we couldn't get the lock immediately, try another lock next
1400  * time. On a system with more insertion locks than concurrent
1401  * inserters, this causes all the inserters to eventually migrate to a
1402  * lock that no-one else is using. On a system with more inserters
1403  * than locks, it still helps to distribute the inserters evenly
1404  * across the locks.
1405  */
1406  lockToTry = (lockToTry + 1) % NUM_XLOGINSERT_LOCKS;
1407  }
1408 }
1409 
1410 /*
1411  * Acquire all WAL insertion locks, to prevent other backends from inserting
1412  * to WAL.
1413  */
1414 static void
1416 {
1417  int i;
1418 
1419  /*
1420  * When holding all the locks, all but the last lock's insertingAt
1421  * indicator is set to 0xFFFFFFFFFFFFFFFF, which is higher than any real
1422  * XLogRecPtr value, to make sure that no-one blocks waiting on those.
1423  */
1424  for (i = 0; i < NUM_XLOGINSERT_LOCKS - 1; i++)
1425  {
1427  LWLockUpdateVar(&WALInsertLocks[i].l.lock,
1429  PG_UINT64_MAX);
1430  }
1431  /* Variable value reset to 0 at release */
1433 
1434  holdingAllLocks = true;
1435 }
1436 
1437 /*
1438  * Release our insertion lock (or locks, if we're holding them all).
1439  *
1440  * NB: Reset all variables to 0, so they cause LWLockWaitForVar to block the
1441  * next time the lock is acquired.
1442  */
1443 static void
1445 {
1446  if (holdingAllLocks)
1447  {
1448  int i;
1449 
1450  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1453  0);
1454 
1455  holdingAllLocks = false;
1456  }
1457  else
1458  {
1461  0);
1462  }
1463 }
1464 
1465 /*
1466  * Update our insertingAt value, to let others know that we've finished
1467  * inserting up to that point.
1468  */
1469 static void
1471 {
1472  if (holdingAllLocks)
1473  {
1474  /*
1475  * We use the last lock to mark our actual position, see comments in
1476  * WALInsertLockAcquireExclusive.
1477  */
1480  insertingAt);
1481  }
1482  else
1485  insertingAt);
1486 }
1487 
1488 /*
1489  * Wait for any WAL insertions < upto to finish.
1490  *
1491  * Returns the location of the oldest insertion that is still in-progress.
1492  * Any WAL prior to that point has been fully copied into WAL buffers, and
1493  * can be flushed out to disk. Because this waits for any insertions older
1494  * than 'upto' to finish, the return value is always >= 'upto'.
1495  *
1496  * Note: When you are about to write out WAL, you must call this function
1497  * *before* acquiring WALWriteLock, to avoid deadlocks. This function might
1498  * need to wait for an insertion to finish (or at least advance to next
1499  * uninitialized page), and the inserter might need to evict an old WAL buffer
1500  * to make room for a new one, which in turn requires WALWriteLock.
1501  */
1502 static XLogRecPtr
1504 {
1505  uint64 bytepos;
1506  XLogRecPtr inserted;
1507  XLogRecPtr reservedUpto;
1508  XLogRecPtr finishedUpto;
1510  int i;
1511 
1512  if (MyProc == NULL)
1513  elog(PANIC, "cannot wait without a PGPROC structure");
1514 
1515  /*
1516  * Check if there's any work to do. Use a barrier to ensure we get the
1517  * freshest value.
1518  */
1520  if (upto <= inserted)
1521  return inserted;
1522 
1523  /* Read the current insert position */
1524  SpinLockAcquire(&Insert->insertpos_lck);
1525  bytepos = Insert->CurrBytePos;
1526  SpinLockRelease(&Insert->insertpos_lck);
1527  reservedUpto = XLogBytePosToEndRecPtr(bytepos);
1528 
1529  /*
1530  * No-one should request to flush a piece of WAL that hasn't even been
1531  * reserved yet. However, it can happen if there is a block with a bogus
1532  * LSN on disk, for example. XLogFlush checks for that situation and
1533  * complains, but only after the flush. Here we just assume that to mean
1534  * that all WAL that has been reserved needs to be finished. In this
1535  * corner-case, the return value can be smaller than 'upto' argument.
1536  */
1537  if (upto > reservedUpto)
1538  {
1539  ereport(LOG,
1540  (errmsg("request to flush past end of generated WAL; request %X/%X, current position %X/%X",
1541  LSN_FORMAT_ARGS(upto), LSN_FORMAT_ARGS(reservedUpto))));
1542  upto = reservedUpto;
1543  }
1544 
1545  /*
1546  * Loop through all the locks, sleeping on any in-progress insert older
1547  * than 'upto'.
1548  *
1549  * finishedUpto is our return value, indicating the point upto which all
1550  * the WAL insertions have been finished. Initialize it to the head of
1551  * reserved WAL, and as we iterate through the insertion locks, back it
1552  * out for any insertion that's still in progress.
1553  */
1554  finishedUpto = reservedUpto;
1555  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1556  {
1557  XLogRecPtr insertingat = InvalidXLogRecPtr;
1558 
1559  do
1560  {
1561  /*
1562  * See if this insertion is in progress. LWLockWaitForVar will
1563  * wait for the lock to be released, or for the 'value' to be set
1564  * by a LWLockUpdateVar call. When a lock is initially acquired,
1565  * its value is 0 (InvalidXLogRecPtr), which means that we don't
1566  * know where it's inserting yet. We will have to wait for it. If
1567  * it's a small insertion, the record will most likely fit on the
1568  * same page and the inserter will release the lock without ever
1569  * calling LWLockUpdateVar. But if it has to sleep, it will
1570  * advertise the insertion point with LWLockUpdateVar before
1571  * sleeping.
1572  *
1573  * In this loop we are only waiting for insertions that started
1574  * before WaitXLogInsertionsToFinish was called. The lack of
1575  * memory barriers in the loop means that we might see locks as
1576  * "unused" that have since become used. This is fine because
1577  * they only can be used for later insertions that we would not
1578  * want to wait on anyway. Not taking a lock to acquire the
1579  * current insertingAt value means that we might see older
1580  * insertingAt values. This is also fine, because if we read a
1581  * value too old, we will add ourselves to the wait queue, which
1582  * contains atomic operations.
1583  */
1584  if (LWLockWaitForVar(&WALInsertLocks[i].l.lock,
1586  insertingat, &insertingat))
1587  {
1588  /* the lock was free, so no insertion in progress */
1589  insertingat = InvalidXLogRecPtr;
1590  break;
1591  }
1592 
1593  /*
1594  * This insertion is still in progress. Have to wait, unless the
1595  * inserter has proceeded past 'upto'.
1596  */
1597  } while (insertingat < upto);
1598 
1599  if (insertingat != InvalidXLogRecPtr && insertingat < finishedUpto)
1600  finishedUpto = insertingat;
1601  }
1602 
1603  /*
1604  * Advance the limit we know to have been inserted and return the freshest
1605  * value we know of, which might be beyond what we requested if somebody
1606  * is concurrently doing this with an 'upto' pointer ahead of us.
1607  */
1609  finishedUpto);
1610 
1611  return finishedUpto;
1612 }
1613 
1614 /*
1615  * Get a pointer to the right location in the WAL buffer containing the
1616  * given XLogRecPtr.
1617  *
1618  * If the page is not initialized yet, it is initialized. That might require
1619  * evicting an old dirty buffer from the buffer cache, which means I/O.
1620  *
1621  * The caller must ensure that the page containing the requested location
1622  * isn't evicted yet, and won't be evicted. The way to ensure that is to
1623  * hold onto a WAL insertion lock with the insertingAt position set to
1624  * something <= ptr. GetXLogBuffer() will update insertingAt if it needs
1625  * to evict an old page from the buffer. (This means that once you call
1626  * GetXLogBuffer() with a given 'ptr', you must not access anything before
1627  * that point anymore, and must not call GetXLogBuffer() with an older 'ptr'
1628  * later, because older buffers might be recycled already)
1629  */
1630 static char *
1632 {
1633  int idx;
1634  XLogRecPtr endptr;
1635  static uint64 cachedPage = 0;
1636  static char *cachedPos = NULL;
1637  XLogRecPtr expectedEndPtr;
1638 
1639  /*
1640  * Fast path for the common case that we need to access again the same
1641  * page as last time.
1642  */
1643  if (ptr / XLOG_BLCKSZ == cachedPage)
1644  {
1645  Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1646  Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1647  return cachedPos + ptr % XLOG_BLCKSZ;
1648  }
1649 
1650  /*
1651  * The XLog buffer cache is organized so that a page is always loaded to a
1652  * particular buffer. That way we can easily calculate the buffer a given
1653  * page must be loaded into, from the XLogRecPtr alone.
1654  */
1655  idx = XLogRecPtrToBufIdx(ptr);
1656 
1657  /*
1658  * See what page is loaded in the buffer at the moment. It could be the
1659  * page we're looking for, or something older. It can't be anything newer
1660  * - that would imply the page we're looking for has already been written
1661  * out to disk and evicted, and the caller is responsible for making sure
1662  * that doesn't happen.
1663  *
1664  * We don't hold a lock while we read the value. If someone is just about
1665  * to initialize or has just initialized the page, it's possible that we
1666  * get InvalidXLogRecPtr. That's ok, we'll grab the mapping lock (in
1667  * AdvanceXLInsertBuffer) and retry if we see anything other than the page
1668  * we're looking for.
1669  */
1670  expectedEndPtr = ptr;
1671  expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
1672 
1673  endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1674  if (expectedEndPtr != endptr)
1675  {
1676  XLogRecPtr initializedUpto;
1677 
1678  /*
1679  * Before calling AdvanceXLInsertBuffer(), which can block, let others
1680  * know how far we're finished with inserting the record.
1681  *
1682  * NB: If 'ptr' points to just after the page header, advertise a
1683  * position at the beginning of the page rather than 'ptr' itself. If
1684  * there are no other insertions running, someone might try to flush
1685  * up to our advertised location. If we advertised a position after
1686  * the page header, someone might try to flush the page header, even
1687  * though page might actually not be initialized yet. As the first
1688  * inserter on the page, we are effectively responsible for making
1689  * sure that it's initialized, before we let insertingAt to move past
1690  * the page header.
1691  */
1692  if (ptr % XLOG_BLCKSZ == SizeOfXLogShortPHD &&
1693  XLogSegmentOffset(ptr, wal_segment_size) > XLOG_BLCKSZ)
1694  initializedUpto = ptr - SizeOfXLogShortPHD;
1695  else if (ptr % XLOG_BLCKSZ == SizeOfXLogLongPHD &&
1696  XLogSegmentOffset(ptr, wal_segment_size) < XLOG_BLCKSZ)
1697  initializedUpto = ptr - SizeOfXLogLongPHD;
1698  else
1699  initializedUpto = ptr;
1700 
1701  WALInsertLockUpdateInsertingAt(initializedUpto);
1702 
1703  AdvanceXLInsertBuffer(ptr, tli, false);
1704  endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1705 
1706  if (expectedEndPtr != endptr)
1707  elog(PANIC, "could not find WAL buffer for %X/%X",
1708  LSN_FORMAT_ARGS(ptr));
1709  }
1710  else
1711  {
1712  /*
1713  * Make sure the initialization of the page is visible to us, and
1714  * won't arrive later to overwrite the WAL data we write on the page.
1715  */
1717  }
1718 
1719  /*
1720  * Found the buffer holding this page. Return a pointer to the right
1721  * offset within the page.
1722  */
1723  cachedPage = ptr / XLOG_BLCKSZ;
1724  cachedPos = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
1725 
1726  Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1727  Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1728 
1729  return cachedPos + ptr % XLOG_BLCKSZ;
1730 }
1731 
1732 /*
1733  * Read WAL data directly from WAL buffers, if available. Returns the number
1734  * of bytes read successfully.
1735  *
1736  * Fewer than 'count' bytes may be read if some of the requested WAL data has
1737  * already been evicted.
1738  *
1739  * No locks are taken.
1740  *
1741  * Caller should ensure that it reads no further than LogwrtResult.Write
1742  * (which should have been updated by the caller when determining how far to
1743  * read). The 'tli' argument is only used as a convenient safety check so that
1744  * callers do not read from WAL buffers on a historical timeline.
1745  */
1746 Size
1747 WALReadFromBuffers(char *dstbuf, XLogRecPtr startptr, Size count,
1748  TimeLineID tli)
1749 {
1750  char *pdst = dstbuf;
1751  XLogRecPtr recptr = startptr;
1752  XLogRecPtr inserted;
1753  Size nbytes = count;
1754 
1755  if (RecoveryInProgress() || tli != GetWALInsertionTimeLine())
1756  return 0;
1757 
1758  Assert(!XLogRecPtrIsInvalid(startptr));
1759 
1760  /*
1761  * Caller should ensure that the requested data has been inserted into WAL
1762  * buffers before we try to read it.
1763  */
1765  if (startptr + count > inserted)
1766  ereport(ERROR,
1767  errmsg("cannot read past end of generated WAL: requested %X/%X, current position %X/%X",
1768  LSN_FORMAT_ARGS(startptr + count),
1769  LSN_FORMAT_ARGS(inserted)));
1770 
1771  /*
1772  * Loop through the buffers without a lock. For each buffer, atomically
1773  * read and verify the end pointer, then copy the data out, and finally
1774  * re-read and re-verify the end pointer.
1775  *
1776  * Once a page is evicted, it never returns to the WAL buffers, so if the
1777  * end pointer matches the expected end pointer before and after we copy
1778  * the data, then the right page must have been present during the data
1779  * copy. Read barriers are necessary to ensure that the data copy actually
1780  * happens between the two verification steps.
1781  *
1782  * If either verification fails, we simply terminate the loop and return
1783  * with the data that had been already copied out successfully.
1784  */
1785  while (nbytes > 0)
1786  {
1787  uint32 offset = recptr % XLOG_BLCKSZ;
1788  int idx = XLogRecPtrToBufIdx(recptr);
1789  XLogRecPtr expectedEndPtr;
1790  XLogRecPtr endptr;
1791  const char *page;
1792  const char *psrc;
1793  Size npagebytes;
1794 
1795  /*
1796  * Calculate the end pointer we expect in the xlblocks array if the
1797  * correct page is present.
1798  */
1799  expectedEndPtr = recptr + (XLOG_BLCKSZ - offset);
1800 
1801  /*
1802  * First verification step: check that the correct page is present in
1803  * the WAL buffers.
1804  */
1805  endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1806  if (expectedEndPtr != endptr)
1807  break;
1808 
1809  /*
1810  * The correct page is present (or was at the time the endptr was
1811  * read; must re-verify later). Calculate pointer to source data and
1812  * determine how much data to read from this page.
1813  */
1814  page = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
1815  psrc = page + offset;
1816  npagebytes = Min(nbytes, XLOG_BLCKSZ - offset);
1817 
1818  /*
1819  * Ensure that the data copy and the first verification step are not
1820  * reordered.
1821  */
1822  pg_read_barrier();
1823 
1824  /* data copy */
1825  memcpy(pdst, psrc, npagebytes);
1826 
1827  /*
1828  * Ensure that the data copy and the second verification step are not
1829  * reordered.
1830  */
1831  pg_read_barrier();
1832 
1833  /*
1834  * Second verification step: check that the page we read from wasn't
1835  * evicted while we were copying the data.
1836  */
1837  endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1838  if (expectedEndPtr != endptr)
1839  break;
1840 
1841  pdst += npagebytes;
1842  recptr += npagebytes;
1843  nbytes -= npagebytes;
1844  }
1845 
1846  Assert(pdst - dstbuf <= count);
1847 
1848  return pdst - dstbuf;
1849 }
1850 
1851 /*
1852  * Converts a "usable byte position" to XLogRecPtr. A usable byte position
1853  * is the position starting from the beginning of WAL, excluding all WAL
1854  * page headers.
1855  */
1856 static XLogRecPtr
1857 XLogBytePosToRecPtr(uint64 bytepos)
1858 {
1859  uint64 fullsegs;
1860  uint64 fullpages;
1861  uint64 bytesleft;
1862  uint32 seg_offset;
1863  XLogRecPtr result;
1864 
1865  fullsegs = bytepos / UsableBytesInSegment;
1866  bytesleft = bytepos % UsableBytesInSegment;
1867 
1868  if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
1869  {
1870  /* fits on first page of segment */
1871  seg_offset = bytesleft + SizeOfXLogLongPHD;
1872  }
1873  else
1874  {
1875  /* account for the first page on segment with long header */
1876  seg_offset = XLOG_BLCKSZ;
1877  bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
1878 
1879  fullpages = bytesleft / UsableBytesInPage;
1880  bytesleft = bytesleft % UsableBytesInPage;
1881 
1882  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
1883  }
1884 
1885  XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
1886 
1887  return result;
1888 }
1889 
1890 /*
1891  * Like XLogBytePosToRecPtr, but if the position is at a page boundary,
1892  * returns a pointer to the beginning of the page (ie. before page header),
1893  * not to where the first xlog record on that page would go to. This is used
1894  * when converting a pointer to the end of a record.
1895  */
1896 static XLogRecPtr
1897 XLogBytePosToEndRecPtr(uint64 bytepos)
1898 {
1899  uint64 fullsegs;
1900  uint64 fullpages;
1901  uint64 bytesleft;
1902  uint32 seg_offset;
1903  XLogRecPtr result;
1904 
1905  fullsegs = bytepos / UsableBytesInSegment;
1906  bytesleft = bytepos % UsableBytesInSegment;
1907 
1908  if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
1909  {
1910  /* fits on first page of segment */
1911  if (bytesleft == 0)
1912  seg_offset = 0;
1913  else
1914  seg_offset = bytesleft + SizeOfXLogLongPHD;
1915  }
1916  else
1917  {
1918  /* account for the first page on segment with long header */
1919  seg_offset = XLOG_BLCKSZ;
1920  bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
1921 
1922  fullpages = bytesleft / UsableBytesInPage;
1923  bytesleft = bytesleft % UsableBytesInPage;
1924 
1925  if (bytesleft == 0)
1926  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
1927  else
1928  seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
1929  }
1930 
1931  XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
1932 
1933  return result;
1934 }
1935 
1936 /*
1937  * Convert an XLogRecPtr to a "usable byte position".
1938  */
1939 static uint64
1941 {
1942  uint64 fullsegs;
1943  uint32 fullpages;
1944  uint32 offset;
1945  uint64 result;
1946 
1947  XLByteToSeg(ptr, fullsegs, wal_segment_size);
1948 
1949  fullpages = (XLogSegmentOffset(ptr, wal_segment_size)) / XLOG_BLCKSZ;
1950  offset = ptr % XLOG_BLCKSZ;
1951 
1952  if (fullpages == 0)
1953  {
1954  result = fullsegs * UsableBytesInSegment;
1955  if (offset > 0)
1956  {
1957  Assert(offset >= SizeOfXLogLongPHD);
1958  result += offset - SizeOfXLogLongPHD;
1959  }
1960  }
1961  else
1962  {
1963  result = fullsegs * UsableBytesInSegment +
1964  (XLOG_BLCKSZ - SizeOfXLogLongPHD) + /* account for first page */
1965  (fullpages - 1) * UsableBytesInPage; /* full pages */
1966  if (offset > 0)
1967  {
1968  Assert(offset >= SizeOfXLogShortPHD);
1969  result += offset - SizeOfXLogShortPHD;
1970  }
1971  }
1972 
1973  return result;
1974 }
1975 
1976 /*
1977  * Initialize XLOG buffers, writing out old buffers if they still contain
1978  * unwritten data, upto the page containing 'upto'. Or if 'opportunistic' is
1979  * true, initialize as many pages as we can without having to write out
1980  * unwritten data. Any new pages are initialized to zeros, with pages headers
1981  * initialized properly.
1982  */
1983 static void
1984 AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli, bool opportunistic)
1985 {
1987  int nextidx;
1988  XLogRecPtr OldPageRqstPtr;
1989  XLogwrtRqst WriteRqst;
1990  XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
1991  XLogRecPtr NewPageBeginPtr;
1992  XLogPageHeader NewPage;
1993  int npages pg_attribute_unused() = 0;
1994 
1995  LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
1996 
1997  /*
1998  * Now that we have the lock, check if someone initialized the page
1999  * already.
2000  */
2001  while (upto >= XLogCtl->InitializedUpTo || opportunistic)
2002  {
2004 
2005  /*
2006  * Get ending-offset of the buffer page we need to replace (this may
2007  * be zero if the buffer hasn't been used yet). Fall through if it's
2008  * already written out.
2009  */
2010  OldPageRqstPtr = pg_atomic_read_u64(&XLogCtl->xlblocks[nextidx]);
2011  if (LogwrtResult.Write < OldPageRqstPtr)
2012  {
2013  /*
2014  * Nope, got work to do. If we just want to pre-initialize as much
2015  * as we can without flushing, give up now.
2016  */
2017  if (opportunistic)
2018  break;
2019 
2020  /* Advance shared memory write request position */
2022  if (XLogCtl->LogwrtRqst.Write < OldPageRqstPtr)
2023  XLogCtl->LogwrtRqst.Write = OldPageRqstPtr;
2025 
2026  /*
2027  * Acquire an up-to-date LogwrtResult value and see if we still
2028  * need to write it or if someone else already did.
2029  */
2031  if (LogwrtResult.Write < OldPageRqstPtr)
2032  {
2033  /*
2034  * Must acquire write lock. Release WALBufMappingLock first,
2035  * to make sure that all insertions that we need to wait for
2036  * can finish (up to this same position). Otherwise we risk
2037  * deadlock.
2038  */
2039  LWLockRelease(WALBufMappingLock);
2040 
2041  WaitXLogInsertionsToFinish(OldPageRqstPtr);
2042 
2043  LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2044 
2046  if (LogwrtResult.Write >= OldPageRqstPtr)
2047  {
2048  /* OK, someone wrote it already */
2049  LWLockRelease(WALWriteLock);
2050  }
2051  else
2052  {
2053  /* Have to write it ourselves */
2054  TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2055  WriteRqst.Write = OldPageRqstPtr;
2056  WriteRqst.Flush = 0;
2057  XLogWrite(WriteRqst, tli, false);
2058  LWLockRelease(WALWriteLock);
2060  TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
2061  }
2062  /* Re-acquire WALBufMappingLock and retry */
2063  LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2064  continue;
2065  }
2066  }
2067 
2068  /*
2069  * Now the next buffer slot is free and we can set it up to be the
2070  * next output page.
2071  */
2072  NewPageBeginPtr = XLogCtl->InitializedUpTo;
2073  NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2074 
2075  Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
2076 
2077  NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
2078 
2079  /*
2080  * Mark the xlblock with InvalidXLogRecPtr and issue a write barrier
2081  * before initializing. Otherwise, the old page may be partially
2082  * zeroed but look valid.
2083  */
2085  pg_write_barrier();
2086 
2087  /*
2088  * Be sure to re-zero the buffer so that bytes beyond what we've
2089  * written will look like zeroes and not valid XLOG records...
2090  */
2091  MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
2092 
2093  /*
2094  * Fill the new page's header
2095  */
2096  NewPage->xlp_magic = XLOG_PAGE_MAGIC;
2097 
2098  /* NewPage->xlp_info = 0; */ /* done by memset */
2099  NewPage->xlp_tli = tli;
2100  NewPage->xlp_pageaddr = NewPageBeginPtr;
2101 
2102  /* NewPage->xlp_rem_len = 0; */ /* done by memset */
2103 
2104  /*
2105  * If online backup is not in progress, mark the header to indicate
2106  * that WAL records beginning in this page have removable backup
2107  * blocks. This allows the WAL archiver to know whether it is safe to
2108  * compress archived WAL data by transforming full-block records into
2109  * the non-full-block format. It is sufficient to record this at the
2110  * page level because we force a page switch (in fact a segment
2111  * switch) when starting a backup, so the flag will be off before any
2112  * records can be written during the backup. At the end of a backup,
2113  * the last page will be marked as all unsafe when perhaps only part
2114  * is unsafe, but at worst the archiver would miss the opportunity to
2115  * compress a few records.
2116  */
2117  if (Insert->runningBackups == 0)
2118  NewPage->xlp_info |= XLP_BKP_REMOVABLE;
2119 
2120  /*
2121  * If first page of an XLOG segment file, make it a long header.
2122  */
2123  if ((XLogSegmentOffset(NewPage->xlp_pageaddr, wal_segment_size)) == 0)
2124  {
2125  XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
2126 
2127  NewLongPage->xlp_sysid = ControlFile->system_identifier;
2128  NewLongPage->xlp_seg_size = wal_segment_size;
2129  NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
2130  NewPage->xlp_info |= XLP_LONG_HEADER;
2131  }
2132 
2133  /*
2134  * Make sure the initialization of the page becomes visible to others
2135  * before the xlblocks update. GetXLogBuffer() reads xlblocks without
2136  * holding a lock.
2137  */
2138  pg_write_barrier();
2139 
2140  pg_atomic_write_u64(&XLogCtl->xlblocks[nextidx], NewPageEndPtr);
2141  XLogCtl->InitializedUpTo = NewPageEndPtr;
2142 
2143  npages++;
2144  }
2145  LWLockRelease(WALBufMappingLock);
2146 
2147 #ifdef WAL_DEBUG
2148  if (XLOG_DEBUG && npages > 0)
2149  {
2150  elog(DEBUG1, "initialized %d pages, up to %X/%X",
2151  npages, LSN_FORMAT_ARGS(NewPageEndPtr));
2152  }
2153 #endif
2154 }
2155 
2156 /*
2157  * Calculate CheckPointSegments based on max_wal_size_mb and
2158  * checkpoint_completion_target.
2159  */
2160 static void
2162 {
2163  double target;
2164 
2165  /*-------
2166  * Calculate the distance at which to trigger a checkpoint, to avoid
2167  * exceeding max_wal_size_mb. This is based on two assumptions:
2168  *
2169  * a) we keep WAL for only one checkpoint cycle (prior to PG11 we kept
2170  * WAL for two checkpoint cycles to allow us to recover from the
2171  * secondary checkpoint if the first checkpoint failed, though we
2172  * only did this on the primary anyway, not on standby. Keeping just
2173  * one checkpoint simplifies processing and reduces disk space in
2174  * many smaller databases.)
2175  * b) during checkpoint, we consume checkpoint_completion_target *
2176  * number of segments consumed between checkpoints.
2177  *-------
2178  */
2179  target = (double) ConvertToXSegs(max_wal_size_mb, wal_segment_size) /
2181 
2182  /* round down */
2183  CheckPointSegments = (int) target;
2184 
2185  if (CheckPointSegments < 1)
2186  CheckPointSegments = 1;
2187 }
2188 
2189 void
2190 assign_max_wal_size(int newval, void *extra)
2191 {
2194 }
2195 
2196 void
2198 {
2201 }
2202 
2203 bool
2205 {
2206  if (!IsValidWalSegSize(*newval))
2207  {
2208  GUC_check_errdetail("The WAL segment size must be a power of two between 1 MB and 1 GB.");
2209  return false;
2210  }
2211 
2212  return true;
2213 }
2214 
2215 /*
2216  * GUC check_hook for max_slot_wal_keep_size
2217  *
2218  * We don't allow the value of max_slot_wal_keep_size other than -1 during the
2219  * binary upgrade. See start_postmaster() in pg_upgrade for more details.
2220  */
2221 bool
2223 {
2224  if (IsBinaryUpgrade && *newval != -1)
2225  {
2226  GUC_check_errdetail("\"%s\" must be set to -1 during binary upgrade mode.",
2227  "max_slot_wal_keep_size");
2228  return false;
2229  }
2230 
2231  return true;
2232 }
2233 
2234 /*
2235  * At a checkpoint, how many WAL segments to recycle as preallocated future
2236  * XLOG segments? Returns the highest segment that should be preallocated.
2237  */
2238 static XLogSegNo
2240 {
2241  XLogSegNo minSegNo;
2242  XLogSegNo maxSegNo;
2243  double distance;
2244  XLogSegNo recycleSegNo;
2245 
2246  /*
2247  * Calculate the segment numbers that min_wal_size_mb and max_wal_size_mb
2248  * correspond to. Always recycle enough segments to meet the minimum, and
2249  * remove enough segments to stay below the maximum.
2250  */
2251  minSegNo = lastredoptr / wal_segment_size +
2253  maxSegNo = lastredoptr / wal_segment_size +
2255 
2256  /*
2257  * Between those limits, recycle enough segments to get us through to the
2258  * estimated end of next checkpoint.
2259  *
2260  * To estimate where the next checkpoint will finish, assume that the
2261  * system runs steadily consuming CheckPointDistanceEstimate bytes between
2262  * every checkpoint.
2263  */
2265  /* add 10% for good measure. */
2266  distance *= 1.10;
2267 
2268  recycleSegNo = (XLogSegNo) ceil(((double) lastredoptr + distance) /
2270 
2271  if (recycleSegNo < minSegNo)
2272  recycleSegNo = minSegNo;
2273  if (recycleSegNo > maxSegNo)
2274  recycleSegNo = maxSegNo;
2275 
2276  return recycleSegNo;
2277 }
2278 
2279 /*
2280  * Check whether we've consumed enough xlog space that a checkpoint is needed.
2281  *
2282  * new_segno indicates a log file that has just been filled up (or read
2283  * during recovery). We measure the distance from RedoRecPtr to new_segno
2284  * and see if that exceeds CheckPointSegments.
2285  *
2286  * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
2287  */
2288 bool
2290 {
2291  XLogSegNo old_segno;
2292 
2294 
2295  if (new_segno >= old_segno + (uint64) (CheckPointSegments - 1))
2296  return true;
2297  return false;
2298 }
2299 
2300 /*
2301  * Write and/or fsync the log at least as far as WriteRqst indicates.
2302  *
2303  * If flexible == true, we don't have to write as far as WriteRqst, but
2304  * may stop at any convenient boundary (such as a cache or logfile boundary).
2305  * This option allows us to avoid uselessly issuing multiple writes when a
2306  * single one would do.
2307  *
2308  * Must be called with WALWriteLock held. WaitXLogInsertionsToFinish(WriteRqst)
2309  * must be called before grabbing the lock, to make sure the data is ready to
2310  * write.
2311  */
2312 static void
2313 XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible)
2314 {
2315  bool ispartialpage;
2316  bool last_iteration;
2317  bool finishing_seg;
2318  int curridx;
2319  int npages;
2320  int startidx;
2321  uint32 startoffset;
2322 
2323  /* We should always be inside a critical section here */
2324  Assert(CritSectionCount > 0);
2325 
2326  /*
2327  * Update local LogwrtResult (caller probably did this already, but...)
2328  */
2330 
2331  /*
2332  * Since successive pages in the xlog cache are consecutively allocated,
2333  * we can usually gather multiple pages together and issue just one
2334  * write() call. npages is the number of pages we have determined can be
2335  * written together; startidx is the cache block index of the first one,
2336  * and startoffset is the file offset at which it should go. The latter
2337  * two variables are only valid when npages > 0, but we must initialize
2338  * all of them to keep the compiler quiet.
2339  */
2340  npages = 0;
2341  startidx = 0;
2342  startoffset = 0;
2343 
2344  /*
2345  * Within the loop, curridx is the cache block index of the page to
2346  * consider writing. Begin at the buffer containing the next unwritten
2347  * page, or last partially written page.
2348  */
2350 
2351  while (LogwrtResult.Write < WriteRqst.Write)
2352  {
2353  /*
2354  * Make sure we're not ahead of the insert process. This could happen
2355  * if we're passed a bogus WriteRqst.Write that is past the end of the
2356  * last page that's been initialized by AdvanceXLInsertBuffer.
2357  */
2358  XLogRecPtr EndPtr = pg_atomic_read_u64(&XLogCtl->xlblocks[curridx]);
2359 
2360  if (LogwrtResult.Write >= EndPtr)
2361  elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
2363  LSN_FORMAT_ARGS(EndPtr));
2364 
2365  /* Advance LogwrtResult.Write to end of current buffer page */
2366  LogwrtResult.Write = EndPtr;
2367  ispartialpage = WriteRqst.Write < LogwrtResult.Write;
2368 
2371  {
2372  /*
2373  * Switch to new logfile segment. We cannot have any pending
2374  * pages here (since we dump what we have at segment end).
2375  */
2376  Assert(npages == 0);
2377  if (openLogFile >= 0)
2378  XLogFileClose();
2381  openLogTLI = tli;
2382 
2383  /* create/use new log file */
2386  }
2387 
2388  /* Make sure we have the current logfile open */
2389  if (openLogFile < 0)
2390  {
2393  openLogTLI = tli;
2396  }
2397 
2398  /* Add current page to the set of pending pages-to-dump */
2399  if (npages == 0)
2400  {
2401  /* first of group */
2402  startidx = curridx;
2403  startoffset = XLogSegmentOffset(LogwrtResult.Write - XLOG_BLCKSZ,
2405  }
2406  npages++;
2407 
2408  /*
2409  * Dump the set if this will be the last loop iteration, or if we are
2410  * at the last page of the cache area (since the next page won't be
2411  * contiguous in memory), or if we are at the end of the logfile
2412  * segment.
2413  */
2414  last_iteration = WriteRqst.Write <= LogwrtResult.Write;
2415 
2416  finishing_seg = !ispartialpage &&
2417  (startoffset + npages * XLOG_BLCKSZ) >= wal_segment_size;
2418 
2419  if (last_iteration ||
2420  curridx == XLogCtl->XLogCacheBlck ||
2421  finishing_seg)
2422  {
2423  char *from;
2424  Size nbytes;
2425  Size nleft;
2426  ssize_t written;
2427  instr_time start;
2428 
2429  /* OK to write the page(s) */
2430  from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
2431  nbytes = npages * (Size) XLOG_BLCKSZ;
2432  nleft = nbytes;
2433  do
2434  {
2435  errno = 0;
2436 
2437  /* Measure I/O timing to write WAL data */
2438  if (track_wal_io_timing)
2440  else
2442 
2443  pgstat_report_wait_start(WAIT_EVENT_WAL_WRITE);
2444  written = pg_pwrite(openLogFile, from, nleft, startoffset);
2446 
2447  /*
2448  * Increment the I/O timing and the number of times WAL data
2449  * were written out to disk.
2450  */
2451  if (track_wal_io_timing)
2452  {
2453  instr_time end;
2454 
2457  }
2458 
2460 
2461  if (written <= 0)
2462  {
2463  char xlogfname[MAXFNAMELEN];
2464  int save_errno;
2465 
2466  if (errno == EINTR)
2467  continue;
2468 
2469  save_errno = errno;
2470  XLogFileName(xlogfname, tli, openLogSegNo,
2472  errno = save_errno;
2473  ereport(PANIC,
2475  errmsg("could not write to log file \"%s\" at offset %u, length %zu: %m",
2476  xlogfname, startoffset, nleft)));
2477  }
2478  nleft -= written;
2479  from += written;
2480  startoffset += written;
2481  } while (nleft > 0);
2482 
2483  npages = 0;
2484 
2485  /*
2486  * If we just wrote the whole last page of a logfile segment,
2487  * fsync the segment immediately. This avoids having to go back
2488  * and re-open prior segments when an fsync request comes along
2489  * later. Doing it here ensures that one and only one backend will
2490  * perform this fsync.
2491  *
2492  * This is also the right place to notify the Archiver that the
2493  * segment is ready to copy to archival storage, and to update the
2494  * timer for archive_timeout, and to signal for a checkpoint if
2495  * too many logfile segments have been used since the last
2496  * checkpoint.
2497  */
2498  if (finishing_seg)
2499  {
2501 
2502  /* signal that we need to wakeup walsenders later */
2504 
2505  LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
2506 
2507  if (XLogArchivingActive())
2509 
2510  XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
2512 
2513  /*
2514  * Request a checkpoint if we've consumed too much xlog since
2515  * the last one. For speed, we first check using the local
2516  * copy of RedoRecPtr, which might be out of date; if it looks
2517  * like a checkpoint is needed, forcibly update RedoRecPtr and
2518  * recheck.
2519  */
2521  {
2522  (void) GetRedoRecPtr();
2525  }
2526  }
2527  }
2528 
2529  if (ispartialpage)
2530  {
2531  /* Only asked to write a partial page */
2532  LogwrtResult.Write = WriteRqst.Write;
2533  break;
2534  }
2535  curridx = NextBufIdx(curridx);
2536 
2537  /* If flexible, break out of loop as soon as we wrote something */
2538  if (flexible && npages == 0)
2539  break;
2540  }
2541 
2542  Assert(npages == 0);
2543 
2544  /*
2545  * If asked to flush, do so
2546  */
2547  if (LogwrtResult.Flush < WriteRqst.Flush &&
2549  {
2550  /*
2551  * Could get here without iterating above loop, in which case we might
2552  * have no open file or the wrong one. However, we do not need to
2553  * fsync more than one file.
2554  */
2557  {
2558  if (openLogFile >= 0 &&
2561  XLogFileClose();
2562  if (openLogFile < 0)
2563  {
2566  openLogTLI = tli;
2569  }
2570 
2572  }
2573 
2574  /* signal that we need to wakeup walsenders later */
2576 
2578  }
2579 
2580  /*
2581  * Update shared-memory status
2582  *
2583  * We make sure that the shared 'request' values do not fall behind the
2584  * 'result' values. This is not absolutely essential, but it saves some
2585  * code in a couple of places.
2586  */
2593 
2594  /*
2595  * We write Write first, bar, then Flush. When reading, the opposite must
2596  * be done (with a matching barrier in between), so that we always see a
2597  * Flush value that trails behind the Write value seen.
2598  */
2600  pg_write_barrier();
2602 
2603 #ifdef USE_ASSERT_CHECKING
2604  {
2605  XLogRecPtr Flush;
2606  XLogRecPtr Write;
2608 
2610  pg_read_barrier();
2612  pg_read_barrier();
2614 
2615  /* WAL written to disk is always ahead of WAL flushed */
2616  Assert(Write >= Flush);
2617 
2618  /* WAL inserted to buffers is always ahead of WAL written */
2619  Assert(Insert >= Write);
2620  }
2621 #endif
2622 }
2623 
2624 /*
2625  * Record the LSN for an asynchronous transaction commit/abort
2626  * and nudge the WALWriter if there is work for it to do.
2627  * (This should not be called for synchronous commits.)
2628  */
2629 void
2631 {
2632  XLogRecPtr WriteRqstPtr = asyncXactLSN;
2633  bool sleeping;
2634  bool wakeup = false;
2635  XLogRecPtr prevAsyncXactLSN;
2636 
2638  sleeping = XLogCtl->WalWriterSleeping;
2639  prevAsyncXactLSN = XLogCtl->asyncXactLSN;
2640  if (XLogCtl->asyncXactLSN < asyncXactLSN)
2641  XLogCtl->asyncXactLSN = asyncXactLSN;
2643 
2644  /*
2645  * If somebody else already called this function with a more aggressive
2646  * LSN, they will have done what we needed (and perhaps more).
2647  */
2648  if (asyncXactLSN <= prevAsyncXactLSN)
2649  return;
2650 
2651  /*
2652  * If the WALWriter is sleeping, kick it to make it come out of low-power
2653  * mode, so that this async commit will reach disk within the expected
2654  * amount of time. Otherwise, determine whether it has enough WAL
2655  * available to flush, the same way that XLogBackgroundFlush() does.
2656  */
2657  if (sleeping)
2658  wakeup = true;
2659  else
2660  {
2661  int flushblocks;
2662 
2664 
2665  flushblocks =
2666  WriteRqstPtr / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
2667 
2668  if (WalWriterFlushAfter == 0 || flushblocks >= WalWriterFlushAfter)
2669  wakeup = true;
2670  }
2671 
2674 }
2675 
2676 /*
2677  * Record the LSN up to which we can remove WAL because it's not required by
2678  * any replication slot.
2679  */
2680 void
2682 {
2686 }
2687 
2688 
2689 /*
2690  * Return the oldest LSN we must retain to satisfy the needs of some
2691  * replication slot.
2692  */
2693 static XLogRecPtr
2695 {
2696  XLogRecPtr retval;
2697 
2699  retval = XLogCtl->replicationSlotMinLSN;
2701 
2702  return retval;
2703 }
2704 
2705 /*
2706  * Advance minRecoveryPoint in control file.
2707  *
2708  * If we crash during recovery, we must reach this point again before the
2709  * database is consistent.
2710  *
2711  * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
2712  * is only updated if it's not already greater than or equal to 'lsn'.
2713  */
2714 static void
2716 {
2717  /* Quick check using our local copy of the variable */
2718  if (!updateMinRecoveryPoint || (!force && lsn <= LocalMinRecoveryPoint))
2719  return;
2720 
2721  /*
2722  * An invalid minRecoveryPoint means that we need to recover all the WAL,
2723  * i.e., we're doing crash recovery. We never modify the control file's
2724  * value in that case, so we can short-circuit future checks here too. The
2725  * local values of minRecoveryPoint and minRecoveryPointTLI should not be
2726  * updated until crash recovery finishes. We only do this for the startup
2727  * process as it should not update its own reference of minRecoveryPoint
2728  * until it has finished crash recovery to make sure that all WAL
2729  * available is replayed in this case. This also saves from extra locks
2730  * taken on the control file from the startup process.
2731  */
2733  {
2734  updateMinRecoveryPoint = false;
2735  return;
2736  }
2737 
2738  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2739 
2740  /* update local copy */
2743 
2745  updateMinRecoveryPoint = false;
2746  else if (force || LocalMinRecoveryPoint < lsn)
2747  {
2748  XLogRecPtr newMinRecoveryPoint;
2749  TimeLineID newMinRecoveryPointTLI;
2750 
2751  /*
2752  * To avoid having to update the control file too often, we update it
2753  * all the way to the last record being replayed, even though 'lsn'
2754  * would suffice for correctness. This also allows the 'force' case
2755  * to not need a valid 'lsn' value.
2756  *
2757  * Another important reason for doing it this way is that the passed
2758  * 'lsn' value could be bogus, i.e., past the end of available WAL, if
2759  * the caller got it from a corrupted heap page. Accepting such a
2760  * value as the min recovery point would prevent us from coming up at
2761  * all. Instead, we just log a warning and continue with recovery.
2762  * (See also the comments about corrupt LSNs in XLogFlush.)
2763  */
2764  newMinRecoveryPoint = GetCurrentReplayRecPtr(&newMinRecoveryPointTLI);
2765  if (!force && newMinRecoveryPoint < lsn)
2766  elog(WARNING,
2767  "xlog min recovery request %X/%X is past current point %X/%X",
2768  LSN_FORMAT_ARGS(lsn), LSN_FORMAT_ARGS(newMinRecoveryPoint));
2769 
2770  /* update control file */
2771  if (ControlFile->minRecoveryPoint < newMinRecoveryPoint)
2772  {
2773  ControlFile->minRecoveryPoint = newMinRecoveryPoint;
2774  ControlFile->minRecoveryPointTLI = newMinRecoveryPointTLI;
2776  LocalMinRecoveryPoint = newMinRecoveryPoint;
2777  LocalMinRecoveryPointTLI = newMinRecoveryPointTLI;
2778 
2779  ereport(DEBUG2,
2780  (errmsg_internal("updated min recovery point to %X/%X on timeline %u",
2781  LSN_FORMAT_ARGS(newMinRecoveryPoint),
2782  newMinRecoveryPointTLI)));
2783  }
2784  }
2785  LWLockRelease(ControlFileLock);
2786 }
2787 
2788 /*
2789  * Ensure that all XLOG data through the given position is flushed to disk.
2790  *
2791  * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
2792  * already held, and we try to avoid acquiring it if possible.
2793  */
2794 void
2796 {
2797  XLogRecPtr WriteRqstPtr;
2798  XLogwrtRqst WriteRqst;
2799  TimeLineID insertTLI = XLogCtl->InsertTimeLineID;
2800 
2801  /*
2802  * During REDO, we are reading not writing WAL. Therefore, instead of
2803  * trying to flush the WAL, we should update minRecoveryPoint instead. We
2804  * test XLogInsertAllowed(), not InRecovery, because we need checkpointer
2805  * to act this way too, and because when it tries to write the
2806  * end-of-recovery checkpoint, it should indeed flush.
2807  */
2808  if (!XLogInsertAllowed())
2809  {
2810  UpdateMinRecoveryPoint(record, false);
2811  return;
2812  }
2813 
2814  /* Quick exit if already known flushed */
2815  if (record <= LogwrtResult.Flush)
2816  return;
2817 
2818 #ifdef WAL_DEBUG
2819  if (XLOG_DEBUG)
2820  elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
2821  LSN_FORMAT_ARGS(record),
2824 #endif
2825 
2827 
2828  /*
2829  * Since fsync is usually a horribly expensive operation, we try to
2830  * piggyback as much data as we can on each fsync: if we see any more data
2831  * entered into the xlog buffer, we'll write and fsync that too, so that
2832  * the final value of LogwrtResult.Flush is as large as possible. This
2833  * gives us some chance of avoiding another fsync immediately after.
2834  */
2835 
2836  /* initialize to given target; may increase below */
2837  WriteRqstPtr = record;
2838 
2839  /*
2840  * Now wait until we get the write lock, or someone else does the flush
2841  * for us.
2842  */
2843  for (;;)
2844  {
2845  XLogRecPtr insertpos;
2846 
2847  /* done already? */
2849  if (record <= LogwrtResult.Flush)
2850  break;
2851 
2852  /*
2853  * Before actually performing the write, wait for all in-flight
2854  * insertions to the pages we're about to write to finish.
2855  */
2857  if (WriteRqstPtr < XLogCtl->LogwrtRqst.Write)
2858  WriteRqstPtr = XLogCtl->LogwrtRqst.Write;
2860  insertpos = WaitXLogInsertionsToFinish(WriteRqstPtr);
2861 
2862  /*
2863  * Try to get the write lock. If we can't get it immediately, wait
2864  * until it's released, and recheck if we still need to do the flush
2865  * or if the backend that held the lock did it for us already. This
2866  * helps to maintain a good rate of group committing when the system
2867  * is bottlenecked by the speed of fsyncing.
2868  */
2869  if (!LWLockAcquireOrWait(WALWriteLock, LW_EXCLUSIVE))
2870  {
2871  /*
2872  * The lock is now free, but we didn't acquire it yet. Before we
2873  * do, loop back to check if someone else flushed the record for
2874  * us already.
2875  */
2876  continue;
2877  }
2878 
2879  /* Got the lock; recheck whether request is satisfied */
2881  if (record <= LogwrtResult.Flush)
2882  {
2883  LWLockRelease(WALWriteLock);
2884  break;
2885  }
2886 
2887  /*
2888  * Sleep before flush! By adding a delay here, we may give further
2889  * backends the opportunity to join the backlog of group commit
2890  * followers; this can significantly improve transaction throughput,
2891  * at the risk of increasing transaction latency.
2892  *
2893  * We do not sleep if enableFsync is not turned on, nor if there are
2894  * fewer than CommitSiblings other backends with active transactions.
2895  */
2896  if (CommitDelay > 0 && enableFsync &&
2898  {
2900 
2901  /*
2902  * Re-check how far we can now flush the WAL. It's generally not
2903  * safe to call WaitXLogInsertionsToFinish while holding
2904  * WALWriteLock, because an in-progress insertion might need to
2905  * also grab WALWriteLock to make progress. But we know that all
2906  * the insertions up to insertpos have already finished, because
2907  * that's what the earlier WaitXLogInsertionsToFinish() returned.
2908  * We're only calling it again to allow insertpos to be moved
2909  * further forward, not to actually wait for anyone.
2910  */
2911  insertpos = WaitXLogInsertionsToFinish(insertpos);
2912  }
2913 
2914  /* try to write/flush later additions to XLOG as well */
2915  WriteRqst.Write = insertpos;
2916  WriteRqst.Flush = insertpos;
2917 
2918  XLogWrite(WriteRqst, insertTLI, false);
2919 
2920  LWLockRelease(WALWriteLock);
2921  /* done */
2922  break;
2923  }
2924 
2925  END_CRIT_SECTION();
2926 
2927  /* wake up walsenders now that we've released heavily contended locks */
2929 
2930  /*
2931  * If we still haven't flushed to the request point then we have a
2932  * problem; most likely, the requested flush point is past end of XLOG.
2933  * This has been seen to occur when a disk page has a corrupted LSN.
2934  *
2935  * Formerly we treated this as a PANIC condition, but that hurts the
2936  * system's robustness rather than helping it: we do not want to take down
2937  * the whole system due to corruption on one data page. In particular, if
2938  * the bad page is encountered again during recovery then we would be
2939  * unable to restart the database at all! (This scenario actually
2940  * happened in the field several times with 7.1 releases.) As of 8.4, bad
2941  * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
2942  * the only time we can reach here during recovery is while flushing the
2943  * end-of-recovery checkpoint record, and we don't expect that to have a
2944  * bad LSN.
2945  *
2946  * Note that for calls from xact.c, the ERROR will be promoted to PANIC
2947  * since xact.c calls this routine inside a critical section. However,
2948  * calls from bufmgr.c are not within critical sections and so we will not
2949  * force a restart for a bad LSN on a data page.
2950  */
2951  if (LogwrtResult.Flush < record)
2952  elog(ERROR,
2953  "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
2954  LSN_FORMAT_ARGS(record),
2956 }
2957 
2958 /*
2959  * Write & flush xlog, but without specifying exactly where to.
2960  *
2961  * We normally write only completed blocks; but if there is nothing to do on
2962  * that basis, we check for unwritten async commits in the current incomplete
2963  * block, and write through the latest one of those. Thus, if async commits
2964  * are not being used, we will write complete blocks only.
2965  *
2966  * If, based on the above, there's anything to write we do so immediately. But
2967  * to avoid calling fsync, fdatasync et. al. at a rate that'd impact
2968  * concurrent IO, we only flush WAL every wal_writer_delay ms, or if there's
2969  * more than wal_writer_flush_after unflushed blocks.
2970  *
2971  * We can guarantee that async commits reach disk after at most three
2972  * wal_writer_delay cycles. (When flushing complete blocks, we allow XLogWrite
2973  * to write "flexibly", meaning it can stop at the end of the buffer ring;
2974  * this makes a difference only with very high load or long wal_writer_delay,
2975  * but imposes one extra cycle for the worst case for async commits.)
2976  *
2977  * This routine is invoked periodically by the background walwriter process.
2978  *
2979  * Returns true if there was any work to do, even if we skipped flushing due
2980  * to wal_writer_delay/wal_writer_flush_after.
2981  */
2982 bool
2984 {
2985  XLogwrtRqst WriteRqst;
2986  bool flexible = true;
2987  static TimestampTz lastflush;
2988  TimestampTz now;
2989  int flushblocks;
2990  TimeLineID insertTLI;
2991 
2992  /* XLOG doesn't need flushing during recovery */
2993  if (RecoveryInProgress())
2994  return false;
2995 
2996  /*
2997  * Since we're not in recovery, InsertTimeLineID is set and can't change,
2998  * so we can read it without a lock.
2999  */
3000  insertTLI = XLogCtl->InsertTimeLineID;
3001 
3002  /* read updated LogwrtRqst */
3004  WriteRqst = XLogCtl->LogwrtRqst;
3006 
3007  /* back off to last completed page boundary */
3008  WriteRqst.Write -= WriteRqst.Write % XLOG_BLCKSZ;
3009 
3010  /* if we have already flushed that far, consider async commit records */
3012  if (WriteRqst.Write <= LogwrtResult.Flush)
3013  {
3015  WriteRqst.Write = XLogCtl->asyncXactLSN;
3017  flexible = false; /* ensure it all gets written */
3018  }
3019 
3020  /*
3021  * If already known flushed, we're done. Just need to check if we are
3022  * holding an open file handle to a logfile that's no longer in use,
3023  * preventing the file from being deleted.
3024  */
3025  if (WriteRqst.Write <= LogwrtResult.Flush)
3026  {
3027  if (openLogFile >= 0)
3028  {
3031  {
3032  XLogFileClose();
3033  }
3034  }
3035  return false;
3036  }
3037 
3038  /*
3039  * Determine how far to flush WAL, based on the wal_writer_delay and
3040  * wal_writer_flush_after GUCs.
3041  *
3042  * Note that XLogSetAsyncXactLSN() performs similar calculation based on
3043  * wal_writer_flush_after, to decide when to wake us up. Make sure the
3044  * logic is the same in both places if you change this.
3045  */
3047  flushblocks =
3048  WriteRqst.Write / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
3049 
3050  if (WalWriterFlushAfter == 0 || lastflush == 0)
3051  {
3052  /* first call, or block based limits disabled */
3053  WriteRqst.Flush = WriteRqst.Write;
3054  lastflush = now;
3055  }
3056  else if (TimestampDifferenceExceeds(lastflush, now, WalWriterDelay))
3057  {
3058  /*
3059  * Flush the writes at least every WalWriterDelay ms. This is
3060  * important to bound the amount of time it takes for an asynchronous
3061  * commit to hit disk.
3062  */
3063  WriteRqst.Flush = WriteRqst.Write;
3064  lastflush = now;
3065  }
3066  else if (flushblocks >= WalWriterFlushAfter)
3067  {
3068  /* exceeded wal_writer_flush_after blocks, flush */
3069  WriteRqst.Flush = WriteRqst.Write;
3070  lastflush = now;
3071  }
3072  else
3073  {
3074  /* no flushing, this time round */
3075  WriteRqst.Flush = 0;
3076  }
3077 
3078 #ifdef WAL_DEBUG
3079  if (XLOG_DEBUG)
3080  elog(LOG, "xlog bg flush request write %X/%X; flush: %X/%X, current is write %X/%X; flush %X/%X",
3081  LSN_FORMAT_ARGS(WriteRqst.Write),
3082  LSN_FORMAT_ARGS(WriteRqst.Flush),
3085 #endif
3086 
3088 
3089  /* now wait for any in-progress insertions to finish and get write lock */
3090  WaitXLogInsertionsToFinish(WriteRqst.Write);
3091  LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
3093  if (WriteRqst.Write > LogwrtResult.Write ||
3094  WriteRqst.Flush > LogwrtResult.Flush)
3095  {
3096  XLogWrite(WriteRqst, insertTLI, flexible);
3097  }
3098  LWLockRelease(WALWriteLock);
3099 
3100  END_CRIT_SECTION();
3101 
3102  /* wake up walsenders now that we've released heavily contended locks */
3104 
3105  /*
3106  * Great, done. To take some work off the critical path, try to initialize
3107  * as many of the no-longer-needed WAL buffers for future use as we can.
3108  */
3109  AdvanceXLInsertBuffer(InvalidXLogRecPtr, insertTLI, true);
3110 
3111  /*
3112  * If we determined that we need to write data, but somebody else
3113  * wrote/flushed already, it should be considered as being active, to
3114  * avoid hibernating too early.
3115  */
3116  return true;
3117 }
3118 
3119 /*
3120  * Test whether XLOG data has been flushed up to (at least) the given position.
3121  *
3122  * Returns true if a flush is still needed. (It may be that someone else
3123  * is already in process of flushing that far, however.)
3124  */
3125 bool
3127 {
3128  /*
3129  * During recovery, we don't flush WAL but update minRecoveryPoint
3130  * instead. So "needs flush" is taken to mean whether minRecoveryPoint
3131  * would need to be updated.
3132  */
3133  if (RecoveryInProgress())
3134  {
3135  /*
3136  * An invalid minRecoveryPoint means that we need to recover all the
3137  * WAL, i.e., we're doing crash recovery. We never modify the control
3138  * file's value in that case, so we can short-circuit future checks
3139  * here too. This triggers a quick exit path for the startup process,
3140  * which cannot update its local copy of minRecoveryPoint as long as
3141  * it has not replayed all WAL available when doing crash recovery.
3142  */
3144  updateMinRecoveryPoint = false;
3145 
3146  /* Quick exit if already known to be updated or cannot be updated */
3148  return false;
3149 
3150  /*
3151  * Update local copy of minRecoveryPoint. But if the lock is busy,
3152  * just return a conservative guess.
3153  */
3154  if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
3155  return true;
3158  LWLockRelease(ControlFileLock);
3159 
3160  /*
3161  * Check minRecoveryPoint for any other process than the startup
3162  * process doing crash recovery, which should not update the control
3163  * file value if crash recovery is still running.
3164  */
3166  updateMinRecoveryPoint = false;
3167 
3168  /* check again */
3170  return false;
3171  else
3172  return true;
3173  }
3174 
3175  /* Quick exit if already known flushed */
3176  if (record <= LogwrtResult.Flush)
3177  return false;
3178 
3179  /* read LogwrtResult and update local state */
3181 
3182  /* check again */
3183  if (record <= LogwrtResult.Flush)
3184  return false;
3185 
3186  return true;
3187 }
3188 
3189 /*
3190  * Try to make a given XLOG file segment exist.
3191  *
3192  * logsegno: identify segment.
3193  *
3194  * *added: on return, true if this call raised the number of extant segments.
3195  *
3196  * path: on return, this char[MAXPGPATH] has the path to the logsegno file.
3197  *
3198  * Returns -1 or FD of opened file. A -1 here is not an error; a caller
3199  * wanting an open segment should attempt to open "path", which usually will
3200  * succeed. (This is weird, but it's efficient for the callers.)
3201  */
3202 static int
3204  bool *added, char *path)
3205 {
3206  char tmppath[MAXPGPATH];
3207  XLogSegNo installed_segno;
3208  XLogSegNo max_segno;
3209  int fd;
3210  int save_errno;
3211  int open_flags = O_RDWR | O_CREAT | O_EXCL | PG_BINARY;
3212 
3213  Assert(logtli != 0);
3214 
3215  XLogFilePath(path, logtli, logsegno, wal_segment_size);
3216 
3217  /*
3218  * Try to use existent file (checkpoint maker may have created it already)
3219  */
3220  *added = false;
3221  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3223  if (fd < 0)
3224  {
3225  if (errno != ENOENT)
3226  ereport(ERROR,
3228  errmsg("could not open file \"%s\": %m", path)));
3229  }
3230  else
3231  return fd;
3232 
3233  /*
3234  * Initialize an empty (all zeroes) segment. NOTE: it is possible that
3235  * another process is doing the same thing. If so, we will end up
3236  * pre-creating an extra log segment. That seems OK, and better than
3237  * holding the lock throughout this lengthy process.
3238  */
3239  elog(DEBUG2, "creating and filling new WAL file");
3240 
3241  snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3242 
3243  unlink(tmppath);
3244 
3246  open_flags |= PG_O_DIRECT;
3247 
3248  /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3249  fd = BasicOpenFile(tmppath, open_flags);
3250  if (fd < 0)
3251  ereport(ERROR,
3253  errmsg("could not create file \"%s\": %m", tmppath)));
3254 
3255  pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_WRITE);
3256  save_errno = 0;
3257  if (wal_init_zero)
3258  {
3259  ssize_t rc;
3260 
3261  /*
3262  * Zero-fill the file. With this setting, we do this the hard way to
3263  * ensure that all the file space has really been allocated. On
3264  * platforms that allow "holes" in files, just seeking to the end
3265  * doesn't allocate intermediate space. This way, we know that we
3266  * have all the space and (after the fsync below) that all the
3267  * indirect blocks are down on disk. Therefore, fdatasync(2) or
3268  * O_DSYNC will be sufficient to sync future writes to the log file.
3269  */
3271 
3272  if (rc < 0)
3273  save_errno = errno;
3274  }
3275  else
3276  {
3277  /*
3278  * Otherwise, seeking to the end and writing a solitary byte is
3279  * enough.
3280  */
3281  errno = 0;
3282  if (pg_pwrite(fd, "\0", 1, wal_segment_size - 1) != 1)
3283  {
3284  /* if write didn't set errno, assume no disk space */
3285  save_errno = errno ? errno : ENOSPC;
3286  }
3287  }
3289 
3290  if (save_errno)
3291  {
3292  /*
3293  * If we fail to make the file, delete it to release disk space
3294  */
3295  unlink(tmppath);
3296 
3297  close(fd);
3298 
3299  errno = save_errno;
3300 
3301  ereport(ERROR,
3303  errmsg("could not write to file \"%s\": %m", tmppath)));
3304  }
3305 
3306  pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_SYNC);
3307  if (pg_fsync(fd) != 0)
3308  {
3309  save_errno = errno;
3310  close(fd);
3311  errno = save_errno;
3312  ereport(ERROR,
3314  errmsg("could not fsync file \"%s\": %m", tmppath)));
3315  }
3317 
3318  if (close(fd) != 0)
3319  ereport(ERROR,
3321  errmsg("could not close file \"%s\": %m", tmppath)));
3322 
3323  /*
3324  * Now move the segment into place with its final name. Cope with
3325  * possibility that someone else has created the file while we were
3326  * filling ours: if so, use ours to pre-create a future log segment.
3327  */
3328  installed_segno = logsegno;
3329 
3330  /*
3331  * XXX: What should we use as max_segno? We used to use XLOGfileslop when
3332  * that was a constant, but that was always a bit dubious: normally, at a
3333  * checkpoint, XLOGfileslop was the offset from the checkpoint record, but
3334  * here, it was the offset from the insert location. We can't do the
3335  * normal XLOGfileslop calculation here because we don't have access to
3336  * the prior checkpoint's redo location. So somewhat arbitrarily, just use
3337  * CheckPointSegments.
3338  */
3339  max_segno = logsegno + CheckPointSegments;
3340  if (InstallXLogFileSegment(&installed_segno, tmppath, true, max_segno,
3341  logtli))
3342  {
3343  *added = true;
3344  elog(DEBUG2, "done creating and filling new WAL file");
3345  }
3346  else
3347  {
3348  /*
3349  * No need for any more future segments, or InstallXLogFileSegment()
3350  * failed to rename the file into place. If the rename failed, a
3351  * caller opening the file may fail.
3352  */
3353  unlink(tmppath);
3354  elog(DEBUG2, "abandoned new WAL file");
3355  }
3356 
3357  return -1;
3358 }
3359 
3360 /*
3361  * Create a new XLOG file segment, or open a pre-existing one.
3362  *
3363  * logsegno: identify segment to be created/opened.
3364  *
3365  * Returns FD of opened file.
3366  *
3367  * Note: errors here are ERROR not PANIC because we might or might not be
3368  * inside a critical section (eg, during checkpoint there is no reason to
3369  * take down the system on failure). They will promote to PANIC if we are
3370  * in a critical section.
3371  */
3372 int
3374 {
3375  bool ignore_added;
3376  char path[MAXPGPATH];
3377  int fd;
3378 
3379  Assert(logtli != 0);
3380 
3381  fd = XLogFileInitInternal(logsegno, logtli, &ignore_added, path);
3382  if (fd >= 0)
3383  return fd;
3384 
3385  /* Now open original target segment (might not be file I just made) */
3386  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3388  if (fd < 0)
3389  ereport(ERROR,
3391  errmsg("could not open file \"%s\": %m", path)));
3392  return fd;
3393 }
3394 
3395 /*
3396  * Create a new XLOG file segment by copying a pre-existing one.
3397  *
3398  * destsegno: identify segment to be created.
3399  *
3400  * srcTLI, srcsegno: identify segment to be copied (could be from
3401  * a different timeline)
3402  *
3403  * upto: how much of the source file to copy (the rest is filled with
3404  * zeros)
3405  *
3406  * Currently this is only used during recovery, and so there are no locking
3407  * considerations. But we should be just as tense as XLogFileInit to avoid
3408  * emplacing a bogus file.
3409  */
3410 static void
3411 XLogFileCopy(TimeLineID destTLI, XLogSegNo destsegno,
3412  TimeLineID srcTLI, XLogSegNo srcsegno,
3413  int upto)
3414 {
3415  char path[MAXPGPATH];
3416  char tmppath[MAXPGPATH];
3417  PGAlignedXLogBlock buffer;
3418  int srcfd;
3419  int fd;
3420  int nbytes;
3421 
3422  /*
3423  * Open the source file
3424  */
3425  XLogFilePath(path, srcTLI, srcsegno, wal_segment_size);
3426  srcfd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3427  if (srcfd < 0)
3428  ereport(ERROR,
3430  errmsg("could not open file \"%s\": %m", path)));
3431 
3432  /*
3433  * Copy into a temp file name.
3434  */
3435  snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3436 
3437  unlink(tmppath);
3438 
3439  /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3440  fd = OpenTransientFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3441  if (fd < 0)
3442  ereport(ERROR,
3444  errmsg("could not create file \"%s\": %m", tmppath)));
3445 
3446  /*
3447  * Do the data copying.
3448  */
3449  for (nbytes = 0; nbytes < wal_segment_size; nbytes += sizeof(buffer))
3450  {
3451  int nread;
3452 
3453  nread = upto - nbytes;
3454 
3455  /*
3456  * The part that is not read from the source file is filled with
3457  * zeros.
3458  */
3459  if (nread < sizeof(buffer))
3460  memset(buffer.data, 0, sizeof(buffer));
3461 
3462  if (nread > 0)
3463  {
3464  int r;
3465 
3466  if (nread > sizeof(buffer))
3467  nread = sizeof(buffer);
3468  pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_READ);
3469  r = read(srcfd, buffer.data, nread);
3470  if (r != nread)
3471  {
3472  if (r < 0)
3473  ereport(ERROR,
3475  errmsg("could not read file \"%s\": %m",
3476  path)));
3477  else
3478  ereport(ERROR,
3480  errmsg("could not read file \"%s\": read %d of %zu",
3481  path, r, (Size) nread)));
3482  }
3484  }
3485  errno = 0;
3486  pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_WRITE);
3487  if ((int) write(fd, buffer.data, sizeof(buffer)) != (int) sizeof(buffer))
3488  {
3489  int save_errno = errno;
3490 
3491  /*
3492  * If we fail to make the file, delete it to release disk space
3493  */
3494  unlink(tmppath);
3495  /* if write didn't set errno, assume problem is no disk space */
3496  errno = save_errno ? save_errno : ENOSPC;
3497 
3498  ereport(ERROR,
3500  errmsg("could not write to file \"%s\": %m", tmppath)));
3501  }
3503  }
3504 
3505  pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_SYNC);
3506  if (pg_fsync(fd) != 0)
3509  errmsg("could not fsync file \"%s\": %m", tmppath)));
3511 
3512  if (CloseTransientFile(fd) != 0)
3513  ereport(ERROR,
3515  errmsg("could not close file \"%s\": %m", tmppath)));
3516 
3517  if (CloseTransientFile(srcfd) != 0)
3518  ereport(ERROR,
3520  errmsg("could not close file \"%s\": %m", path)));
3521 
3522  /*
3523  * Now move the segment into place with its final name.
3524  */
3525  if (!InstallXLogFileSegment(&destsegno, tmppath, false, 0, destTLI))
3526  elog(ERROR, "InstallXLogFileSegment should not have failed");
3527 }
3528 
3529 /*
3530  * Install a new XLOG segment file as a current or future log segment.
3531  *
3532  * This is used both to install a newly-created segment (which has a temp
3533  * filename while it's being created) and to recycle an old segment.
3534  *
3535  * *segno: identify segment to install as (or first possible target).
3536  * When find_free is true, this is modified on return to indicate the
3537  * actual installation location or last segment searched.
3538  *
3539  * tmppath: initial name of file to install. It will be renamed into place.
3540  *
3541  * find_free: if true, install the new segment at the first empty segno
3542  * number at or after the passed numbers. If false, install the new segment
3543  * exactly where specified, deleting any existing segment file there.
3544  *
3545  * max_segno: maximum segment number to install the new file as. Fail if no
3546  * free slot is found between *segno and max_segno. (Ignored when find_free
3547  * is false.)
3548  *
3549  * tli: The timeline on which the new segment should be installed.
3550  *
3551  * Returns true if the file was installed successfully. false indicates that
3552  * max_segno limit was exceeded, the startup process has disabled this
3553  * function for now, or an error occurred while renaming the file into place.
3554  */
3555 static bool
3556 InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
3557  bool find_free, XLogSegNo max_segno, TimeLineID tli)
3558 {
3559  char path[MAXPGPATH];
3560  struct stat stat_buf;
3561 
3562  Assert(tli != 0);
3563 
3564  XLogFilePath(path, tli, *segno, wal_segment_size);
3565 
3566  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3568  {
3569  LWLockRelease(ControlFileLock);
3570  return false;
3571  }
3572 
3573  if (!find_free)
3574  {
3575  /* Force installation: get rid of any pre-existing segment file */
3576  durable_unlink(path, DEBUG1);
3577  }
3578  else
3579  {
3580  /* Find a free slot to put it in */
3581  while (stat(path, &stat_buf) == 0)
3582  {
3583  if ((*segno) >= max_segno)
3584  {
3585  /* Failed to find a free slot within specified range */
3586  LWLockRelease(ControlFileLock);
3587  return false;
3588  }
3589  (*segno)++;
3590  XLogFilePath(path, tli, *segno, wal_segment_size);
3591  }
3592  }
3593 
3594  Assert(access(path, F_OK) != 0 && errno == ENOENT);
3595  if (durable_rename(tmppath, path, LOG) != 0)
3596  {
3597  LWLockRelease(ControlFileLock);
3598  /* durable_rename already emitted log message */
3599  return false;
3600  }
3601 
3602  LWLockRelease(ControlFileLock);
3603 
3604  return true;
3605 }
3606 
3607 /*
3608  * Open a pre-existing logfile segment for writing.
3609  */
3610 int
3612 {
3613  char path[MAXPGPATH];
3614  int fd;
3615 
3616  XLogFilePath(path, tli, segno, wal_segment_size);
3617 
3618  fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3620  if (fd < 0)
3621  ereport(PANIC,
3623  errmsg("could not open file \"%s\": %m", path)));
3624 
3625  return fd;
3626 }
3627 
3628 /*
3629  * Close the current logfile segment for writing.
3630  */
3631 static void
3633 {
3634  Assert(openLogFile >= 0);
3635 
3636  /*
3637  * WAL segment files will not be re-read in normal operation, so we advise
3638  * the OS to release any cached pages. But do not do so if WAL archiving
3639  * or streaming is active, because archiver and walsender process could
3640  * use the cache to read the WAL segment.
3641  */
3642 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3643  if (!XLogIsNeeded() && (io_direct_flags & IO_DIRECT_WAL) == 0)
3644  (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3645 #endif
3646 
3647  if (close(openLogFile) != 0)
3648  {
3649  char xlogfname[MAXFNAMELEN];
3650  int save_errno = errno;
3651 
3653  errno = save_errno;
3654  ereport(PANIC,
3656  errmsg("could not close file \"%s\": %m", xlogfname)));
3657  }
3658 
3659  openLogFile = -1;
3661 }
3662 
3663 /*
3664  * Preallocate log files beyond the specified log endpoint.
3665  *
3666  * XXX this is currently extremely conservative, since it forces only one
3667  * future log segment to exist, and even that only if we are 75% done with
3668  * the current one. This is only appropriate for very low-WAL-volume systems.
3669  * High-volume systems will be OK once they've built up a sufficient set of
3670  * recycled log segments, but the startup transient is likely to include
3671  * a lot of segment creations by foreground processes, which is not so good.
3672  *
3673  * XLogFileInitInternal() can ereport(ERROR). All known causes indicate big
3674  * trouble; for example, a full filesystem is one cause. The checkpoint WAL
3675  * and/or ControlFile updates already completed. If a RequestCheckpoint()
3676  * initiated the present checkpoint and an ERROR ends this function, the
3677  * command that called RequestCheckpoint() fails. That's not ideal, but it's
3678  * not worth contorting more functions to use caller-specified elevel values.
3679  * (With or without RequestCheckpoint(), an ERROR forestalls some inessential
3680  * reporting and resource reclamation.)
3681  */
3682 static void
3684 {
3685  XLogSegNo _logSegNo;
3686  int lf;
3687  bool added;
3688  char path[MAXPGPATH];
3689  uint64 offset;
3690 
3692  return; /* unlocked check says no */
3693 
3694  XLByteToPrevSeg(endptr, _logSegNo, wal_segment_size);
3695  offset = XLogSegmentOffset(endptr - 1, wal_segment_size);
3696  if (offset >= (uint32) (0.75 * wal_segment_size))
3697  {
3698  _logSegNo++;
3699  lf = XLogFileInitInternal(_logSegNo, tli, &added, path);
3700  if (lf >= 0)
3701  close(lf);
3702  if (added)
3704  }
3705 }
3706 
3707 /*
3708  * Throws an error if the given log segment has already been removed or
3709  * recycled. The caller should only pass a segment that it knows to have
3710  * existed while the server has been running, as this function always
3711  * succeeds if no WAL segments have been removed since startup.
3712  * 'tli' is only used in the error message.
3713  *
3714  * Note: this function guarantees to keep errno unchanged on return.
3715  * This supports callers that use this to possibly deliver a better
3716  * error message about a missing file, while still being able to throw
3717  * a normal file-access error afterwards, if this does return.
3718  */
3719 void
3721 {
3722  int save_errno = errno;
3723  XLogSegNo lastRemovedSegNo;
3724 
3726  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3728 
3729  if (segno <= lastRemovedSegNo)
3730  {
3731  char filename[MAXFNAMELEN];
3732 
3733  XLogFileName(filename, tli, segno, wal_segment_size);
3734  errno = save_errno;
3735  ereport(ERROR,
3737  errmsg("requested WAL segment %s has already been removed",
3738  filename)));
3739  }
3740  errno = save_errno;
3741 }
3742 
3743 /*
3744  * Return the last WAL segment removed, or 0 if no segment has been removed
3745  * since startup.
3746  *
3747  * NB: the result can be out of date arbitrarily fast, the caller has to deal
3748  * with that.
3749  */
3750 XLogSegNo
3752 {
3753  XLogSegNo lastRemovedSegNo;
3754 
3756  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3758 
3759  return lastRemovedSegNo;
3760 }
3761 
3762 /*
3763  * Return the oldest WAL segment on the given TLI that still exists in
3764  * XLOGDIR, or 0 if none.
3765  */
3766 XLogSegNo
3768 {
3769  DIR *xldir;
3770  struct dirent *xlde;
3771  XLogSegNo oldest_segno = 0;
3772 
3773  xldir = AllocateDir(XLOGDIR);
3774  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3775  {
3776  TimeLineID file_tli;
3777  XLogSegNo file_segno;
3778 
3779  /* Ignore files that are not XLOG segments. */
3780  if (!IsXLogFileName(xlde->d_name))
3781  continue;
3782 
3783  /* Parse filename to get TLI and segno. */
3784  XLogFromFileName(xlde->d_name, &file_tli, &file_segno,
3786 
3787  /* Ignore anything that's not from the TLI of interest. */
3788  if (tli != file_tli)
3789  continue;
3790 
3791  /* If it's the oldest so far, update oldest_segno. */
3792  if (oldest_segno == 0 || file_segno < oldest_segno)
3793  oldest_segno = file_segno;
3794  }
3795 
3796  FreeDir(xldir);
3797  return oldest_segno;
3798 }
3799 
3800 /*
3801  * Update the last removed segno pointer in shared memory, to reflect that the
3802  * given XLOG file has been removed.
3803  */
3804 static void
3806 {
3807  uint32 tli;
3808  XLogSegNo segno;
3809 
3810  XLogFromFileName(filename, &tli, &segno, wal_segment_size);
3811 
3813  if (segno > XLogCtl->lastRemovedSegNo)
3814  XLogCtl->lastRemovedSegNo = segno;
3816 }
3817 
3818 /*
3819  * Remove all temporary log files in pg_wal
3820  *
3821  * This is called at the beginning of recovery after a previous crash,
3822  * at a point where no other processes write fresh WAL data.
3823  */
3824 static void
3826 {
3827  DIR *xldir;
3828  struct dirent *xlde;
3829 
3830  elog(DEBUG2, "removing all temporary WAL segments");
3831 
3832  xldir = AllocateDir(XLOGDIR);
3833  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3834  {
3835  char path[MAXPGPATH];
3836 
3837  if (strncmp(xlde->d_name, "xlogtemp.", 9) != 0)
3838  continue;
3839 
3840  snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3841  unlink(path);
3842  elog(DEBUG2, "removed temporary WAL segment \"%s\"", path);
3843  }
3844  FreeDir(xldir);
3845 }
3846 
3847 /*
3848  * Recycle or remove all log files older or equal to passed segno.
3849  *
3850  * endptr is current (or recent) end of xlog, and lastredoptr is the
3851  * redo pointer of the last checkpoint. These are used to determine
3852  * whether we want to recycle rather than delete no-longer-wanted log files.
3853  *
3854  * insertTLI is the current timeline for XLOG insertion. Any recycled
3855  * segments should be reused for this timeline.
3856  */
3857 static void
3859  TimeLineID insertTLI)
3860 {
3861  DIR *xldir;
3862  struct dirent *xlde;
3863  char lastoff[MAXFNAMELEN];
3864  XLogSegNo endlogSegNo;
3865  XLogSegNo recycleSegNo;
3866 
3867  /* Initialize info about where to try to recycle to */
3868  XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
3869  recycleSegNo = XLOGfileslop(lastredoptr);
3870 
3871  /*
3872  * Construct a filename of the last segment to be kept. The timeline ID
3873  * doesn't matter, we ignore that in the comparison. (During recovery,
3874  * InsertTimeLineID isn't set, so we can't use that.)
3875  */
3876  XLogFileName(lastoff, 0, segno, wal_segment_size);
3877 
3878  elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
3879  lastoff);
3880 
3881  xldir = AllocateDir(XLOGDIR);
3882 
3883  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3884  {
3885  /* Ignore files that are not XLOG segments */
3886  if (!IsXLogFileName(xlde->d_name) &&
3887  !IsPartialXLogFileName(xlde->d_name))
3888  continue;
3889 
3890  /*
3891  * We ignore the timeline part of the XLOG segment identifiers in
3892  * deciding whether a segment is still needed. This ensures that we
3893  * won't prematurely remove a segment from a parent timeline. We could
3894  * probably be a little more proactive about removing segments of
3895  * non-parent timelines, but that would be a whole lot more
3896  * complicated.
3897  *
3898  * We use the alphanumeric sorting property of the filenames to decide
3899  * which ones are earlier than the lastoff segment.
3900  */
3901  if (strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
3902  {
3903  if (XLogArchiveCheckDone(xlde->d_name))
3904  {
3905  /* Update the last removed location in shared memory first */
3907 
3908  RemoveXlogFile(xlde, recycleSegNo, &endlogSegNo, insertTLI);
3909  }
3910  }
3911  }
3912 
3913  FreeDir(xldir);
3914 }
3915 
3916 /*
3917  * Recycle or remove WAL files that are not part of the given timeline's
3918  * history.
3919  *
3920  * This is called during recovery, whenever we switch to follow a new
3921  * timeline, and at the end of recovery when we create a new timeline. We
3922  * wouldn't otherwise care about extra WAL files lying in pg_wal, but they
3923  * might be leftover pre-allocated or recycled WAL segments on the old timeline
3924  * that we haven't used yet, and contain garbage. If we just leave them in
3925  * pg_wal, they will eventually be archived, and we can't let that happen.
3926  * Files that belong to our timeline history are valid, because we have
3927  * successfully replayed them, but from others we can't be sure.
3928  *
3929  * 'switchpoint' is the current point in WAL where we switch to new timeline,
3930  * and 'newTLI' is the new timeline we switch to.
3931  */
3932 void
3934 {
3935  DIR *xldir;
3936  struct dirent *xlde;
3937  char switchseg[MAXFNAMELEN];
3938  XLogSegNo endLogSegNo;
3939  XLogSegNo switchLogSegNo;
3940  XLogSegNo recycleSegNo;
3941 
3942  /*
3943  * Initialize info about where to begin the work. This will recycle,
3944  * somewhat arbitrarily, 10 future segments.
3945  */
3946  XLByteToPrevSeg(switchpoint, switchLogSegNo, wal_segment_size);
3947  XLByteToSeg(switchpoint, endLogSegNo, wal_segment_size);
3948  recycleSegNo = endLogSegNo + 10;
3949 
3950  /*
3951  * Construct a filename of the last segment to be kept.
3952  */
3953  XLogFileName(switchseg, newTLI, switchLogSegNo, wal_segment_size);
3954 
3955  elog(DEBUG2, "attempting to remove WAL segments newer than log file %s",
3956  switchseg);
3957 
3958  xldir = AllocateDir(XLOGDIR);
3959 
3960  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3961  {
3962  /* Ignore files that are not XLOG segments */
3963  if (!IsXLogFileName(xlde->d_name))
3964  continue;
3965 
3966  /*
3967  * Remove files that are on a timeline older than the new one we're
3968  * switching to, but with a segment number >= the first segment on the
3969  * new timeline.
3970  */
3971  if (strncmp(xlde->d_name, switchseg, 8) < 0 &&
3972  strcmp(xlde->d_name + 8, switchseg + 8) > 0)
3973  {
3974  /*
3975  * If the file has already been marked as .ready, however, don't
3976  * remove it yet. It should be OK to remove it - files that are
3977  * not part of our timeline history are not required for recovery
3978  * - but seems safer to let them be archived and removed later.
3979  */
3980  if (!XLogArchiveIsReady(xlde->d_name))
3981  RemoveXlogFile(xlde, recycleSegNo, &endLogSegNo, newTLI);
3982  }
3983  }
3984 
3985  FreeDir(xldir);
3986 }
3987 
3988 /*
3989  * Recycle or remove a log file that's no longer needed.
3990  *
3991  * segment_de is the dirent structure of the segment to recycle or remove.
3992  * recycleSegNo is the segment number to recycle up to. endlogSegNo is
3993  * the segment number of the current (or recent) end of WAL.
3994  *
3995  * endlogSegNo gets incremented if the segment is recycled so as it is not
3996  * checked again with future callers of this function.
3997  *
3998  * insertTLI is the current timeline for XLOG insertion. Any recycled segments
3999  * should be used for this timeline.
4000  */
4001 static void
4002 RemoveXlogFile(const struct dirent *segment_de,
4003  XLogSegNo recycleSegNo, XLogSegNo *endlogSegNo,
4004  TimeLineID insertTLI)
4005 {
4006  char path[MAXPGPATH];
4007 #ifdef WIN32
4008  char newpath[MAXPGPATH];
4009 #endif
4010  const char *segname = segment_de->d_name;
4011 
4012  snprintf(path, MAXPGPATH, XLOGDIR "/%s", segname);
4013 
4014  /*
4015  * Before deleting the file, see if it can be recycled as a future log
4016  * segment. Only recycle normal files, because we don't want to recycle
4017  * symbolic links pointing to a separate archive directory.
4018  */
4019  if (wal_recycle &&
4020  *endlogSegNo <= recycleSegNo &&
4021  XLogCtl->InstallXLogFileSegmentActive && /* callee rechecks this */
4022  get_dirent_type(path, segment_de, false, DEBUG2) == PGFILETYPE_REG &&
4023  InstallXLogFileSegment(endlogSegNo, path,
4024  true, recycleSegNo, insertTLI))
4025  {
4026  ereport(DEBUG2,
4027  (errmsg_internal("recycled write-ahead log file \"%s\"",
4028  segname)));
4030  /* Needn't recheck that slot on future iterations */
4031  (*endlogSegNo)++;
4032  }
4033  else
4034  {
4035  /* No need for any more future segments, or recycling failed ... */
4036  int rc;
4037 
4038  ereport(DEBUG2,
4039  (errmsg_internal("removing write-ahead log file \"%s\"",
4040  segname)));
4041 
4042 #ifdef WIN32
4043 
4044  /*
4045  * On Windows, if another process (e.g another backend) holds the file
4046  * open in FILE_SHARE_DELETE mode, unlink will succeed, but the file
4047  * will still show up in directory listing until the last handle is
4048  * closed. To avoid confusing the lingering deleted file for a live
4049  * WAL file that needs to be archived, rename it before deleting it.
4050  *
4051  * If another process holds the file open without FILE_SHARE_DELETE
4052  * flag, rename will fail. We'll try again at the next checkpoint.
4053  */
4054  snprintf(newpath, MAXPGPATH, "%s.deleted", path);
4055  if (rename(path, newpath) != 0)
4056  {
4057  ereport(LOG,
4059  errmsg("could not rename file \"%s\": %m",
4060  path)));
4061  return;
4062  }
4063  rc = durable_unlink(newpath, LOG);
4064 #else
4065  rc = durable_unlink(path, LOG);
4066 #endif
4067  if (rc != 0)
4068  {
4069  /* Message already logged by durable_unlink() */
4070  return;
4071  }
4073  }
4074 
4075  XLogArchiveCleanup(segname);
4076 }
4077 
4078 /*
4079  * Verify whether pg_wal, pg_wal/archive_status, and pg_wal/summaries exist.
4080  * If the latter do not exist, recreate them.
4081  *
4082  * It is not the goal of this function to verify the contents of these
4083  * directories, but to help in cases where someone has performed a cluster
4084  * copy for PITR purposes but omitted pg_wal from the copy.
4085  *
4086  * We could also recreate pg_wal if it doesn't exist, but a deliberate
4087  * policy decision was made not to. It is fairly common for pg_wal to be
4088  * a symlink, and if that was the DBA's intent then automatically making a
4089  * plain directory would result in degraded performance with no notice.
4090  */
4091 static void
4093 {
4094  char path[MAXPGPATH];
4095  struct stat stat_buf;
4096 
4097  /* Check for pg_wal; if it doesn't exist, error out */
4098  if (stat(XLOGDIR, &stat_buf) != 0 ||
4099  !S_ISDIR(stat_buf.st_mode))
4100  ereport(FATAL,
4102  errmsg("required WAL directory \"%s\" does not exist",
4103  XLOGDIR)));
4104 
4105  /* Check for archive_status */
4106  snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
4107  if (stat(path, &stat_buf) == 0)
4108  {
4109  /* Check for weird cases where it exists but isn't a directory */
4110  if (!S_ISDIR(stat_buf.st_mode))
4111  ereport(FATAL,
4113  errmsg("required WAL directory \"%s\" does not exist",
4114  path)));
4115  }
4116  else
4117  {
4118  ereport(LOG,
4119  (errmsg("creating missing WAL directory \"%s\"", path)));
4120  if (MakePGDirectory(path) < 0)
4121  ereport(FATAL,
4123  errmsg("could not create missing directory \"%s\": %m",
4124  path)));
4125  }
4126 
4127  /* Check for summaries */
4128  snprintf(path, MAXPGPATH, XLOGDIR "/summaries");
4129  if (stat(path, &stat_buf) == 0)
4130  {
4131  /* Check for weird cases where it exists but isn't a directory */
4132  if (!S_ISDIR(stat_buf.st_mode))
4133  ereport(FATAL,
4134  (errmsg("required WAL directory \"%s\" does not exist",
4135  path)));
4136  }
4137  else
4138  {
4139  ereport(LOG,
4140  (errmsg("creating missing WAL directory \"%s\"", path)));
4141  if (MakePGDirectory(path) < 0)
4142  ereport(FATAL,
4143  (errmsg("could not create missing directory \"%s\": %m",
4144  path)));
4145  }
4146 }
4147 
4148 /*
4149  * Remove previous backup history files. This also retries creation of
4150  * .ready files for any backup history files for which XLogArchiveNotify
4151  * failed earlier.
4152  */
4153 static void
4155 {
4156  DIR *xldir;
4157  struct dirent *xlde;
4158  char path[MAXPGPATH + sizeof(XLOGDIR)];
4159 
4160  xldir = AllocateDir(XLOGDIR);
4161 
4162  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4163  {
4164  if (IsBackupHistoryFileName(xlde->d_name))
4165  {
4166  if (XLogArchiveCheckDone(xlde->d_name))
4167  {
4168  elog(DEBUG2, "removing WAL backup history file \"%s\"",
4169  xlde->d_name);
4170  snprintf(path, sizeof(path), XLOGDIR "/%s", xlde->d_name);
4171  unlink(path);
4172  XLogArchiveCleanup(xlde->d_name);
4173  }
4174  }
4175  }
4176 
4177  FreeDir(xldir);
4178 }
4179 
4180 /*
4181  * I/O routines for pg_control
4182  *
4183  * *ControlFile is a buffer in shared memory that holds an image of the
4184  * contents of pg_control. WriteControlFile() initializes pg_control
4185  * given a preloaded buffer, ReadControlFile() loads the buffer from
4186  * the pg_control file (during postmaster or standalone-backend startup),
4187  * and UpdateControlFile() rewrites pg_control after we modify xlog state.
4188  * InitControlFile() fills the buffer with initial values.
4189  *
4190  * For simplicity, WriteControlFile() initializes the fields of pg_control
4191  * that are related to checking backend/database compatibility, and
4192  * ReadControlFile() verifies they are correct. We could split out the
4193  * I/O and compatibility-check functions, but there seems no need currently.
4194  */
4195 
4196 static void
4197 InitControlFile(uint64 sysidentifier, uint32 data_checksum_version)
4198 {
4199  char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
4200 
4201  /*
4202  * Generate a random nonce. This is used for authentication requests that
4203  * will fail because the user does not exist. The nonce is used to create
4204  * a genuine-looking password challenge for the non-existent user, in lieu
4205  * of an actual stored password.
4206  */
4207  if (!pg_strong_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
4208  ereport(PANIC,
4209  (errcode(ERRCODE_INTERNAL_ERROR),
4210  errmsg("could not generate secret authorization token")));
4211 
4212  memset(ControlFile, 0, sizeof(ControlFileData));
4213  /* Initialize pg_control status fields */
4214  ControlFile->system_identifier = sysidentifier;
4215  memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
4218 
4219  /* Set important parameter values for use when replaying WAL */
4228  ControlFile->data_checksum_version = data_checksum_version;
4229 }
4230 
4231 static void
4233 {
4234  int fd;
4235  char buffer[PG_CONTROL_FILE_SIZE]; /* need not be aligned */
4236 
4237  /*
4238  * Initialize version and compatibility-check fields
4239  */
4242 
4243  ControlFile->maxAlign = MAXIMUM_ALIGNOF;
4245 
4246  ControlFile->blcksz = BLCKSZ;
4247  ControlFile->relseg_size = RELSEG_SIZE;
4248  ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4250 
4253 
4256 
4258 
4259  /* Contents are protected with a CRC */
4262  (char *) ControlFile,
4263  offsetof(ControlFileData, crc));
4265 
4266  /*
4267  * We write out PG_CONTROL_FILE_SIZE bytes into pg_control, zero-padding
4268  * the excess over sizeof(ControlFileData). This reduces the odds of
4269  * premature-EOF errors when reading pg_control. We'll still fail when we
4270  * check the contents of the file, but hopefully with a more specific
4271  * error than "couldn't read pg_control".
4272  */
4273  memset(buffer, 0, PG_CONTROL_FILE_SIZE);
4274  memcpy(buffer, ControlFile, sizeof(ControlFileData));
4275 
4277  O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
4278  if (fd < 0)
4279  ereport(PANIC,
4281  errmsg("could not create file \"%s\": %m",
4282  XLOG_CONTROL_FILE)));
4283 
4284  errno = 0;
4285  pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_WRITE);
4287  {
4288  /* if write didn't set errno, assume problem is no disk space */
4289  if (errno == 0)
4290  errno = ENOSPC;
4291  ereport(PANIC,
4293  errmsg("could not write to file \"%s\": %m",
4294  XLOG_CONTROL_FILE)));
4295  }
4297 
4298  pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_SYNC);
4299  if (pg_fsync(fd) != 0)
4300  ereport(PANIC,
4302  errmsg("could not fsync file \"%s\": %m",
4303  XLOG_CONTROL_FILE)));
4305 
4306  if (close(fd) != 0)
4307  ereport(PANIC,
4309  errmsg("could not close file \"%s\": %m",
4310  XLOG_CONTROL_FILE)));
4311 }
4312 
4313 static void
4315 {
4316  pg_crc32c crc;
4317  int fd;
4318  char wal_segsz_str[20];
4319  int r;
4320 
4321  /*
4322  * Read data...
4323  */
4325  O_RDWR | PG_BINARY);
4326  if (fd < 0)
4327  ereport(PANIC,
4329  errmsg("could not open file \"%s\": %m",
4330  XLOG_CONTROL_FILE)));
4331 
4332  pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_READ);
4333  r = read(fd, ControlFile, sizeof(ControlFileData));
4334  if (r != sizeof(ControlFileData))
4335  {
4336  if (r < 0)
4337  ereport(PANIC,
4339  errmsg("could not read file \"%s\": %m",
4340  XLOG_CONTROL_FILE)));
4341  else
4342  ereport(PANIC,
4344  errmsg("could not read file \"%s\": read %d of %zu",
4345  XLOG_CONTROL_FILE, r, sizeof(ControlFileData))));
4346  }
4348 
4349  close(fd);
4350 
4351  /*
4352  * Check for expected pg_control format version. If this is wrong, the
4353  * CRC check will likely fail because we'll be checking the wrong number
4354  * of bytes. Complaining about wrong version will probably be more
4355  * enlightening than complaining about wrong CRC.
4356  */
4357 
4359  ereport(FATAL,
4360  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4361  errmsg("database files are incompatible with server"),
4362  errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4363  " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4366  errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4367 
4369  ereport(FATAL,
4370  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4371  errmsg("database files are incompatible with server"),
4372  errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4373  " but the server was compiled with PG_CONTROL_VERSION %d.",
4375  errhint("It looks like you need to initdb.")));
4376 
4377  /* Now check the CRC. */
4378  INIT_CRC32C(crc);
4379  COMP_CRC32C(crc,
4380  (char *) ControlFile,
4381  offsetof(ControlFileData, crc));
4382  FIN_CRC32C(crc);
4383 
4384  if (!EQ_CRC32C(crc, ControlFile->crc))
4385  ereport(FATAL,
4386  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4387  errmsg("incorrect checksum in control file")));
4388 
4389  /*
4390  * Do compatibility checking immediately. If the database isn't
4391  * compatible with the backend executable, we want to abort before we can
4392  * possibly do any damage.
4393  */
4395  ereport(FATAL,
4396  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4397  errmsg("database files are incompatible with server"),
4398  /* translator: %s is a variable name and %d is its value */
4399  errdetail("The database cluster was initialized with %s %d,"
4400  " but the server was compiled with %s %d.",
4401  "CATALOG_VERSION_NO", ControlFile->catalog_version_no,
4402  "CATALOG_VERSION_NO", CATALOG_VERSION_NO),
4403  errhint("It looks like you need to initdb.")));
4404  if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4405  ereport(FATAL,
4406  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4407  errmsg("database files are incompatible with server"),
4408  /* translator: %s is a variable name and %d is its value */
4409  errdetail("The database cluster was initialized with %s %d,"
4410  " but the server was compiled with %s %d.",
4411  "MAXALIGN", ControlFile->maxAlign,
4412  "MAXALIGN", MAXIMUM_ALIGNOF),
4413  errhint("It looks like you need to initdb.")));
4415  ereport(FATAL,
4416  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4417  errmsg("database files are incompatible with server"),
4418  errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4419  errhint("It looks like you need to initdb.")));
4420  if (ControlFile->blcksz != BLCKSZ)
4421  ereport(FATAL,
4422  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4423  errmsg("database files are incompatible with server"),
4424  /* translator: %s is a variable name and %d is its value */
4425  errdetail("The database cluster was initialized with %s %d,"
4426  " but the server was compiled with %s %d.",
4427  "BLCKSZ", ControlFile->blcksz,
4428  "BLCKSZ", BLCKSZ),
4429  errhint("It looks like you need to recompile or initdb.")));
4430  if (ControlFile->relseg_size != RELSEG_SIZE)
4431  ereport(FATAL,
4432  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4433  errmsg("database files are incompatible with server"),
4434  /* translator: %s is a variable name and %d is its value */
4435  errdetail("The database cluster was initialized with %s %d,"
4436  " but the server was compiled with %s %d.",
4437  "RELSEG_SIZE", ControlFile->relseg_size,
4438  "RELSEG_SIZE", RELSEG_SIZE),
4439  errhint("It looks like you need to recompile or initdb.")));
4440  if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4441  ereport(FATAL,
4442  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4443  errmsg("database files are incompatible with server"),
4444  /* translator: %s is a variable name and %d is its value */
4445  errdetail("The database cluster was initialized with %s %d,"
4446  " but the server was compiled with %s %d.",
4447  "XLOG_BLCKSZ", ControlFile->xlog_blcksz,
4448  "XLOG_BLCKSZ", XLOG_BLCKSZ),
4449  errhint("It looks like you need to recompile or initdb.")));
4451  ereport(FATAL,
4452  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4453  errmsg("database files are incompatible with server"),
4454  /* translator: %s is a variable name and %d is its value */
4455  errdetail("The database cluster was initialized with %s %d,"
4456  " but the server was compiled with %s %d.",
4457  "NAMEDATALEN", ControlFile->nameDataLen,
4458  "NAMEDATALEN", NAMEDATALEN),
4459  errhint("It looks like you need to recompile or initdb.")));
4461  ereport(FATAL,
4462  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4463  errmsg("database files are incompatible with server"),
4464  /* translator: %s is a variable name and %d is its value */
4465  errdetail("The database cluster was initialized with %s %d,"
4466  " but the server was compiled with %s %d.",
4467  "INDEX_MAX_KEYS", ControlFile->indexMaxKeys,
4468  "INDEX_MAX_KEYS", INDEX_MAX_KEYS),
4469  errhint("It looks like you need to recompile or initdb.")));
4471  ereport(FATAL,
4472  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4473  errmsg("database files are incompatible with server"),
4474  /* translator: %s is a variable name and %d is its value */
4475  errdetail("The database cluster was initialized with %s %d,"
4476  " but the server was compiled with %s %d.",
4477  "TOAST_MAX_CHUNK_SIZE", ControlFile->toast_max_chunk_size,
4478  "TOAST_MAX_CHUNK_SIZE", (int) TOAST_MAX_CHUNK_SIZE),
4479  errhint("It looks like you need to recompile or initdb.")));
4481  ereport(FATAL,
4482  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4483  errmsg("database files are incompatible with server"),
4484  /* translator: %s is a variable name and %d is its value */
4485  errdetail("The database cluster was initialized with %s %d,"
4486  " but the server was compiled with %s %d.",
4487  "LOBLKSIZE", ControlFile->loblksize,
4488  "LOBLKSIZE", (int) LOBLKSIZE),
4489  errhint("It looks like you need to recompile or initdb.")));
4490 
4491 #ifdef USE_FLOAT8_BYVAL
4492  if (ControlFile->float8ByVal != true)
4493  ereport(FATAL,
4494  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4495  errmsg("database files are incompatible with server"),
4496  errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4497  " but the server was compiled with USE_FLOAT8_BYVAL."),
4498  errhint("It looks like you need to recompile or initdb.")));
4499 #else
4500  if (ControlFile->float8ByVal != false)
4501  ereport(FATAL,
4502  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4503  errmsg("database files are incompatible with server"),
4504  errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4505  " but the server was compiled without USE_FLOAT8_BYVAL."),
4506  errhint("It looks like you need to recompile or initdb.")));
4507 #endif
4508 
4510 
4512  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4513  errmsg_plural("invalid WAL segment size in control file (%d byte)",
4514  "invalid WAL segment size in control file (%d bytes)",
4517  errdetail("The WAL segment size must be a power of two between 1 MB and 1 GB.")));
4518 
4519  snprintf(wal_segsz_str, sizeof(wal_segsz_str), "%d", wal_segment_size);
4520  SetConfigOption("wal_segment_size", wal_segsz_str, PGC_INTERNAL,
4522 
4523  /* check and update variables dependent on wal_segment_size */
4525  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4526  /* translator: both %s are GUC names */
4527  errmsg("\"%s\" must be at least twice \"%s\"",
4528  "min_wal_size", "wal_segment_size")));
4529 
4531  ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4532  /* translator: both %s are GUC names */
4533  errmsg("\"%s\" must be at least twice \"%s\"",
4534  "max_wal_size", "wal_segment_size")));
4535 
4537  (wal_segment_size / XLOG_BLCKSZ * UsableBytesInPage) -
4539 
4541 
4542  /* Make the initdb settings visible as GUC variables, too */
4543  SetConfigOption("data_checksums", DataChecksumsEnabled() ? "yes" : "no",
4545 }
4546 
4547 /*
4548  * Utility wrapper to update the control file. Note that the control
4549  * file gets flushed.
4550  */
4551 static void
4553 {
4555 }
4556 
4557 /*
4558  * Returns the unique system identifier from control file.
4559  */
4560 uint64
4562 {
4563  Assert(ControlFile != NULL);
4565 }
4566 
4567 /*
4568  * Returns the random nonce from control file.
4569  */
4570 char *
4572 {
4573  Assert(ControlFile != NULL);
4575 }
4576 
4577 /*
4578  * Are checksums enabled for data pages?
4579  */
4580 bool
4582 {
4583  Assert(ControlFile != NULL);
4584  return (ControlFile->data_checksum_version > 0);
4585 }
4586 
4587 /*
4588  * Returns a fake LSN for unlogged relations.
4589  *
4590  * Each call generates an LSN that is greater than any previous value
4591  * returned. The current counter value is saved and restored across clean
4592  * shutdowns, but like unlogged relations, does not survive a crash. This can
4593  * be used in lieu of real LSN values returned by XLogInsert, if you need an
4594  * LSN-like increasing sequence of numbers without writing any WAL.
4595  */
4596 XLogRecPtr
4598 {
4600 }
4601 
4602 /*
4603  * Auto-tune the number of XLOG buffers.
4604  *
4605  * The preferred setting for wal_buffers is about 3% of shared_buffers, with
4606  * a maximum of one XLOG segment (there is little reason to think that more
4607  * is helpful, at least so long as we force an fsync when switching log files)
4608  * and a minimum of 8 blocks (which was the default value prior to PostgreSQL
4609  * 9.1, when auto-tuning was added).
4610  *
4611  * This should not be called until NBuffers has received its final value.
4612  */
4613 static int
4615 {
4616  int xbuffers;
4617 
4618  xbuffers = NBuffers / 32;
4619  if (xbuffers > (wal_segment_size / XLOG_BLCKSZ))
4620  xbuffers = (wal_segment_size / XLOG_BLCKSZ);
4621  if (xbuffers < 8)
4622  xbuffers = 8;
4623  return xbuffers;
4624 }
4625 
4626 /*
4627  * GUC check_hook for wal_buffers
4628  */
4629 bool
4631 {
4632  /*
4633  * -1 indicates a request for auto-tune.
4634  */
4635  if (*newval == -1)
4636  {
4637  /*
4638  * If we haven't yet changed the boot_val default of -1, just let it
4639  * be. We'll fix it when XLOGShmemSize is called.
4640  */
4641  if (XLOGbuffers == -1)
4642  return true;
4643 
4644  /* Otherwise, substitute the auto-tune value */
4646  }
4647 
4648  /*
4649  * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
4650  * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
4651  * the case, we just silently treat such values as a request for the
4652  * minimum. (We could throw an error instead, but that doesn't seem very
4653  * helpful.)
4654  */
4655  if (*newval < 4)
4656  *newval = 4;
4657 
4658  return true;
4659 }
4660 
4661 /*
4662  * GUC check_hook for wal_consistency_checking
4663  */
4664 bool
4666 {
4667  char *rawstring;
4668  List *elemlist;
4669  ListCell *l;
4670  bool newwalconsistency[RM_MAX_ID + 1];
4671 
4672  /* Initialize the array */
4673  MemSet(newwalconsistency, 0, (RM_MAX_ID + 1) * sizeof(bool));
4674 
4675  /* Need a modifiable copy of string */
4676  rawstring = pstrdup(*newval);
4677 
4678  /* Parse string into list of identifiers */
4679  if (!SplitIdentifierString(rawstring, ',', &elemlist))
4680  {
4681  /* syntax error in list */
4682  GUC_check_errdetail("List syntax is invalid.");
4683  pfree(rawstring);
4684  list_free(elemlist);
4685  return false;
4686  }
4687 
4688  foreach(l, elemlist)
4689  {
4690  char *tok = (char *) lfirst(l);
4691  int rmid;
4692 
4693  /* Check for 'all'. */
4694  if (pg_strcasecmp(tok, "all") == 0)
4695  {
4696  for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4697  if (RmgrIdExists(rmid) && GetRmgr(rmid).rm_mask != NULL)
4698  newwalconsistency[rmid] = true;
4699  }
4700  else
4701  {
4702  /* Check if the token matches any known resource manager. */
4703  bool found = false;
4704 
4705  for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4706  {
4707  if (RmgrIdExists(rmid) && GetRmgr(rmid).rm_mask != NULL &&
4708  pg_strcasecmp(tok, GetRmgr(rmid).rm_name) == 0)
4709  {
4710  newwalconsistency[rmid] = true;
4711  found = true;
4712  break;
4713  }
4714  }
4715  if (!found)
4716  {
4717  /*
4718  * During startup, it might be a not-yet-loaded custom
4719  * resource manager. Defer checking until
4720  * InitializeWalConsistencyChecking().
4721  */
4723  {
4725  }
4726  else
4727  {
4728  GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
4729  pfree(rawstring);
4730  list_free(elemlist);
4731  return false;
4732  }
4733  }
4734  }
4735  }
4736 
4737  pfree(rawstring);
4738  list_free(elemlist);
4739 
4740  /* assign new value */
4741  *extra = guc_malloc(ERROR, (RM_MAX_ID + 1) * sizeof(bool));
4742  memcpy(*extra, newwalconsistency, (RM_MAX_ID + 1) * sizeof(bool));
4743  return true;
4744 }
4745 
4746 /*
4747  * GUC assign_hook for wal_consistency_checking
4748  */
4749 void
4750 assign_wal_consistency_checking(const char *newval, void *extra)
4751 {
4752  /*
4753  * If some checks were deferred, it's possible that the checks will fail
4754  * later during InitializeWalConsistencyChecking(). But in that case, the
4755  * postmaster will exit anyway, so it's safe to proceed with the
4756  * assignment.
4757  *
4758  * Any built-in resource managers specified are assigned immediately,
4759  * which affects WAL created before shared_preload_libraries are
4760  * processed. Any custom resource managers specified won't be assigned
4761  * until after shared_preload_libraries are processed, but that's OK
4762  * because WAL for a custom resource manager can't be written before the
4763  * module is loaded anyway.
4764  */
4765  wal_consistency_checking = extra;
4766 }
4767 
4768 /*
4769  * InitializeWalConsistencyChecking: run after loading custom resource managers
4770  *
4771  * If any unknown resource managers were specified in the
4772  * wal_consistency_checking GUC, processing was deferred. Now that
4773  * shared_preload_libraries have been loaded, process wal_consistency_checking
4774  * again.
4775  */
4776 void
4778 {
4780 
4782  {
4783  struct config_generic *guc;
4784 
4785  guc = find_option("wal_consistency_checking", false, false, ERROR);
4786 
4788 
4789  set_config_option_ext("wal_consistency_checking",
4791  guc->scontext, guc->source, guc->srole,
4792  GUC_ACTION_SET, true, ERROR, false);
4793 
4794  /* checking should not be deferred again */
4796  }
4797 }
4798 
4799 /*
4800  * GUC show_hook for archive_command
4801  */
4802 const char *
4804 {
4805  if (XLogArchivingActive())
4806  return XLogArchiveCommand;
4807  else
4808  return "(disabled)";
4809 }
4810 
4811 /*
4812  * GUC show_hook for in_hot_standby
4813  */
4814 const char *
4816 {
4817  /*
4818  * We display the actual state based on shared memory, so that this GUC
4819  * reports up-to-date state if examined intra-query. The underlying
4820  * variable (in_hot_standby_guc) changes only when we transmit a new value
4821  * to the client.
4822  */
4823  return RecoveryInProgress() ? "on" : "off";
4824 }
4825 
4826 /*
4827  * Read the control file, set respective GUCs.
4828  *
4829  * This is to be called during startup, including a crash recovery cycle,
4830  * unless in bootstrap mode, where no control file yet exists. As there's no
4831  * usable shared memory yet (its sizing can depend on the contents of the
4832  * control file!), first store the contents in local memory. XLOGShmemInit()
4833  * will then copy it to shared memory later.
4834  *
4835  * reset just controls whether previous contents are to be expected (in the
4836  * reset case, there's a dangling pointer into old shared memory), or not.
4837  */
4838 void
4840 {
4841  Assert(reset || ControlFile == NULL);
4842  ControlFile = palloc(sizeof(ControlFileData));
4843  ReadControlFile();
4844 }
4845 
4846 /*
4847  * Get the wal_level from the control file. For a standby, this value should be
4848  * considered as its active wal_level, because it may be different from what
4849  * was originally configured on standby.
4850  */
4851 WalLevel
4853 {
4854  return ControlFile->wal_level;
4855 }
4856 
4857 /*
4858  * Initialization of shared memory for XLOG
4859  */
4860 Size
4862 {
4863  Size size;
4864 
4865  /*
4866  * If the value of wal_buffers is -1, use the preferred auto-tune value.
4867  * This isn't an amazingly clean place to do this, but we must wait till
4868  * NBuffers has received its final value, and must do it before using the
4869  * value of XLOGbuffers to do anything important.
4870  *
4871  * We prefer to report this value's source as PGC_S_DYNAMIC_DEFAULT.
4872  * However, if the DBA explicitly set wal_buffers = -1 in the config file,
4873  * then PGC_S_DYNAMIC_DEFAULT will fail to override that and we must force
4874  * the matter with PGC_S_OVERRIDE.
4875  */
4876  if (XLOGbuffers == -1)
4877  {
4878  char buf[32];
4879 
4880  snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
4881  SetConfigOption("wal_buffers", buf, PGC_POSTMASTER,
4883  if (XLOGbuffers == -1) /* failed to apply it? */
4884  SetConfigOption("wal_buffers", buf, PGC_POSTMASTER,
4885  PGC_S_OVERRIDE);
4886  }
4887  Assert(XLOGbuffers > 0);
4888 
4889  /* XLogCtl */
4890  size = sizeof(XLogCtlData);
4891 
4892  /* WAL insertion locks, plus alignment */
4894  /* xlblocks array */
4896  /* extra alignment padding for XLOG I/O buffers */
4897  size = add_size(size, Max(XLOG_BLCKSZ, PG_IO_ALIGN_SIZE));
4898  /* and the buffers themselves */
4899  size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4900 
4901  /*
4902  * Note: we don't count ControlFileData, it comes out of the "slop factor"
4903  * added by CreateSharedMemoryAndSemaphores. This lets us use this
4904  * routine again below to compute the actual allocation size.
4905  */
4906 
4907  return size;
4908 }
4909 
4910 void
4912 {
4913  bool foundCFile,
4914  foundXLog;
4915  char *allocptr;
4916  int i;
4917  ControlFileData *localControlFile;
4918 
4919 #ifdef WAL_DEBUG
4920 
4921  /*
4922  * Create a memory context for WAL debugging that's exempt from the normal
4923  * "no pallocs in critical section" rule. Yes, that can lead to a PANIC if
4924  * an allocation fails, but wal_debug is not for production use anyway.
4925  */
4926  if (walDebugCxt == NULL)
4927  {
4929  "WAL Debug",
4931  MemoryContextAllowInCriticalSection(walDebugCxt, true);
4932  }
4933 #endif
4934 
4935 
4936  XLogCtl = (XLogCtlData *)
4937  ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4938 
4939  localControlFile = ControlFile;
4941  ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4942 
4943  if (foundCFile || foundXLog)
4944  {
4945  /* both should be present or neither */
4946  Assert(foundCFile && foundXLog);
4947 
4948  /* Initialize local copy of WALInsertLocks */
4950 
4951  if (localControlFile)
4952  pfree(localControlFile);
4953  return;
4954  }
4955  memset(XLogCtl, 0, sizeof(XLogCtlData));
4956 
4957  /*
4958  * Already have read control file locally, unless in bootstrap mode. Move
4959  * contents into shared memory.
4960  */
4961  if (localControlFile)
4962  {
4963  memcpy(ControlFile, localControlFile, sizeof(ControlFileData));
4964  pfree(localControlFile);
4965  }
4966 
4967  /*
4968  * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4969  * multiple of the alignment for same, so no extra alignment padding is
4970  * needed here.
4971  */
4972  allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4973  XLogCtl->xlblocks = (pg_atomic_uint64 *) allocptr;
4974  allocptr += sizeof(pg_atomic_uint64) * XLOGbuffers;
4975 
4976  for (i = 0; i < XLOGbuffers; i++)
4977  {
4979  }
4980 
4981  /* WAL insertion locks. Ensure they're aligned to the full padded size */
4982  allocptr += sizeof(WALInsertLockPadded) -
4983  ((uintptr_t) allocptr) % sizeof(WALInsertLockPadded);
4985  (WALInsertLockPadded *) allocptr;
4986  allocptr += sizeof(WALInsertLockPadded) * NUM_XLOGINSERT_LOCKS;
4987 
4988  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
4989  {
4993  }
4994 
4995  /*
4996  * Align the start of the page buffers to a full xlog block size boundary.
4997  * This simplifies some calculations in XLOG insertion. It is also
4998  * required for O_DIRECT.
4999  */
5000  allocptr = (char *) TYPEALIGN(XLOG_BLCKSZ, allocptr);
5001  XLogCtl->pages = allocptr;
5002  memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
5003 
5004  /*
5005  * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
5006  * in additional info.)
5007  */
5011  XLogCtl->WalWriterSleeping = false;
5012 
5019 }
5020 
5021 /*
5022  * This func must be called ONCE on system install. It creates pg_control
5023  * and the initial XLOG segment.
5024  */
5025 void
5026 BootStrapXLOG(uint32 data_checksum_version)
5027 {
5028  CheckPoint checkPoint;
5029  char *buffer;
5030  XLogPageHeader page;
5031  XLogLongPageHeader longpage;
5032  XLogRecord *record;
5033  char *recptr;
5034  uint64 sysidentifier;
5035  struct timeval tv;
5036  pg_crc32c crc;
5037 
5038  /* allow ordinary WAL segment creation, like StartupXLOG() would */
5040 
5041  /*
5042  * Select a hopefully-unique system identifier code for this installation.
5043  * We use the result of gettimeofday(), including the fractional seconds
5044  * field, as being about as unique as we can easily get. (Think not to
5045  * use random(), since it hasn't been seeded and there's no portable way
5046  * to seed it other than the system clock value...) The upper half of the
5047  * uint64 value is just the tv_sec part, while the lower half contains the
5048  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5049  * PID for a little extra uniqueness. A person knowing this encoding can
5050  * determine the initialization time of the installation, which could
5051  * perhaps be useful sometimes.
5052  */
5053  gettimeofday(&tv, NULL);
5054  sysidentifier = ((uint64) tv.tv_sec) << 32;
5055  sysidentifier |= ((uint64) tv.tv_usec) << 12;
5056  sysidentifier |= getpid() & 0xFFF;
5057 
5058  /* page buffer must be aligned suitably for O_DIRECT */
5059  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5060  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5061  memset(page, 0, XLOG_BLCKSZ);
5062 
5063  /*
5064  * Set up information for the initial checkpoint record
5065  *
5066  * The initial checkpoint record is written to the beginning of the WAL
5067  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5068  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5069  */
5070  checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5071  checkPoint.ThisTimeLineID = BootstrapTimeLineID;
5072  checkPoint.PrevTimeLineID = BootstrapTimeLineID;
5073  checkPoint.fullPageWrites = fullPageWrites;
5074  checkPoint.wal_level = wal_level;
5075  checkPoint.nextXid =
5077  checkPoint.nextOid = FirstGenbkiObjectId;
5078  checkPoint.nextMulti = FirstMultiXactId;
5079  checkPoint.nextMultiOffset = 0;
5080  checkPoint.oldestXid = FirstNormalTransactionId;
5081  checkPoint.oldestXidDB = Template1DbOid;
5082  checkPoint.oldestMulti = FirstMultiXactId;
5083  checkPoint.oldestMultiDB = Template1DbOid;
5086  checkPoint.time = (pg_time_t) time(NULL);
5088 
5089  TransamVariables->nextXid = checkPoint.nextXid;
5090  TransamVariables->nextOid = checkPoint.nextOid;
5092  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5093  AdvanceOldestClogXid(checkPoint.oldestXid);
5094  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5095  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5097 
5098  /* Set up the XLOG page header */
5099  page->xlp_magic = XLOG_PAGE_MAGIC;
5100  page->xlp_info = XLP_LONG_HEADER;
5101  page->xlp_tli = BootstrapTimeLineID;
5103  longpage = (XLogLongPageHeader) page;
5104  longpage->xlp_sysid = sysidentifier;
5105  longpage->xlp_seg_size = wal_segment_size;
5106  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5107 
5108  /* Insert the initial checkpoint record */
5109  recptr = ((char *) page + SizeOfXLogLongPHD);
5110  record = (XLogRecord *) recptr;
5111  record->xl_prev = 0;
5112  record->xl_xid = InvalidTransactionId;
5113  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5115  record->xl_rmid = RM_XLOG_ID;
5116  recptr += SizeOfXLogRecord;
5117  /* fill the XLogRecordDataHeaderShort struct */
5118  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5119  *(recptr++) = sizeof(checkPoint);
5120  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5121  recptr += sizeof(checkPoint);
5122  Assert(recptr - (char *) record == record->xl_tot_len);
5123 
5124  INIT_CRC32C(crc);
5125  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5126  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5127  FIN_CRC32C(crc);
5128  record->xl_crc = crc;
5129 
5130  /* Create first XLOG segment file */
5133 
5134  /*
5135  * We needn't bother with Reserve/ReleaseExternalFD here, since we'll
5136  * close the file again in a moment.
5137  */
5138 
5139  /* Write the first page with the initial record */
5140  errno = 0;
5141  pgstat_report_wait_start(WAIT_EVENT_WAL_BOOTSTRAP_WRITE);
5142  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5143  {
5144  /* if write didn't set errno, assume problem is no disk space */
5145  if (errno == 0)
5146  errno = ENOSPC;
5147  ereport(PANIC,
5149  errmsg("could not write bootstrap write-ahead log file: %m")));
5150  }
5152 
5153  pgstat_report_wait_start(WAIT_EVENT_WAL_BOOTSTRAP_SYNC);
5154  if (pg_fsync(openLogFile) != 0)
5155  ereport(PANIC,
5157  errmsg("could not fsync bootstrap write-ahead log file: %m")));
5159 
5160  if (close(openLogFile) != 0)
5161  ereport(PANIC,
5163  errmsg("could not close bootstrap write-ahead log file: %m")));
5164 
5165  openLogFile = -1;
5166 
5167  /* Now create pg_control */
5168  InitControlFile(sysidentifier, data_checksum_version);
5169  ControlFile->time = checkPoint.time;
5170  ControlFile->checkPoint = checkPoint.redo;
5171  ControlFile->checkPointCopy = checkPoint;
5172 
5173  /* some additional ControlFile fields are set in WriteControlFile() */
5174  WriteControlFile();
5175 
5176  /* Bootstrap the commit log, too */
5177  BootStrapCLOG();
5181 
5182  pfree(buffer);
5183 
5184  /*
5185  * Force control file to be read - in contrast to normal processing we'd
5186  * otherwise never run the checks and GUC related initializations therein.
5187  */
5188  ReadControlFile();
5189 }
5190 
5191 static char *
5193 {
5194  char *buf = palloc(128);
5195 
5196  pg_strftime(buf, 128,
5197  "%Y-%m-%d %H:%M:%S %Z",
5198  pg_localtime(&tnow, log_timezone));
5199 
5200  return buf;
5201 }
5202 
5203 /*
5204  * Initialize the first WAL segment on new timeline.
5205  */
5206 static void
5208 {
5209  char xlogfname[MAXFNAMELEN];
5210  XLogSegNo endLogSegNo;
5211  XLogSegNo startLogSegNo;
5212 
5213  /* we always switch to a new timeline after archive recovery */
5214  Assert(endTLI != newTLI);
5215 
5216  /*
5217  * Update min recovery point one last time.
5218  */
5220 
5221  /*
5222  * Calculate the last segment on the old timeline, and the first segment
5223  * on the new timeline. If the switch happens in the middle of a segment,
5224  * they are the same, but if the switch happens exactly at a segment
5225  * boundary, startLogSegNo will be endLogSegNo + 1.
5226  */
5227  XLByteToPrevSeg(endOfLog, endLogSegNo, wal_segment_size);
5228  XLByteToSeg(endOfLog, startLogSegNo, wal_segment_size);
5229 
5230  /*
5231  * Initialize the starting WAL segment for the new timeline. If the switch
5232  * happens in the middle of a segment, copy data from the last WAL segment
5233  * of the old timeline up to the switch point, to the starting WAL segment
5234  * on the new timeline.
5235  */
5236  if (endLogSegNo == startLogSegNo)
5237  {
5238  /*
5239  * Make a copy of the file on the new timeline.
5240  *
5241  * Writing WAL isn't allowed yet, so there are no locking
5242  * considerations. But we should be just as tense as XLogFileInit to
5243  * avoid emplacing a bogus file.
5244  */
5245  XLogFileCopy(newTLI, endLogSegNo, endTLI, endLogSegNo,
5246  XLogSegmentOffset(endOfLog, wal_segment_size));
5247  }
5248  else
5249  {
5250  /*
5251  * The switch happened at a segment boundary, so just create the next
5252  * segment on the new timeline.
5253  */
5254  int fd;
5255 
5256  fd = XLogFileInit(startLogSegNo, newTLI);
5257 
5258  if (close(fd) != 0)
5259  {
5260  int save_errno = errno;
5261 
5262  XLogFileName(xlogfname, newTLI, startLogSegNo, wal_segment_size);
5263  errno = save_errno;
5264  ereport(ERROR,
5266  errmsg("could not close file \"%s\": %m", xlogfname)));
5267  }
5268  }
5269 
5270  /*
5271  * Let's just make real sure there are not .ready or .done flags posted
5272  * for the new segment.
5273  */
5274  XLogFileName(xlogfname, newTLI, startLogSegNo, wal_segment_size);
5275  XLogArchiveCleanup(xlogfname);
5276 }
5277 
5278 /*
5279  * Perform cleanup actions at the conclusion of archive recovery.
5280  */
5281 static void
5283  TimeLineID newTLI)
5284 {
5285  /*
5286  * Execute the recovery_end_command, if any.
5287  */
5288  if (recoveryEndCommand && strcmp(recoveryEndCommand, "") != 0)
5290  "recovery_end_command",
5291  true,
5292  WAIT_EVENT_RECOVERY_END_COMMAND);
5293 
5294  /*
5295  * We switched to a new timeline. Clean up segments on the old timeline.
5296  *
5297  * If there are any higher-numbered segments on the old timeline, remove
5298  * them. They might contain valid WAL, but they might also be
5299  * pre-allocated files containing garbage. In any case, they are not part
5300  * of the new timeline's history so we don't need them.
5301  */
5302  RemoveNonParentXlogFiles(EndOfLog, newTLI);
5303 
5304  /*
5305  * If the switch happened in the middle of a segment, what to do with the
5306  * last, partial segment on the old timeline? If we don't archive it, and
5307  * the server that created the WAL never archives it either (e.g. because
5308  * it was hit by a meteor), it will never make it to the archive. That's
5309  * OK from our point of view, because the new segment that we created with
5310  * the new TLI contains all the WAL from the old timeline up to the switch
5311  * point. But if you later try to do PITR to the "missing" WAL on the old
5312  * timeline, recovery won't find it in the archive. It's physically
5313  * present in the new file with new TLI, but recovery won't look there
5314  * when it's recovering to the older timeline. On the other hand, if we
5315  * archive the partial segment, and the original server on that timeline
5316  * is still running and archives the completed version of the same segment
5317  * later, it will fail. (We used to do that in 9.4 and below, and it
5318  * caused such problems).
5319  *
5320  * As a compromise, we rename the last segment with the .partial suffix,
5321  * and archive it. Archive recovery will never try to read .partial
5322  * segments, so they will normally go unused. But in the odd PITR case,
5323  * the administrator can copy them manually to the pg_wal directory
5324  * (removing the suffix). They can be useful in debugging, too.
5325  *
5326  * If a .done or .ready file already exists for the old timeline, however,
5327  * we had already determined that the segment is complete, so we can let
5328  * it be archived normally. (In particular, if it was restored from the
5329  * archive to begin with, it's expected to have a .done file).
5330  */
5331  if (XLogSegmentOffset(EndOfLog, wal_segment_size) != 0 &&
5333  {
5334  char origfname[MAXFNAMELEN];
5335  XLogSegNo endLogSegNo;
5336 
5337  XLByteToPrevSeg(EndOfLog, endLogSegNo, wal_segment_size);
5338  XLogFileName(origfname, EndOfLogTLI, endLogSegNo, wal_segment_size);
5339 
5340  if (!XLogArchiveIsReadyOrDone(origfname))
5341  {
5342  char origpath[MAXPGPATH];
5343  char partialfname[MAXFNAMELEN];
5344  char partialpath[MAXPGPATH];
5345 
5346  /*
5347  * If we're summarizing WAL, we can't rename the partial file
5348  * until the summarizer finishes with it, else it will fail.
5349  */
5350  if (summarize_wal)
5351  WaitForWalSummarization(EndOfLog);
5352 
5353  XLogFilePath(origpath, EndOfLogTLI, endLogSegNo, wal_segment_size);
5354  snprintf(partialfname, MAXFNAMELEN, "%s.partial", origfname);
5355  snprintf(partialpath, MAXPGPATH, "%s.partial", origpath);
5356 
5357  /*
5358  * Make sure there's no .done or .ready file for the .partial
5359  * file.
5360  */
5361  XLogArchiveCleanup(partialfname);
5362 
5363  durable_rename(origpath, partialpath, ERROR);
5364  XLogArchiveNotify(partialfname);
5365  }
5366  }
5367 }
5368 
5369 /*
5370  * Check to see if required parameters are set high enough on this server
5371  * for various aspects of recovery operation.
5372  *
5373  * Note that all the parameters which this function tests need to be
5374  * listed in Administrator's Overview section in high-availability.sgml.
5375  * If you change them, don't forget to update the list.
5376  */
5377 static void
5379 {
5380  /*
5381  * For archive recovery, the WAL must be generated with at least 'replica'
5382  * wal_level.
5383  */
5385  {
5386  ereport(FATAL,
5387  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5388  errmsg("WAL was generated with \"wal_level=minimal\", cannot continue recovering"),
5389  errdetail("This happens if you temporarily set \"wal_level=minimal\" on the server."),
5390  errhint("Use a backup taken after setting \"wal_level\" to higher than \"minimal\".")));
5391  }
5392 
5393  /*
5394  * For Hot Standby, the WAL must be generated with 'replica' mode, and we
5395  * must have at least as many backend slots as the primary.
5396  */
5398  {
5399  /* We ignore autovacuum_max_workers when we make this test. */
5400  RecoveryRequiresIntParameter("max_connections",
5403  RecoveryRequiresIntParameter("max_worker_processes",
5406  RecoveryRequiresIntParameter("max_wal_senders",
5409  RecoveryRequiresIntParameter("max_prepared_transactions",
5412  RecoveryRequiresIntParameter("max_locks_per_transaction",
5415  }
5416 }
5417 
5418 /*
5419  * This must be called ONCE during postmaster or standalone-backend startup
5420  */
5421 void
5423 {
5425  CheckPoint checkPoint;
5426  bool wasShutdown;
5427  bool didCrash;
5428  bool haveTblspcMap;
5429  bool haveBackupLabel;
5430  XLogRecPtr EndOfLog;
5431  TimeLineID EndOfLogTLI;
5432  TimeLineID newTLI;
5433  bool performedWalRecovery;
5434  EndOfWalRecoveryInfo *endOfRecoveryInfo;
5437  TransactionId oldestActiveXID;
5438  bool promoted = false;
5439 
5440  /*
5441  * We should have an aux process resource owner to use, and we should not
5442  * be in a transaction that's installed some other resowner.
5443  */
5445  Assert(CurrentResourceOwner == NULL ||
5448 
5449  /*
5450  * Check that contents look valid.
5451  */
5453  ereport(FATAL,
5455  errmsg("control file contains invalid checkpoint location")));
5456 
5457  switch (ControlFile->state)
5458  {
5459  case DB_SHUTDOWNED:
5460 
5461  /*
5462  * This is the expected case, so don't be chatty in standalone
5463  * mode
5464  */
5466  (errmsg("database system was shut down at %s",
5467  str_time(ControlFile->time))));
5468  break;
5469 
5471  ereport(LOG,
5472  (errmsg("database system was shut down in recovery at %s",
5473  str_time(ControlFile->time))));
5474  break;
5475 
5476  case DB_SHUTDOWNING:
5477  ereport(LOG,
5478  (errmsg("database system shutdown was interrupted; last known up at %s",
5479  str_time(ControlFile->time))));
5480  break;
5481 
5482  case DB_IN_CRASH_RECOVERY:
5483  ereport(LOG,
5484  (errmsg("database system was interrupted while in recovery at %s",
5486  errhint("This probably means that some data is corrupted and"
5487  " you will have to use the last backup for recovery.")));
5488  break;
5489 
5491  ereport(LOG,
5492  (errmsg("database system was interrupted while in recovery at log time %s",
5494  errhint("If this has occurred more than once some data might be corrupted"
5495  " and you might need to choose an earlier recovery target.")));
5496  break;
5497 
5498  case DB_IN_PRODUCTION:
5499  ereport(LOG,
5500  (errmsg("database system was interrupted; last known up at %s",
5501  str_time(ControlFile->time))));
5502  break;
5503 
5504  default:
5505  ereport(FATAL,
5507  errmsg("control file contains invalid database cluster state")));
5508  }
5509 
5510  /* This is just to allow attaching to startup process with a debugger */
5511 #ifdef XLOG_REPLAY_DELAY
5513  pg_usleep(60000000L);
5514 #endif
5515 
5516  /*
5517  * Verify that pg_wal, pg_wal/archive_status, and pg_wal/summaries exist.
5518  * In cases where someone has performed a copy for PITR, these directories
5519  * may have been excluded and need to be re-created.
5520  */
5522 
5523  /* Set up timeout handler needed to report startup progress. */
5527 
5528  /*----------
5529  * If we previously crashed, perform a couple of actions:
5530  *
5531  * - The pg_wal directory may still include some temporary WAL segments
5532  * used when creating a new segment, so perform some clean up to not
5533  * bloat this path. This is done first as there is no point to sync
5534  * this temporary data.
5535  *
5536  * - There might be data which we had written, intending to fsync it, but
5537  * which we had not actually fsync'd yet. Therefore, a power failure in
5538  * the near future might cause earlier unflushed writes to be lost, even
5539  * though more recent data written to disk from here on would be
5540  * persisted. To avoid that, fsync the entire data directory.
5541  */
5542  if (ControlFile->state != DB_SHUTDOWNED &&
5544  {
5547  didCrash = true;
5548  }
5549  else
5550  didCrash = false;
5551 
5552  /*
5553  * Prepare for WAL recovery if needed.
5554  *
5555  * InitWalRecovery analyzes the control file and the backup label file, if
5556  * any. It updates the in-memory ControlFile buffer according to the
5557  * starting checkpoint, and sets InRecovery and ArchiveRecoveryRequested.
5558  * It also applies the tablespace map file, if any.
5559  */
5560  InitWalRecovery(ControlFile, &wasShutdown,
5561  &haveBackupLabel, &haveTblspcMap);
5562  checkPoint = ControlFile->checkPointCopy;
5563 
5564  /* initialize shared memory variables from the checkpoint record */
5565  TransamVariables->nextXid = checkPoint.nextXid;
5566  TransamVariables->nextOid = checkPoint.nextOid;
5568  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5569  AdvanceOldestClogXid(checkPoint.oldestXid);
5570  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5571  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5573  checkPoint.newestCommitTsXid);
5574  XLogCtl->ckptFullXid = checkPoint.nextXid;
5575 
5576  /*
5577  * Clear out any old relcache cache files. This is *necessary* if we do
5578  * any WAL replay, since that would probably result in the cache files
5579  * being out of sync with database reality. In theory we could leave them
5580  * in place if the database had been cleanly shut down, but it seems
5581  * safest to just remove them always and let them be rebuilt during the
5582  * first backend startup. These files needs to be removed from all
5583  * directories including pg_tblspc, however the symlinks are created only
5584  * after reading tablespace_map file in case of archive recovery from
5585  * backup, so needs to clear old relcache files here after creating
5586  * symlinks.
5587  */
5589 
5590  /*
5591  * Initialize replication slots, before there's a chance to remove
5592  * required resources.
5593  */
5595 
5596  /*
5597  * Startup logical state, needs to be setup now so we have proper data
5598  * during crash recovery.
5599  */
5601 
5602  /*
5603  * Startup CLOG. This must be done after TransamVariables->nextXid has
5604  * been initialized and before we accept connections or begin WAL replay.
5605  */
5606  StartupCLOG();
5607 
5608  /*
5609  * Startup MultiXact. We need to do this early to be able to replay
5610  * truncations.
5611  */
5612  StartupMultiXact();
5613 
5614  /*
5615  * Ditto for commit timestamps. Activate the facility if the setting is
5616  * enabled in the control file, as there should be no tracking of commit
5617  * timestamps done when the setting was disabled. This facility can be
5618  * started or stopped when replaying a XLOG_PARAMETER_CHANGE record.
5619  */
5621  StartupCommitTs();
5622 
5623  /*
5624  * Recover knowledge about replay progress of known replication partners.
5625  */
5627 
5628  /*
5629  * Initialize unlogged LSN. On a clean shutdown, it's restored from the
5630  * control file. On recovery, all unlogged relations are blown away, so
5631  * the unlogged LSN counter can be reset too.
5632  */
5636  else
5639 
5640  /*
5641  * Copy any missing timeline history files between 'now' and the recovery
5642  * target timeline from archive to pg_wal. While we don't need those files
5643  * ourselves - the history file of the recovery target timeline covers all
5644  * the previous timelines in the history too - a cascading standby server
5645  * might be interested in them. Or, if you archive the WAL from this
5646  * server to a different archive than the primary, it'd be good for all
5647  * the history files to get archived there after failover, so that you can
5648  * use one of the old timelines as a PITR target. Timeline history files
5649  * are small, so it's better to copy them unnecessarily than not copy them
5650  * and regret later.
5651  */
5653 
5654  /*
5655  * Before running in recovery, scan pg_twophase and fill in its status to
5656  * be able to work on entries generated by redo. Doing a scan before
5657  * taking any recovery action has the merit to discard any 2PC files that
5658  * are newer than the first record to replay, saving from any conflicts at
5659  * replay. This avoids as well any subsequent scans when doing recovery
5660  * of the on-disk two-phase data.
5661  */
5663 
5664  /*
5665  * When starting with crash recovery, reset pgstat data - it might not be
5666  * valid. Otherwise restore pgstat data. It's safe to do this here,
5667  * because postmaster will not yet have started any other processes.
5668  *
5669  * NB: Restoring replication slot stats relies on slot state to have
5670  * already been restored from disk.
5671  *
5672  * TODO: With a bit of extra work we could just start with a pgstat file
5673  * associated with the checkpoint redo location we're starting from.
5674  */
5675  if (didCrash)
5677  else
5678  pgstat_restore_stats(checkPoint.redo);
5679 
5680  lastFullPageWrites = checkPoint.fullPageWrites;
5681 
5684 
5685  /* REDO */
5686  if (InRecovery)
5687  {
5688  /* Initialize state for RecoveryInProgress() */
5690  if (InArchiveRecovery)
5692  else
5695 
5696  /*
5697  * Update pg_control to show that we are recovering and to show the
5698  * selected checkpoint as the place we are starting from. We also mark
5699  * pg_control with any minimum recovery stop point obtained from a
5700  * backup history file.
5701  *
5702  * No need to hold ControlFileLock yet, we aren't up far enough.
5703  */
5705 
5706  /*
5707  * If there was a backup label file, it's done its job and the info
5708  * has now been propagated into pg_control. We must get rid of the
5709  * label file so that if we crash during recovery, we'll pick up at
5710  * the latest recovery restartpoint instead of going all the way back
5711  * to the backup start point. It seems prudent though to just rename
5712  * the file out of the way rather than delete it completely.
5713  */
5714  if (haveBackupLabel)
5715  {
5716  unlink(BACKUP_LABEL_OLD);
5718  }
5719 
5720  /*
5721  * If there was a tablespace_map file, it's done its job and the
5722  * symlinks have been created. We must get rid of the map file so
5723  * that if we crash during recovery, we don't create symlinks again.
5724  * It seems prudent though to just rename the file out of the way
5725  * rather than delete it completely.
5726  */
5727  if (haveTblspcMap)
5728  {
5729  unlink(TABLESPACE_MAP_OLD);
5731  }
5732 
5733  /*
5734  * Initialize our local copy of minRecoveryPoint. When doing crash
5735  * recovery we want to replay up to the end of WAL. Particularly, in
5736  * the case of a promoted standby minRecoveryPoint value in the
5737  * control file is only updated after the first checkpoint. However,
5738  * if the instance crashes before the first post-recovery checkpoint
5739  * is completed then recovery will use a stale location causing the
5740  * startup process to think that there are still invalid page
5741  * references when checking for data consistency.
5742  */
5743  if (InArchiveRecovery)
5744  {
5747  }
5748  else
5749  {
5752  }
5753 
5754  /* Check that the GUCs used to generate the WAL allow recovery */
5756 
5757  /*
5758  * We're in recovery, so unlogged relations may be trashed and must be
5759  * reset. This should be done BEFORE allowing Hot Standby
5760  * connections, so that read-only backends don't try to read whatever
5761  * garbage is left over from before.
5762  */
5764 
5765  /*
5766  * Likewise, delete any saved transaction snapshot files that got left
5767  * behind by crashed backends.
5768  */
5770 
5771  /*
5772  * Initialize for Hot Standby, if enabled. We won't let backends in
5773  * yet, not until we've reached the min recovery point specified in
5774  * control file and we've established a recovery snapshot from a
5775  * running-xacts WAL record.
5776  */
5778  {
5779  TransactionId *xids;
5780  int nxids;
5781 
5782  ereport(DEBUG1,
5783  (errmsg_internal("initializing for hot standby")));
5784 
5786 
5787  if (wasShutdown)
5788  oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
5789  else
5790  oldestActiveXID = checkPoint.oldestActiveXid;
5791  Assert(TransactionIdIsValid(oldestActiveXID));
5792 
5793  /* Tell procarray about the range of xids it has to deal with */
5795 
5796  /*
5797  * Startup subtrans only. CLOG, MultiXact and commit timestamp
5798  * have already been started up and other SLRUs are not maintained
5799  * during recovery and need not be started yet.
5800  */
5801  StartupSUBTRANS(oldestActiveXID);
5802 
5803  /*
5804  * If we're beginning at a shutdown checkpoint, we know that
5805  * nothing was running on the primary at this point. So fake-up an
5806  * empty running-xacts record and use that here and now. Recover
5807  * additional standby state for prepared transactions.
5808  */
5809  if (wasShutdown)
5810  {
5811  RunningTransactionsData running;
5812  TransactionId latestCompletedXid;
5813 
5814  /* Update pg_subtrans entries for any prepared transactions */
5816 
5817  /*
5818  * Construct a RunningTransactions snapshot representing a
5819  * shut down server, with only prepared transactions still
5820  * alive. We're never overflowed at this point because all
5821  * subxids are listed with their parent prepared transactions.
5822  */
5823  running.xcnt = nxids;
5824  running.subxcnt = 0;
5826  running.nextXid = XidFromFullTransactionId(checkPoint.nextXid);
5827  running.oldestRunningXid = oldestActiveXID;
5828  latestCompletedXid = XidFromFullTransactionId(checkPoint.nextXid);
5829  TransactionIdRetreat(latestCompletedXid);
5830  Assert(TransactionIdIsNormal(latestCompletedXid));
5831  running.latestCompletedXid = latestCompletedXid;
5832  running.xids = xids;
5833 
5834  ProcArrayApplyRecoveryInfo(&running);
5835  }
5836  }
5837 
5838  /*
5839  * We're all set for replaying the WAL now. Do it.
5840  */
5842  performedWalRecovery = true;
5843  }
5844  else
5845  performedWalRecovery = false;
5846 
5847  /*
5848  * Finish WAL recovery.
5849  */
5850  endOfRecoveryInfo = FinishWalRecovery();
5851  EndOfLog = endOfRecoveryInfo->endOfLog;
5852  EndOfLogTLI = endOfRecoveryInfo->endOfLogTLI;
5853  abortedRecPtr = endOfRecoveryInfo->abortedRecPtr;
5854  missingContrecPtr = endOfRecoveryInfo->missingContrecPtr;
5855 
5856  /*
5857  * Reset ps status display, so as no information related to recovery shows
5858  * up.
5859  */
5860  set_ps_display("");
5861 
5862  /*
5863  * When recovering from a backup (we are in recovery, and archive recovery
5864  * was requested), complain if we did not roll forward far enough to reach
5865  * the point where the database is consistent. For regular online
5866  * backup-from-primary, that means reaching the end-of-backup WAL record
5867  * (at which point we reset backupStartPoint to be Invalid), for
5868  * backup-from-replica (which can't inject records into the WAL stream),
5869  * that point is when we reach the minRecoveryPoint in pg_control (which
5870  * we purposefully copy last when backing up from a replica). For
5871  * pg_rewind (which creates a backup_label with a method of "pg_rewind")
5872  * or snapshot-style backups (which don't), backupEndRequired will be set
5873  * to false.
5874  *
5875  * Note: it is indeed okay to look at the local variable
5876  * LocalMinRecoveryPoint here, even though ControlFile->minRecoveryPoint
5877  * might be further ahead --- ControlFile->minRecoveryPoint cannot have
5878  * been advanced beyond the WAL we processed.
5879  */
5880  if (InRecovery &&
5881  (EndOfLog < LocalMinRecoveryPoint ||
5883  {
5884  /*
5885  * Ran off end of WAL before reaching end-of-backup WAL record, or
5886  * minRecoveryPoint. That's a bad sign, indicating that you tried to
5887  * recover from an online backup but never called pg_backup_stop(), or
5888  * you didn't archive all the WAL needed.
5889  */
5891  {
5893  ereport(FATAL,
5894  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5895  errmsg("WAL ends before end of online backup"),
5896  errhint("All WAL generated while online backup was taken must be available at recovery.")));
5897  else
5898  ereport(FATAL,
5899  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5900  errmsg("WAL ends before consistent recovery point")));
5901  }
5902  }
5903 
5904  /*
5905  * Reset unlogged relations to the contents of their INIT fork. This is
5906  * done AFTER recovery is complete so as to include any unlogged relations
5907  * created during recovery, but BEFORE recovery is marked as having
5908  * completed successfully. Otherwise we'd not retry if any of the post
5909  * end-of-recovery steps fail.
5910  */
5911  if (InRecovery)
5913 
5914  /*
5915  * Pre-scan prepared transactions to find out the range of XIDs present.
5916  * This information is not quite needed yet, but it is positioned here so
5917  * as potential problems are detected before any on-disk change is done.
5918  */
5919  oldestActiveXID = PrescanPreparedTransactions(NULL, NULL);
5920 
5921  /*
5922  * Allow ordinary WAL segment creation before possibly switching to a new
5923  * timeline, which creates a new segment, and after the last ReadRecord().
5924  */
5926 
5927  /*
5928  * Consider whether we need to assign a new timeline ID.
5929  *
5930  * If we did archive recovery, we always assign a new ID. This handles a
5931  * couple of issues. If we stopped short of the end of WAL during
5932  * recovery, then we are clearly generating a new timeline and must assign
5933  * it a unique new ID. Even if we ran to the end, modifying the current
5934  * last segment is problematic because it may result in trying to
5935  * overwrite an already-archived copy of that segment, and we encourage
5936  * DBAs to make their archive_commands reject that. We can dodge the
5937  * problem by making the new active segment have a new timeline ID.
5938  *
5939  * In a normal crash recovery, we can just extend the timeline we were in.
5940  */
5941  newTLI = endOfRecoveryInfo->lastRecTLI;
5943  {
5944  newTLI = findNewestTimeLine(recoveryTargetTLI) + 1;
5945  ereport(LOG,
5946  (errmsg("selected new timeline ID: %u", newTLI)));
5947 
5948  /*
5949  * Make a writable copy of the last WAL segment. (Note that we also
5950  * have a copy of the last block of the old WAL in
5951  * endOfRecovery->lastPage; we will use that below.)
5952  */
5953  XLogInitNewTimeline(EndOfLogTLI, EndOfLog, newTLI);
5954 
5955  /*
5956  * Remove the signal files out of the way, so that we don't
5957  * accidentally re-enter archive recovery mode in a subsequent crash.
5958  */
5959  if (endOfRecoveryInfo->standby_signal_file_found)
5961 
5962  if (endOfRecoveryInfo->recovery_signal_file_found)
5964 
5965  /*
5966  * Write the timeline history file, and have it archived. After this
5967  * point (or rather, as soon as the file is archived), the timeline
5968  * will appear as "taken" in the WAL archive and to any standby
5969  * servers. If we crash before actually switching to the new
5970  * timeline, standby servers will nevertheless think that we switched
5971  * to the new timeline, and will try to connect to the new timeline.
5972  * To minimize the window for that, try to do as little as possible
5973  * between here and writing the end-of-recovery record.
5974  */
5976  EndOfLog, endOfRecoveryInfo->recoveryStopReason);
5977 
5978  ereport(LOG,
5979  (errmsg("archive recovery complete")));
5980  }
5981 
5982  /* Save the selected TimeLineID in shared memory, too */
5984  XLogCtl->InsertTimeLineID = newTLI;
5985  XLogCtl->PrevTimeLineID = endOfRecoveryInfo->lastRecTLI;
5987 
5988  /*
5989  * Actually, if WAL ended in an incomplete record, skip the parts that
5990  * made it through and start writing after the portion that persisted.
5991  * (It's critical to first write an OVERWRITE_CONTRECORD message, which
5992  * we'll do as soon as we're open for writing new WAL.)
5993  */
5995  {
5996  /*
5997  * We should only have a missingContrecPtr if we're not switching to a
5998  * new timeline. When a timeline switch occurs, WAL is copied from the
5999  * old timeline to the new only up to the end of the last complete
6000  * record, so there can't be an incomplete WAL record that we need to
6001  * disregard.
6002  */
6003  Assert(newTLI == endOfRecoveryInfo->lastRecTLI);
6005  EndOfLog = missingContrecPtr;
6006  }
6007 
6008  /*
6009  * Prepare to write WAL starting at EndOfLog location, and init xlog
6010  * buffer cache using the block containing the last record from the
6011  * previous incarnation.
6012  */
6013  Insert = &XLogCtl->Insert;
6014  Insert->PrevBytePos = XLogRecPtrToBytePos(endOfRecoveryInfo->lastRec);
6015  Insert->CurrBytePos = XLogRecPtrToBytePos(EndOfLog);
6016 
6017  /*
6018  * Tricky point here: lastPage contains the *last* block that the LastRec
6019  * record spans, not the one it starts in. The last block is indeed the
6020  * one we want to use.
6021  */
6022  if (EndOfLog % XLOG_BLCKSZ != 0)
6023  {
6024  char *page;
6025  int len;
6026  int firstIdx;
6027 
6028  firstIdx = XLogRecPtrToBufIdx(EndOfLog);
6029  len = EndOfLog - endOfRecoveryInfo->lastPageBeginPtr;
6030  Assert(len < XLOG_BLCKSZ);
6031 
6032  /* Copy the valid part of the last block, and zero the rest */
6033  page = &XLogCtl->pages[firstIdx * XLOG_BLCKSZ];
6034  memcpy(page, endOfRecoveryInfo->lastPage, len);
6035  memset(page + len, 0, XLOG_BLCKSZ - len);
6036 
6037  pg_atomic_write_u64(&XLogCtl->xlblocks[firstIdx], endOfRecoveryInfo->lastPageBeginPtr + XLOG_BLCKSZ);
6038  XLogCtl->InitializedUpTo = endOfRecoveryInfo->lastPageBeginPtr + XLOG_BLCKSZ;
6039  }
6040  else
6041  {
6042  /*
6043  * There is no partial block to copy. Just set InitializedUpTo, and
6044  * let the first attempt to insert a log record to initialize the next
6045  * buffer.
6046  */
6047  XLogCtl->InitializedUpTo = EndOfLog;
6048  }
6049 
6050  /*
6051  * Update local and shared status. This is OK to do without any locks
6052  * because no other process can be reading or writing WAL yet.
6053  */
6054  LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
6058  XLogCtl->LogwrtRqst.Write = EndOfLog;
6059  XLogCtl->LogwrtRqst.Flush = EndOfLog;
6060 
6061  /*
6062  * Preallocate additional log files, if wanted.
6063  */
6064  PreallocXlogFiles(EndOfLog, newTLI);
6065 
6066  /*
6067  * Okay, we're officially UP.
6068  */
6069  InRecovery = false;
6070 
6071  /* start the archive_timeout timer and LSN running */
6072  XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
6073  XLogCtl->lastSegSwitchLSN = EndOfLog;
6074 
6075  /* also initialize latestCompletedXid, to nextXid - 1 */
6076  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
6079  LWLockRelease(ProcArrayLock);
6080 
6081  /*
6082  * Start up subtrans, if not already done for hot standby. (commit
6083  * timestamps are started below, if necessary.)
6084  */
6086  StartupSUBTRANS(oldestActiveXID);
6087 
6088  /*
6089  * Perform end of recovery actions for any SLRUs that need it.
6090  */
6091  TrimCLOG();
6092  TrimMultiXact();
6093 
6094  /*
6095  * Reload shared-memory state for prepared transactions. This needs to
6096  * happen before renaming the last partial segment of the old timeline as
6097  * it may be possible that we have to recovery some transactions from it.
6098  */
6100 
6101  /* Shut down xlogreader */
6103 
6104  /* Enable WAL writes for this backend only. */
6106 
6107  /* If necessary, write overwrite-contrecord before doing anything else */
6109  {
6112  }
6113 
6114  /*
6115  * Update full_page_writes in shared memory and write an XLOG_FPW_CHANGE
6116  * record before resource manager writes cleanup WAL records or checkpoint
6117  * record is written.
6118  */
6119  Insert->fullPageWrites = lastFullPageWrites;
6121 
6122  /*
6123  * Emit checkpoint or end-of-recovery record in XLOG, if required.
6124  */
6125  if (performedWalRecovery)
6126  promoted = PerformRecoveryXLogAction();
6127 
6128  /*
6129  * If any of the critical GUCs have changed, log them before we allow
6130  * backends to write WAL.
6131  */
6133 
6134  /* If this is archive recovery, perform post-recovery cleanup actions. */
6136  CleanupAfterArchiveRecovery(EndOfLogTLI, EndOfLog, newTLI);
6137 
6138  /*
6139  * Local WAL inserts enabled, so it's time to finish initialization of
6140  * commit timestamp.
6141  */
6143 
6144  /*
6145  * All done with end-of-recovery actions.
6146  *
6147  * Now allow backends to write WAL and update the control file status in
6148  * consequence. SharedRecoveryState, that controls if backends can write
6149  * WAL, is updated while holding ControlFileLock to prevent other backends
6150  * to look at an inconsistent state of the control file in shared memory.
6151  * There is still a small window during which backends can write WAL and
6152  * the control file is still referring to a system not in DB_IN_PRODUCTION
6153  * state while looking at the on-disk control file.
6154  *
6155  * Also, we use info_lck to update SharedRecoveryState to ensure that
6156  * there are no race conditions concerning visibility of other recent
6157  * updates to shared memory.
6158  */
6159  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6161 
6165 
6167  LWLockRelease(ControlFileLock);
6168 
6169  /*
6170  * Wake up all waiters for replay LSN. They need to report an error that
6171  * recovery was ended before reaching the target LSN.
6172  */
6174 
6175  /*
6176  * Shutdown the recovery environment. This must occur after
6177  * RecoverPreparedTransactions() (see notes in lock_twophase_recover())
6178  * and after switching SharedRecoveryState to RECOVERY_STATE_DONE so as
6179  * any session building a snapshot will not rely on KnownAssignedXids as
6180  * RecoveryInProgress() would return false at this stage. This is
6181  * particularly critical for prepared 2PC transactions, that would still
6182  * need to be included in snapshots once recovery has ended.
6183  */
6186 
6187  /*
6188  * If there were cascading standby servers connected to us, nudge any wal
6189  * sender processes to notice that we've been promoted.
6190  */
6191  WalSndWakeup(true, true);
6192 
6193  /*
6194  * If this was a promotion, request an (online) checkpoint now. This isn't
6195  * required for consistency, but the last restartpoint might be far back,
6196  * and in case of a crash, recovering from it might take a longer than is
6197  * appropriate now that we're not in standby mode anymore.
6198  */
6199  if (promoted)
6201 }
6202 
6203 /*
6204  * Callback from PerformWalRecovery(), called when we switch from crash
6205  * recovery to archive recovery mode. Updates the control file accordingly.
6206  */
6207 void
6209 {
6210  /* initialize minRecoveryPoint to this record */
6211  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6213  if (ControlFile->minRecoveryPoint < EndRecPtr)
6214  {
6215  ControlFile->minRecoveryPoint = EndRecPtr;
6216  ControlFile->minRecoveryPointTLI = replayTLI;
6217  }
6218  /* update local copy */
6221 
6222  /*
6223  * The startup process can update its local copy of minRecoveryPoint from
6224  * this point.
6225  */
6226  updateMinRecoveryPoint = true;
6227 
6229 
6230  /*
6231  * We update SharedRecoveryState while holding the lock on ControlFileLock
6232  * so both states are consistent in shared memory.
6233  */
6237 
6238  LWLockRelease(ControlFileLock);
6239 }
6240 
6241 /*
6242  * Callback from PerformWalRecovery(), called when we reach the end of backup.
6243  * Updates the control file accordingly.
6244  */
6245 void
6247 {
6248  /*
6249  * We have reached the end of base backup, as indicated by pg_control. The
6250  * data on disk is now consistent (unless minRecoveryPoint is further
6251  * ahead, which can happen if we crashed during previous recovery). Reset
6252  * backupStartPoint and backupEndPoint, and update minRecoveryPoint to
6253  * make sure we don't allow starting up at an earlier point even if
6254  * recovery is stopped and restarted soon after this.
6255  */
6256  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6257 
6258  if (ControlFile->minRecoveryPoint < EndRecPtr)
6259  {
6260  ControlFile->minRecoveryPoint = EndRecPtr;
6262  }
6263 
6266  ControlFile->backupEndRequired = false;
6268 
6269  LWLockRelease(ControlFileLock);
6270 }
6271 
6272 /*
6273  * Perform whatever XLOG actions are necessary at end of REDO.
6274  *
6275  * The goal here is to make sure that we'll be able to recover properly if
6276  * we crash again. If we choose to write a checkpoint, we'll write a shutdown
6277  * checkpoint rather than an on-line one. This is not particularly critical,
6278  * but since we may be assigning a new TLI, using a shutdown checkpoint allows
6279  * us to have the rule that TLI only changes in shutdown checkpoints, which
6280  * allows some extra error checking in xlog_redo.
6281  */
6282 static bool
6284 {
6285  bool promoted = false;
6286 
6287  /*
6288  * Perform a checkpoint to update all our recovery activity to disk.
6289  *
6290  * Note that we write a shutdown checkpoint rather than an on-line one.
6291  * This is not particularly critical, but since we may be assigning a new
6292  * TLI, using a shutdown checkpoint allows us to have the rule that TLI
6293  * only changes in shutdown checkpoints, which allows some extra error
6294  * checking in xlog_redo.
6295  *
6296  * In promotion, only create a lightweight end-of-recovery record instead
6297  * of a full checkpoint. A checkpoint is requested later, after we're
6298  * fully out of recovery mode and already accepting queries.
6299  */
6302  {
6303  promoted = true;
6304 
6305  /*
6306  * Insert a special WAL record to mark the end of recovery, since we
6307  * aren't doing a checkpoint. That means that the checkpointer process
6308  * may likely be in the middle of a time-smoothed restartpoint and
6309  * could continue to be for minutes after this. That sounds strange,
6310  * but the effect is roughly the same and it would be stranger to try
6311  * to come out of the restartpoint and then checkpoint. We request a
6312  * checkpoint later anyway, just for safety.
6313  */
6315  }
6316  else
6317  {
6320  CHECKPOINT_WAIT);
6321  }
6322 
6323  return promoted;
6324 }
6325 
6326 /*
6327  * Is the system still in recovery?
6328  *
6329  * Unlike testing InRecovery, this works in any process that's connected to
6330  * shared memory.
6331  */
6332 bool
6334 {
6335  /*
6336  * We check shared state each time only until we leave recovery mode. We
6337  * can't re-enter recovery, so there's no need to keep checking after the
6338  * shared variable has once been seen false.
6339  */
6341  return false;
6342  else
6343  {
6344  /*
6345  * use volatile pointer to make sure we make a fresh read of the
6346  * shared variable.
6347  */
6348  volatile XLogCtlData *xlogctl = XLogCtl;
6349 
6351 
6352  /*
6353  * Note: We don't need a memory barrier when we're still in recovery.
6354  * We might exit recovery immediately after return, so the caller
6355  * can't rely on 'true' meaning that we're still in recovery anyway.
6356  */
6357 
6358  return LocalRecoveryInProgress;
6359  }
6360 }
6361 
6362 /*
6363  * Returns current recovery state from shared memory.
6364  *
6365  * This returned state is kept consistent with the contents of the control
6366  * file. See details about the possible values of RecoveryState in xlog.h.
6367  */
6370 {
6371  RecoveryState retval;
6372 
6374  retval = XLogCtl->SharedRecoveryState;
6376 
6377  return retval;
6378 }
6379 
6380 /*
6381  * Is this process allowed to insert new WAL records?
6382  *
6383  * Ordinarily this is essentially equivalent to !RecoveryInProgress().
6384  * But we also have provisions for forcing the result "true" or "false"
6385  * within specific processes regardless of the global state.
6386  */
6387 bool
6389 {
6390  /*
6391  * If value is "unconditionally true" or "unconditionally false", just
6392  * return it. This provides the normal fast path once recovery is known
6393  * done.
6394  */
6395  if (LocalXLogInsertAllowed >= 0)
6396  return (bool) LocalXLogInsertAllowed;
6397 
6398  /*
6399  * Else, must check to see if we're still in recovery.
6400  */
6401  if (RecoveryInProgress())
6402  return false;
6403 
6404  /*
6405  * On exit from recovery, reset to "unconditionally true", since there is
6406  * no need to keep checking.
6407  */
6409  return true;
6410 }
6411 
6412 /*
6413  * Make XLogInsertAllowed() return true in the current process only.
6414  *
6415  * Note: it is allowed to switch LocalXLogInsertAllowed back to -1 later,
6416  * and even call LocalSetXLogInsertAllowed() again after that.
6417  *
6418  * Returns the previous value of LocalXLogInsertAllowed.
6419  */
6420 static int
6422 {
6423  int oldXLogAllowed = LocalXLogInsertAllowed;
6424 
6426 
6427  return oldXLogAllowed;
6428 }
6429 
6430 /*
6431  * Return the current Redo pointer from shared memory.
6432  *
6433  * As a side-effect, the local RedoRecPtr copy is updated.
6434  */
6435 XLogRecPtr
6437 {
6438  XLogRecPtr ptr;
6439 
6440  /*
6441  * The possibly not up-to-date copy in XlogCtl is enough. Even if we
6442  * grabbed a WAL insertion lock to read the authoritative value in
6443  * Insert->RedoRecPtr, someone might update it just after we've released
6444  * the lock.
6445  */
6447  ptr = XLogCtl->RedoRecPtr;
6449 
6450  if (RedoRecPtr < ptr)
6451  RedoRecPtr = ptr;
6452 
6453  return RedoRecPtr;
6454 }
6455 
6456 /*
6457  * Return information needed to decide whether a modified block needs a
6458  * full-page image to be included in the WAL record.
6459  *
6460  * The returned values are cached copies from backend-private memory, and
6461  * possibly out-of-date or, indeed, uninitialized, in which case they will
6462  * be InvalidXLogRecPtr and false, respectively. XLogInsertRecord will
6463  * re-check them against up-to-date values, while holding the WAL insert lock.
6464  */
6465 void
6466 GetFullPageWriteInfo(XLogRecPtr *RedoRecPtr_p, bool *doPageWrites_p)
6467 {
6468  *RedoRecPtr_p = RedoRecPtr;
6469  *doPageWrites_p = doPageWrites;
6470 }
6471 
6472 /*
6473  * GetInsertRecPtr -- Returns the current insert position.
6474  *
6475  * NOTE: The value *actually* returned is the position of the last full
6476  * xlog page. It lags behind the real insert position by at most 1 page.
6477  * For that, we don't need to scan through WAL insertion locks, and an
6478  * approximation is enough for the current usage of this function.
6479  */
6480 XLogRecPtr
6482 {
6483  XLogRecPtr recptr;
6484 
6486  recptr = XLogCtl->LogwrtRqst.Write;
6488 
6489  return recptr;
6490 }
6491 
6492 /*
6493  * GetFlushRecPtr -- Returns the current flush position, ie, the last WAL
6494  * position known to be fsync'd to disk. This should only be used on a
6495  * system that is known not to be in recovery.
6496  */
6497 XLogRecPtr
6499 {
6501 
6503 
6504  /*
6505  * If we're writing and flushing WAL, the time line can't be changing, so
6506  * no lock is required.
6507  */
6508  if (insertTLI)
6509  *insertTLI = XLogCtl->InsertTimeLineID;
6510 
6511  return LogwrtResult.Flush;
6512 }
6513 
6514 /*
6515  * GetWALInsertionTimeLine -- Returns the current timeline of a system that
6516  * is not in recovery.
6517  */
6518 TimeLineID
6520 {
6522 
6523  /* Since the value can't be changing, no lock is required. */
6524  return XLogCtl->InsertTimeLineID;
6525 }
6526 
6527 /*
6528  * GetWALInsertionTimeLineIfSet -- If the system is not in recovery, returns
6529  * the WAL insertion timeline; else, returns 0. Wherever possible, use
6530  * GetWALInsertionTimeLine() instead, since it's cheaper. Note that this
6531  * function decides recovery has ended as soon as the insert TLI is set, which
6532  * happens before we set XLogCtl->SharedRecoveryState to RECOVERY_STATE_DONE.
6533  */
6534 TimeLineID
6536 {
6537  TimeLineID insertTLI;
6538 
6540  insertTLI = XLogCtl->InsertTimeLineID;
6542 
6543  return insertTLI;
6544 }
6545 
6546 /*
6547  * GetLastImportantRecPtr -- Returns the LSN of the last important record
6548  * inserted. All records not explicitly marked as unimportant are considered
6549  * important.
6550  *
6551  * The LSN is determined by computing the maximum of
6552  * WALInsertLocks[i].lastImportantAt.
6553  */
6554 XLogRecPtr
6556 {
6558  int i;
6559 
6560  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
6561  {
6562  XLogRecPtr last_important;
6563 
6564  /*
6565  * Need to take a lock to prevent torn reads of the LSN, which are
6566  * possible on some of the supported platforms. WAL insert locks only
6567  * support exclusive mode, so we have to use that.
6568  */
6570  last_important = WALInsertLocks[i].l.lastImportantAt;
6571  LWLockRelease(&WALInsertLocks[i].l.lock);
6572 
6573  if (res < last_important)
6574  res = last_important;
6575  }
6576 
6577  return res;
6578 }
6579 
6580 /*
6581  * Get the time and LSN of the last xlog segment switch
6582  */
6583 pg_time_t
6585 {
6586  pg_time_t result;
6587 
6588  /* Need WALWriteLock, but shared lock is sufficient */
6589  LWLockAcquire(WALWriteLock, LW_SHARED);
6590  result = XLogCtl->lastSegSwitchTime;
6591  *lastSwitchLSN = XLogCtl->lastSegSwitchLSN;
6592  LWLockRelease(WALWriteLock);
6593 
6594  return result;
6595 }
6596 
6597 /*
6598  * This must be called ONCE during postmaster or standalone-backend shutdown
6599  */
6600 void
6602 {
6603  /*
6604  * We should have an aux process resource owner to use, and we should not
6605  * be in a transaction that's installed some other resowner.
6606  */
6608  Assert(CurrentResourceOwner == NULL ||
6611 
6612  /* Don't be chatty in standalone mode */
6614  (errmsg("shutting down")));
6615 
6616  /*
6617  * Signal walsenders to move to stopping state.
6618  */
6620 
6621  /*
6622  * Wait for WAL senders to be in stopping state. This prevents commands
6623  * from writing new WAL.
6624  */
6626 
6627  if (RecoveryInProgress())
6629  else
6630  {
6631  /*
6632  * If archiving is enabled, rotate the last XLOG file so that all the
6633  * remaining records are archived (postmaster wakes up the archiver
6634  * process one more time at the end of shutdown). The checkpoint
6635  * record will go to the next XLOG file and won't be archived (yet).
6636  */
6637  if (XLogArchivingActive())
6638  RequestXLogSwitch(false);
6639 
6641  }
6642 }
6643 
6644 /*
6645  * Log start of a checkpoint.
6646  */
6647 static void
6648 LogCheckpointStart(int flags, bool restartpoint)
6649 {
6650  if (restartpoint)
6651  ereport(LOG,
6652  /* translator: the placeholders show checkpoint options */
6653  (errmsg("restartpoint starting:%s%s%s%s%s%s%s%s",
6654  (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
6655  (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
6656  (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
6657  (flags & CHECKPOINT_FORCE) ? " force" : "",
6658  (flags & CHECKPOINT_WAIT) ? " wait" : "",
6659  (flags & CHECKPOINT_CAUSE_XLOG) ? " wal" : "",
6660  (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "",
6661  (flags & CHECKPOINT_FLUSH_ALL) ? " flush-all" : "")));
6662  else
6663  ereport(LOG,
6664  /* translator: the placeholders show checkpoint options */
6665  (errmsg("checkpoint starting:%s%s%s%s%s%s%s%s",
6666  (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
6667  (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
6668  (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
6669  (flags & CHECKPOINT_FORCE) ? " force" : "",
6670  (flags & CHECKPOINT_WAIT) ? " wait" : "",
6671  (flags & CHECKPOINT_CAUSE_XLOG) ? " wal" : "",
6672  (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "",
6673  (flags & CHECKPOINT_FLUSH_ALL) ? " flush-all" : "")));
6674 }
6675 
6676 /*
6677  * Log end of a checkpoint.
6678  */
6679 static void
6680 LogCheckpointEnd(bool restartpoint)
6681 {
6682  long write_msecs,
6683  sync_msecs,
6684  total_msecs,
6685  longest_msecs,
6686  average_msecs;
6687  uint64 average_sync_time;
6688 
6690 
6693 
6696 
6697  /* Accumulate checkpoint timing summary data, in milliseconds. */
6698  PendingCheckpointerStats.write_time += write_msecs;
6699  PendingCheckpointerStats.sync_time += sync_msecs;
6700 
6701  /*
6702  * All of the published timing statistics are accounted for. Only
6703  * continue if a log message is to be written.
6704  */
6705  if (!log_checkpoints)
6706  return;
6707 
6710 
6711  /*
6712  * Timing values returned from CheckpointStats are in microseconds.
6713  * Convert to milliseconds for consistent printing.
6714  */
6715  longest_msecs = (long) ((CheckpointStats.ckpt_longest_sync + 999) / 1000);
6716 
6717  average_sync_time = 0;
6719  average_sync_time = CheckpointStats.ckpt_agg_sync_time /
6721  average_msecs = (long) ((average_sync_time + 999) / 1000);
6722 
6723  /*
6724  * ControlFileLock is not required to see ControlFile->checkPoint and
6725  * ->checkPointCopy here as we are the only updator of those variables at
6726  * this moment.
6727  */
6728  if (restartpoint)
6729  ereport(LOG,
6730  (errmsg("restartpoint complete: wrote %d buffers (%.1f%%), "
6731  "wrote %d SLRU buffers; %d WAL file(s) added, "
6732  "%d removed, %d recycled; write=%ld.%03d s, "
6733  "sync=%ld.%03d s, total=%ld.%03d s; sync files=%d, "
6734  "longest=%ld.%03d s, average=%ld.%03d s; distance=%d kB, "
6735  "estimate=%d kB; lsn=%X/%X, redo lsn=%X/%X",
6737  (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
6742  write_msecs / 1000, (int) (write_msecs % 1000),
6743  sync_msecs / 1000, (int) (sync_msecs % 1000),
6744  total_msecs / 1000, (int) (total_msecs % 1000),
6746  longest_msecs / 1000, (int) (longest_msecs % 1000),
6747  average_msecs / 1000, (int) (average_msecs % 1000),
6748  (int) (PrevCheckPointDistance / 1024.0),
6749  (int) (CheckPointDistanceEstimate / 1024.0),
6752  else
6753  ereport(LOG,
6754  (errmsg("checkpoint complete: wrote %d buffers (%.1f%%), "
6755  "wrote %d SLRU buffers; %d WAL file(s) added, "
6756  "%d removed, %d recycled; write=%ld.%03d s, "
6757  "sync=%ld.%03d s, total=%ld.%03d s; sync files=%d, "
6758  "longest=%ld.%03d s, average=%ld.%03d s; distance=%d kB, "
6759  "estimate=%d kB; lsn=%X/%X, redo lsn=%X/%X",
6761  (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
6766  write_msecs / 1000, (int) (write_msecs % 1000),
6767  sync_msecs / 1000, (int) (sync_msecs % 1000),
6768  total_msecs / 1000, (int) (total_msecs % 1000),
6770  longest_msecs / 1000, (int) (longest_msecs % 1000),
6771  average_msecs / 1000, (int) (average_msecs % 1000),
6772  (int) (PrevCheckPointDistance / 1024.0),
6773  (int) (CheckPointDistanceEstimate / 1024.0),
6776 }
6777 
6778 /*
6779  * Update the estimate of distance between checkpoints.
6780  *
6781  * The estimate is used to calculate the number of WAL segments to keep
6782  * preallocated, see XLOGfileslop().
6783  */
6784 static void
6786 {
6787  /*
6788  * To estimate the number of segments consumed between checkpoints, keep a
6789  * moving average of the amount of WAL generated in previous checkpoint
6790  * cycles. However, if the load is bursty, with quiet periods and busy
6791  * periods, we want to cater for the peak load. So instead of a plain
6792  * moving average, let the average decline slowly if the previous cycle
6793  * used less WAL than estimated, but bump it up immediately if it used
6794  * more.
6795  *
6796  * When checkpoints are triggered by max_wal_size, this should converge to
6797  * CheckpointSegments * wal_segment_size,
6798  *
6799  * Note: This doesn't pay any attention to what caused the checkpoint.
6800  * Checkpoints triggered manually with CHECKPOINT command, or by e.g.
6801  * starting a base backup, are counted the same as those created
6802  * automatically. The slow-decline will largely mask them out, if they are
6803  * not frequent. If they are frequent, it seems reasonable to count them
6804  * in as any others; if you issue a manual checkpoint every 5 minutes and
6805  * never let a timed checkpoint happen, it makes sense to base the
6806  * preallocation on that 5 minute interval rather than whatever
6807  * checkpoint_timeout is set to.
6808  */
6809  PrevCheckPointDistance = nbytes;
6810  if (CheckPointDistanceEstimate < nbytes)
6811  CheckPointDistanceEstimate = nbytes;
6812  else
6814  (0.90 * CheckPointDistanceEstimate + 0.10 * (double) nbytes);
6815 }
6816 
6817 /*
6818  * Update the ps display for a process running a checkpoint. Note that
6819  * this routine should not do any allocations so as it can be called
6820  * from a critical section.
6821  */
6822 static void
6823 update_checkpoint_display(int flags, bool restartpoint, bool reset)
6824 {
6825  /*
6826  * The status is reported only for end-of-recovery and shutdown
6827  * checkpoints or shutdown restartpoints. Updating the ps display is
6828  * useful in those situations as it may not be possible to rely on
6829  * pg_stat_activity to see the status of the checkpointer or the startup
6830  * process.
6831  */
6832  if ((flags & (CHECKPOINT_END_OF_RECOVERY | CHECKPOINT_IS_SHUTDOWN)) == 0)
6833  return;
6834 
6835  if (reset)
6836  set_ps_display("");
6837  else
6838  {
6839  char activitymsg[128];
6840 
6841  snprintf(activitymsg, sizeof(activitymsg), "performing %s%s%s",
6842  (flags & CHECKPOINT_END_OF_RECOVERY) ? "end-of-recovery " : "",
6843  (flags & CHECKPOINT_IS_SHUTDOWN) ? "shutdown " : "",
6844  restartpoint ? "restartpoint" : "checkpoint");
6845  set_ps_display(activitymsg);
6846  }
6847 }
6848 
6849 
6850 /*
6851  * Perform a checkpoint --- either during shutdown, or on-the-fly
6852  *
6853  * flags is a bitwise OR of the following:
6854  * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
6855  * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
6856  * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
6857  * ignoring checkpoint_completion_target parameter.
6858  * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
6859  * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
6860  * CHECKPOINT_END_OF_RECOVERY).
6861  * CHECKPOINT_FLUSH_ALL: also flush buffers of unlogged tables.
6862  *
6863  * Note: flags contains other bits, of interest here only for logging purposes.
6864  * In particular note that this routine is synchronous and does not pay
6865  * attention to CHECKPOINT_WAIT.
6866  *
6867  * If !shutdown then we are writing an online checkpoint. An XLOG_CHECKPOINT_REDO
6868  * record is inserted into WAL at the logical location of the checkpoint, before
6869  * flushing anything to disk, and when the checkpoint is eventually completed,
6870  * and it is from this point that WAL replay will begin in the case of a recovery
6871  * from this checkpoint. Once everything is written to disk, an
6872  * XLOG_CHECKPOINT_ONLINE record is written to complete the checkpoint, and
6873  * points back to the earlier XLOG_CHECKPOINT_REDO record. This mechanism allows
6874  * other write-ahead log records to be written while the checkpoint is in
6875  * progress, but we must be very careful about order of operations. This function
6876  * may take many minutes to execute on a busy system.
6877  *
6878  * On the other hand, when shutdown is true, concurrent insertion into the
6879  * write-ahead log is impossible, so there is no need for two separate records.
6880  * In this case, we only insert an XLOG_CHECKPOINT_SHUTDOWN record, and it's
6881  * both the record marking the completion of the checkpoint and the location
6882  * from which WAL replay would begin if needed.
6883  *
6884  * Returns true if a new checkpoint was performed, or false if it was skipped
6885  * because the system was idle.
6886  */
6887 bool
6889 {
6890  bool shutdown;
6891  CheckPoint checkPoint;
6892  XLogRecPtr recptr;
6893  XLogSegNo _logSegNo;
6895  uint32 freespace;
6896  XLogRecPtr PriorRedoPtr;
6897  XLogRecPtr last_important_lsn;
6898  VirtualTransactionId *vxids;
6899  int nvxids;
6900  int oldXLogAllowed = 0;
6901 
6902  /*
6903  * An end-of-recovery checkpoint is really a shutdown checkpoint, just
6904  * issued at a different time.
6905  */
6907  shutdown = true;
6908  else
6909  shutdown = false;
6910 
6911  /* sanity check */
6912  if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
6913  elog(ERROR, "can't create a checkpoint during recovery");
6914 
6915  /*
6916  * Prepare to accumulate statistics.
6917  *
6918  * Note: because it is possible for log_checkpoints to change while a
6919  * checkpoint proceeds, we always accumulate stats, even if
6920  * log_checkpoints is currently off.
6921  */
6922  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
6924 
6925  /*
6926  * Let smgr prepare for checkpoint; this has to happen outside the
6927  * critical section and before we determine the REDO pointer. Note that
6928  * smgr must not do anything that'd have to be undone if we decide no
6929  * checkpoint is needed.
6930  */
6932 
6933  /*
6934  * Use a critical section to force system panic if we have trouble.
6935  */
6937 
6938  if (shutdown)
6939  {
6940  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6943  LWLockRelease(ControlFileLock);
6944  }
6945 
6946  /* Begin filling in the checkpoint WAL record */
6947  MemSet(&checkPoint, 0, sizeof(checkPoint));
6948  checkPoint.time = (pg_time_t) time(NULL);
6949 
6950  /*
6951  * For Hot Standby, derive the oldestActiveXid before we fix the redo
6952  * pointer. This allows us to begin accumulating changes to assemble our
6953  * starting snapshot of locks and transactions.
6954  */
6955  if (!shutdown && XLogStandbyInfoActive())
6957  else
6959 
6960  /*
6961  * Get location of last important record before acquiring insert locks (as
6962  * GetLastImportantRecPtr() also locks WAL locks).
6963  */
6964  last_important_lsn = GetLastImportantRecPtr();
6965 
6966  /*
6967  * If this isn't a shutdown or forced checkpoint, and if there has been no
6968  * WAL activity requiring a checkpoint, skip it. The idea here is to
6969  * avoid inserting duplicate checkpoints when the system is idle.
6970  */
6972  CHECKPOINT_FORCE)) == 0)
6973  {
6974  if (last_important_lsn == ControlFile->checkPoint)
6975  {
6976  END_CRIT_SECTION();
6977  ereport(DEBUG1,
6978  (errmsg_internal("checkpoint skipped because system is idle")));
6979  return false;
6980  }
6981  }
6982 
6983  /*
6984  * An end-of-recovery checkpoint is created before anyone is allowed to
6985  * write WAL. To allow us to write the checkpoint record, temporarily
6986  * enable XLogInsertAllowed.
6987  */
6988  if (flags & CHECKPOINT_END_OF_RECOVERY)
6989  oldXLogAllowed = LocalSetXLogInsertAllowed();
6990 
6991  checkPoint.ThisTimeLineID = XLogCtl->InsertTimeLineID;
6992  if (flags & CHECKPOINT_END_OF_RECOVERY)
6993  checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
6994  else
6995  checkPoint.PrevTimeLineID = checkPoint.ThisTimeLineID;
6996 
6997  /*
6998  * We must block concurrent insertions while examining insert state.
6999  */
7001 
7002  checkPoint.fullPageWrites = Insert->fullPageWrites;
7003  checkPoint.wal_level = wal_level;
7004 
7005  if (shutdown)
7006  {
7007  XLogRecPtr curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
7008 
7009  /*
7010  * Compute new REDO record ptr = location of next XLOG record.
7011  *
7012  * Since this is a shutdown checkpoint, there can't be any concurrent
7013  * WAL insertion.
7014  */
7015  freespace = INSERT_FREESPACE(curInsert);
7016  if (freespace == 0)
7017  {
7018  if (XLogSegmentOffset(curInsert, wal_segment_size) == 0)
7019  curInsert += SizeOfXLogLongPHD;
7020  else
7021  curInsert += SizeOfXLogShortPHD;
7022  }
7023  checkPoint.redo = curInsert;
7024 
7025  /*
7026  * Here we update the shared RedoRecPtr for future XLogInsert calls;
7027  * this must be done while holding all the insertion locks.
7028  *
7029  * Note: if we fail to complete the checkpoint, RedoRecPtr will be
7030  * left pointing past where it really needs to point. This is okay;
7031  * the only consequence is that XLogInsert might back up whole buffers
7032  * that it didn't really need to. We can't postpone advancing
7033  * RedoRecPtr because XLogInserts that happen while we are dumping
7034  * buffers must assume that their buffer changes are not included in
7035  * the checkpoint.
7036  */
7037  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
7038  }
7039 
7040  /*
7041  * Now we can release the WAL insertion locks, allowing other xacts to
7042  * proceed while we are flushing disk buffers.
7043  */
7045 
7046  /*
7047  * If this is an online checkpoint, we have not yet determined the redo
7048  * point. We do so now by inserting the special XLOG_CHECKPOINT_REDO
7049  * record; the LSN at which it starts becomes the new redo pointer. We
7050  * don't do this for a shutdown checkpoint, because in that case no WAL
7051  * can be written between the redo point and the insertion of the
7052  * checkpoint record itself, so the checkpoint record itself serves to
7053  * mark the redo point.
7054  */
7055  if (!shutdown)
7056  {
7057  /* Include WAL level in record for WAL summarizer's benefit. */
7058  XLogBeginInsert();
7059  XLogRegisterData((char *) &wal_level, sizeof(wal_level));
7060  (void) XLogInsert(RM_XLOG_ID, XLOG_CHECKPOINT_REDO);
7061 
7062  /*
7063  * XLogInsertRecord will have updated XLogCtl->Insert.RedoRecPtr in
7064  * shared memory and RedoRecPtr in backend-local memory, but we need
7065  * to copy that into the record that will be inserted when the
7066  * checkpoint is complete.
7067  */
7068  checkPoint.redo = RedoRecPtr;
7069  }
7070 
7071  /* Update the info_lck-protected copy of RedoRecPtr as well */
7073  XLogCtl->RedoRecPtr = checkPoint.redo;
7075 
7076  /*
7077  * If enabled, log checkpoint start. We postpone this until now so as not
7078  * to log anything if we decided to skip the checkpoint.
7079  */
7080  if (log_checkpoints)
7081  LogCheckpointStart(flags, false);
7082 
7083  /* Update the process title */
7084  update_checkpoint_display(flags, false, false);
7085 
7086  TRACE_POSTGRESQL_CHECKPOINT_START(flags);
7087 
7088  /*
7089  * Get the other info we need for the checkpoint record.
7090  *
7091  * We don't need to save oldestClogXid in the checkpoint, it only matters
7092  * for the short period in which clog is being truncated, and if we crash
7093  * during that we'll redo the clog truncation and fix up oldestClogXid
7094  * there.
7095  */
7096  LWLockAcquire(XidGenLock, LW_SHARED);
7097  checkPoint.nextXid = TransamVariables->nextXid;
7098  checkPoint.oldestXid = TransamVariables->oldestXid;
7100  LWLockRelease(XidGenLock);
7101 
7102  LWLockAcquire(CommitTsLock, LW_SHARED);
7105  LWLockRelease(CommitTsLock);
7106 
7107  LWLockAcquire(OidGenLock, LW_SHARED);
7108  checkPoint.nextOid = TransamVariables->nextOid;
7109  if (!shutdown)
7110  checkPoint.nextOid += TransamVariables->oidCount;
7111  LWLockRelease(OidGenLock);
7112 
7113  MultiXactGetCheckptMulti(shutdown,
7114  &checkPoint.nextMulti,
7115  &checkPoint.nextMultiOffset,
7116  &checkPoint.oldestMulti,
7117  &checkPoint.oldestMultiDB);
7118 
7119  /*
7120  * Having constructed the checkpoint record, ensure all shmem disk buffers
7121  * and commit-log buffers are flushed to disk.
7122  *
7123  * This I/O could fail for various reasons. If so, we will fail to
7124  * complete the checkpoint, but there is no reason to force a system
7125  * panic. Accordingly, exit critical section while doing it.
7126  */
7127  END_CRIT_SECTION();
7128 
7129  /*
7130  * In some cases there are groups of actions that must all occur on one
7131  * side or the other of a checkpoint record. Before flushing the
7132  * checkpoint record we must explicitly wait for any backend currently
7133  * performing those groups of actions.
7134  *
7135  * One example is end of transaction, so we must wait for any transactions
7136  * that are currently in commit critical sections. If an xact inserted
7137  * its commit record into XLOG just before the REDO point, then a crash
7138  * restart from the REDO point would not replay that record, which means
7139  * that our flushing had better include the xact's update of pg_xact. So
7140  * we wait till he's out of his commit critical section before proceeding.
7141  * See notes in RecordTransactionCommit().
7142  *
7143  * Because we've already released the insertion locks, this test is a bit
7144  * fuzzy: it is possible that we will wait for xacts we didn't really need
7145  * to wait for. But the delay should be short and it seems better to make
7146  * checkpoint take a bit longer than to hold off insertions longer than
7147  * necessary. (In fact, the whole reason we have this issue is that xact.c
7148  * does commit record XLOG insertion and clog update as two separate steps
7149  * protected by different locks, but again that seems best on grounds of
7150  * minimizing lock contention.)
7151  *
7152  * A transaction that has not yet set delayChkptFlags when we look cannot
7153  * be at risk, since it has not inserted its commit record yet; and one
7154  * that's already cleared it is not at risk either, since it's done fixing
7155  * clog and we will correctly flush the update below. So we cannot miss
7156  * any xacts we need to wait for.
7157  */
7159  if (nvxids > 0)
7160  {
7161  do
7162  {
7163  /*
7164  * Keep absorbing fsync requests while we wait. There could even
7165  * be a deadlock if we don't, if the process that prevents the
7166  * checkpoint is trying to add a request to the queue.
7167  */
7169 
7170  pgstat_report_wait_start(WAIT_EVENT_CHECKPOINT_DELAY_START);
7171  pg_usleep(10000L); /* wait for 10 msec */
7173  } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids,
7175  }
7176  pfree(vxids);
7177 
7178  CheckPointGuts(checkPoint.redo, flags);
7179 
7181  if (nvxids > 0)
7182  {
7183  do
7184  {
7186 
7187  pgstat_report_wait_start(WAIT_EVENT_CHECKPOINT_DELAY_COMPLETE);
7188  pg_usleep(10000L); /* wait for 10 msec */
7190  } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids,
7192  }
7193  pfree(vxids);
7194 
7195  /*
7196  * Take a snapshot of running transactions and write this to WAL. This
7197  * allows us to reconstruct the state of running transactions during
7198  * archive recovery, if required. Skip, if this info disabled.
7199  *
7200  * If we are shutting down, or Startup process is completing crash
7201  * recovery we don't need to write running xact data.
7202  */
7203  if (!shutdown && XLogStandbyInfoActive())
7205 
7207 
7208  /*
7209  * Now insert the checkpoint record into XLOG.
7210  */
7211  XLogBeginInsert();
7212  XLogRegisterData((char *) (&checkPoint), sizeof(checkPoint));
7213  recptr = XLogInsert(RM_XLOG_ID,
7214  shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
7216 
7217  XLogFlush(recptr);
7218 
7219  /*
7220  * We mustn't write any new WAL after a shutdown checkpoint, or it will be
7221  * overwritten at next startup. No-one should even try, this just allows
7222  * sanity-checking. In the case of an end-of-recovery checkpoint, we want
7223  * to just temporarily disable writing until the system has exited
7224  * recovery.
7225  */
7226  if (shutdown)
7227  {
7228  if (flags & CHECKPOINT_END_OF_RECOVERY)
7229  LocalXLogInsertAllowed = oldXLogAllowed;
7230  else
7231  LocalXLogInsertAllowed = 0; /* never again write WAL */
7232  }
7233 
7234  /*
7235  * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
7236  * = end of actual checkpoint record.
7237  */
7238  if (shutdown && checkPoint.redo != ProcLastRecPtr)
7239  ereport(PANIC,
7240  (errmsg("concurrent write-ahead log activity while database system is shutting down")));
7241 
7242  /*
7243  * Remember the prior checkpoint's redo ptr for
7244  * UpdateCheckPointDistanceEstimate()
7245  */
7246  PriorRedoPtr = ControlFile->checkPointCopy.redo;
7247 
7248  /*
7249  * Update the control file.
7250  */
7251  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7252  if (shutdown)
7255  ControlFile->checkPointCopy = checkPoint;
7256  /* crash recovery should always recover to the end of WAL */
7259 
7260  /*
7261  * Persist unloggedLSN value. It's reset on crash recovery, so this goes
7262  * unused on non-shutdown checkpoints, but seems useful to store it always
7263  * for debugging purposes.
7264  */
7266 
7268  LWLockRelease(ControlFileLock);
7269 
7270  /* Update shared-memory copy of checkpoint XID/epoch */
7272  XLogCtl->ckptFullXid = checkPoint.nextXid;
7274 
7275  /*
7276  * We are now done with critical updates; no need for system panic if we
7277  * have trouble while fooling with old log segments.
7278  */
7279  END_CRIT_SECTION();
7280 
7281  /*
7282  * WAL summaries end when the next XLOG_CHECKPOINT_REDO or
7283  * XLOG_CHECKPOINT_SHUTDOWN record is reached. This is the first point
7284  * where (a) we're not inside of a critical section and (b) we can be
7285  * certain that the relevant record has been flushed to disk, which must
7286  * happen before it can be summarized.
7287  *
7288  * If this is a shutdown checkpoint, then this happens reasonably
7289  * promptly: we've only just inserted and flushed the
7290  * XLOG_CHECKPOINT_SHUTDOWN record. If this is not a shutdown checkpoint,
7291  * then this might not be very prompt at all: the XLOG_CHECKPOINT_REDO
7292  * record was written before we began flushing data to disk, and that
7293  * could be many minutes ago at this point. However, we don't XLogFlush()
7294  * after inserting that record, so we're not guaranteed that it's on disk
7295  * until after the above call that flushes the XLOG_CHECKPOINT_ONLINE
7296  * record.
7297  */
7299 
7300  /*
7301  * Let smgr do post-checkpoint cleanup (eg, deleting old files).
7302  */
7304 
7305  /*
7306  * Update the average distance between checkpoints if the prior checkpoint
7307  * exists.
7308  */
7309  if (PriorRedoPtr != InvalidXLogRecPtr)
7311 
7312  /*
7313  * Delete old log files, those no longer needed for last checkpoint to
7314  * prevent the disk holding the xlog from growing full.
7315  */
7317  KeepLogSeg(recptr, &_logSegNo);
7319  _logSegNo, InvalidOid,
7321  {
7322  /*
7323  * Some slots have been invalidated; recalculate the old-segment
7324  * horizon, starting again from RedoRecPtr.
7325  */
7327  KeepLogSeg(recptr, &_logSegNo);
7328  }
7329  _logSegNo--;
7330  RemoveOldXlogFiles(_logSegNo, RedoRecPtr, recptr,
7331  checkPoint.ThisTimeLineID);
7332 
7333  /*
7334  * Make more log segments if needed. (Do this after recycling old log
7335  * segments, since that may supply some of the needed files.)
7336  */
7337  if (!shutdown)
7338  PreallocXlogFiles(recptr, checkPoint.ThisTimeLineID);
7339 
7340  /*
7341  * Truncate pg_subtrans if possible. We can throw away all data before
7342  * the oldest XMIN of any running transaction. No future transaction will
7343  * attempt to reference any pg_subtrans entry older than that (see Asserts
7344  * in subtrans.c). During recovery, though, we mustn't do this because
7345  * StartupSUBTRANS hasn't been called yet.
7346  */
7347  if (!RecoveryInProgress())
7349 
7350  /* Real work is done; log and update stats. */
7351  LogCheckpointEnd(false);
7352 
7353  /* Reset the process title */
7354  update_checkpoint_display(flags, false, true);
7355 
7356  TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
7357  NBuffers,
7361 
7362  return true;
7363 }
7364 
7365 /*
7366  * Mark the end of recovery in WAL though without running a full checkpoint.
7367  * We can expect that a restartpoint is likely to be in progress as we
7368  * do this, though we are unwilling to wait for it to complete.
7369  *
7370  * CreateRestartPoint() allows for the case where recovery may end before
7371  * the restartpoint completes so there is no concern of concurrent behaviour.
7372  */
7373 static void
7375 {
7376  xl_end_of_recovery xlrec;
7377  XLogRecPtr recptr;
7378 
7379  /* sanity check */
7380  if (!RecoveryInProgress())
7381  elog(ERROR, "can only be used to end recovery");
7382 
7383  xlrec.end_time = GetCurrentTimestamp();
7384  xlrec.wal_level = wal_level;
7385 
7390 
7392 
7393  XLogBeginInsert();
7394  XLogRegisterData((char *) &xlrec, sizeof(xl_end_of_recovery));
7395  recptr = XLogInsert(RM_XLOG_ID, XLOG_END_OF_RECOVERY);
7396 
7397  XLogFlush(recptr);
7398 
7399  /*
7400  * Update the control file so that crash recovery can follow the timeline
7401  * changes to this point.
7402  */
7403  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7404  ControlFile->minRecoveryPoint = recptr;
7407  LWLockRelease(ControlFileLock);
7408 
7409  END_CRIT_SECTION();
7410 }
7411 
7412 /*
7413  * Write an OVERWRITE_CONTRECORD message.
7414  *
7415  * When on WAL replay we expect a continuation record at the start of a page
7416  * that is not there, recovery ends and WAL writing resumes at that point.
7417  * But it's wrong to resume writing new WAL back at the start of the record
7418  * that was broken, because downstream consumers of that WAL (physical
7419  * replicas) are not prepared to "rewind". So the first action after
7420  * finishing replay of all valid WAL must be to write a record of this type
7421  * at the point where the contrecord was missing; to support xlogreader
7422  * detecting the special case, XLP_FIRST_IS_OVERWRITE_CONTRECORD is also added
7423  * to the page header where the record occurs. xlogreader has an ad-hoc
7424  * mechanism to report metadata about the broken record, which is what we
7425  * use here.
7426  *
7427  * At replay time, XLP_FIRST_IS_OVERWRITE_CONTRECORD instructs xlogreader to
7428  * skip the record it was reading, and pass back the LSN of the skipped
7429  * record, so that its caller can verify (on "replay" of that record) that the
7430  * XLOG_OVERWRITE_CONTRECORD matches what was effectively overwritten.
7431  *
7432  * 'aborted_lsn' is the beginning position of the record that was incomplete.
7433  * It is included in the WAL record. 'pagePtr' and 'newTLI' point to the
7434  * beginning of the XLOG page where the record is to be inserted. They must
7435  * match the current WAL insert position, they're passed here just so that we
7436  * can verify that.
7437  */
7438 static XLogRecPtr
7440  TimeLineID newTLI)
7441 {
7443  XLogRecPtr recptr;
7444  XLogPageHeader pagehdr;
7445  XLogRecPtr startPos;
7446 
7447  /* sanity checks */
7448  if (!RecoveryInProgress())
7449  elog(ERROR, "can only be used at end of recovery");
7450  if (pagePtr % XLOG_BLCKSZ != 0)
7451  elog(ERROR, "invalid position for missing continuation record %X/%X",
7452  LSN_FORMAT_ARGS(pagePtr));
7453 
7454  /* The current WAL insert position should be right after the page header */
7455  startPos = pagePtr;
7456  if (XLogSegmentOffset(startPos, wal_segment_size) == 0)
7457  startPos += SizeOfXLogLongPHD;
7458  else
7459  startPos += SizeOfXLogShortPHD;
7460  recptr = GetXLogInsertRecPtr();
7461  if (recptr != startPos)
7462  elog(ERROR, "invalid WAL insert position %X/%X for OVERWRITE_CONTRECORD",
7463  LSN_FORMAT_ARGS(recptr));
7464 
7466 
7467  /*
7468  * Initialize the XLOG page header (by GetXLogBuffer), and set the
7469  * XLP_FIRST_IS_OVERWRITE_CONTRECORD flag.
7470  *
7471  * No other backend is allowed to write WAL yet, so acquiring the WAL
7472  * insertion lock is just pro forma.
7473  */
7475  pagehdr = (XLogPageHeader) GetXLogBuffer(pagePtr, newTLI);
7478 
7479  /*
7480  * Insert the XLOG_OVERWRITE_CONTRECORD record as the first record on the
7481  * page. We know it becomes the first record, because no other backend is
7482  * allowed to write WAL yet.
7483  */
7484  XLogBeginInsert();
7485  xlrec.overwritten_lsn = aborted_lsn;
7487  XLogRegisterData((char *) &xlrec, sizeof(xl_overwrite_contrecord));
7488  recptr = XLogInsert(RM_XLOG_ID, XLOG_OVERWRITE_CONTRECORD);
7489 
7490  /* check that the record was inserted to the right place */
7491  if (ProcLastRecPtr != startPos)
7492  elog(ERROR, "OVERWRITE_CONTRECORD was inserted to unexpected position %X/%X",
7494 
7495  XLogFlush(recptr);
7496 
7497  END_CRIT_SECTION();
7498 
7499  return recptr;
7500 }
7501 
7502 /*
7503  * Flush all data in shared memory to disk, and fsync
7504  *
7505  * This is the common code shared between regular checkpoints and
7506  * recovery restartpoints.
7507  */
7508 static void
7509 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
7510 {
7516 
7517  /* Write out all dirty data in SLRUs and the main buffer pool */
7518  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START(flags);
7520  CheckPointCLOG();
7525  CheckPointBuffers(flags);
7526 
7527  /* Perform all queued up fsyncs */
7528  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START();
7532  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE();
7533 
7534  /* We deliberately delay 2PC checkpointing as long as possible */
7535  CheckPointTwoPhase(checkPointRedo);
7536 }
7537 
7538 /*
7539  * Save a checkpoint for recovery restart if appropriate
7540  *
7541  * This function is called each time a checkpoint record is read from XLOG.
7542  * It must determine whether the checkpoint represents a safe restartpoint or
7543  * not. If so, the checkpoint record is stashed in shared memory so that
7544  * CreateRestartPoint can consult it. (Note that the latter function is
7545  * executed by the checkpointer, while this one will be executed by the
7546  * startup process.)
7547  */
7548 static void
7550 {
7551  /*
7552  * Also refrain from creating a restartpoint if we have seen any
7553  * references to non-existent pages. Restarting recovery from the
7554  * restartpoint would not see the references, so we would lose the
7555  * cross-check that the pages belonged to a relation that was dropped
7556  * later.
7557  */
7558  if (XLogHaveInvalidPages())
7559  {
7560  elog(DEBUG2,
7561  "could not record restart point at %X/%X because there "
7562  "are unresolved references to invalid pages",
7563  LSN_FORMAT_ARGS(checkPoint->redo));
7564  return;
7565  }
7566 
7567  /*
7568  * Copy the checkpoint record to shared memory, so that checkpointer can
7569  * work out the next time it wants to perform a restartpoint.
7570  */
7574  XLogCtl->lastCheckPoint = *checkPoint;
7576 }
7577 
7578 /*
7579  * Establish a restartpoint if possible.
7580  *
7581  * This is similar to CreateCheckPoint, but is used during WAL recovery
7582  * to establish a point from which recovery can roll forward without
7583  * replaying the entire recovery log.
7584  *
7585  * Returns true if a new restartpoint was established. We can only establish
7586  * a restartpoint if we have replayed a safe checkpoint record since last
7587  * restartpoint.
7588  */
7589 bool
7591 {
7592  XLogRecPtr lastCheckPointRecPtr;
7593  XLogRecPtr lastCheckPointEndPtr;
7594  CheckPoint lastCheckPoint;
7595  XLogRecPtr PriorRedoPtr;
7596  XLogRecPtr receivePtr;
7597  XLogRecPtr replayPtr;
7598  TimeLineID replayTLI;
7599  XLogRecPtr endptr;
7600  XLogSegNo _logSegNo;
7601  TimestampTz xtime;
7602 
7603  /* Concurrent checkpoint/restartpoint cannot happen */
7605 
7606  /* Get a local copy of the last safe checkpoint record. */
7608  lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
7609  lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
7610  lastCheckPoint = XLogCtl->lastCheckPoint;
7612 
7613  /*
7614  * Check that we're still in recovery mode. It's ok if we exit recovery
7615  * mode after this check, the restart point is valid anyway.
7616  */
7617  if (!RecoveryInProgress())
7618  {
7619  ereport(DEBUG2,
7620  (errmsg_internal("skipping restartpoint, recovery has already ended")));
7621  return false;
7622  }
7623 
7624  /*
7625  * If the last checkpoint record we've replayed is already our last
7626  * restartpoint, we can't perform a new restart point. We still update
7627  * minRecoveryPoint in that case, so that if this is a shutdown restart
7628  * point, we won't start up earlier than before. That's not strictly
7629  * necessary, but when hot standby is enabled, it would be rather weird if
7630  * the database opened up for read-only connections at a point-in-time
7631  * before the last shutdown. Such time travel is still possible in case of
7632  * immediate shutdown, though.
7633  *
7634  * We don't explicitly advance minRecoveryPoint when we do create a
7635  * restartpoint. It's assumed that flushing the buffers will do that as a
7636  * side-effect.
7637  */
7638  if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
7639  lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
7640  {
7641  ereport(DEBUG2,
7642  (errmsg_internal("skipping restartpoint, already performed at %X/%X",
7643  LSN_FORMAT_ARGS(lastCheckPoint.redo))));
7644 
7646  if (flags & CHECKPOINT_IS_SHUTDOWN)
7647  {
7648  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7651  LWLockRelease(ControlFileLock);
7652  }
7653  return false;
7654  }
7655 
7656  /*
7657  * Update the shared RedoRecPtr so that the startup process can calculate
7658  * the number of segments replayed since last restartpoint, and request a
7659  * restartpoint if it exceeds CheckPointSegments.
7660  *
7661  * Like in CreateCheckPoint(), hold off insertions to update it, although
7662  * during recovery this is just pro forma, because no WAL insertions are
7663  * happening.
7664  */
7666  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
7668 
7669  /* Also update the info_lck-protected copy */
7671  XLogCtl->RedoRecPtr = lastCheckPoint.redo;
7673 
7674  /*
7675  * Prepare to accumulate statistics.
7676  *
7677  * Note: because it is possible for log_checkpoints to change while a
7678  * checkpoint proceeds, we always accumulate stats, even if
7679  * log_checkpoints is currently off.
7680  */
7681  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
7683 
7684  if (log_checkpoints)
7685  LogCheckpointStart(flags, true);
7686 
7687  /* Update the process title */
7688  update_checkpoint_display(flags, true, false);
7689 
7690  CheckPointGuts(lastCheckPoint.redo, flags);
7691 
7692  /*
7693  * This location needs to be after CheckPointGuts() to ensure that some
7694  * work has already happened during this checkpoint.
7695  */
7696  INJECTION_POINT("create-restart-point");
7697 
7698  /*
7699  * Remember the prior checkpoint's redo ptr for
7700  * UpdateCheckPointDistanceEstimate()
7701  */
7702  PriorRedoPtr = ControlFile->checkPointCopy.redo;
7703 
7704  /*
7705  * Update pg_control, using current time. Check that it still shows an
7706  * older checkpoint, else do nothing; this is a quick hack to make sure
7707  * nothing really bad happens if somehow we get here after the
7708  * end-of-recovery checkpoint.
7709  */
7710  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7711  if (ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
7712  {
7713  /*
7714  * Update the checkpoint information. We do this even if the cluster
7715  * does not show DB_IN_ARCHIVE_RECOVERY to match with the set of WAL
7716  * segments recycled below.
7717  */
7718  ControlFile->checkPoint = lastCheckPointRecPtr;
7719  ControlFile->checkPointCopy = lastCheckPoint;
7720 
7721  /*
7722  * Ensure minRecoveryPoint is past the checkpoint record and update it
7723  * if the control file still shows DB_IN_ARCHIVE_RECOVERY. Normally,
7724  * this will have happened already while writing out dirty buffers,
7725  * but not necessarily - e.g. because no buffers were dirtied. We do
7726  * this because a backup performed in recovery uses minRecoveryPoint
7727  * to determine which WAL files must be included in the backup, and
7728  * the file (or files) containing the checkpoint record must be
7729  * included, at a minimum. Note that for an ordinary restart of
7730  * recovery there's no value in having the minimum recovery point any
7731  * earlier than this anyway, because redo will begin just after the
7732  * checkpoint record.
7733  */
7735  {
7736  if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
7737  {
7738  ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
7740 
7741  /* update local copy */
7744  }
7745  if (flags & CHECKPOINT_IS_SHUTDOWN)
7747  }
7749  }
7750  LWLockRelease(ControlFileLock);
7751 
7752  /*
7753  * Update the average distance between checkpoints/restartpoints if the
7754  * prior checkpoint exists.
7755  */
7756  if (PriorRedoPtr != InvalidXLogRecPtr)
7758 
7759  /*
7760  * Delete old log files, those no longer needed for last restartpoint to
7761  * prevent the disk holding the xlog from growing full.
7762  */
7764 
7765  /*
7766  * Retreat _logSegNo using the current end of xlog replayed or received,
7767  * whichever is later.
7768  */
7769  receivePtr = GetWalRcvFlushRecPtr(NULL, NULL);
7770  replayPtr = GetXLogReplayRecPtr(&replayTLI);
7771  endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
7772  KeepLogSeg(endptr, &_logSegNo);
7774  _logSegNo, InvalidOid,
7776  {
7777  /*
7778  * Some slots have been invalidated; recalculate the old-segment
7779  * horizon, starting again from RedoRecPtr.
7780  */
7782  KeepLogSeg(endptr, &_logSegNo);
7783  }
7784  _logSegNo--;
7785 
7786  /*
7787  * Try to recycle segments on a useful timeline. If we've been promoted
7788  * since the beginning of this restartpoint, use the new timeline chosen
7789  * at end of recovery. If we're still in recovery, use the timeline we're
7790  * currently replaying.
7791  *
7792  * There is no guarantee that the WAL segments will be useful on the
7793  * current timeline; if recovery proceeds to a new timeline right after
7794  * this, the pre-allocated WAL segments on this timeline will not be used,
7795  * and will go wasted until recycled on the next restartpoint. We'll live
7796  * with that.
7797  */
7798  if (!RecoveryInProgress())
7799  replayTLI = XLogCtl->InsertTimeLineID;
7800 
7801  RemoveOldXlogFiles(_logSegNo, RedoRecPtr, endptr, replayTLI);
7802 
7803  /*
7804  * Make more log segments if needed. (Do this after recycling old log
7805  * segments, since that may supply some of the needed files.)
7806  */
7807  PreallocXlogFiles(endptr, replayTLI);
7808 
7809  /*
7810  * Truncate pg_subtrans if possible. We can throw away all data before
7811  * the oldest XMIN of any running transaction. No future transaction will
7812  * attempt to reference any pg_subtrans entry older than that (see Asserts
7813  * in subtrans.c). When hot standby is disabled, though, we mustn't do
7814  * this because StartupSUBTRANS hasn't been called yet.
7815  */
7816  if (EnableHotStandby)
7818 
7819  /* Real work is done; log and update stats. */
7820  LogCheckpointEnd(true);
7821 
7822  /* Reset the process title */
7823  update_checkpoint_display(flags, true, true);
7824 
7825  xtime = GetLatestXTime();
7827  (errmsg("recovery restart point at %X/%X",
7828  LSN_FORMAT_ARGS(lastCheckPoint.redo)),
7829  xtime ? errdetail("Last completed transaction was at log time %s.",
7830  timestamptz_to_str(xtime)) : 0));
7831 
7832  /*
7833  * Finally, execute archive_cleanup_command, if any.
7834  */
7835  if (archiveCleanupCommand && strcmp(archiveCleanupCommand, "") != 0)
7837  "archive_cleanup_command",
7838  false,
7839  WAIT_EVENT_ARCHIVE_CLEANUP_COMMAND);
7840 
7841  return true;
7842 }
7843 
7844 /*
7845  * Report availability of WAL for the given target LSN
7846  * (typically a slot's restart_lsn)
7847  *
7848  * Returns one of the following enum values:
7849  *
7850  * * WALAVAIL_RESERVED means targetLSN is available and it is in the range of
7851  * max_wal_size.
7852  *
7853  * * WALAVAIL_EXTENDED means it is still available by preserving extra
7854  * segments beyond max_wal_size. If max_slot_wal_keep_size is smaller
7855  * than max_wal_size, this state is not returned.
7856  *
7857  * * WALAVAIL_UNRESERVED means it is being lost and the next checkpoint will
7858  * remove reserved segments. The walsender using this slot may return to the
7859  * above.
7860  *
7861  * * WALAVAIL_REMOVED means it has been removed. A replication stream on
7862  * a slot with this LSN cannot continue. (Any associated walsender
7863  * processes should have been terminated already.)
7864  *
7865  * * WALAVAIL_INVALID_LSN means the slot hasn't been set to reserve WAL.
7866  */
7869 {
7870  XLogRecPtr currpos; /* current write LSN */
7871  XLogSegNo currSeg; /* segid of currpos */
7872  XLogSegNo targetSeg; /* segid of targetLSN */
7873  XLogSegNo oldestSeg; /* actual oldest segid */
7874  XLogSegNo oldestSegMaxWalSize; /* oldest segid kept by max_wal_size */
7875  XLogSegNo oldestSlotSeg; /* oldest segid kept by slot */
7876  uint64 keepSegs;
7877 
7878  /*
7879  * slot does not reserve WAL. Either deactivated, or has never been active
7880  */
7881  if (XLogRecPtrIsInvalid(targetLSN))
7882  return WALAVAIL_INVALID_LSN;
7883 
7884  /*
7885  * Calculate the oldest segment currently reserved by all slots,
7886  * considering wal_keep_size and max_slot_wal_keep_size. Initialize
7887  * oldestSlotSeg to the current segment.
7888  */
7889  currpos = GetXLogWriteRecPtr();
7890  XLByteToSeg(currpos, oldestSlotSeg, wal_segment_size);
7891  KeepLogSeg(currpos, &oldestSlotSeg);
7892 
7893  /*
7894  * Find the oldest extant segment file. We get 1 until checkpoint removes
7895  * the first WAL segment file since startup, which causes the status being
7896  * wrong under certain abnormal conditions but that doesn't actually harm.
7897  */
7898  oldestSeg = XLogGetLastRemovedSegno() + 1;
7899 
7900  /* calculate oldest segment by max_wal_size */
7901  XLByteToSeg(currpos, currSeg, wal_segment_size);
7903 
7904  if (currSeg > keepSegs)
7905  oldestSegMaxWalSize = currSeg - keepSegs;
7906  else
7907  oldestSegMaxWalSize = 1;
7908 
7909  /* the segment we care about */
7910  XLByteToSeg(targetLSN, targetSeg, wal_segment_size);
7911 
7912  /*
7913  * No point in returning reserved or extended status values if the
7914  * targetSeg is known to be lost.
7915  */
7916  if (targetSeg >= oldestSlotSeg)
7917  {
7918  /* show "reserved" when targetSeg is within max_wal_size */
7919  if (targetSeg >= oldestSegMaxWalSize)
7920  return WALAVAIL_RESERVED;
7921 
7922  /* being retained by slots exceeding max_wal_size */
7923  return WALAVAIL_EXTENDED;
7924  }
7925 
7926  /* WAL segments are no longer retained but haven't been removed yet */
7927  if (targetSeg >= oldestSeg)
7928  return WALAVAIL_UNRESERVED;
7929 
7930  /* Definitely lost */
7931  return WALAVAIL_REMOVED;
7932 }
7933 
7934 
7935 /*
7936  * Retreat *logSegNo to the last segment that we need to retain because of
7937  * either wal_keep_size or replication slots.
7938  *
7939  * This is calculated by subtracting wal_keep_size from the given xlog
7940  * location, recptr and by making sure that that result is below the
7941  * requirement of replication slots. For the latter criterion we do consider
7942  * the effects of max_slot_wal_keep_size: reserve at most that much space back
7943  * from recptr.
7944  *
7945  * Note about replication slots: if this function calculates a value
7946  * that's further ahead than what slots need reserved, then affected
7947  * slots need to be invalidated and this function invoked again.
7948  * XXX it might be a good idea to rewrite this function so that
7949  * invalidation is optionally done here, instead.
7950  */
7951 static void
7952 KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
7953 {
7954  XLogSegNo currSegNo;
7955  XLogSegNo segno;
7956  XLogRecPtr keep;
7957 
7958  XLByteToSeg(recptr, currSegNo, wal_segment_size);
7959  segno = currSegNo;
7960 
7961  /*
7962  * Calculate how many segments are kept by slots first, adjusting for
7963  * max_slot_wal_keep_size.
7964  */
7966  if (keep != InvalidXLogRecPtr && keep < recptr)
7967  {
7968  XLByteToSeg(keep, segno, wal_segment_size);
7969 
7970  /* Cap by max_slot_wal_keep_size ... */
7971  if (max_slot_wal_keep_size_mb >= 0)
7972  {
7973  uint64 slot_keep_segs;
7974 
7975  slot_keep_segs =
7977 
7978  if (currSegNo - segno > slot_keep_segs)
7979  segno = currSegNo - slot_keep_segs;
7980  }
7981  }
7982 
7983  /*
7984  * If WAL summarization is in use, don't remove WAL that has yet to be
7985  * summarized.
7986  */
7987  keep = GetOldestUnsummarizedLSN(NULL, NULL);
7988  if (keep != InvalidXLogRecPtr)
7989  {
7990  XLogSegNo unsummarized_segno;
7991 
7992  XLByteToSeg(keep, unsummarized_segno, wal_segment_size);
7993  if (unsummarized_segno < segno)
7994  segno = unsummarized_segno;
7995  }
7996 
7997  /* but, keep at least wal_keep_size if that's set */
7998  if (wal_keep_size_mb > 0)
7999  {
8000  uint64 keep_segs;
8001 
8003  if (currSegNo - segno < keep_segs)
8004  {
8005  /* avoid underflow, don't go below 1 */
8006  if (currSegNo <= keep_segs)
8007  segno = 1;
8008  else
8009  segno = currSegNo - keep_segs;
8010  }
8011  }
8012 
8013  /* don't delete WAL segments newer than the calculated segment */
8014  if (segno < *logSegNo)
8015  *logSegNo = segno;
8016 }
8017 
8018 /*
8019  * Write a NEXTOID log record
8020  */
8021 void
8023 {
8024  XLogBeginInsert();
8025  XLogRegisterData((char *) (&nextOid), sizeof(Oid));
8026  (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID);
8027 
8028  /*
8029  * We need not flush the NEXTOID record immediately, because any of the
8030  * just-allocated OIDs could only reach disk as part of a tuple insert or
8031  * update that would have its own XLOG record that must follow the NEXTOID
8032  * record. Therefore, the standard buffer LSN interlock applied to those
8033  * records will ensure no such OID reaches disk before the NEXTOID record
8034  * does.
8035  *
8036  * Note, however, that the above statement only covers state "within" the
8037  * database. When we use a generated OID as a file or directory name, we
8038  * are in a sense violating the basic WAL rule, because that filesystem
8039  * change may reach disk before the NEXTOID WAL record does. The impact
8040  * of this is that if a database crash occurs immediately afterward, we
8041  * might after restart re-generate the same OID and find that it conflicts
8042  * with the leftover file or directory. But since for safety's sake we
8043  * always loop until finding a nonconflicting filename, this poses no real
8044  * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
8045  */
8046 }
8047 
8048 /*
8049  * Write an XLOG SWITCH record.
8050  *
8051  * Here we just blindly issue an XLogInsert request for the record.
8052  * All the magic happens inside XLogInsert.
8053  *
8054  * The return value is either the end+1 address of the switch record,
8055  * or the end+1 address of the prior segment if we did not need to
8056  * write a switch record because we are already at segment start.
8057  */
8058 XLogRecPtr
8059 RequestXLogSwitch(bool mark_unimportant)
8060 {
8061  XLogRecPtr RecPtr;
8062 
8063  /* XLOG SWITCH has no data */
8064  XLogBeginInsert();
8065 
8066  if (mark_unimportant)
8068  RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH);
8069 
8070  return RecPtr;
8071 }
8072 
8073 /*
8074  * Write a RESTORE POINT record
8075  */
8076 XLogRecPtr
8077 XLogRestorePoint(const char *rpName)
8078 {
8079  XLogRecPtr RecPtr;
8080  xl_restore_point xlrec;
8081 
8082  xlrec.rp_time = GetCurrentTimestamp();
8083  strlcpy(xlrec.rp_name, rpName, MAXFNAMELEN);
8084 
8085  XLogBeginInsert();
8086  XLogRegisterData((char *) &xlrec, sizeof(xl_restore_point));
8087 
8088  RecPtr = XLogInsert(RM_XLOG_ID, XLOG_RESTORE_POINT);
8089 
8090  ereport(LOG,
8091  (errmsg("restore point \"%s\" created at %X/%X",
8092  rpName, LSN_FORMAT_ARGS(RecPtr))));
8093 
8094  return RecPtr;
8095 }
8096 
8097 /*
8098  * Check if any of the GUC parameters that are critical for hot standby
8099  * have changed, and update the value in pg_control file if necessary.
8100  */
8101 static void
8103 {
8104  if (wal_level != ControlFile->wal_level ||
8112  {
8113  /*
8114  * The change in number of backend slots doesn't need to be WAL-logged
8115  * if archiving is not enabled, as you can't start archive recovery
8116  * with wal_level=minimal anyway. We don't really care about the
8117  * values in pg_control either if wal_level=minimal, but seems better
8118  * to keep them up-to-date to avoid confusion.
8119  */
8121  {
8122  xl_parameter_change xlrec;
8123  XLogRecPtr recptr;
8124 
8130  xlrec.wal_level = wal_level;
8131  xlrec.wal_log_hints = wal_log_hints;
8133 
8134  XLogBeginInsert();
8135  XLogRegisterData((char *) &xlrec, sizeof(xlrec));
8136 
8137  recptr = XLogInsert(RM_XLOG_ID, XLOG_PARAMETER_CHANGE);
8138  XLogFlush(recptr);
8139  }
8140 
8141  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8142 
8152 
8153  LWLockRelease(ControlFileLock);
8154  }
8155 }
8156 
8157 /*
8158  * Update full_page_writes in shared memory, and write an
8159  * XLOG_FPW_CHANGE record if necessary.
8160  *
8161  * Note: this function assumes there is no other process running
8162  * concurrently that could update it.
8163  */
8164 void
8166 {
8168  bool recoveryInProgress;
8169 
8170  /*
8171  * Do nothing if full_page_writes has not been changed.
8172  *
8173  * It's safe to check the shared full_page_writes without the lock,
8174  * because we assume that there is no concurrently running process which
8175  * can update it.
8176  */
8177  if (fullPageWrites == Insert->fullPageWrites)
8178  return;
8179 
8180  /*
8181  * Perform this outside critical section so that the WAL insert
8182  * initialization done by RecoveryInProgress() doesn't trigger an
8183  * assertion failure.
8184  */
8185  recoveryInProgress = RecoveryInProgress();
8186 
8188 
8189  /*
8190  * It's always safe to take full page images, even when not strictly
8191  * required, but not the other round. So if we're setting full_page_writes
8192  * to true, first set it true and then write the WAL record. If we're
8193  * setting it to false, first write the WAL record and then set the global
8194  * flag.
8195  */
8196  if (fullPageWrites)
8197  {
8199  Insert->fullPageWrites = true;
8201  }
8202 
8203  /*
8204  * Write an XLOG_FPW_CHANGE record. This allows us to keep track of
8205  * full_page_writes during archive recovery, if required.
8206  */
8207  if (XLogStandbyInfoActive() && !recoveryInProgress)
8208  {
8209  XLogBeginInsert();
8210  XLogRegisterData((char *) (&fullPageWrites), sizeof(bool));
8211 
8212  XLogInsert(RM_XLOG_ID, XLOG_FPW_CHANGE);
8213  }
8214 
8215  if (!fullPageWrites)
8216  {
8218  Insert->fullPageWrites = false;
8220  }
8221  END_CRIT_SECTION();
8222 }
8223 
8224 /*
8225  * XLOG resource manager's routines
8226  *
8227  * Definitions of info values are in include/catalog/pg_control.h, though
8228  * not all record types are related to control file updates.
8229  *
8230  * NOTE: Some XLOG record types that are directly related to WAL recovery
8231  * are handled in xlogrecovery_redo().
8232  */
8233 void
8235 {
8236  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
8237  XLogRecPtr lsn = record->EndRecPtr;
8238 
8239  /*
8240  * In XLOG rmgr, backup blocks are only used by XLOG_FPI and
8241  * XLOG_FPI_FOR_HINT records.
8242  */
8243  Assert(info == XLOG_FPI || info == XLOG_FPI_FOR_HINT ||
8244  !XLogRecHasAnyBlockRefs(record));
8245 
8246  if (info == XLOG_NEXTOID)
8247  {
8248  Oid nextOid;
8249 
8250  /*
8251  * We used to try to take the maximum of TransamVariables->nextOid and
8252  * the recorded nextOid, but that fails if the OID counter wraps
8253  * around. Since no OID allocation should be happening during replay
8254  * anyway, better to just believe the record exactly. We still take
8255  * OidGenLock while setting the variable, just in case.
8256  */
8257  memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
8258  LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
8259  TransamVariables->nextOid = nextOid;
8261  LWLockRelease(OidGenLock);
8262  }
8263  else if (info == XLOG_CHECKPOINT_SHUTDOWN)
8264  {
8265  CheckPoint checkPoint;
8266  TimeLineID replayTLI;
8267 
8268  memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
8269  /* In a SHUTDOWN checkpoint, believe the counters exactly */
8270  LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
8271  TransamVariables->nextXid = checkPoint.nextXid;
8272  LWLockRelease(XidGenLock);
8273  LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
8274  TransamVariables->nextOid = checkPoint.nextOid;
8276  LWLockRelease(OidGenLock);
8277  MultiXactSetNextMXact(checkPoint.nextMulti,
8278  checkPoint.nextMultiOffset);
8279 
8281  checkPoint.oldestMultiDB);
8282 
8283  /*
8284  * No need to set oldestClogXid here as well; it'll be set when we
8285  * redo an xl_clog_truncate if it changed since initialization.
8286  */
8287  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
8288 
8289  /*
8290  * If we see a shutdown checkpoint while waiting for an end-of-backup
8291  * record, the backup was canceled and the end-of-backup record will
8292  * never arrive.
8293  */
8297  ereport(PANIC,
8298  (errmsg("online backup was canceled, recovery cannot continue")));
8299 
8300  /*
8301  * If we see a shutdown checkpoint, we know that nothing was running
8302  * on the primary at this point. So fake-up an empty running-xacts
8303  * record and use that here and now. Recover additional standby state
8304  * for prepared transactions.
8305  */
8307  {
8308  TransactionId *xids;
8309  int nxids;
8310  TransactionId oldestActiveXID;
8311  TransactionId latestCompletedXid;
8312  RunningTransactionsData running;
8313 
8314  oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
8315 
8316  /* Update pg_subtrans entries for any prepared transactions */
8318 
8319  /*
8320  * Construct a RunningTransactions snapshot representing a shut
8321  * down server, with only prepared transactions still alive. We're
8322  * never overflowed at this point because all subxids are listed
8323  * with their parent prepared transactions.
8324  */
8325  running.xcnt = nxids;
8326  running.subxcnt = 0;
8328  running.nextXid = XidFromFullTransactionId(checkPoint.nextXid);
8329  running.oldestRunningXid = oldestActiveXID;
8330  latestCompletedXid = XidFromFullTransactionId(checkPoint.nextXid);
8331  TransactionIdRetreat(latestCompletedXid);
8332  Assert(TransactionIdIsNormal(latestCompletedXid));
8333  running.latestCompletedXid = latestCompletedXid;
8334  running.xids = xids;
8335 
8336  ProcArrayApplyRecoveryInfo(&running);
8337  }
8338 
8339  /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
8340  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8341  ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
8342  LWLockRelease(ControlFileLock);
8343 
8344  /* Update shared-memory copy of checkpoint XID/epoch */
8346  XLogCtl->ckptFullXid = checkPoint.nextXid;
8348 
8349  /*
8350  * We should've already switched to the new TLI before replaying this
8351  * record.
8352  */
8353  (void) GetCurrentReplayRecPtr(&replayTLI);
8354  if (checkPoint.ThisTimeLineID != replayTLI)
8355  ereport(PANIC,
8356  (errmsg("unexpected timeline ID %u (should be %u) in shutdown checkpoint record",
8357  checkPoint.ThisTimeLineID, replayTLI)));
8358 
8359  RecoveryRestartPoint(&checkPoint, record);
8360  }
8361  else if (info == XLOG_CHECKPOINT_ONLINE)
8362  {
8363  CheckPoint checkPoint;
8364  TimeLineID replayTLI;
8365 
8366  memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
8367  /* In an ONLINE checkpoint, treat the XID counter as a minimum */
8368  LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
8370  checkPoint.nextXid))
8371  TransamVariables->nextXid = checkPoint.nextXid;
8372  LWLockRelease(XidGenLock);
8373 
8374  /*
8375  * We ignore the nextOid counter in an ONLINE checkpoint, preferring
8376  * to track OID assignment through XLOG_NEXTOID records. The nextOid
8377  * counter is from the start of the checkpoint and might well be stale
8378  * compared to later XLOG_NEXTOID records. We could try to take the
8379  * maximum of the nextOid counter and our latest value, but since
8380  * there's no particular guarantee about the speed with which the OID
8381  * counter wraps around, that's a risky thing to do. In any case,
8382  * users of the nextOid counter are required to avoid assignment of
8383  * duplicates, so that a somewhat out-of-date value should be safe.
8384  */
8385 
8386  /* Handle multixact */
8388  checkPoint.nextMultiOffset);
8389 
8390  /*
8391  * NB: This may perform multixact truncation when replaying WAL
8392  * generated by an older primary.
8393  */
8395  checkPoint.oldestMultiDB);
8397  checkPoint.oldestXid))
8398  SetTransactionIdLimit(checkPoint.oldestXid,
8399  checkPoint.oldestXidDB);
8400  /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
8401  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8402  ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
8403  LWLockRelease(ControlFileLock);
8404 
8405  /* Update shared-memory copy of checkpoint XID/epoch */
8407  XLogCtl->ckptFullXid = checkPoint.nextXid;
8409 
8410  /* TLI should not change in an on-line checkpoint */
8411  (void) GetCurrentReplayRecPtr(&replayTLI);
8412  if (checkPoint.ThisTimeLineID != replayTLI)
8413  ereport(PANIC,
8414  (errmsg("unexpected timeline ID %u (should be %u) in online checkpoint record",
8415  checkPoint.ThisTimeLineID, replayTLI)));
8416 
8417  RecoveryRestartPoint(&checkPoint, record);
8418  }
8419  else if (info == XLOG_OVERWRITE_CONTRECORD)
8420  {
8421  /* nothing to do here, handled in xlogrecovery_redo() */
8422  }
8423  else if (info == XLOG_END_OF_RECOVERY)
8424  {
8425  xl_end_of_recovery xlrec;
8426  TimeLineID replayTLI;
8427 
8428  memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_end_of_recovery));
8429 
8430  /*
8431  * For Hot Standby, we could treat this like a Shutdown Checkpoint,
8432  * but this case is rarer and harder to test, so the benefit doesn't
8433  * outweigh the potential extra cost of maintenance.
8434  */
8435 
8436  /*
8437  * We should've already switched to the new TLI before replaying this
8438  * record.
8439  */
8440  (void) GetCurrentReplayRecPtr(&replayTLI);
8441  if (xlrec.ThisTimeLineID != replayTLI)
8442  ereport(PANIC,
8443  (errmsg("unexpected timeline ID %u (should be %u) in end-of-recovery record",
8444  xlrec.ThisTimeLineID, replayTLI)));
8445  }
8446  else if (info == XLOG_NOOP)
8447  {
8448  /* nothing to do here */
8449  }
8450  else if (info == XLOG_SWITCH)
8451  {
8452  /* nothing to do here */
8453  }
8454  else if (info == XLOG_RESTORE_POINT)
8455  {
8456  /* nothing to do here, handled in xlogrecovery.c */
8457  }
8458  else if (info == XLOG_FPI || info == XLOG_FPI_FOR_HINT)
8459  {
8460  /*
8461  * XLOG_FPI records contain nothing else but one or more block
8462  * references. Every block reference must include a full-page image
8463  * even if full_page_writes was disabled when the record was generated
8464  * - otherwise there would be no point in this record.
8465  *
8466  * XLOG_FPI_FOR_HINT records are generated when a page needs to be
8467  * WAL-logged because of a hint bit update. They are only generated
8468  * when checksums and/or wal_log_hints are enabled. They may include
8469  * no full-page images if full_page_writes was disabled when they were
8470  * generated. In this case there is nothing to do here.
8471  *
8472  * No recovery conflicts are generated by these generic records - if a
8473  * resource manager needs to generate conflicts, it has to define a
8474  * separate WAL record type and redo routine.
8475  */
8476  for (uint8 block_id = 0; block_id <= XLogRecMaxBlockId(record); block_id++)
8477  {
8478  Buffer buffer;
8479 
8480  if (!XLogRecHasBlockImage(record, block_id))
8481  {
8482  if (info == XLOG_FPI)
8483  elog(ERROR, "XLOG_FPI record did not contain a full-page image");
8484  continue;
8485  }
8486 
8487  if (XLogReadBufferForRedo(record, block_id, &buffer) != BLK_RESTORED)
8488  elog(ERROR, "unexpected XLogReadBufferForRedo result when restoring backup block");
8489  UnlockReleaseBuffer(buffer);
8490  }
8491  }
8492  else if (info == XLOG_BACKUP_END)
8493  {
8494  /* nothing to do here, handled in xlogrecovery_redo() */
8495  }
8496  else if (info == XLOG_PARAMETER_CHANGE)
8497  {
8498  xl_parameter_change xlrec;
8499 
8500  /* Update our copy of the parameters in pg_control */
8501  memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_parameter_change));
8502 
8503  /*
8504  * Invalidate logical slots if we are in hot standby and the primary
8505  * does not have a WAL level sufficient for logical decoding. No need
8506  * to search for potentially conflicting logically slots if standby is
8507  * running with wal_level lower than logical, because in that case, we
8508  * would have either disallowed creation of logical slots or
8509  * invalidated existing ones.
8510  */
8511  if (InRecovery && InHotStandby &&
8512  xlrec.wal_level < WAL_LEVEL_LOGICAL &&
8515  0, InvalidOid,
8517 
8518  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8524  ControlFile->wal_level = xlrec.wal_level;
8526 
8527  /*
8528  * Update minRecoveryPoint to ensure that if recovery is aborted, we
8529  * recover back up to this point before allowing hot standby again.
8530  * This is important if the max_* settings are decreased, to ensure
8531  * you don't run queries against the WAL preceding the change. The
8532  * local copies cannot be updated as long as crash recovery is
8533  * happening and we expect all the WAL to be replayed.
8534  */
8535  if (InArchiveRecovery)
8536  {
8539  }
8541  {
8542  TimeLineID replayTLI;
8543 
8544  (void) GetCurrentReplayRecPtr(&replayTLI);
8546  ControlFile->minRecoveryPointTLI = replayTLI;
8547  }
8548 
8552 
8554  LWLockRelease(ControlFileLock);
8555 
8556  /* Check to see if any parameter change gives a problem on recovery */
8558  }
8559  else if (info == XLOG_FPW_CHANGE)
8560  {
8561  bool fpw;
8562 
8563  memcpy(&fpw, XLogRecGetData(record), sizeof(bool));
8564 
8565  /*
8566  * Update the LSN of the last replayed XLOG_FPW_CHANGE record so that
8567  * do_pg_backup_start() and do_pg_backup_stop() can check whether
8568  * full_page_writes has been disabled during online backup.
8569  */
8570  if (!fpw)
8571  {
8573  if (XLogCtl->lastFpwDisableRecPtr < record->ReadRecPtr)
8576  }
8577 
8578  /* Keep track of full_page_writes */
8579  lastFullPageWrites = fpw;
8580  }
8581  else if (info == XLOG_CHECKPOINT_REDO)
8582  {
8583  /* nothing to do here, just for informational purposes */
8584  }
8585 }
8586 
8587 /*
8588  * Return the extra open flags used for opening a file, depending on the
8589  * value of the GUCs wal_sync_method, fsync and debug_io_direct.
8590  */
8591 static int
8592 get_sync_bit(int method)
8593 {
8594  int o_direct_flag = 0;
8595 
8596  /*
8597  * Use O_DIRECT if requested, except in walreceiver process. The WAL
8598  * written by walreceiver is normally read by the startup process soon
8599  * after it's written. Also, walreceiver performs unaligned writes, which
8600  * don't work with O_DIRECT, so it is required for correctness too.
8601  */
8603  o_direct_flag = PG_O_DIRECT;
8604 
8605  /* If fsync is disabled, never open in sync mode */
8606  if (!enableFsync)
8607  return o_direct_flag;
8608 
8609  switch (method)
8610  {
8611  /*
8612  * enum values for all sync options are defined even if they are
8613  * not supported on the current platform. But if not, they are
8614  * not included in the enum option array, and therefore will never
8615  * be seen here.
8616  */
8617  case WAL_SYNC_METHOD_FSYNC:
8620  return o_direct_flag;
8621 #ifdef O_SYNC
8622  case WAL_SYNC_METHOD_OPEN:
8623  return O_SYNC | o_direct_flag;
8624 #endif
8625 #ifdef O_DSYNC
8627  return O_DSYNC | o_direct_flag;
8628 #endif
8629  default:
8630  /* can't happen (unless we are out of sync with option array) */
8631  elog(ERROR, "unrecognized \"wal_sync_method\": %d", method);
8632  return 0; /* silence warning */
8633  }
8634 }
8635 
8636 /*
8637  * GUC support
8638  */
8639 void
8640 assign_wal_sync_method(int new_wal_sync_method, void *extra)
8641 {
8642  if (wal_sync_method != new_wal_sync_method)
8643  {
8644  /*
8645  * To ensure that no blocks escape unsynced, force an fsync on the
8646  * currently open log segment (if any). Also, if the open flag is
8647  * changing, close the log file so it will be reopened (with new flag
8648  * bit) at next use.
8649  */
8650  if (openLogFile >= 0)
8651  {
8652  pgstat_report_wait_start(WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN);
8653  if (pg_fsync(openLogFile) != 0)
8654  {
8655  char xlogfname[MAXFNAMELEN];
8656  int save_errno;
8657 
8658  save_errno = errno;
8659  XLogFileName(xlogfname, openLogTLI, openLogSegNo,
8661  errno = save_errno;
8662  ereport(PANIC,
8664  errmsg("could not fsync file \"%s\": %m", xlogfname)));
8665  }
8666 
8668  if (get_sync_bit(wal_sync_method) != get_sync_bit(new_wal_sync_method))
8669  XLogFileClose();
8670  }
8671  }
8672 }
8673 
8674 
8675 /*
8676  * Issue appropriate kind of fsync (if any) for an XLOG output file.
8677  *
8678  * 'fd' is a file descriptor for the XLOG file to be fsync'd.
8679  * 'segno' is for error reporting purposes.
8680  */
8681 void
8683 {
8684  char *msg = NULL;
8685  instr_time start;
8686 
8687  Assert(tli != 0);
8688 
8689  /*
8690  * Quick exit if fsync is disabled or write() has already synced the WAL
8691  * file.
8692  */
8693  if (!enableFsync ||
8696  return;
8697 
8698  /* Measure I/O timing to sync the WAL file */
8699  if (track_wal_io_timing)
8701  else
8703 
8704  pgstat_report_wait_start(WAIT_EVENT_WAL_SYNC);
8705  switch (wal_sync_method)
8706  {
8707  case WAL_SYNC_METHOD_FSYNC:
8708  if (pg_fsync_no_writethrough(fd) != 0)
8709  msg = _("could not fsync file \"%s\": %m");
8710  break;
8711 #ifdef HAVE_FSYNC_WRITETHROUGH
8713  if (pg_fsync_writethrough(fd) != 0)
8714  msg = _("could not fsync write-through file \"%s\": %m");
8715  break;
8716 #endif
8718  if (pg_fdatasync(fd) != 0)
8719  msg = _("could not fdatasync file \"%s\": %m");
8720  break;
8721  case WAL_SYNC_METHOD_OPEN:
8723  /* not reachable */
8724  Assert(false);
8725  break;
8726  default:
8727  ereport(PANIC,
8728  errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8729  errmsg_internal("unrecognized \"wal_sync_method\": %d", wal_sync_method));
8730  break;
8731  }
8732 
8733  /* PANIC if failed to fsync */
8734  if (msg)
8735  {
8736  char xlogfname[MAXFNAMELEN];
8737  int save_errno = errno;
8738 
8739  XLogFileName(xlogfname, tli, segno, wal_segment_size);
8740  errno = save_errno;
8741  ereport(PANIC,
8743  errmsg(msg, xlogfname)));
8744  }
8745 
8747 
8748  /*
8749  * Increment the I/O timing and the number of times WAL files were synced.
8750  */
8751  if (track_wal_io_timing)
8752  {
8753  instr_time end;
8754 
8757  }
8758 
8760 }
8761 
8762 /*
8763  * do_pg_backup_start is the workhorse of the user-visible pg_backup_start()
8764  * function. It creates the necessary starting checkpoint and constructs the
8765  * backup state and tablespace map.
8766  *
8767  * Input parameters are "state" (the backup state), "fast" (if true, we do
8768  * the checkpoint in immediate mode to make it faster), and "tablespaces"
8769  * (if non-NULL, indicates a list of tablespaceinfo structs describing the
8770  * cluster's tablespaces.).
8771  *
8772  * The tablespace map contents are appended to passed-in parameter
8773  * tablespace_map and the caller is responsible for including it in the backup
8774  * archive as 'tablespace_map'. The tablespace_map file is required mainly for
8775  * tar format in windows as native windows utilities are not able to create
8776  * symlinks while extracting files from tar. However for consistency and
8777  * platform-independence, we do it the same way everywhere.
8778  *
8779  * It fills in "state" with the information required for the backup, such
8780  * as the minimum WAL location that must be present to restore from this
8781  * backup (starttli) and the corresponding timeline ID (starttli).
8782  *
8783  * Every successfully started backup must be stopped by calling
8784  * do_pg_backup_stop() or do_pg_abort_backup(). There can be many
8785  * backups active at the same time.
8786  *
8787  * It is the responsibility of the caller of this function to verify the
8788  * permissions of the calling user!
8789  */
8790 void
8791 do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces,
8792  BackupState *state, StringInfo tblspcmapfile)
8793 {
8795 
8796  Assert(state != NULL);
8798 
8799  /*
8800  * During recovery, we don't need to check WAL level. Because, if WAL
8801  * level is not sufficient, it's impossible to get here during recovery.
8802  */
8804  ereport(ERROR,
8805  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8806  errmsg("WAL level not sufficient for making an online backup"),
8807  errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start.")));
8808 
8809  if (strlen(backupidstr) > MAXPGPATH)
8810  ereport(ERROR,
8811  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8812  errmsg("backup label too long (max %d bytes)",
8813  MAXPGPATH)));
8814 
8815  strlcpy(state->name, backupidstr, sizeof(state->name));
8816 
8817  /*
8818  * Mark backup active in shared memory. We must do full-page WAL writes
8819  * during an on-line backup even if not doing so at other times, because
8820  * it's quite possible for the backup dump to obtain a "torn" (partially
8821  * written) copy of a database page if it reads the page concurrently with
8822  * our write to the same page. This can be fixed as long as the first
8823  * write to the page in the WAL sequence is a full-page write. Hence, we
8824  * increment runningBackups then force a CHECKPOINT, to ensure there are
8825  * no dirty pages in shared memory that might get dumped while the backup
8826  * is in progress without having a corresponding WAL record. (Once the
8827  * backup is complete, we need not force full-page writes anymore, since
8828  * we expect that any pages not modified during the backup interval must
8829  * have been correctly captured by the backup.)
8830  *
8831  * Note that forcing full-page writes has no effect during an online
8832  * backup from the standby.
8833  *
8834  * We must hold all the insertion locks to change the value of
8835  * runningBackups, to ensure adequate interlocking against
8836  * XLogInsertRecord().
8837  */
8841 
8842  /*
8843  * Ensure we decrement runningBackups if we fail below. NB -- for this to
8844  * work correctly, it is critical that sessionBackupState is only updated
8845  * after this block is over.
8846  */
8848  {
8849  bool gotUniqueStartpoint = false;
8850  DIR *tblspcdir;
8851  struct dirent *de;
8852  tablespaceinfo *ti;
8853  int datadirpathlen;
8854 
8855  /*
8856  * Force an XLOG file switch before the checkpoint, to ensure that the
8857  * WAL segment the checkpoint is written to doesn't contain pages with
8858  * old timeline IDs. That would otherwise happen if you called
8859  * pg_backup_start() right after restoring from a PITR archive: the
8860  * first WAL segment containing the startup checkpoint has pages in
8861  * the beginning with the old timeline ID. That can cause trouble at
8862  * recovery: we won't have a history file covering the old timeline if
8863  * pg_wal directory was not included in the base backup and the WAL
8864  * archive was cleared too before starting the backup.
8865  *
8866  * This also ensures that we have emitted a WAL page header that has
8867  * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
8868  * Therefore, if a WAL archiver (such as pglesslog) is trying to
8869  * compress out removable backup blocks, it won't remove any that
8870  * occur after this point.
8871  *
8872  * During recovery, we skip forcing XLOG file switch, which means that
8873  * the backup taken during recovery is not available for the special
8874  * recovery case described above.
8875  */
8877  RequestXLogSwitch(false);
8878 
8879  do
8880  {
8881  bool checkpointfpw;
8882 
8883  /*
8884  * Force a CHECKPOINT. Aside from being necessary to prevent torn
8885  * page problems, this guarantees that two successive backup runs
8886  * will have different checkpoint positions and hence different
8887  * history file names, even if nothing happened in between.
8888  *
8889  * During recovery, establish a restartpoint if possible. We use
8890  * the last restartpoint as the backup starting checkpoint. This
8891  * means that two successive backup runs can have same checkpoint
8892  * positions.
8893  *
8894  * Since the fact that we are executing do_pg_backup_start()
8895  * during recovery means that checkpointer is running, we can use
8896  * RequestCheckpoint() to establish a restartpoint.
8897  *
8898  * We use CHECKPOINT_IMMEDIATE only if requested by user (via
8899  * passing fast = true). Otherwise this can take awhile.
8900  */
8902  (fast ? CHECKPOINT_IMMEDIATE : 0));
8903 
8904  /*
8905  * Now we need to fetch the checkpoint record location, and also
8906  * its REDO pointer. The oldest point in WAL that would be needed
8907  * to restore starting from the checkpoint is precisely the REDO
8908  * pointer.
8909  */
8910  LWLockAcquire(ControlFileLock, LW_SHARED);
8911  state->checkpointloc = ControlFile->checkPoint;
8912  state->startpoint = ControlFile->checkPointCopy.redo;
8914  checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
8915  LWLockRelease(ControlFileLock);
8916 
8918  {
8919  XLogRecPtr recptr;
8920 
8921  /*
8922  * Check to see if all WAL replayed during online backup
8923  * (i.e., since last restartpoint used as backup starting
8924  * checkpoint) contain full-page writes.
8925  */
8927  recptr = XLogCtl->lastFpwDisableRecPtr;
8929 
8930  if (!checkpointfpw || state->startpoint <= recptr)
8931  ereport(ERROR,
8932  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8933  errmsg("WAL generated with \"full_page_writes=off\" was replayed "
8934  "since last restartpoint"),
8935  errhint("This means that the backup being taken on the standby "
8936  "is corrupt and should not be used. "
8937  "Enable \"full_page_writes\" and run CHECKPOINT on the primary, "
8938  "and then try an online backup again.")));
8939 
8940  /*
8941  * During recovery, since we don't use the end-of-backup WAL
8942  * record and don't write the backup history file, the
8943  * starting WAL location doesn't need to be unique. This means
8944  * that two base backups started at the same time might use
8945  * the same checkpoint as starting locations.
8946  */
8947  gotUniqueStartpoint = true;
8948  }
8949 
8950  /*
8951  * If two base backups are started at the same time (in WAL sender
8952  * processes), we need to make sure that they use different
8953  * checkpoints as starting locations, because we use the starting
8954  * WAL location as a unique identifier for the base backup in the
8955  * end-of-backup WAL record and when we write the backup history
8956  * file. Perhaps it would be better generate a separate unique ID
8957  * for each backup instead of forcing another checkpoint, but
8958  * taking a checkpoint right after another is not that expensive
8959  * either because only few buffers have been dirtied yet.
8960  */
8962  if (XLogCtl->Insert.lastBackupStart < state->startpoint)
8963  {
8964  XLogCtl->Insert.lastBackupStart = state->startpoint;
8965  gotUniqueStartpoint = true;
8966  }
8968  } while (!gotUniqueStartpoint);
8969 
8970  /*
8971  * Construct tablespace_map file.
8972  */
8973  datadirpathlen = strlen(DataDir);
8974 
8975  /* Collect information about all tablespaces */
8976  tblspcdir = AllocateDir(PG_TBLSPC_DIR);
8977  while ((de = ReadDir(tblspcdir, PG_TBLSPC_DIR)) != NULL)
8978  {
8979  char fullpath[MAXPGPATH + sizeof(PG_TBLSPC_DIR)];
8980  char linkpath[MAXPGPATH];
8981  char *relpath = NULL;
8982  char *s;
8983  PGFileType de_type;
8984  char *badp;
8985  Oid tsoid;
8986 
8987  /*
8988  * Try to parse the directory name as an unsigned integer.
8989  *
8990  * Tablespace directories should be positive integers that can be
8991  * represented in 32 bits, with no leading zeroes or trailing
8992  * garbage. If we come across a name that doesn't meet those
8993  * criteria, skip it.
8994  */
8995  if (de->d_name[0] < '1' || de->d_name[1] > '9')
8996  continue;
8997  errno = 0;
8998  tsoid = strtoul(de->d_name, &badp, 10);
8999  if (*badp != '\0' || errno == EINVAL || errno == ERANGE)
9000  continue;
9001 
9002  snprintf(fullpath, sizeof(fullpath), "%s/%s", PG_TBLSPC_DIR, de->d_name);
9003 
9004  de_type = get_dirent_type(fullpath, de, false, ERROR);
9005 
9006  if (de_type == PGFILETYPE_LNK)
9007  {
9008  StringInfoData escapedpath;
9009  int rllen;
9010 
9011  rllen = readlink(fullpath, linkpath, sizeof(linkpath));
9012  if (rllen < 0)
9013  {
9014  ereport(WARNING,
9015  (errmsg("could not read symbolic link \"%s\": %m",
9016  fullpath)));
9017  continue;
9018  }
9019  else if (rllen >= sizeof(linkpath))
9020  {
9021  ereport(WARNING,
9022  (errmsg("symbolic link \"%s\" target is too long",
9023  fullpath)));
9024  continue;
9025  }
9026  linkpath[rllen] = '\0';
9027 
9028  /*
9029  * Relpath holds the relative path of the tablespace directory
9030  * when it's located within PGDATA, or NULL if it's located
9031  * elsewhere.
9032  */
9033  if (rllen > datadirpathlen &&
9034  strncmp(linkpath, DataDir, datadirpathlen) == 0 &&
9035  IS_DIR_SEP(linkpath[datadirpathlen]))
9036  relpath = pstrdup(linkpath + datadirpathlen + 1);
9037 
9038  /*
9039  * Add a backslash-escaped version of the link path to the
9040  * tablespace map file.
9041  */
9042  initStringInfo(&escapedpath);
9043  for (s = linkpath; *s; s++)
9044  {
9045  if (*s == '\n' || *s == '\r' || *s == '\\')
9046  appendStringInfoChar(&escapedpath, '\\');
9047  appendStringInfoChar(&escapedpath, *s);
9048  }
9049  appendStringInfo(tblspcmapfile, "%s %s\n",
9050  de->d_name, escapedpath.data);
9051  pfree(escapedpath.data);
9052  }
9053  else if (de_type == PGFILETYPE_DIR)
9054  {
9055  /*
9056  * It's possible to use allow_in_place_tablespaces to create
9057  * directories directly under pg_tblspc, for testing purposes
9058  * only.
9059  *
9060  * In this case, we store a relative path rather than an
9061  * absolute path into the tablespaceinfo.
9062  */
9063  snprintf(linkpath, sizeof(linkpath), "%s/%s",
9064  PG_TBLSPC_DIR, de->d_name);
9065  relpath = pstrdup(linkpath);
9066  }
9067  else
9068  {
9069  /* Skip any other file type that appears here. */
9070  continue;
9071  }
9072 
9073  ti = palloc(sizeof(tablespaceinfo));
9074  ti->oid = tsoid;
9075  ti->path = pstrdup(linkpath);
9076  ti->rpath = relpath;
9077  ti->size = -1;
9078 
9079  if (tablespaces)
9080  *tablespaces = lappend(*tablespaces, ti);
9081  }
9082  FreeDir(tblspcdir);
9083 
9084  state->starttime = (pg_time_t) time(NULL);
9085  }
9087 
9088  state->started_in_recovery = backup_started_in_recovery;
9089 
9090  /*
9091  * Mark that the start phase has correctly finished for the backup.
9092  */
9094 }
9095 
9096 /*
9097  * Utility routine to fetch the session-level status of a backup running.
9098  */
9101 {
9102  return sessionBackupState;
9103 }
9104 
9105 /*
9106  * do_pg_backup_stop
9107  *
9108  * Utility function called at the end of an online backup. It creates history
9109  * file (if required), resets sessionBackupState and so on. It can optionally
9110  * wait for WAL segments to be archived.
9111  *
9112  * "state" is filled with the information necessary to restore from this
9113  * backup with its stop LSN (stoppoint), its timeline ID (stoptli), etc.
9114  *
9115  * It is the responsibility of the caller of this function to verify the
9116  * permissions of the calling user!
9117  */
9118 void
9119 do_pg_backup_stop(BackupState *state, bool waitforarchive)
9120 {
9121  bool backup_stopped_in_recovery = false;
9122  char histfilepath[MAXPGPATH];
9123  char lastxlogfilename[MAXFNAMELEN];
9124  char histfilename[MAXFNAMELEN];
9125  XLogSegNo _logSegNo;
9126  FILE *fp;
9127  int seconds_before_warning;
9128  int waits = 0;
9129  bool reported_waiting = false;
9130 
9131  Assert(state != NULL);
9132 
9133  backup_stopped_in_recovery = RecoveryInProgress();
9134 
9135  /*
9136  * During recovery, we don't need to check WAL level. Because, if WAL
9137  * level is not sufficient, it's impossible to get here during recovery.
9138  */
9139  if (!backup_stopped_in_recovery && !XLogIsNeeded())
9140  ereport(ERROR,
9141  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9142  errmsg("WAL level not sufficient for making an online backup"),
9143  errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start.")));
9144 
9145  /*
9146  * OK to update backup counter and session-level lock.
9147  *
9148  * Note that CHECK_FOR_INTERRUPTS() must not occur while updating them,
9149  * otherwise they can be updated inconsistently, which might cause
9150  * do_pg_abort_backup() to fail.
9151  */
9153 
9154  /*
9155  * It is expected that each do_pg_backup_start() call is matched by
9156  * exactly one do_pg_backup_stop() call.
9157  */
9160 
9161  /*
9162  * Clean up session-level lock.
9163  *
9164  * You might think that WALInsertLockRelease() can be called before
9165  * cleaning up session-level lock because session-level lock doesn't need
9166  * to be protected with WAL insertion lock. But since
9167  * CHECK_FOR_INTERRUPTS() can occur in it, session-level lock must be
9168  * cleaned up before it.
9169  */
9171 
9173 
9174  /*
9175  * If we are taking an online backup from the standby, we confirm that the
9176  * standby has not been promoted during the backup.
9177  */
9178  if (state->started_in_recovery && !backup_stopped_in_recovery)
9179  ereport(ERROR,
9180  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9181  errmsg("the standby was promoted during online backup"),
9182  errhint("This means that the backup being taken is corrupt "
9183  "and should not be used. "
9184  "Try taking another online backup.")));
9185 
9186  /*
9187  * During recovery, we don't write an end-of-backup record. We assume that
9188  * pg_control was backed up last and its minimum recovery point can be
9189  * available as the backup end location. Since we don't have an
9190  * end-of-backup record, we use the pg_control value to check whether
9191  * we've reached the end of backup when starting recovery from this
9192  * backup. We have no way of checking if pg_control wasn't backed up last
9193  * however.
9194  *
9195  * We don't force a switch to new WAL file but it is still possible to
9196  * wait for all the required files to be archived if waitforarchive is
9197  * true. This is okay if we use the backup to start a standby and fetch
9198  * the missing WAL using streaming replication. But in the case of an
9199  * archive recovery, a user should set waitforarchive to true and wait for
9200  * them to be archived to ensure that all the required files are
9201  * available.
9202  *
9203  * We return the current minimum recovery point as the backup end
9204  * location. Note that it can be greater than the exact backup end
9205  * location if the minimum recovery point is updated after the backup of
9206  * pg_control. This is harmless for current uses.
9207  *
9208  * XXX currently a backup history file is for informational and debug
9209  * purposes only. It's not essential for an online backup. Furthermore,
9210  * even if it's created, it will not be archived during recovery because
9211  * an archiver is not invoked. So it doesn't seem worthwhile to write a
9212  * backup history file during recovery.
9213  */
9214  if (backup_stopped_in_recovery)
9215  {
9216  XLogRecPtr recptr;
9217 
9218  /*
9219  * Check to see if all WAL replayed during online backup contain
9220  * full-page writes.
9221  */
9223  recptr = XLogCtl->lastFpwDisableRecPtr;
9225 
9226  if (state->startpoint <= recptr)
9227  ereport(ERROR,
9228  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9229  errmsg("WAL generated with \"full_page_writes=off\" was replayed "
9230  "during online backup"),
9231  errhint("This means that the backup being taken on the standby "
9232  "is corrupt and should not be used. "
9233  "Enable \"full_page_writes\" and run CHECKPOINT on the primary, "
9234  "and then try an online backup again.")));
9235 
9236 
9237  LWLockAcquire(ControlFileLock, LW_SHARED);
9238  state->stoppoint = ControlFile->minRecoveryPoint;
9240  LWLockRelease(ControlFileLock);
9241  }
9242  else
9243  {
9244  char *history_file;
9245 
9246  /*
9247  * Write the backup-end xlog record
9248  */
9249  XLogBeginInsert();
9250  XLogRegisterData((char *) (&state->startpoint),
9251  sizeof(state->startpoint));
9252  state->stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END);
9253 
9254  /*
9255  * Given that we're not in recovery, InsertTimeLineID is set and can't
9256  * change, so we can read it without a lock.
9257  */
9258  state->stoptli = XLogCtl->InsertTimeLineID;
9259 
9260  /*
9261  * Force a switch to a new xlog segment file, so that the backup is
9262  * valid as soon as archiver moves out the current segment file.
9263  */
9264  RequestXLogSwitch(false);
9265 
9266  state->stoptime = (pg_time_t) time(NULL);
9267 
9268  /*
9269  * Write the backup history file
9270  */
9271  XLByteToSeg(state->startpoint, _logSegNo, wal_segment_size);
9272  BackupHistoryFilePath(histfilepath, state->stoptli, _logSegNo,
9273  state->startpoint, wal_segment_size);
9274  fp = AllocateFile(histfilepath, "w");
9275  if (!fp)
9276  ereport(ERROR,
9278  errmsg("could not create file \"%s\": %m",
9279  histfilepath)));
9280 
9281  /* Build and save the contents of the backup history file */
9282  history_file = build_backup_content(state, true);
9283  fprintf(fp, "%s", history_file);
9284  pfree(history_file);
9285 
9286  if (fflush(fp) || ferror(fp) || FreeFile(fp))
9287  ereport(ERROR,
9289  errmsg("could not write file \"%s\": %m",
9290  histfilepath)));
9291 
9292  /*
9293  * Clean out any no-longer-needed history files. As a side effect,
9294  * this will post a .ready file for the newly created history file,
9295  * notifying the archiver that history file may be archived
9296  * immediately.
9297  */
9299  }
9300 
9301  /*
9302  * If archiving is enabled, wait for all the required WAL files to be
9303  * archived before returning. If archiving isn't enabled, the required WAL
9304  * needs to be transported via streaming replication (hopefully with
9305  * wal_keep_size set high enough), or some more exotic mechanism like
9306  * polling and copying files from pg_wal with script. We have no knowledge
9307  * of those mechanisms, so it's up to the user to ensure that he gets all
9308  * the required WAL.
9309  *
9310  * We wait until both the last WAL file filled during backup and the
9311  * history file have been archived, and assume that the alphabetic sorting
9312  * property of the WAL files ensures any earlier WAL files are safely
9313  * archived as well.
9314  *
9315  * We wait forever, since archive_command is supposed to work and we
9316  * assume the admin wanted his backup to work completely. If you don't
9317  * wish to wait, then either waitforarchive should be passed in as false,
9318  * or you can set statement_timeout. Also, some notices are issued to
9319  * clue in anyone who might be doing this interactively.
9320  */
9321 
9322  if (waitforarchive &&
9323  ((!backup_stopped_in_recovery && XLogArchivingActive()) ||
9324  (backup_stopped_in_recovery && XLogArchivingAlways())))
9325  {
9326  XLByteToPrevSeg(state->stoppoint, _logSegNo, wal_segment_size);
9327  XLogFileName(lastxlogfilename, state->stoptli, _logSegNo,
9329 
9330  XLByteToSeg(state->startpoint, _logSegNo, wal_segment_size);
9331  BackupHistoryFileName(histfilename, state->stoptli, _logSegNo,
9332  state->startpoint, wal_segment_size);
9333 
9334  seconds_before_warning = 60;
9335  waits = 0;
9336 
9337  while (XLogArchiveIsBusy(lastxlogfilename) ||
9338  XLogArchiveIsBusy(histfilename))
9339  {
9341 
9342  if (!reported_waiting && waits > 5)
9343  {
9344  ereport(NOTICE,
9345  (errmsg("base backup done, waiting for required WAL segments to be archived")));
9346  reported_waiting = true;
9347  }
9348 
9349  (void) WaitLatch(MyLatch,
9351  1000L,
9352  WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE);
9354 
9355  if (++waits >= seconds_before_warning)
9356  {
9357  seconds_before_warning *= 2; /* This wraps in >10 years... */
9358  ereport(WARNING,
9359  (errmsg("still waiting for all required WAL segments to be archived (%d seconds elapsed)",
9360  waits),
9361  errhint("Check that your \"archive_command\" is executing properly. "
9362  "You can safely cancel this backup, "
9363  "but the database backup will not be usable without all the WAL segments.")));
9364  }
9365  }
9366 
9367  ereport(NOTICE,
9368  (errmsg("all required WAL segments have been archived")));
9369  }
9370  else if (waitforarchive)
9371  ereport(NOTICE,
9372  (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
9373 }
9374 
9375 
9376 /*
9377  * do_pg_abort_backup: abort a running backup
9378  *
9379  * This does just the most basic steps of do_pg_backup_stop(), by taking the
9380  * system out of backup mode, thus making it a lot more safe to call from
9381  * an error handler.
9382  *
9383  * 'arg' indicates that it's being called during backup setup; so
9384  * sessionBackupState has not been modified yet, but runningBackups has
9385  * already been incremented. When it's false, then it's invoked as a
9386  * before_shmem_exit handler, and therefore we must not change state
9387  * unless sessionBackupState indicates that a backup is actually running.
9388  *
9389  * NB: This gets used as a PG_ENSURE_ERROR_CLEANUP callback and
9390  * before_shmem_exit handler, hence the odd-looking signature.
9391  */
9392 void
9394 {
9395  bool during_backup_start = DatumGetBool(arg);
9396 
9397  /* If called during backup start, there shouldn't be one already running */
9398  Assert(!during_backup_start || sessionBackupState == SESSION_BACKUP_NONE);
9399 
9400  if (during_backup_start || sessionBackupState != SESSION_BACKUP_NONE)
9401  {
9405 
9408 
9409  if (!during_backup_start)
9410  ereport(WARNING,
9411  errmsg("aborting backup due to backend exiting before pg_backup_stop was called"));
9412  }
9413 }
9414 
9415 /*
9416  * Register a handler that will warn about unterminated backups at end of
9417  * session, unless this has already been done.
9418  */
9419 void
9421 {
9422  static bool already_done = false;
9423 
9424  if (already_done)
9425  return;
9427  already_done = true;
9428 }
9429 
9430 /*
9431  * Get latest WAL insert pointer
9432  */
9433 XLogRecPtr
9435 {
9437  uint64 current_bytepos;
9438 
9439  SpinLockAcquire(&Insert->insertpos_lck);
9440  current_bytepos = Insert->CurrBytePos;
9441  SpinLockRelease(&Insert->insertpos_lck);
9442 
9443  return XLogBytePosToRecPtr(current_bytepos);
9444 }
9445 
9446 /*
9447  * Get latest WAL write pointer
9448  */
9449 XLogRecPtr
9451 {
9453 
9454  return LogwrtResult.Write;
9455 }
9456 
9457 /*
9458  * Returns the redo pointer of the last checkpoint or restartpoint. This is
9459  * the oldest point in WAL that we still need, if we have to restart recovery.
9460  */
9461 void
9463 {
9464  LWLockAcquire(ControlFileLock, LW_SHARED);
9465  *oldrecptr = ControlFile->checkPointCopy.redo;
9467  LWLockRelease(ControlFileLock);
9468 }
9469 
9470 /* Thin wrapper around ShutdownWalRcv(). */
9471 void
9473 {
9474  ShutdownWalRcv();
9475 
9476  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9478  LWLockRelease(ControlFileLock);
9479 }
9480 
9481 /* Enable WAL file recycling and preallocation. */
9482 void
9484 {
9485  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9487  LWLockRelease(ControlFileLock);
9488 }
9489 
9490 bool
9492 {
9493  bool result;
9494 
9495  LWLockAcquire(ControlFileLock, LW_SHARED);
9497  LWLockRelease(ControlFileLock);
9498 
9499  return result;
9500 }
9501 
9502 /*
9503  * Update the WalWriterSleeping flag.
9504  */
9505 void
9506 SetWalWriterSleeping(bool sleeping)
9507 {
9509  XLogCtl->WalWriterSleeping = sleeping;
9511 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
static void pg_atomic_write_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:485
#define pg_memory_barrier()
Definition: atomics.h:143
#define pg_read_barrier()
Definition: atomics.h:156
static uint64 pg_atomic_read_membarrier_u64(volatile pg_atomic_uint64 *ptr)
Definition: atomics.h:476
#define pg_write_barrier()
Definition: atomics.h:157
static uint64 pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target)
Definition: atomics.h:585
static uint64 pg_atomic_fetch_add_u64(volatile pg_atomic_uint64 *ptr, int64 add_)
Definition: atomics.h:522
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:453
static void pg_atomic_write_membarrier_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:494
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition: atomics.h:467
TimeLineID findNewestTimeLine(TimeLineID startTLI)
Definition: timeline.c:264
void restoreTimeLineHistoryFiles(TimeLineID begin, TimeLineID end)
Definition: timeline.c:50
void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI, XLogRecPtr switchpoint, char *reason)
Definition: timeline.c:304
void startup_progress_timeout_handler(void)
Definition: startup.c:303
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1756
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1780
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1608
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1843
static bool backup_started_in_recovery
Definition: basebackup.c:124
int Buffer
Definition: buf.h:23
void CheckPointBuffers(int flags)
Definition: bufmgr.c:3710
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4941
unsigned int uint32
Definition: c.h:506
#define Min(x, y)
Definition: c.h:995
#define pg_attribute_unused()
Definition: c.h:126
#define likely(x)
Definition: c.h:313
#define MAXALIGN(LEN)
Definition: c.h:802
#define TYPEALIGN(ALIGNVAL, LEN)
Definition: c.h:795
#define Max(x, y)
Definition: c.h:989
#define Assert(condition)
Definition: c.h:849
#define PG_BINARY
Definition: c.h:1264
#define pg_attribute_always_inline
Definition: c.h:237
#define FLOAT8PASSBYVAL
Definition: c.h:626
#define unlikely(x)
Definition: c.h:314
#define MAXALIGN64(LEN)
Definition: c.h:827
#define PG_UINT64_MAX
Definition: c.h:584
unsigned char uint8
Definition: c.h:504
#define MemSet(start, val, len)
Definition: c.h:1011
uint32 TransactionId
Definition: c.h:643
size_t Size
Definition: c.h:596
#define CATALOG_VERSION_NO
Definition: catversion.h:60
void AbsorbSyncRequests(void)
double CheckPointCompletionTarget
Definition: checkpointer.c:138
void RequestCheckpoint(int flags)
Definition: checkpointer.c:952
void BootStrapCLOG(void)
Definition: clog.c:833
void StartupCLOG(void)
Definition: clog.c:877
void CheckPointCLOG(void)
Definition: clog.c:937
void TrimCLOG(void)
Definition: clog.c:892
void StartupCommitTs(void)
Definition: commit_ts.c:632
void CommitTsParameterChange(bool newvalue, bool oldvalue)
Definition: commit_ts.c:664
bool track_commit_timestamp
Definition: commit_ts.c:109
void CompleteCommitTsInitialization(void)
Definition: commit_ts.c:642
void BootStrapCommitTs(void)
Definition: commit_ts.c:596
void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact)
Definition: commit_ts.c:909
void CheckPointCommitTs(void)
Definition: commit_ts.c:820
void update_controlfile(const char *DataDir, ControlFileData *ControlFile, bool do_sync)
int64 TimestampTz
Definition: timestamp.h:39
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1180
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errcode_for_file_access(void)
Definition: elog.c:876
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define _(x)
Definition: elog.c:90
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define WARNING
Definition: elog.h:36
#define DEBUG2
Definition: elog.h:29
#define PANIC
Definition: elog.h:42
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define NOTICE
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:149
struct pg_atomic_uint64 pg_atomic_uint64
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2932
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3937
int FreeDir(DIR *dir)
Definition: fd.c:2984
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:441
int io_direct_flags
Definition: fd.c:168
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2606
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:782
int pg_fdatasync(int fd)
Definition: fd.c:480
int CloseTransientFile(int fd)
Definition: fd.c:2832
int BasicOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:1087
int FreeFile(FILE *file)
Definition: fd.c:2804
int pg_fsync_writethrough(int fd)
Definition: fd.c:461
void ReleaseExternalFD(void)
Definition: fd.c:1239
int data_sync_elevel(int elevel)
Definition: fd.c:3960
static void Insert(File file)
Definition: fd.c:1313
int durable_unlink(const char *fname, int elevel)
Definition: fd.c:872
void ReserveExternalFD(void)
Definition: fd.c:1221
int pg_fsync(int fd)
Definition: fd.c:386
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2656
void SyncDataDirectory(void)
Definition: fd.c:3568
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2866
#define IO_DIRECT_WAL
Definition: fd.h:55
#define IO_DIRECT_WAL_INIT
Definition: fd.h:56
#define PG_O_DIRECT
Definition: fd.h:97
ssize_t pg_pwrite_zeros(int fd, size_t size, off_t offset)
Definition: file_utils.c:688
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition: file_utils.c:526
PGFileType
Definition: file_utils.h:19
@ PGFILETYPE_LNK
Definition: file_utils.h:24
@ PGFILETYPE_DIR
Definition: file_utils.h:23
@ PGFILETYPE_REG
Definition: file_utils.h:22
bool IsBinaryUpgrade
Definition: globals.c:120
int NBuffers
Definition: globals.c:141
bool enableFsync
Definition: globals.c:128
ProcNumber MyProcNumber
Definition: globals.c:89
bool IsUnderPostmaster
Definition: globals.c:119
int MaxConnections
Definition: globals.c:142
volatile uint32 CritSectionCount
Definition: globals.c:44
char * DataDir
Definition: globals.c:70
bool IsPostmasterEnvironment
Definition: globals.c:118
struct Latch * MyLatch
Definition: globals.c:62
int max_worker_processes
Definition: globals.c:143
void * guc_malloc(int elevel, size_t size)
Definition: guc.c:637
struct config_generic * find_option(const char *name, bool create_placeholders, bool skip_errors, int elevel)
Definition: guc.c:1234
int set_config_option_ext(const char *name, const char *value, GucContext context, GucSource source, Oid srole, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:3381
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4290
#define newval
@ GUC_ACTION_SET
Definition: guc.h:199
#define GUC_check_errdetail
Definition: guc.h:476
GucSource
Definition: guc.h:108
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:110
@ PGC_S_OVERRIDE
Definition: guc.h:119
@ PGC_INTERNAL
Definition: guc.h:69
@ PGC_POSTMASTER
Definition: guc.h:70
return str start
#define TOAST_MAX_CHUNK_SIZE
Definition: heaptoast.h:84
#define INJECTION_POINT(name)
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:122
#define INSTR_TIME_SET_ZERO(t)
Definition: instr_time.h:172
#define INSTR_TIME_ACCUM_DIFF(x, y, z)
Definition: instr_time.h:184
WalUsage pgWalUsage
Definition: instrument.c:22
#define close(a)
Definition: win32.h:12
#define write(a, b, c)
Definition: win32.h:14
#define read(a, b, c)
Definition: win32.h:13
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define LOBLKSIZE
Definition: large_object.h:70
void SetLatch(Latch *latch)
Definition: latch.c:632
void ResetLatch(Latch *latch)
Definition: latch.c:724
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:517
#define WL_TIMEOUT
Definition: latch.h:130
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_LATCH_SET
Definition: latch.h:127
static void const char fflush(stdout)
List * lappend(List *list, void *datum)
Definition: list.c:339
void list_free(List *list)
Definition: list.c:1546
int max_locks_per_xact
Definition: lock.c:53
void LWLockUpdateVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
Definition: lwlock.c:1720
void LWLockReleaseClearVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
Definition: lwlock.c:1854
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1168
bool LWLockWaitForVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 oldval, uint64 *newval)
Definition: lwlock.c:1584
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:707
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1339
bool LWLockAcquireOrWait(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1396
@ LWTRANCHE_WAL_INSERT
Definition: lwlock.h:186
@ LW_SHARED
Definition: lwlock.h:115
@ LW_EXCLUSIVE
Definition: lwlock.h:114
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void pfree(void *pointer)
Definition: mcxt.c:1521
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition: mcxt.c:694
void * palloc(Size size)
Definition: mcxt.c:1317
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:451
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
@ B_CHECKPOINTER
Definition: miscadmin.h:354
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
#define AmWalReceiverProcess()
Definition: miscadmin.h:380
bool process_shared_preload_libraries_done
Definition: miscinit.c:1779
BackendType MyBackendType
Definition: miscinit.c:63
void MultiXactSetNextMXact(MultiXactId nextMulti, MultiXactOffset nextMultiOffset)
Definition: multixact.c:2328
void MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
Definition: multixact.c:2536
void MultiXactGetCheckptMulti(bool is_shutdown, MultiXactId *nextMulti, MultiXactOffset *nextMultiOffset, MultiXactId *oldestMulti, Oid *oldestMultiDB)
Definition: multixact.c:2282
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2362
void CheckPointMultiXact(void)
Definition: multixact.c:2304
void TrimMultiXact(void)
Definition: multixact.c:2178
void MultiXactAdvanceNextMXact(MultiXactId minMulti, MultiXactOffset minMultiOffset)
Definition: multixact.c:2511
void BootStrapMultiXact(void)
Definition: multixact.c:2034
void StartupMultiXact(void)
Definition: multixact.c:2153
#define FirstMultiXactId
Definition: multixact.h:25
void StartupReplicationOrigin(void)
Definition: origin.c:703
void CheckPointReplicationOrigin(void)
Definition: origin.c:577
void * arg
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
#define INDEX_MAX_KEYS
#define NAMEDATALEN
#define MAXPGPATH
#define DEFAULT_XLOG_SEG_SIZE
#define PG_IO_ALIGN_SIZE
#define PG_CACHE_LINE_SIZE
#define FLOATFORMAT_VALUE
Definition: pg_control.h:201
#define XLOG_RESTORE_POINT
Definition: pg_control.h:75
#define XLOG_FPW_CHANGE
Definition: pg_control.h:76
#define XLOG_CHECKPOINT_REDO
Definition: pg_control.h:82
#define PG_CONTROL_VERSION
Definition: pg_control.h:25
#define XLOG_OVERWRITE_CONTRECORD
Definition: pg_control.h:81
#define XLOG_FPI
Definition: pg_control.h:79
#define XLOG_FPI_FOR_HINT
Definition: pg_control.h:78
#define MOCK_AUTH_NONCE_LEN
Definition: pg_control.h:28
#define XLOG_NEXTOID
Definition: pg_control.h:71
@ DB_IN_PRODUCTION
Definition: pg_control.h:97
@ DB_SHUTDOWNING
Definition: pg_control.h:94
@ DB_IN_ARCHIVE_RECOVERY
Definition: pg_control.h:96
@ DB_SHUTDOWNED_IN_RECOVERY
Definition: pg_control.h:93
@ DB_SHUTDOWNED
Definition: pg_control.h:92
@ DB_IN_CRASH_RECOVERY
Definition: pg_control.h:95
#define XLOG_NOOP
Definition: pg_control.h:70
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:68
#define PG_CONTROL_FILE_SIZE
Definition: pg_control.h:250
#define XLOG_SWITCH
Definition: pg_control.h:72
#define XLOG_BACKUP_END
Definition: pg_control.h:73
#define XLOG_PARAMETER_CHANGE
Definition: pg_control.h:74
#define XLOG_CHECKPOINT_ONLINE
Definition: pg_control.h:69
#define XLOG_END_OF_RECOVERY
Definition: pg_control.h:77
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:98
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:103
const void size_t len
return crc
static char * filename
Definition: pg_dumpall.c:119
#define lfirst(lc)
Definition: pg_list.h:172
static rewind_source * source
Definition: pg_rewind.c:89
static char * buf
Definition: pg_test_fsync.c:73
void pgstat_restore_stats(XLogRecPtr redo)
Definition: pgstat.c:477
void pgstat_discard_stats(void)
Definition: pgstat.c:489
PgStat_CheckpointerStats PendingCheckpointerStats
PgStat_PendingWalStats PendingWalStats
Definition: pgstat_wal.c:24
int64 pg_time_t
Definition: pgtime.h:23
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
Definition: localtime.c:1344
size_t pg_strftime(char *s, size_t maxsize, const char *format, const struct pg_tm *t)
Definition: strftime.c:128
PGDLLIMPORT pg_tz * log_timezone
Definition: pgtz.c:31
bool pg_strong_random(void *buf, size_t len)
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define pg_pwrite
Definition: port.h:226
#define snprintf
Definition: port.h:238
#define fprintf
Definition: port.h:242
#define IS_DIR_SEP(ch)
Definition: port.h:102
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
uintptr_t Datum
Definition: postgres.h:64
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void CheckPointPredicate(void)
Definition: predicate.c:1041
static int fd(const char *x, int i)
Definition: preproc-init.c:105
short access
Definition: preproc-type.c:36
#define DELAY_CHKPT_START
Definition: proc.h:119
#define DELAY_CHKPT_COMPLETE
Definition: proc.h:120
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids, int type)
Definition: procarray.c:3047
bool MinimumActiveBackends(int min)
Definition: procarray.c:3550
TransactionId GetOldestActiveTransactionId(void)
Definition: procarray.c:2884
TransactionId GetOldestTransactionIdConsideredRunning(void)
Definition: procarray.c:2034
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids, int type)
Definition: procarray.c:3093
void ProcArrayApplyRecoveryInfo(RunningTransactions running)
Definition: procarray.c:1054
void ProcArrayInitRecovery(TransactionId initializedUptoXID)
Definition: procarray.c:1023
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
MemoryContextSwitchTo(old_ctx)
void ResetUnloggedRelations(int op)
Definition: reinit.c:47
#define UNLOGGED_RELATION_INIT
Definition: reinit.h:28
#define UNLOGGED_RELATION_CLEANUP
Definition: reinit.h:27
void RelationCacheInitFileRemove(void)
Definition: relcache.c:6810
void CheckPointRelationMap(void)
Definition: relmapper.c:611
#define relpath(rlocator, forknum)
Definition: relpath.h:102
#define PG_TBLSPC_DIR
Definition: relpath.h:41
void StartupReorderBuffer(void)
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
ResourceOwner AuxProcessResourceOwner
Definition: resowner.c:168
void CheckPointLogicalRewriteHeap(void)
Definition: rewriteheap.c:1155
#define RM_MAX_ID
Definition: rmgr.h:33
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
void pg_usleep(long microsec)
Definition: signal.c:53
static pg_noinline void Size size
Definition: slab.c:607
void CheckPointReplicationSlots(bool is_shutdown)
Definition: slot.c:1867
bool InvalidateObsoleteReplicationSlots(ReplicationSlotInvalidationCause cause, XLogSegNo oldestSegno, Oid dboid, TransactionId snapshotConflictHorizon)
Definition: slot.c:1811
void StartupReplicationSlots(void)
Definition: slot.c:1924
@ RS_INVAL_WAL_REMOVED
Definition: slot.h:54
@ RS_INVAL_WAL_LEVEL
Definition: slot.h:58
void CheckPointSnapBuild(void)
Definition: snapbuild.c:1922
void DeleteAllExportedSnapshotFiles(void)
Definition: snapmgr.c:1567
#define SpinLockInit(lock)
Definition: spin.h:57
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
void reset(void)
Definition: sql-declare.c:600
PGPROC * MyProc
Definition: proc.c:67
PROC_HDR * ProcGlobal
Definition: proc.c:79
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1281
void InitRecoveryTransactionEnvironment(void)
Definition: standby.c:94
void ShutdownRecoveryTransactionEnvironment(void)
Definition: standby.c:160
@ SUBXIDS_IN_SUBTRANS
Definition: standby.h:82
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:233
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Oid oldestMultiDB
Definition: pg_control.h:51
MultiXactId oldestMulti
Definition: pg_control.h:50
MultiXactOffset nextMultiOffset
Definition: pg_control.h:47
TransactionId newestCommitTsXid
Definition: pg_control.h:55
TransactionId oldestXid
Definition: pg_control.h:48
TimeLineID PrevTimeLineID
Definition: pg_control.h:40
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
Oid nextOid
Definition: pg_control.h:45
TransactionId oldestActiveXid
Definition: pg_control.h:64
bool fullPageWrites
Definition: pg_control.h:42
MultiXactId nextMulti
Definition: pg_control.h:46
FullTransactionId nextXid
Definition: pg_control.h:44
TransactionId oldestCommitTsXid
Definition: pg_control.h:53
pg_time_t time
Definition: pg_control.h:52
int wal_level
Definition: pg_control.h:43
XLogRecPtr redo
Definition: pg_control.h:37
Oid oldestXidDB
Definition: pg_control.h:49
uint64 ckpt_agg_sync_time
Definition: xlog.h:176
uint64 ckpt_longest_sync
Definition: xlog.h:175
TimestampTz ckpt_start_t
Definition: xlog.h:161
TimestampTz ckpt_end_t
Definition: xlog.h:165
int ckpt_segs_removed
Definition: xlog.h:171
TimestampTz ckpt_write_t
Definition: xlog.h:162
int ckpt_segs_added
Definition: xlog.h:170
TimestampTz ckpt_sync_end_t
Definition: xlog.h:164
TimestampTz ckpt_sync_t
Definition: xlog.h:163
int ckpt_bufs_written
Definition: xlog.h:167
int ckpt_segs_recycled
Definition: xlog.h:172
int ckpt_slru_written
Definition: xlog.h:168
int ckpt_sync_rels
Definition: xlog.h:174
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:229
int max_worker_processes
Definition: pg_control.h:181
uint32 pg_control_version
Definition: pg_control.h:125
uint32 xlog_seg_size
Definition: pg_control.h:211
XLogRecPtr backupStartPoint
Definition: pg_control.h:170
bool track_commit_timestamp
Definition: pg_control.h:185
bool backupEndRequired
Definition: pg_control.h:172
int max_locks_per_xact
Definition: pg_control.h:184
uint32 nameDataLen
Definition: pg_control.h:213
CheckPoint checkPointCopy
Definition: pg_control.h:135
XLogRecPtr backupEndPoint
Definition: pg_control.h:171
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:168
uint32 data_checksum_version
Definition: pg_control.h:222
XLogRecPtr unloggedLSN
Definition: pg_control.h:137
uint32 indexMaxKeys
Definition: pg_control.h:214
uint32 relseg_size
Definition: pg_control.h:208
pg_time_t time
Definition: pg_control.h:132
XLogRecPtr checkPoint
Definition: pg_control.h:133
uint64 system_identifier
Definition: pg_control.h:110
uint32 catalog_version_no
Definition: pg_control.h:126
double floatFormat
Definition: pg_control.h:200
int max_prepared_xacts
Definition: pg_control.h:183
uint32 xlog_blcksz
Definition: pg_control.h:210
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:169
uint32 loblksize
Definition: pg_control.h:217
pg_crc32c crc
Definition: pg_control.h:232
uint32 toast_max_chunk_size
Definition: pg_control.h:216
Definition: dirent.c:26
XLogRecPtr lastPageBeginPtr
Definition: xlogrecovery.h:111
XLogRecPtr abortedRecPtr
Definition: xlogrecovery.h:120
XLogRecPtr missingContrecPtr
Definition: xlogrecovery.h:121
TimeLineID endOfLogTLI
Definition: xlogrecovery.h:109
Definition: lwlock.h:42
Definition: pg_list.h:54
Latch * walwriterLatch
Definition: proc.h:416
PgStat_Counter sync_time
Definition: pgstat.h:302
PgStat_Counter write_time
Definition: pgstat.h:301
instr_time wal_sync_time
Definition: pgstat.h:491
PgStat_Counter wal_write
Definition: pgstat.h:488
PgStat_Counter wal_buffers_full
Definition: pgstat.h:487
PgStat_Counter wal_sync
Definition: pgstat.h:489
instr_time wal_write_time
Definition: pgstat.h:490
void(* rm_mask)(char *pagedata, BlockNumber blkno)
TransactionId oldestRunningXid
Definition: standby.h:92
TransactionId nextXid
Definition: standby.h:91
TransactionId latestCompletedXid
Definition: standby.h:95
subxids_array_status subxid_status
Definition: standby.h:90
TransactionId * xids
Definition: standby.h:97
TransactionId oldestCommitTsXid
Definition: transam.h:232
TransactionId newestCommitTsXid
Definition: transam.h:233
FullTransactionId latestCompletedXid
Definition: transam.h:238
FullTransactionId nextXid
Definition: transam.h:220
TransactionId oldestXid
Definition: transam.h:222
pg_atomic_uint64 insertingAt
Definition: xlog.c:369
XLogRecPtr lastImportantAt
Definition: xlog.c:370
LWLock lock
Definition: xlog.c:368
uint64 wal_bytes
Definition: instrument.h:55
int64 wal_fpi
Definition: instrument.h:54
int64 wal_records
Definition: instrument.h:53
CheckPoint lastCheckPoint
Definition: xlog.c:544
XLogwrtRqst LogwrtRqst
Definition: xlog.c:454
slock_t info_lck
Definition: xlog.c:552
XLogRecPtr InitializedUpTo
Definition: xlog.c:484
char * pages
Definition: xlog.c:491
FullTransactionId ckptFullXid
Definition: xlog.c:456
pg_time_t lastSegSwitchTime
Definition: xlog.c:466
XLogRecPtr replicationSlotMinLSN
Definition: xlog.c:458
RecoveryState SharedRecoveryState
Definition: xlog.c:515
TimeLineID InsertTimeLineID
Definition: xlog.c:508
XLogRecPtr lastSegSwitchLSN
Definition: xlog.c:467
XLogSegNo lastRemovedSegNo
Definition: xlog.c:460
pg_atomic_uint64 * xlblocks
Definition: xlog.c:492
pg_atomic_uint64 logWriteResult
Definition: xlog.c:471
int XLogCacheBlck
Definition: xlog.c:493
XLogRecPtr RedoRecPtr
Definition: xlog.c:455
XLogRecPtr lastCheckPointRecPtr
Definition: xlog.c:542
XLogRecPtr lastFpwDisableRecPtr
Definition: xlog.c:550
XLogCtlInsert Insert
Definition: xlog.c:451
bool InstallXLogFileSegmentActive
Definition: xlog.c:525
bool WalWriterSleeping
Definition: xlog.c:532
XLogRecPtr asyncXactLSN
Definition: xlog.c:457
XLogRecPtr lastCheckPointEndPtr
Definition: xlog.c:543
pg_atomic_uint64 logFlushResult
Definition: xlog.c:472
pg_atomic_uint64 logInsertResult
Definition: xlog.c:470
TimeLineID PrevTimeLineID
Definition: xlog.c:509
pg_atomic_uint64 unloggedLSN
Definition: xlog.c:463
WALInsertLockPadded * WALInsertLocks
Definition: xlog.c:443
XLogRecPtr RedoRecPtr
Definition: xlog.c:429
uint64 PrevBytePos
Definition: xlog.c:407
char pad[PG_CACHE_LINE_SIZE]
Definition: xlog.c:416
int runningBackups
Definition: xlog.c:437
slock_t insertpos_lck
Definition: xlog.c:397
uint64 CurrBytePos
Definition: xlog.c:406
bool fullPageWrites
Definition: xlog.c:430
XLogRecPtr lastBackupStart
Definition: xlog.c:438
TimeLineID xlp_tli
Definition: xlog_internal.h:40
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
DecodedXLogRecord * record
Definition: xlogreader.h:236
XLogRecPtr EndRecPtr
Definition: xlogreader.h:207
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:206
const char * data
struct XLogRecData * next
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
pg_crc32c xl_crc
Definition: xlogrecord.h:49
uint8 xl_info
Definition: xlogrecord.h:46
uint32 xl_tot_len
Definition: xlogrecord.h:43
TransactionId xl_xid
Definition: xlogrecord.h:44
RmgrId xl_rmid
Definition: xlogrecord.h:47
XLogRecPtr Flush
Definition: xlog.c:327
XLogRecPtr Write
Definition: xlog.c:326
XLogRecPtr Flush
Definition: xlog.c:321
XLogRecPtr Write
Definition: xlog.c:320
Definition: guc.h:170
GucContext scontext
Definition: guc_tables.h:167
GucSource source
Definition: guc_tables.h:165
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
unsigned short st_mode
Definition: win32_port.h:268
Definition: regguts.h:323
char * rpath
Definition: basebackup.h:32
TimeLineID PrevTimeLineID
TimestampTz end_time
TimeLineID ThisTimeLineID
char rp_name[MAXFNAMELEN]
TimestampTz rp_time
void StartupSUBTRANS(TransactionId oldestActiveXID)
Definition: subtrans.c:309
void CheckPointSUBTRANS(void)
Definition: subtrans.c:355
void BootStrapSUBTRANS(void)
Definition: subtrans.c:270
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:411
void ProcessSyncRequests(void)
Definition: sync.c:286
void SyncPreCheckpoint(void)
Definition: sync.c:177
void SyncPostCheckpoint(void)
Definition: sync.c:202
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:505
@ STARTUP_PROGRESS_TIMEOUT
Definition: timeout.h:38
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define TransactionIdRetreat(dest)
Definition: transam.h:141
#define InvalidTransactionId
Definition: transam.h:31
static void FullTransactionIdRetreat(FullTransactionId *dest)
Definition: transam.h:103
#define XidFromFullTransactionId(x)
Definition: transam.h:48
#define FirstGenbkiObjectId
Definition: transam.h:195
#define FirstNormalTransactionId
Definition: transam.h:34
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static FullTransactionId FullTransactionIdFromEpochAndXid(uint32 epoch, TransactionId xid)
Definition: transam.h:71
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define FullTransactionIdPrecedes(a, b)
Definition: transam.h:51
void RecoverPreparedTransactions(void)
Definition: twophase.c:2090
void restoreTwoPhaseData(void)
Definition: twophase.c:1905
int max_prepared_xacts
Definition: twophase.c:115
TransactionId PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
Definition: twophase.c:1969
void StandbyRecoverPreparedTransactions(void)
Definition: twophase.c:2049
void CheckPointTwoPhase(XLogRecPtr redo_horizon)
Definition: twophase.c:1823
char data[XLOG_BLCKSZ]
Definition: c.h:1139
WALInsertLock l
Definition: xlog.c:382
char pad[PG_CACHE_LINE_SIZE]
Definition: xlog.c:383
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3432
void SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
Definition: varsup.c:372
void AdvanceOldestClogXid(TransactionId oldest_datfrozenxid)
Definition: varsup.c:355
TransamVariablesData * TransamVariables
Definition: varsup.c:34
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:85
static void pgstat_report_wait_end(void)
Definition: wait_event.h:101
void WaitLSNSetLatches(XLogRecPtr currentLSN)
Definition: waitlsn.c:155
static TimestampTz wakeup[NUM_WALRCV_WAKEUPS]
Definition: walreceiver.c:129
XLogRecPtr Flush
Definition: walreceiver.c:111
XLogRecPtr Write
Definition: walreceiver.c:110
XLogRecPtr GetWalRcvFlushRecPtr(XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI)
void ShutdownWalRcv(void)
void WalSndWakeup(bool physical, bool logical)
Definition: walsender.c:3638
int max_wal_senders
Definition: walsender.c:121
void WalSndInitStopping(void)
Definition: walsender.c:3717
void WalSndWaitStopping(void)
Definition: walsender.c:3743
static void WalSndWakeupProcessRequests(bool physical, bool logical)
Definition: walsender.h:65
#define WalSndWakeupRequest()
Definition: walsender.h:58
void SetWalSummarizerLatch(void)
bool summarize_wal
void WaitForWalSummarization(XLogRecPtr lsn)
XLogRecPtr GetOldestUnsummarizedLSN(TimeLineID *tli, bool *lsn_is_exact)
int WalWriterFlushAfter
Definition: walwriter.c:72
int WalWriterDelay
Definition: walwriter.c:71
#define stat
Definition: win32_port.h:284
#define EINTR
Definition: win32_port.h:374
#define S_ISDIR(m)
Definition: win32_port.h:325
#define readlink(path, buf, size)
Definition: win32_port.h:236
#define O_CLOEXEC
Definition: win32_port.h:359
#define O_DSYNC
Definition: win32_port.h:352
int gettimeofday(struct timeval *tp, void *tzp)
void MarkSubxactTopXidLogged(void)
Definition: xact.c:590
void MarkCurrentTransactionIdLoggedIfAny(void)
Definition: xact.c:540
int XLogFileInit(XLogSegNo logsegno, TimeLineID logtli)
Definition: xlog.c:3373
void assign_wal_sync_method(int new_wal_sync_method, void *extra)
Definition: xlog.c:8640
static void CreateEndOfRecoveryRecord(void)
Definition: xlog.c:7374
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4561
int wal_decode_buffer_size
Definition: xlog.c:135
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:252
static XLogCtlData * XLogCtl
Definition: xlog.c:565
bool fullPageWrites
Definition: xlog.c:121
void UpdateFullPageWrites(void)
Definition: xlog.c:8165
bool RecoveryInProgress(void)
Definition: xlog.c:6333
static void CleanupBackupHistory(void)
Definition: xlog.c:4154
void GetFullPageWriteInfo(XLogRecPtr *RedoRecPtr_p, bool *doPageWrites_p)
Definition: xlog.c:6466
TimeLineID GetWALInsertionTimeLine(void)
Definition: xlog.c:6519
bool check_max_slot_wal_keep_size(int *newval, void **extra, GucSource source)
Definition: xlog.c:2222
const char * show_in_hot_standby(void)
Definition: xlog.c:4815
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:8059
void do_pg_abort_backup(int code, Datum arg)
Definition: xlog.c:9393
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3751
static char * str_time(pg_time_t tnow)
Definition: xlog.c:5192
char * XLogArchiveCommand
Definition: xlog.c:119
struct XLogCtlInsert XLogCtlInsert
int wal_keep_size_mb
Definition: xlog.c:115
Size WALReadFromBuffers(char *dstbuf, XLogRecPtr startptr, Size count, TimeLineID tli)
Definition: xlog.c:1747
static XLogRecPtr WaitXLogInsertionsToFinish(XLogRecPtr upto)
Definition: xlog.c:1503
static void WALInsertLockRelease(void)
Definition: xlog.c:1444
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:1857
bool EnableHotStandby
Definition: xlog.c:120
static void WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt)
Definition: xlog.c:1470
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:6436
void assign_wal_consistency_checking(const char *newval, void *extra)
Definition: xlog.c:4750
static void InitControlFile(uint64 sysidentifier, uint32 data_checksum_version)
Definition: xlog.c:4197
void SetInstallXLogFileSegmentActive(void)
Definition: xlog.c:9483
static void AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli, bool opportunistic)
Definition: xlog.c:1984
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1415
static void UpdateControlFile(void)
Definition: xlog.c:4552
void StartupXLOG(void)
Definition: xlog.c:5422
bool IsInstallXLogFileSegmentActive(void)
Definition: xlog.c:9491
static int openLogFile
Definition: xlog.c:634
void BootStrapXLOG(uint32 data_checksum_version)
Definition: xlog.c:5026
XLogRecPtr XactLastRecEnd
Definition: xlog.c:253
bool CreateRestartPoint(int flags)
Definition: xlog.c:7590
static void ValidateXLOGDirectoryStructure(void)
Definition: xlog.c:4092
int CommitDelay
Definition: xlog.c:131
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr, TimeLineID insertTLI)
Definition: xlog.c:3858
static XLogRecPtr CreateOverwriteContrecordRecord(XLogRecPtr aborted_lsn, XLogRecPtr pagePtr, TimeLineID newTLI)
Definition: xlog.c:7439
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:6481
bool wal_init_zero
Definition: xlog.c:126
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2161
int XLogArchiveMode
Definition: xlog.c:118
SessionBackupState get_backup_status(void)
Definition: xlog.c:9100
static void XLogReportParameters(void)
Definition: xlog.c:8102
#define RefreshXLogWriteResult(_target)
Definition: xlog.c:619
void CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
Definition: xlog.c:3720
int wal_level
Definition: xlog.c:130
static void LogCheckpointStart(int flags, bool restartpoint)
Definition: xlog.c:6648
static XLogRecPtr RedoRecPtr
Definition: xlog.c:272
void assign_checkpoint_completion_target(double newval, void *extra)
Definition: xlog.c:2197
static XLogRecPtr XLogGetReplicationSlotMinimumLSN(void)
Definition: xlog.c:2694
XLogRecPtr XLogInsertRecord(XLogRecData *rdata, XLogRecPtr fpw_lsn, uint8 flags, int num_fpi, bool topxid_included)
Definition: xlog.c:747
static bool InstallXLogFileSegment(XLogSegNo *segno, char *tmppath, bool find_free, XLogSegNo max_segno, TimeLineID tli)
Definition: xlog.c:3556
static void WriteControlFile(void)
Definition: xlog.c:4232
int wal_segment_size
Definition: xlog.c:142
struct XLogwrtResult XLogwrtResult
WALAvailability GetWALAvailability(XLogRecPtr targetLSN)
Definition: xlog.c:7868
#define UsableBytesInPage
Definition: xlog.c:596
int max_wal_size_mb
Definition: xlog.c:113
void XLOGShmemInit(void)
Definition: xlog.c:4911
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6601
bool DataChecksumsEnabled(void)
Definition: xlog.c:4581
static bool PerformRecoveryXLogAction(void)
Definition: xlog.c:6283
RecoveryState GetRecoveryState(void)
Definition: xlog.c:6369
int XLogArchiveTimeout
Definition: xlog.c:117
static void CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI, XLogRecPtr EndOfLog, TimeLineID newTLI)
Definition: xlog.c:5282
#define ConvertToXSegs(x, segsize)
Definition: xlog.c:602
bool wal_recycle
Definition: xlog.c:127
static void RemoveXlogFile(const struct dirent *segment_de, XLogSegNo recycleSegNo, XLogSegNo *endlogSegNo, TimeLineID insertTLI)
Definition: xlog.c:4002
pg_time_t GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
Definition: xlog.c:6584
char * GetMockAuthenticationNonce(void)
Definition: xlog.c:4571
static int XLOGChooseNumBuffers(void)
Definition: xlog.c:4614
static XLogRecPtr XLogBytePosToEndRecPtr(uint64 bytepos)
Definition: xlog.c:1897
static int get_sync_bit(int method)
Definition: xlog.c:8592
static XLogwrtResult LogwrtResult
Definition: xlog.c:611
void XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
Definition: xlog.c:2681
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:6680
union WALInsertLockPadded WALInsertLockPadded
void SwitchIntoArchiveRecovery(XLogRecPtr EndRecPtr, TimeLineID replayTLI)
Definition: xlog.c:6208
static bool lastFullPageWrites
Definition: xlog.c:216
char * wal_consistency_checking_string
Definition: xlog.c:124
static void WALInsertLockAcquire(void)
Definition: xlog.c:1370
int CommitSiblings
Definition: xlog.c:132
static void CopyXLogRecordToWAL(int write_len, bool isLogSwitch, XLogRecData *rdata, XLogRecPtr StartPos, XLogRecPtr EndPos, TimeLineID tli)
Definition: xlog.c:1224
static double CheckPointDistanceEstimate
Definition: xlog.c:158
static uint64 XLogRecPtrToBytePos(XLogRecPtr ptr)
Definition: xlog.c:1940
XLogRecPtr GetXLogInsertRecPtr(void)
Definition: xlog.c:9434
Size XLOGShmemSize(void)
Definition: xlog.c:4861
void SetWalWriterSleeping(bool sleeping)
Definition: xlog.c:9506
bool wal_log_hints
Definition: xlog.c:122
static void XLogInitNewTimeline(TimeLineID endTLI, XLogRecPtr endOfLog, TimeLineID newTLI)
Definition: xlog.c:5207
static void CheckRequiredParameterValues(void)
Definition: xlog.c:5378
#define XLogRecPtrToBufIdx(recptr)
Definition: xlog.c:590
int wal_sync_method
Definition: xlog.c:129
int XLogFileOpen(XLogSegNo segno, TimeLineID tli)
Definition: xlog.c:3611
int max_slot_wal_keep_size_mb
Definition: xlog.c:134
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
Definition: xlog.c:6498
static void PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli)
Definition: xlog.c:3683
static bool doPageWrites
Definition: xlog.c:285
static bool holdingAllLocks
Definition: xlog.c:651
static TimeLineID openLogTLI
Definition: xlog.c:636
XLogRecPtr XactLastCommitEnd
Definition: xlog.c:254
WalLevel GetActiveWalLevelOnStandby(void)
Definition: xlog.c:4852
bool log_checkpoints
Definition: xlog.c:128
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:7952
static void XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible)
Definition: xlog.c:2313
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4777
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
Definition: xlog.c:2715
static int LocalSetXLogInsertAllowed(void)
Definition: xlog.c:6421
void assign_max_wal_size(int newval, void *extra)
Definition: xlog.c:2190
void RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
Definition: xlog.c:3933
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:6555
void xlog_redo(XLogReaderState *record)
Definition: xlog.c:8234
static int MyLockNo
Definition: xlog.c:650
static void RecoveryRestartPoint(const CheckPoint *checkPoint, XLogReaderState *record)
Definition: xlog.c:7549
bool XLogNeedsFlush(XLogRecPtr record)
Definition: xlog.c:3126
void register_persistent_abort_backup_handler(void)
Definition: xlog.c:9420
static double PrevCheckPointDistance
Definition: xlog.c:159
void ReachedEndOfBackup(XLogRecPtr EndRecPtr, TimeLineID tli)
Definition: xlog.c:6246
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4839
static void XLogFileClose(void)
Definition: xlog.c:3632
int wal_compression
Definition: xlog.c:123
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:6785
static bool LocalRecoveryInProgress
Definition: xlog.c:223
XLogSegNo XLogGetOldestSegno(TimeLineID tli)
Definition: xlog.c:3767
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:9450
static WALInsertLockPadded * WALInsertLocks
Definition: xlog.c:568
static XLogSegNo openLogSegNo
Definition: xlog.c:635
#define INSERT_FREESPACE(endptr)
Definition: xlog.c:579
int wal_retrieve_retry_interval
Definition: xlog.c:133
int XLOGbuffers
Definition: xlog.c:116
bool XLogBackgroundFlush(void)
Definition: xlog.c:2983
const struct config_enum_entry archive_mode_options[]
Definition: xlog.c:190
void GetOldestRestartPoint(XLogRecPtr *oldrecptr, TimeLineID *oldtli)
Definition: xlog.c:9462
bool track_wal_io_timing
Definition: xlog.c:136
static XLogSegNo XLOGfileslop(XLogRecPtr lastredoptr)
Definition: xlog.c:2239
static int UsableBytesInSegment
Definition: xlog.c:605
static char * GetXLogBuffer(XLogRecPtr ptr, TimeLineID tli)
Definition: xlog.c:1631
const char * show_archive_command(void)
Definition: xlog.c:4803
WalInsertClass
Definition: xlog.c:559
@ WALINSERT_SPECIAL_SWITCH
Definition: xlog.c:561
@ WALINSERT_NORMAL
Definition: xlog.c:560
@ WALINSERT_SPECIAL_CHECKPOINT
Definition: xlog.c:562
bool XLogInsertAllowed(void)
Definition: xlog.c:6388
void do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces, BackupState *state, StringInfo tblspcmapfile)
Definition: xlog.c:8791
static ControlFileData * ControlFile
Definition: xlog.c:573
bool check_wal_segment_size(int *newval, void **extra, GucSource source)
Definition: xlog.c:2204
static void XLogFileCopy(TimeLineID destTLI, XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno, int upto)
Definition: xlog.c:3411
static int LocalXLogInsertAllowed
Definition: xlog.c:235
static void RemoveTempXlogFiles(void)
Definition: xlog.c:3825
XLogRecPtr XLogRestorePoint(const char *rpName)
Definition: xlog.c:8077
static XLogRecPtr LocalMinRecoveryPoint
Definition: xlog.c:645
#define NUM_XLOGINSERT_LOCKS
Definition: xlog.c:149
struct XLogwrtRqst XLogwrtRqst
TimeLineID GetWALInsertionTimeLineIfSet(void)
Definition: xlog.c:6535
void do_pg_backup_stop(BackupState *state, bool waitforarchive)
Definition: xlog.c:9119
bool check_wal_consistency_checking(char **newval, void **extra, GucSource source)
Definition: xlog.c:4665
const struct config_enum_entry wal_sync_method_options[]
Definition: xlog.c:170
int min_wal_size_mb
Definition: xlog.c:114
bool CreateCheckPoint(int flags)
Definition: xlog.c:6888
#define BootstrapTimeLineID
Definition: xlog.c:110
CheckpointStatsData CheckpointStats
Definition: xlog.c:208
bool check_wal_buffers(int *newval, void **extra, GucSource source)
Definition: xlog.c:4630
XLogRecPtr GetFakeLSNForUnloggedRel(void)
Definition: xlog.c:4597
void XLogPutNextOid(Oid nextOid)
Definition: xlog.c:8022
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2795
static void ReadControlFile(void)
Definition: xlog.c:4314
static SessionBackupState sessionBackupState
Definition: xlog.c:390
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:7509
static bool updateMinRecoveryPoint
Definition: xlog.c:647
int CheckPointSegments
Definition: xlog.c:155
static bool check_wal_consistency_checking_deferred
Definition: xlog.c:165
static void ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
Definition: xlog.c:1107
void XLogShutdownWalRcv(void)
Definition: xlog.c:9472
#define NextBufIdx(idx)
Definition: xlog.c:583
static void UpdateLastRemovedPtr(char *filename)
Definition: xlog.c:3805
static TimeLineID LocalMinRecoveryPointTLI
Definition: xlog.c:646
void issue_xlog_fsync(int fd, XLogSegNo segno, TimeLineID tli)
Definition: xlog.c:8682
struct XLogCtlData XLogCtlData
static bool ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
Definition: xlog.c:1163
void XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
Definition: xlog.c:2630
bool XLogCheckpointNeeded(XLogSegNo new_segno)
Definition: xlog.c:2289
bool * wal_consistency_checking
Definition: xlog.c:125
static int XLogFileInitInternal(XLogSegNo logsegno, TimeLineID logtli, bool *added, char *path)
Definition: xlog.c:3203
static void update_checkpoint_display(int flags, bool restartpoint, bool reset)
Definition: xlog.c:6823
#define XLogArchivingActive()
Definition: xlog.h:99
#define TABLESPACE_MAP_OLD
Definition: xlog.h:306
#define XLOG_MARK_UNIMPORTANT
Definition: xlog.h:155
#define TABLESPACE_MAP
Definition: xlog.h:305
@ ARCHIVE_MODE_ALWAYS
Definition: xlog.h:67
@ ARCHIVE_MODE_OFF
Definition: xlog.h:65
@ ARCHIVE_MODE_ON
Definition: xlog.h:66
#define STANDBY_SIGNAL_FILE
Definition: xlog.h:301
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:148
WALAvailability
Definition: xlog.h:188
@ WALAVAIL_REMOVED
Definition: xlog.h:194
@ WALAVAIL_RESERVED
Definition: xlog.h:190
@ WALAVAIL_UNRESERVED
Definition: xlog.h:193
@ WALAVAIL_EXTENDED
Definition: xlog.h:191
@ WALAVAIL_INVALID_LSN
Definition: xlog.h:189
#define BACKUP_LABEL_OLD
Definition: xlog.h:303
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:140
#define CHECKPOINT_FLUSH_ALL
Definition: xlog.h:143
@ WAL_COMPRESSION_NONE
Definition: xlog.h:82
#define BACKUP_LABEL_FILE
Definition: xlog.h:302
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:149
#define CHECKPOINT_FORCE
Definition: xlog.h:142
SessionBackupState
Definition: xlog.h:286
@ SESSION_BACKUP_RUNNING
Definition: xlog.h:288
@ SESSION_BACKUP_NONE
Definition: xlog.h:287
#define CHECKPOINT_WAIT
Definition: xlog.h:145
#define RECOVERY_SIGNAL_FILE
Definition: xlog.h:300
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:139
#define XLogArchivingAlways()
Definition: xlog.h:102
WalLevel
Definition: xlog.h:73
@ WAL_LEVEL_REPLICA
Definition: xlog.h:75
@ WAL_LEVEL_LOGICAL
Definition: xlog.h:76
@ WAL_LEVEL_MINIMAL
Definition: xlog.h:74
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:141
RecoveryState
Definition: xlog.h:90
@ RECOVERY_STATE_CRASH
Definition: xlog.h:91
@ RECOVERY_STATE_DONE
Definition: xlog.h:93
@ RECOVERY_STATE_ARCHIVE
Definition: xlog.h:92
#define XLogIsNeeded()
Definition: xlog.h:109
@ WAL_SYNC_METHOD_OPEN
Definition: xlog.h:26
@ WAL_SYNC_METHOD_FDATASYNC
Definition: xlog.h:25
@ WAL_SYNC_METHOD_FSYNC_WRITETHROUGH
Definition: xlog.h:27
@ WAL_SYNC_METHOD_OPEN_DSYNC
Definition: xlog.h:28
@ WAL_SYNC_METHOD_FSYNC
Definition: xlog.h:24
#define XLogStandbyInfoActive()
Definition: xlog.h:123
#define XLP_FIRST_IS_CONTRECORD
Definition: xlog_internal.h:74
static RmgrData GetRmgr(RmgrId rmid)
#define IsValidWalSegSize(size)
Definition: xlog_internal.h:96
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:71
#define XLP_FIRST_IS_OVERWRITE_CONTRECORD
Definition: xlog_internal.h:80
#define XLOG_CONTROL_FILE
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
static bool IsXLogFileName(const char *fname)
static void XLogFromFileName(const char *fname, TimeLineID *tli, XLogSegNo *logSegNo, int wal_segsz_bytes)
#define XLByteToPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
#define MAXFNAMELEN
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:54
#define XLOGDIR
#define XLP_LONG_HEADER
Definition: xlog_internal.h:76
static bool IsBackupHistoryFileName(const char *fname)
#define XLP_BKP_REMOVABLE
Definition: xlog_internal.h:78
#define XLOG_PAGE_MAGIC
Definition: xlog_internal.h:34
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
static void BackupHistoryFileName(char *fname, TimeLineID tli, XLogSegNo logSegNo, XLogRecPtr startpoint, int wal_segsz_bytes)
static void XLogFilePath(char *path, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)
#define XRecOffIsValid(xlrp)
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:52
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:69
static void XLogFileName(char *fname, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)
static void BackupHistoryFilePath(char *path, TimeLineID tli, XLogSegNo logSegNo, XLogRecPtr startpoint, int wal_segsz_bytes)
static bool RmgrIdExists(RmgrId rmid)
#define XLByteInPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
static bool IsPartialXLogFileName(const char *fname)
bool XLogArchiveIsReadyOrDone(const char *xlog)
Definition: xlogarchive.c:664
bool XLogArchiveIsBusy(const char *xlog)
Definition: xlogarchive.c:619
bool XLogArchiveIsReady(const char *xlog)
Definition: xlogarchive.c:694
void XLogArchiveNotifySeg(XLogSegNo segno, TimeLineID tli)
Definition: xlogarchive.c:492
void ExecuteRecoveryCommand(const char *command, const char *commandName, bool failOnSignal, uint32 wait_event_info)
Definition: xlogarchive.c:295
bool XLogArchiveCheckDone(const char *xlog)
Definition: xlogarchive.c:565
void XLogArchiveNotify(const char *xlog)
Definition: xlogarchive.c:444
void XLogArchiveCleanup(const char *xlog)
Definition: xlogarchive.c:712
char * build_backup_content(BackupState *state, bool ishistoryfile)
Definition: xlogbackup.c:29
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define FirstNormalUnloggedLSN
Definition: xlogdefs.h:36
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TimeLineID
Definition: xlogdefs.h:59
#define DEFAULT_WAL_SYNC_METHOD
Definition: xlogdefs.h:79
uint64 XLogSegNo
Definition: xlogdefs.h:48
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:456
void XLogRegisterData(const char *data, uint32 len)
Definition: xloginsert.c:364
void XLogBeginInsert(void)
Definition: xloginsert.c:149
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:106
bool DecodeXLogRecord(XLogReaderState *state, DecodedXLogRecord *decoded, XLogRecord *record, XLogRecPtr lsn, char **errormsg)
Definition: xlogreader.c:1662
size_t DecodeXLogRecordRequiredSpace(size_t xl_tot_len)
Definition: xlogreader.c:1629
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
#define XLogRecMaxBlockId(decoder)
Definition: xlogreader.h:418
#define XLogRecHasBlockImage(decoder, block_id)
Definition: xlogreader.h:423
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:417
#define SizeOfXLogRecordDataHeaderShort
Definition: xlogrecord.h:217
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:241
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
void ShutdownWalRecovery(void)
bool ArchiveRecoveryRequested
Definition: xlogrecovery.c:138
bool InArchiveRecovery
Definition: xlogrecovery.c:139
void RecoveryRequiresIntParameter(const char *param_name, int currValue, int minValue)
void PerformWalRecovery(void)
EndOfWalRecoveryInfo * FinishWalRecovery(void)
char * archiveCleanupCommand
Definition: xlogrecovery.c:85
XLogRecPtr GetCurrentReplayRecPtr(TimeLineID *replayEndTLI)
void xlog_outdesc(StringInfo buf, XLogReaderState *record)
bool PromoteIsTriggered(void)
static XLogRecPtr missingContrecPtr
Definition: xlogrecovery.c:374
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
static XLogRecPtr abortedRecPtr
Definition: xlogrecovery.c:373
void InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr, bool *haveBackupLabel_ptr, bool *haveTblspcMap_ptr)
Definition: xlogrecovery.c:513
char * recoveryEndCommand
Definition: xlogrecovery.c:84
TimeLineID recoveryTargetTLI
Definition: xlogrecovery.c:123
TimestampTz GetLatestXTime(void)
bool XLogHaveInvalidPages(void)
Definition: xlogutils.c:235
XLogRedoAction XLogReadBufferForRedo(XLogReaderState *record, uint8 block_id, Buffer *buf)
Definition: xlogutils.c:314
HotStandbyState standbyState
Definition: xlogutils.c:53
bool InRecovery
Definition: xlogutils.c:50
@ STANDBY_DISABLED
Definition: xlogutils.h:52
@ STANDBY_INITIALIZED
Definition: xlogutils.h:53
#define InHotStandby
Definition: xlogutils.h:60
@ BLK_RESTORED
Definition: xlogutils.h:76