Branch data Line data Source code
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-2026, 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 "access/xlogwait.h"
66 : : #include "backup/basebackup.h"
67 : : #include "catalog/catversion.h"
68 : : #include "catalog/pg_control.h"
69 : : #include "catalog/pg_database.h"
70 : : #include "common/controldata_utils.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 "postmaster/bgwriter.h"
78 : : #include "postmaster/datachecksum_state.h"
79 : : #include "postmaster/startup.h"
80 : : #include "postmaster/walsummarizer.h"
81 : : #include "postmaster/walwriter.h"
82 : : #include "replication/origin.h"
83 : : #include "replication/slot.h"
84 : : #include "replication/slotsync.h"
85 : : #include "replication/snapbuild.h"
86 : : #include "replication/walreceiver.h"
87 : : #include "replication/walsender.h"
88 : : #include "storage/bufmgr.h"
89 : : #include "storage/fd.h"
90 : : #include "storage/ipc.h"
91 : : #include "storage/large_object.h"
92 : : #include "storage/latch.h"
93 : : #include "storage/predicate.h"
94 : : #include "storage/proc.h"
95 : : #include "storage/procarray.h"
96 : : #include "storage/procsignal.h"
97 : : #include "storage/reinit.h"
98 : : #include "storage/spin.h"
99 : : #include "storage/subsystems.h"
100 : : #include "storage/sync.h"
101 : : #include "utils/guc_hooks.h"
102 : : #include "utils/guc_tables.h"
103 : : #include "utils/injection_point.h"
104 : : #include "utils/pgstat_internal.h"
105 : : #include "utils/ps_status.h"
106 : : #include "utils/relmapper.h"
107 : : #include "utils/snapmgr.h"
108 : : #include "utils/timeout.h"
109 : : #include "utils/timestamp.h"
110 : : #include "utils/varlena.h"
111 : : #include "utils/wait_event.h"
112 : :
113 : : #ifdef WAL_DEBUG
114 : : #include "utils/memutils.h"
115 : : #endif
116 : :
117 : : /* timeline ID to be used when bootstrapping */
118 : : #define BootstrapTimeLineID 1
119 : :
120 : : /* User-settable parameters */
121 : : int max_wal_size_mb = 1024; /* 1 GB */
122 : : int min_wal_size_mb = 80; /* 80 MB */
123 : : int wal_keep_size_mb = 0;
124 : : int XLOGbuffers = -1;
125 : : int XLogArchiveTimeout = 0;
126 : : int XLogArchiveMode = ARCHIVE_MODE_OFF;
127 : : char *XLogArchiveCommand = NULL;
128 : : bool EnableHotStandby = false;
129 : : bool fullPageWrites = true;
130 : : bool wal_log_hints = false;
131 : : int wal_compression = WAL_COMPRESSION_NONE;
132 : : char *wal_consistency_checking_string = NULL;
133 : : bool *wal_consistency_checking = NULL;
134 : : bool wal_init_zero = true;
135 : : bool wal_recycle = true;
136 : : bool log_checkpoints = true;
137 : : int wal_sync_method = DEFAULT_WAL_SYNC_METHOD;
138 : : int wal_level = WAL_LEVEL_REPLICA;
139 : : int CommitDelay = 0; /* precommit delay in microseconds */
140 : : int CommitSiblings = 5; /* # concurrent xacts needed to sleep */
141 : : int wal_retrieve_retry_interval = 5000;
142 : : int max_slot_wal_keep_size_mb = -1;
143 : : int wal_decode_buffer_size = 512 * 1024;
144 : : bool track_wal_io_timing = false;
145 : :
146 : : #ifdef WAL_DEBUG
147 : : bool XLOG_DEBUG = false;
148 : : #endif
149 : :
150 : : int wal_segment_size = DEFAULT_XLOG_SEG_SIZE;
151 : :
152 : : /*
153 : : * Number of WAL insertion locks to use. A higher value allows more insertions
154 : : * to happen concurrently, but adds some CPU overhead to flushing the WAL,
155 : : * which needs to iterate all the locks.
156 : : */
157 : : #define NUM_XLOGINSERT_LOCKS 8
158 : :
159 : : /*
160 : : * Max distance from last checkpoint, before triggering a new xlog-based
161 : : * checkpoint.
162 : : */
163 : : int CheckPointSegments;
164 : :
165 : : /* Estimated distance between checkpoints, in bytes */
166 : : static double CheckPointDistanceEstimate = 0;
167 : : static double PrevCheckPointDistance = 0;
168 : :
169 : : /*
170 : : * Track whether there were any deferred checks for custom resource managers
171 : : * specified in wal_consistency_checking.
172 : : */
173 : : static bool check_wal_consistency_checking_deferred = false;
174 : :
175 : : /*
176 : : * GUC support
177 : : */
178 : : const struct config_enum_entry wal_sync_method_options[] = {
179 : : {"fsync", WAL_SYNC_METHOD_FSYNC, false},
180 : : #ifdef HAVE_FSYNC_WRITETHROUGH
181 : : {"fsync_writethrough", WAL_SYNC_METHOD_FSYNC_WRITETHROUGH, false},
182 : : #endif
183 : : {"fdatasync", WAL_SYNC_METHOD_FDATASYNC, false},
184 : : #ifdef O_SYNC
185 : : {"open_sync", WAL_SYNC_METHOD_OPEN, false},
186 : : #endif
187 : : #ifdef O_DSYNC
188 : : {"open_datasync", WAL_SYNC_METHOD_OPEN_DSYNC, false},
189 : : #endif
190 : : {NULL, 0, false}
191 : : };
192 : :
193 : :
194 : : /*
195 : : * Although only "on", "off", and "always" are documented,
196 : : * we accept all the likely variants of "on" and "off".
197 : : */
198 : : const struct config_enum_entry archive_mode_options[] = {
199 : : {"always", ARCHIVE_MODE_ALWAYS, false},
200 : : {"on", ARCHIVE_MODE_ON, false},
201 : : {"off", ARCHIVE_MODE_OFF, false},
202 : : {"true", ARCHIVE_MODE_ON, true},
203 : : {"false", ARCHIVE_MODE_OFF, true},
204 : : {"yes", ARCHIVE_MODE_ON, true},
205 : : {"no", ARCHIVE_MODE_OFF, true},
206 : : {"1", ARCHIVE_MODE_ON, true},
207 : : {"0", ARCHIVE_MODE_OFF, true},
208 : : {NULL, 0, false}
209 : : };
210 : :
211 : : /*
212 : : * Statistics for current checkpoint are collected in this global struct.
213 : : * Because only the checkpointer or a stand-alone backend can perform
214 : : * checkpoints, this will be unused in normal backends.
215 : : */
216 : : CheckpointStatsData CheckpointStats;
217 : :
218 : : /*
219 : : * During recovery, lastFullPageWrites keeps track of full_page_writes that
220 : : * the replayed WAL records indicate. It's initialized with full_page_writes
221 : : * that the recovery starting checkpoint record indicates, and then updated
222 : : * each time XLOG_FPW_CHANGE record is replayed.
223 : : */
224 : : static bool lastFullPageWrites;
225 : :
226 : : /*
227 : : * Local copy of the state tracked by SharedRecoveryState in shared memory,
228 : : * It is false if SharedRecoveryState is RECOVERY_STATE_DONE. True actually
229 : : * means "not known, need to check the shared state".
230 : : */
231 : : static bool LocalRecoveryInProgress = true;
232 : :
233 : : /*
234 : : * Local state for XLogInsertAllowed():
235 : : * 1: unconditionally allowed to insert XLOG
236 : : * 0: unconditionally not allowed to insert XLOG
237 : : * -1: must check RecoveryInProgress(); disallow until it is false
238 : : * Most processes start with -1 and transition to 1 after seeing that recovery
239 : : * is not in progress. But we can also force the value for special cases.
240 : : * The coding in XLogInsertAllowed() depends on the first two of these states
241 : : * being numerically the same as bool true and false.
242 : : */
243 : : static int LocalXLogInsertAllowed = -1;
244 : :
245 : : /*
246 : : * ProcLastRecPtr points to the start of the last XLOG record inserted by the
247 : : * current backend. It is updated for all inserts. XactLastRecEnd points to
248 : : * end+1 of the last record, and is reset when we end a top-level transaction,
249 : : * or start a new one; so it can be used to tell if the current transaction has
250 : : * created any XLOG records.
251 : : *
252 : : * While in parallel mode, this may not be fully up to date. When committing,
253 : : * a transaction can assume this covers all xlog records written either by the
254 : : * user backend or by any parallel worker which was present at any point during
255 : : * the transaction. But when aborting, or when still in parallel mode, other
256 : : * parallel backends may have written WAL records at later LSNs than the value
257 : : * stored here. The parallel leader advances its own copy, when necessary,
258 : : * in WaitForParallelWorkersToFinish.
259 : : */
260 : : XLogRecPtr ProcLastRecPtr = InvalidXLogRecPtr;
261 : : XLogRecPtr XactLastRecEnd = InvalidXLogRecPtr;
262 : : XLogRecPtr XactLastCommitEnd = InvalidXLogRecPtr;
263 : :
264 : : /*
265 : : * RedoRecPtr is this backend's local copy of the REDO record pointer
266 : : * (which is almost but not quite the same as a pointer to the most recent
267 : : * CHECKPOINT record). We update this from the shared-memory copy,
268 : : * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
269 : : * hold an insertion lock). See XLogInsertRecord for details. We are also
270 : : * allowed to update from XLogCtl->RedoRecPtr if we hold the info_lck;
271 : : * see GetRedoRecPtr.
272 : : *
273 : : * NB: Code that uses this variable must be prepared not only for the
274 : : * possibility that it may be arbitrarily out of date, but also for the
275 : : * possibility that it might be set to InvalidXLogRecPtr. We used to
276 : : * initialize it as a side effect of the first call to RecoveryInProgress(),
277 : : * which meant that most code that might use it could assume that it had a
278 : : * real if perhaps stale value. That's no longer the case.
279 : : */
280 : : static XLogRecPtr RedoRecPtr;
281 : :
282 : : /*
283 : : * doPageWrites is this backend's local copy of (fullPageWrites ||
284 : : * runningBackups > 0). It is used together with RedoRecPtr to decide whether
285 : : * a full-page image of a page need to be taken.
286 : : *
287 : : * NB: Initially this is false, and there's no guarantee that it will be
288 : : * initialized to any other value before it is first used. Any code that
289 : : * makes use of it must recheck the value after obtaining a WALInsertLock,
290 : : * and respond appropriately if it turns out that the previous value wasn't
291 : : * accurate.
292 : : */
293 : : static bool doPageWrites;
294 : :
295 : : /*----------
296 : : * Shared-memory data structures for XLOG control
297 : : *
298 : : * LogwrtRqst indicates a byte position that we need to write and/or fsync
299 : : * the log up to (all records before that point must be written or fsynced).
300 : : * The positions already written/fsynced are maintained in logWriteResult
301 : : * and logFlushResult using atomic access.
302 : : * In addition to the shared variable, each backend has a private copy of
303 : : * both in LogwrtResult, which is updated when convenient.
304 : : *
305 : : * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
306 : : * (protected by info_lck), but we don't need to cache any copies of it.
307 : : *
308 : : * info_lck is only held long enough to read/update the protected variables,
309 : : * so it's a plain spinlock. The other locks are held longer (potentially
310 : : * over I/O operations), so we use LWLocks for them. These locks are:
311 : : *
312 : : * WALBufMappingLock: must be held to replace a page in the WAL buffer cache.
313 : : * It is only held while initializing and changing the mapping. If the
314 : : * contents of the buffer being replaced haven't been written yet, the mapping
315 : : * lock is released while the write is done, and reacquired afterwards.
316 : : *
317 : : * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
318 : : * XLogFlush).
319 : : *
320 : : * ControlFileLock: must be held to read/update control file or create
321 : : * new log file.
322 : : *
323 : : *----------
324 : : */
325 : :
326 : : typedef struct XLogwrtRqst
327 : : {
328 : : XLogRecPtr Write; /* last byte + 1 to write out */
329 : : XLogRecPtr Flush; /* last byte + 1 to flush */
330 : : } XLogwrtRqst;
331 : :
332 : : typedef struct XLogwrtResult
333 : : {
334 : : XLogRecPtr Write; /* last byte + 1 written out */
335 : : XLogRecPtr Flush; /* last byte + 1 flushed */
336 : : } XLogwrtResult;
337 : :
338 : : /*
339 : : * Inserting to WAL is protected by a small fixed number of WAL insertion
340 : : * locks. To insert to the WAL, you must hold one of the locks - it doesn't
341 : : * matter which one. To lock out other concurrent insertions, you must hold
342 : : * of them. Each WAL insertion lock consists of a lightweight lock, plus an
343 : : * indicator of how far the insertion has progressed (insertingAt).
344 : : *
345 : : * The insertingAt values are read when a process wants to flush WAL from
346 : : * the in-memory buffers to disk, to check that all the insertions to the
347 : : * region the process is about to write out have finished. You could simply
348 : : * wait for all currently in-progress insertions to finish, but the
349 : : * insertingAt indicator allows you to ignore insertions to later in the WAL,
350 : : * so that you only wait for the insertions that are modifying the buffers
351 : : * you're about to write out.
352 : : *
353 : : * This isn't just an optimization. If all the WAL buffers are dirty, an
354 : : * inserter that's holding a WAL insert lock might need to evict an old WAL
355 : : * buffer, which requires flushing the WAL. If it's possible for an inserter
356 : : * to block on another inserter unnecessarily, deadlock can arise when two
357 : : * inserters holding a WAL insert lock wait for each other to finish their
358 : : * insertion.
359 : : *
360 : : * Small WAL records that don't cross a page boundary never update the value,
361 : : * the WAL record is just copied to the page and the lock is released. But
362 : : * to avoid the deadlock-scenario explained above, the indicator is always
363 : : * updated before sleeping while holding an insertion lock.
364 : : *
365 : : * lastImportantAt contains the LSN of the last important WAL record inserted
366 : : * using a given lock. This value is used to detect if there has been
367 : : * important WAL activity since the last time some action, like a checkpoint,
368 : : * was performed - allowing to not repeat the action if not. The LSN is
369 : : * updated for all insertions, unless the XLOG_MARK_UNIMPORTANT flag was
370 : : * set. lastImportantAt is never cleared, only overwritten by the LSN of newer
371 : : * records. Tracking the WAL activity directly in WALInsertLock has the
372 : : * advantage of not needing any additional locks to update the value.
373 : : */
374 : : typedef struct
375 : : {
376 : : LWLock lock;
377 : : pg_atomic_uint64 insertingAt;
378 : : XLogRecPtr lastImportantAt;
379 : : } WALInsertLock;
380 : :
381 : : /*
382 : : * All the WAL insertion locks are allocated as an array in shared memory. We
383 : : * force the array stride to be a power of 2, which saves a few cycles in
384 : : * indexing, but more importantly also ensures that individual slots don't
385 : : * cross cache line boundaries. (Of course, we have to also ensure that the
386 : : * array start address is suitably aligned.)
387 : : */
388 : : typedef union WALInsertLockPadded
389 : : {
390 : : WALInsertLock l;
391 : : char pad[PG_CACHE_LINE_SIZE];
392 : : } WALInsertLockPadded;
393 : :
394 : : /*
395 : : * Session status of running backup, used for sanity checks in SQL-callable
396 : : * functions to start and stop backups.
397 : : */
398 : : static SessionBackupState sessionBackupState = SESSION_BACKUP_NONE;
399 : :
400 : : /*
401 : : * Shared state data for WAL insertion.
402 : : */
403 : : typedef struct XLogCtlInsert
404 : : {
405 : : slock_t insertpos_lck; /* protects CurrBytePos and PrevBytePos */
406 : :
407 : : /*
408 : : * CurrBytePos is the end of reserved WAL. The next record will be
409 : : * inserted at that position. PrevBytePos is the start position of the
410 : : * previously inserted (or rather, reserved) record - it is copied to the
411 : : * prev-link of the next record. These are stored as "usable byte
412 : : * positions" rather than XLogRecPtrs (see XLogBytePosToRecPtr()).
413 : : */
414 : : uint64 CurrBytePos;
415 : : uint64 PrevBytePos;
416 : :
417 : : /*
418 : : * Make sure the above heavily-contended spinlock and byte positions are
419 : : * on their own cache line. In particular, the RedoRecPtr and full page
420 : : * write variables below should be on a different cache line. They are
421 : : * read on every WAL insertion, but updated rarely, and we don't want
422 : : * those reads to steal the cache line containing Curr/PrevBytePos.
423 : : */
424 : : char pad[PG_CACHE_LINE_SIZE];
425 : :
426 : : /*
427 : : * fullPageWrites is the authoritative value used by all backends to
428 : : * determine whether to write full-page image to WAL. This shared value,
429 : : * instead of the process-local fullPageWrites, is required because, when
430 : : * full_page_writes is changed by SIGHUP, we must WAL-log it before it
431 : : * actually affects WAL-logging by backends. Checkpointer sets at startup
432 : : * or after SIGHUP.
433 : : *
434 : : * To read these fields, you must hold an insertion lock. To modify them,
435 : : * you must hold ALL the locks.
436 : : */
437 : : XLogRecPtr RedoRecPtr; /* current redo point for insertions */
438 : : bool fullPageWrites;
439 : :
440 : : /*
441 : : * runningBackups is a counter indicating the number of backups currently
442 : : * in progress. lastBackupStart is the latest checkpoint redo location
443 : : * used as a starting point for an online backup.
444 : : */
445 : : int runningBackups;
446 : : XLogRecPtr lastBackupStart;
447 : :
448 : : /*
449 : : * WAL insertion locks.
450 : : */
451 : : WALInsertLockPadded *WALInsertLocks;
452 : : } XLogCtlInsert;
453 : :
454 : : /*
455 : : * Total shared-memory state for XLOG.
456 : : */
457 : : typedef struct XLogCtlData
458 : : {
459 : : XLogCtlInsert Insert;
460 : :
461 : : /* Protected by info_lck: */
462 : : XLogwrtRqst LogwrtRqst;
463 : : XLogRecPtr RedoRecPtr; /* a recent copy of Insert->RedoRecPtr */
464 : : XLogRecPtr asyncXactLSN; /* LSN of newest async commit/abort */
465 : : XLogRecPtr replicationSlotMinLSN; /* oldest LSN needed by any slot */
466 : :
467 : : XLogSegNo lastRemovedSegNo; /* latest removed/recycled XLOG segment */
468 : :
469 : : /* Fake LSN counter, for unlogged relations. */
470 : : pg_atomic_uint64 unloggedLSN;
471 : :
472 : : /* Time and LSN of last xlog segment switch. Protected by WALWriteLock. */
473 : : pg_time_t lastSegSwitchTime;
474 : : XLogRecPtr lastSegSwitchLSN;
475 : :
476 : : /* These are accessed using atomics -- info_lck not needed */
477 : : pg_atomic_uint64 logInsertResult; /* last byte + 1 inserted to buffers */
478 : : pg_atomic_uint64 logWriteResult; /* last byte + 1 written out */
479 : : pg_atomic_uint64 logFlushResult; /* last byte + 1 flushed */
480 : :
481 : : /*
482 : : * Latest initialized page in the cache (last byte position + 1).
483 : : *
484 : : * To change the identity of a buffer (and InitializedUpTo), you need to
485 : : * hold WALBufMappingLock. To change the identity of a buffer that's
486 : : * still dirty, the old page needs to be written out first, and for that
487 : : * you need WALWriteLock, and you need to ensure that there are no
488 : : * in-progress insertions to the page by calling
489 : : * WaitXLogInsertionsToFinish().
490 : : */
491 : : XLogRecPtr InitializedUpTo;
492 : :
493 : : /*
494 : : * These values do not change after startup, although the pointed-to pages
495 : : * and xlblocks values certainly do. xlblocks values are protected by
496 : : * WALBufMappingLock.
497 : : */
498 : : char *pages; /* buffers for unwritten XLOG pages */
499 : : pg_atomic_uint64 *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
500 : : int XLogCacheBlck; /* highest allocated xlog buffer index */
501 : :
502 : : /*
503 : : * InsertTimeLineID is the timeline into which new WAL is being inserted
504 : : * and flushed. It is zero during recovery, and does not change once set.
505 : : *
506 : : * If we create a new timeline when the system was started up,
507 : : * PrevTimeLineID is the old timeline's ID that we forked off from.
508 : : * Otherwise it's equal to InsertTimeLineID.
509 : : *
510 : : * We set these fields while holding info_lck. Most that reads these
511 : : * values knows that recovery is no longer in progress and so can safely
512 : : * read the value without a lock, but code that could be run either during
513 : : * or after recovery can take info_lck while reading these values.
514 : : */
515 : : TimeLineID InsertTimeLineID;
516 : : TimeLineID PrevTimeLineID;
517 : :
518 : : /*
519 : : * SharedRecoveryState indicates if we're still in crash or archive
520 : : * recovery. Protected by info_lck.
521 : : */
522 : : RecoveryState SharedRecoveryState;
523 : :
524 : : /*
525 : : * InstallXLogFileSegmentActive indicates whether the checkpointer should
526 : : * arrange for future segments by recycling and/or PreallocXlogFiles().
527 : : * Protected by ControlFileLock. Only the startup process changes it. If
528 : : * true, anyone can use InstallXLogFileSegment(). If false, the startup
529 : : * process owns the exclusive right to install segments, by reading from
530 : : * the archive and possibly replacing existing files.
531 : : */
532 : : bool InstallXLogFileSegmentActive;
533 : :
534 : : /*
535 : : * WalWriterSleeping indicates whether the WAL writer is currently in
536 : : * low-power mode (and hence should be nudged if an async commit occurs).
537 : : * Protected by info_lck.
538 : : */
539 : : bool WalWriterSleeping;
540 : :
541 : : /*
542 : : * During recovery, we keep a copy of the latest checkpoint record here.
543 : : * lastCheckPointRecPtr points to start of checkpoint record and
544 : : * lastCheckPointEndPtr points to end+1 of checkpoint record. Used by the
545 : : * checkpointer when it wants to create a restartpoint.
546 : : *
547 : : * Protected by info_lck.
548 : : */
549 : : XLogRecPtr lastCheckPointRecPtr;
550 : : XLogRecPtr lastCheckPointEndPtr;
551 : : CheckPoint lastCheckPoint;
552 : :
553 : : /*
554 : : * lastFpwDisableRecPtr points to the start of the last replayed
555 : : * XLOG_FPW_CHANGE record that instructs full_page_writes is disabled.
556 : : */
557 : : XLogRecPtr lastFpwDisableRecPtr;
558 : :
559 : : /* current data checksum state of this node */
560 : : uint32 data_checksum_version;
561 : :
562 : : /*
563 : : * Copies of control file fields with the same names, see pg_control.h for
564 : : * an in-depth description of these fields. Must be updated together with
565 : : * data_checksum_version under info_lck.
566 : : */
567 : : XLogRecPtr data_checksum_lsn;
568 : : bool data_checksum_is_local;
569 : :
570 : : slock_t info_lck; /* locks shared variables shown above */
571 : :
572 : : /*
573 : : * lastChecksumChangeRecPtr points to the end of the last XLOG2_CHECKSUMS
574 : : * record inserted or replayed which corresponds to the last change of
575 : : * data_checksum_version. InvalidXLogRecPtr if the state hasn't changed
576 : : * since the server started.
577 : : */
578 : : pg_atomic_uint64 lastChecksumChangeRecPtr;
579 : : } XLogCtlData;
580 : :
581 : : /*
582 : : * Classification of XLogInsertRecord operations.
583 : : */
584 : : typedef enum
585 : : {
586 : : WALINSERT_NORMAL,
587 : : WALINSERT_SPECIAL_SWITCH,
588 : : WALINSERT_SPECIAL_CHECKPOINT
589 : : } WalInsertClass;
590 : :
591 : : static XLogCtlData *XLogCtl = NULL;
592 : :
593 : : /* a private copy of XLogCtl->Insert.WALInsertLocks, for convenience */
594 : : static WALInsertLockPadded *WALInsertLocks = NULL;
595 : :
596 : : /*
597 : : * We maintain an image of pg_control in shared memory.
598 : : */
599 : : static ControlFileData *LocalControlFile = NULL;
600 : : static ControlFileData *ControlFile = NULL;
601 : :
602 : : static void XLOGShmemRequest(void *arg);
603 : : static void XLOGShmemInit(void *arg);
604 : : static void XLOGShmemAttach(void *arg);
605 : :
606 : : const ShmemCallbacks XLOGShmemCallbacks = {
607 : : .request_fn = XLOGShmemRequest,
608 : : .init_fn = XLOGShmemInit,
609 : : .attach_fn = XLOGShmemAttach,
610 : : };
611 : :
612 : : /*
613 : : * Calculate the amount of space left on the page after 'endptr'. Beware
614 : : * multiple evaluation!
615 : : */
616 : : #define INSERT_FREESPACE(endptr) \
617 : : (((endptr) % XLOG_BLCKSZ == 0) ? 0 : (XLOG_BLCKSZ - (endptr) % XLOG_BLCKSZ))
618 : :
619 : : /* Macro to advance to next buffer index. */
620 : : #define NextBufIdx(idx) \
621 : : (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
622 : :
623 : : /*
624 : : * XLogRecPtrToBufIdx returns the index of the WAL buffer that holds, or
625 : : * would hold if it was in cache, the page containing 'recptr'.
626 : : */
627 : : #define XLogRecPtrToBufIdx(recptr) \
628 : : (((recptr) / XLOG_BLCKSZ) % (XLogCtl->XLogCacheBlck + 1))
629 : :
630 : : /*
631 : : * These are the number of bytes in a WAL page usable for WAL data.
632 : : */
633 : : #define UsableBytesInPage (XLOG_BLCKSZ - SizeOfXLogShortPHD)
634 : :
635 : : /*
636 : : * Convert values of GUCs measured in megabytes to equiv. segment count.
637 : : * Rounds down.
638 : : */
639 : : #define ConvertToXSegs(x, segsize) XLogMBVarToSegs((x), (segsize))
640 : :
641 : : /* The number of bytes in a WAL segment usable for WAL data. */
642 : : static int UsableBytesInSegment;
643 : :
644 : : /*
645 : : * Private, possibly out-of-date copy of shared LogwrtResult.
646 : : * See discussion above.
647 : : */
648 : : static XLogwrtResult LogwrtResult = {0, 0};
649 : :
650 : : /*
651 : : * True if this process has published primary-flush progress that has not yet
652 : : * been reported to primary-flush waiters.
653 : : */
654 : : static bool primaryFlushWakeupPending = false;
655 : :
656 : : /*
657 : : * Update local copy of shared XLogCtl->log{Write,Flush}Result
658 : : *
659 : : * It's critical that Flush always trails Write, so the order of the reads is
660 : : * important, as is the barrier. See also XLogWrite.
661 : : */
662 : : #define RefreshXLogWriteResult(_target) \
663 : : do { \
664 : : _target.Flush = pg_atomic_read_u64(&XLogCtl->logFlushResult); \
665 : : pg_read_barrier(); \
666 : : _target.Write = pg_atomic_read_u64(&XLogCtl->logWriteResult); \
667 : : } while (0)
668 : :
669 : : /*
670 : : * Process a primary-flush wakeup requested by XLogWrite(). The caller must
671 : : * not hold WALWriteLock or any WAL insertion lock.
672 : : */
673 : : static void
674 : 25216470 : PrimaryFlushWakeupProcessRequests(void)
675 : : {
676 [ + + ]: 25216470 : if (unlikely(primaryFlushWakeupPending))
677 : : {
678 : : /* Clear the process-local request before satisfying it. */
679 : 771 : primaryFlushWakeupPending = false;
680 : :
681 : : /* XLogWrite() published this frontier before setting the request. */
682 : 771 : WaitLSNWakeup(WAIT_LSN_TYPE_PRIMARY_FLUSH, LogwrtResult.Flush);
683 : : }
684 : 25216470 : }
685 : :
686 : : /*
687 : : * openLogFile is -1 or a kernel FD for an open log file segment.
688 : : * openLogSegNo identifies the segment, and openLogTLI the corresponding TLI.
689 : : * These variables are only used to write the XLOG, and so will normally refer
690 : : * to the active segment.
691 : : *
692 : : * Note: call Reserve/ReleaseExternalFD to track consumption of this FD.
693 : : */
694 : : static int openLogFile = -1;
695 : : static XLogSegNo openLogSegNo = 0;
696 : : static TimeLineID openLogTLI = 0;
697 : :
698 : : /*
699 : : * Local copies of equivalent fields in the control file. When running
700 : : * crash recovery, LocalMinRecoveryPoint is set to InvalidXLogRecPtr as we
701 : : * expect to replay all the WAL available, and updateMinRecoveryPoint is
702 : : * switched to false to prevent any updates while replaying records.
703 : : * Those values are kept consistent as long as crash recovery runs.
704 : : */
705 : : static XLogRecPtr LocalMinRecoveryPoint;
706 : : static bool updateMinRecoveryPoint = true;
707 : :
708 : : /*
709 : : * Local state for ControlFile data_checksum_version. After initialization
710 : : * this is only updated when absorbing a procsignal barrier during interrupt
711 : : * processing. The reason for keeping a copy in backend-private memory is to
712 : : * avoid locking for interrogating the data checksum state. Possible values
713 : : * are the data checksum versions defined in storage/checksum.h.
714 : : */
715 : : static ChecksumStateType LocalDataChecksumState = 0;
716 : :
717 : : /*
718 : : * Variable backing the GUC, keep it in sync with LocalDataChecksumState.
719 : : * See SetLocalDataChecksumState().
720 : : */
721 : : int data_checksums = 0;
722 : :
723 : : /*
724 : : * Whether replay of the next checkpoint-family record must adopt the data
725 : : * checksum state it carries. Set when recovery starts from a base backup,
726 : : * where the state at the redo point takes precedence over the control file
727 : : * copied with the backup later.
728 : : */
729 : : static bool adoptChecksumStateFromNextCheckpoint = false;
730 : :
731 : : /*
732 : : * Sentinel for the data checksum mismatch warning tracking in
733 : : * CheckReplayedDataChecksumState(): no warning is outstanding.
734 : : */
735 : : #define NO_WARNING_ISSUED PG_UINT32_MAX
736 : :
737 : : /* For WALInsertLockAcquire/Release functions */
738 : : static int MyLockNo = 0;
739 : : static bool holdingAllLocks = false;
740 : :
741 : : #ifdef WAL_DEBUG
742 : : static MemoryContext walDebugCxt = NULL;
743 : : #endif
744 : :
745 : : static void CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI,
746 : : XLogRecPtr EndOfLog,
747 : : TimeLineID newTLI);
748 : : static void CheckRequiredParameterValues(void);
749 : : static void XLogReportParameters(void);
750 : : static int LocalSetXLogInsertAllowed(void);
751 : : static void CreateEndOfRecoveryRecord(void);
752 : : static XLogRecPtr CreateOverwriteContrecordRecord(XLogRecPtr aborted_lsn,
753 : : XLogRecPtr pagePtr,
754 : : TimeLineID newTLI);
755 : : static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
756 : : static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo);
757 : :
758 : : static void AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli,
759 : : bool opportunistic);
760 : : static void XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible);
761 : : static bool InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
762 : : bool find_free, XLogSegNo max_segno,
763 : : TimeLineID tli);
764 : : static void XLogFileClose(void);
765 : : static void PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli);
766 : : static void RemoveTempXlogFiles(void);
767 : : static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr,
768 : : XLogRecPtr endptr, TimeLineID insertTLI);
769 : : static void RemoveXlogFile(const struct dirent *segment_de,
770 : : XLogSegNo recycleSegNo, XLogSegNo *endlogSegNo,
771 : : TimeLineID insertTLI);
772 : : static void UpdateLastRemovedPtr(char *filename);
773 : : static void ValidateXLOGDirectoryStructure(void);
774 : : static void CleanupBackupHistory(void);
775 : : static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
776 : : static bool PerformRecoveryXLogAction(void);
777 : : static void CheckReplayedDataChecksumState(uint32 replayed_state);
778 : : static void AdoptReplayedDataChecksumState(uint32 new_version, XLogRecPtr lsn);
779 : : static void InitControlFile(uint64 sysidentifier, uint32 data_checksum_version);
780 : : static void WriteControlFile(void);
781 : : static void ReadControlFile(void);
782 : : static void UpdateControlFile(void);
783 : : static char *str_time(pg_time_t tnow, char *buf, size_t bufsize);
784 : :
785 : : static int get_sync_bit(int method);
786 : :
787 : : static void CopyXLogRecordToWAL(int write_len, bool isLogSwitch,
788 : : XLogRecData *rdata,
789 : : XLogRecPtr StartPos, XLogRecPtr EndPos,
790 : : TimeLineID tli);
791 : : static void ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos,
792 : : XLogRecPtr *EndPos, XLogRecPtr *PrevPtr);
793 : : static bool ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos,
794 : : XLogRecPtr *PrevPtr);
795 : : static XLogRecPtr WaitXLogInsertionsToFinish(XLogRecPtr upto);
796 : : static char *GetXLogBuffer(XLogRecPtr ptr, TimeLineID tli);
797 : : static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos);
798 : : static XLogRecPtr XLogBytePosToEndRecPtr(uint64 bytepos);
799 : : static uint64 XLogRecPtrToBytePos(XLogRecPtr ptr);
800 : :
801 : : static void WALInsertLockAcquire(void);
802 : : static void WALInsertLockAcquireExclusive(void);
803 : : static void WALInsertLockRelease(void);
804 : : static void WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt);
805 : :
806 : : static XLogRecPtr XLogChecksums(uint32 new_type);
807 : :
808 : : /*
809 : : * Insert an XLOG record represented by an already-constructed chain of data
810 : : * chunks. This is a low-level routine; to construct the WAL record header
811 : : * and data, use the higher-level routines in xloginsert.c.
812 : : *
813 : : * If 'fpw_lsn' is valid, it is the oldest LSN among the pages that this
814 : : * WAL record applies to, that were not included in the record as full page
815 : : * images. If fpw_lsn <= RedoRecPtr, the function does not perform the
816 : : * insertion and returns InvalidXLogRecPtr. The caller can then recalculate
817 : : * which pages need a full-page image, and retry. If fpw_lsn is invalid, the
818 : : * record is always inserted.
819 : : *
820 : : * 'flags' gives more in-depth control on the record being inserted. See
821 : : * XLogSetRecordFlags() for details.
822 : : *
823 : : * 'topxid_included' tells whether the top-transaction id is logged along with
824 : : * current subtransaction. See XLogRecordAssemble().
825 : : *
826 : : * The first XLogRecData in the chain must be for the record header, and its
827 : : * data must be MAXALIGNed. XLogInsertRecord fills in the xl_prev and
828 : : * xl_crc fields in the header, the rest of the header must already be filled
829 : : * by the caller.
830 : : *
831 : : * Returns XLOG pointer to end of record (beginning of next record).
832 : : * This can be used as LSN for data pages affected by the logged action.
833 : : * (LSN is the XLOG point up to which the XLOG must be flushed to disk
834 : : * before the data page can be written out. This implements the basic
835 : : * WAL rule "write the log before the data".)
836 : : */
837 : : XLogRecPtr
838 : 25225764 : XLogInsertRecord(XLogRecData *rdata,
839 : : XLogRecPtr fpw_lsn,
840 : : uint8 flags,
841 : : int num_fpi,
842 : : uint64 fpi_bytes,
843 : : bool topxid_included)
844 : : {
845 : 25225764 : XLogCtlInsert *Insert = &XLogCtl->Insert;
846 : : pg_crc32c rdata_crc;
847 : : bool inserted;
848 : 25225764 : XLogRecord *rechdr = (XLogRecord *) rdata->data;
849 : 25225764 : uint8 info = rechdr->xl_info & ~XLR_INFO_MASK;
850 : 25225764 : WalInsertClass class = WALINSERT_NORMAL;
851 : : XLogRecPtr StartPos;
852 : : XLogRecPtr EndPos;
853 : 25225764 : bool prevDoPageWrites = doPageWrites;
854 : : TimeLineID insertTLI;
855 : :
856 : : /* Does this record type require special handling? */
857 [ + + ]: 25225764 : if (unlikely(rechdr->xl_rmid == RM_XLOG_ID))
858 : : {
859 [ + + ]: 343842 : if (info == XLOG_SWITCH)
860 : 862 : class = WALINSERT_SPECIAL_SWITCH;
861 [ + + ]: 342980 : else if (info == XLOG_CHECKPOINT_REDO)
862 : 1038 : class = WALINSERT_SPECIAL_CHECKPOINT;
863 : : }
864 : :
865 : : /* we assume that all of the record header is in the first chunk */
866 : : Assert(rdata->len >= SizeOfXLogRecord);
867 : :
868 : : /* cross-check on whether we should be here or not */
869 [ - + ]: 25225764 : if (!XLogInsertAllowed())
870 [ # # ]: 0 : elog(ERROR, "cannot make new WAL entries during recovery");
871 : :
872 : : /*
873 : : * Given that we're not in recovery, InsertTimeLineID is set and can't
874 : : * change, so we can read it without a lock.
875 : : */
876 : 25225764 : insertTLI = XLogCtl->InsertTimeLineID;
877 : :
878 : : /*----------
879 : : *
880 : : * We have now done all the preparatory work we can without holding a
881 : : * lock or modifying shared state. From here on, inserting the new WAL
882 : : * record to the shared WAL buffer cache is a two-step process:
883 : : *
884 : : * 1. Reserve the right amount of space from the WAL. The current head of
885 : : * reserved space is kept in Insert->CurrBytePos, and is protected by
886 : : * insertpos_lck.
887 : : *
888 : : * 2. Copy the record to the reserved WAL space. This involves finding the
889 : : * correct WAL buffer containing the reserved space, and copying the
890 : : * record in place. This can be done concurrently in multiple processes.
891 : : *
892 : : * To keep track of which insertions are still in-progress, each concurrent
893 : : * inserter acquires an insertion lock. In addition to just indicating that
894 : : * an insertion is in progress, the lock tells others how far the inserter
895 : : * has progressed. There is a small fixed number of insertion locks,
896 : : * determined by NUM_XLOGINSERT_LOCKS. When an inserter crosses a page
897 : : * boundary, it updates the value stored in the lock to the how far it has
898 : : * inserted, to allow the previous buffer to be flushed.
899 : : *
900 : : * Holding onto an insertion lock also protects RedoRecPtr and
901 : : * fullPageWrites from changing until the insertion is finished.
902 : : *
903 : : * Step 2 can usually be done completely in parallel. If the required WAL
904 : : * page is not initialized yet, you have to grab WALBufMappingLock to
905 : : * initialize it, but the WAL writer tries to do that ahead of insertions
906 : : * to avoid that from happening in the critical path.
907 : : *
908 : : *----------
909 : : */
910 : 25225764 : START_CRIT_SECTION();
911 : :
912 [ + + ]: 25225764 : if (likely(class == WALINSERT_NORMAL))
913 : : {
914 : 25223864 : WALInsertLockAcquire();
915 : :
916 : : /*
917 : : * Check to see if my copy of RedoRecPtr is out of date. If so, may
918 : : * have to go back and have the caller recompute everything. This can
919 : : * only happen just after a checkpoint, so it's better to be slow in
920 : : * this case and fast otherwise.
921 : : *
922 : : * Also check to see if fullPageWrites was just turned on or there's a
923 : : * running backup (which forces full-page writes); if we weren't
924 : : * already doing full-page writes then go back and recompute.
925 : : *
926 : : * If we aren't doing full-page writes then RedoRecPtr doesn't
927 : : * actually affect the contents of the XLOG record, so we'll update
928 : : * our local copy but not force a recomputation. (If doPageWrites was
929 : : * just turned off, we could recompute the record without full pages,
930 : : * but we choose not to bother.)
931 : : */
932 [ + + ]: 25223864 : if (RedoRecPtr != Insert->RedoRecPtr)
933 : : {
934 : : Assert(RedoRecPtr < Insert->RedoRecPtr);
935 : 8472 : RedoRecPtr = Insert->RedoRecPtr;
936 : : }
937 [ + + + + ]: 25223864 : doPageWrites = (Insert->fullPageWrites || Insert->runningBackups > 0);
938 : :
939 [ + + ]: 25223864 : if (doPageWrites &&
940 [ + + + + ]: 22916427 : (!prevDoPageWrites ||
941 [ + + ]: 21467092 : (XLogRecPtrIsValid(fpw_lsn) && fpw_lsn <= RedoRecPtr)))
942 : : {
943 : : /*
944 : : * Oops, some buffer now needs to be backed up that the caller
945 : : * didn't back up. Start over.
946 : : */
947 : 9294 : WALInsertLockRelease();
948 : 9294 : END_CRIT_SECTION();
949 : 9294 : return InvalidXLogRecPtr;
950 : : }
951 : :
952 : : /*
953 : : * Reserve space for the record in the WAL. This also sets the xl_prev
954 : : * pointer.
955 : : */
956 : 25214570 : ReserveXLogInsertLocation(rechdr->xl_tot_len, &StartPos, &EndPos,
957 : : &rechdr->xl_prev);
958 : :
959 : : /* Normal records are always inserted. */
960 : 25214570 : inserted = true;
961 : : }
962 [ + + ]: 1900 : else if (class == WALINSERT_SPECIAL_SWITCH)
963 : : {
964 : : /*
965 : : * In order to insert an XLOG_SWITCH record, we need to hold all of
966 : : * the WAL insertion locks, not just one, so that no one else can
967 : : * begin inserting a record until we've figured out how much space
968 : : * remains in the current WAL segment and claimed all of it.
969 : : *
970 : : * Nonetheless, this case is simpler than the normal cases handled
971 : : * below, which must check for changes in doPageWrites and RedoRecPtr.
972 : : * Those checks are only needed for records that can contain buffer
973 : : * references, and an XLOG_SWITCH record never does.
974 : : */
975 : : Assert(!XLogRecPtrIsValid(fpw_lsn));
976 : 862 : WALInsertLockAcquireExclusive();
977 : 862 : inserted = ReserveXLogSwitch(&StartPos, &EndPos, &rechdr->xl_prev);
978 : : }
979 : : else
980 : : {
981 : : Assert(class == WALINSERT_SPECIAL_CHECKPOINT);
982 : :
983 : : /*
984 : : * We need to update both the local and shared copies of RedoRecPtr,
985 : : * which means that we need to hold all the WAL insertion locks.
986 : : * However, there can't be any buffer references, so as above, we need
987 : : * not check RedoRecPtr before inserting the record; we just need to
988 : : * update it afterwards.
989 : : */
990 : : Assert(!XLogRecPtrIsValid(fpw_lsn));
991 : 1038 : WALInsertLockAcquireExclusive();
992 : 1038 : ReserveXLogInsertLocation(rechdr->xl_tot_len, &StartPos, &EndPos,
993 : : &rechdr->xl_prev);
994 : 1038 : RedoRecPtr = Insert->RedoRecPtr = StartPos;
995 : 1038 : inserted = true;
996 : : }
997 : :
998 [ + + ]: 25216470 : if (inserted)
999 : : {
1000 : : /*
1001 : : * Now that xl_prev has been filled in, calculate CRC of the record
1002 : : * header.
1003 : : */
1004 : 25216405 : rdata_crc = rechdr->xl_crc;
1005 : 25216405 : COMP_CRC32C(rdata_crc, rechdr, offsetof(XLogRecord, xl_crc));
1006 : 25216405 : FIN_CRC32C(rdata_crc);
1007 : 25216405 : rechdr->xl_crc = rdata_crc;
1008 : :
1009 : : /*
1010 : : * All the record data, including the header, is now ready to be
1011 : : * inserted. Copy the record in the space reserved.
1012 : : */
1013 : 25216405 : CopyXLogRecordToWAL(rechdr->xl_tot_len,
1014 : : class == WALINSERT_SPECIAL_SWITCH, rdata,
1015 : : StartPos, EndPos, insertTLI);
1016 : :
1017 : : /*
1018 : : * Unless record is flagged as not important, update LSN of last
1019 : : * important record in the current slot. When holding all locks, just
1020 : : * update the first one.
1021 : : */
1022 [ + + ]: 25216405 : if ((flags & XLOG_MARK_UNIMPORTANT) == 0)
1023 : : {
1024 [ + + ]: 25059644 : int lockno = holdingAllLocks ? 0 : MyLockNo;
1025 : :
1026 : 25059644 : WALInsertLocks[lockno].l.lastImportantAt = StartPos;
1027 : : }
1028 : : }
1029 : : else
1030 : : {
1031 : : /*
1032 : : * This was an xlog-switch record, but the current insert location was
1033 : : * already exactly at the beginning of a segment, so there was no need
1034 : : * to do anything.
1035 : : */
1036 : : }
1037 : :
1038 : : /*
1039 : : * Done! Let others know that we're finished.
1040 : : */
1041 : 25216470 : WALInsertLockRelease();
1042 : :
1043 : 25216470 : END_CRIT_SECTION();
1044 : :
1045 : 25216470 : MarkCurrentTransactionIdLoggedIfAny();
1046 : :
1047 : : /*
1048 : : * Mark top transaction id is logged (if needed) so that we should not try
1049 : : * to log it again with the next WAL record in the current subtransaction.
1050 : : */
1051 [ + + ]: 25216470 : if (topxid_included)
1052 : 224 : MarkSubxactTopXidLogged();
1053 : :
1054 : : /*
1055 : : * Update shared LogwrtRqst.Write, if we crossed page boundary.
1056 : : */
1057 [ + + ]: 25216470 : if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
1058 : : {
1059 : 1897721 : SpinLockAcquire(&XLogCtl->info_lck);
1060 : : /* advance global request to include new block(s) */
1061 [ + + ]: 1897721 : if (XLogCtl->LogwrtRqst.Write < EndPos)
1062 : 1836556 : XLogCtl->LogwrtRqst.Write = EndPos;
1063 : 1897721 : SpinLockRelease(&XLogCtl->info_lck);
1064 : 1897721 : RefreshXLogWriteResult(LogwrtResult);
1065 : : }
1066 : :
1067 : : /*
1068 : : * If this was an XLOG_SWITCH record, flush the record and the empty
1069 : : * padding space that fills the rest of the segment, and perform
1070 : : * end-of-segment actions (eg, notifying archiver).
1071 : : */
1072 [ + + ]: 25216470 : if (class == WALINSERT_SPECIAL_SWITCH)
1073 : : {
1074 : : TRACE_POSTGRESQL_WAL_SWITCH();
1075 : 862 : XLogFlush(EndPos);
1076 : :
1077 : : /*
1078 : : * Even though we reserved the rest of the segment for us, which is
1079 : : * reflected in EndPos, we return a pointer to just the end of the
1080 : : * xlog-switch record.
1081 : : */
1082 [ + + ]: 862 : if (inserted)
1083 : : {
1084 : 797 : EndPos = StartPos + SizeOfXLogRecord;
1085 [ - + ]: 797 : if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
1086 : : {
1087 : 0 : uint64 offset = XLogSegmentOffset(EndPos, wal_segment_size);
1088 : :
1089 [ # # ]: 0 : if (offset == EndPos % XLOG_BLCKSZ)
1090 : 0 : EndPos += SizeOfXLogLongPHD;
1091 : : else
1092 : 0 : EndPos += SizeOfXLogShortPHD;
1093 : : }
1094 : : }
1095 : : }
1096 : :
1097 : : /* Process any flush progress published while making room for the record. */
1098 : 25216470 : PrimaryFlushWakeupProcessRequests();
1099 : :
1100 : : #ifdef WAL_DEBUG
1101 : : if (XLOG_DEBUG)
1102 : : {
1103 : : static XLogReaderState *debug_reader = NULL;
1104 : : XLogRecord *record;
1105 : : DecodedXLogRecord *decoded;
1106 : : StringInfoData buf;
1107 : : StringInfoData recordBuf;
1108 : : char *errormsg = NULL;
1109 : : MemoryContext oldCxt;
1110 : :
1111 : : oldCxt = MemoryContextSwitchTo(walDebugCxt);
1112 : :
1113 : : initStringInfo(&buf);
1114 : : appendStringInfo(&buf, "INSERT @ %X/%08X: ", LSN_FORMAT_ARGS(EndPos));
1115 : :
1116 : : /*
1117 : : * We have to piece together the WAL record data from the XLogRecData
1118 : : * entries, so that we can pass it to the rm_desc function as one
1119 : : * contiguous chunk.
1120 : : */
1121 : : initStringInfo(&recordBuf);
1122 : : for (; rdata != NULL; rdata = rdata->next)
1123 : : appendBinaryStringInfo(&recordBuf, rdata->data, rdata->len);
1124 : :
1125 : : /* We also need temporary space to decode the record. */
1126 : : record = (XLogRecord *) recordBuf.data;
1127 : : decoded = (DecodedXLogRecord *)
1128 : : palloc(DecodeXLogRecordRequiredSpace(record->xl_tot_len));
1129 : :
1130 : : if (!debug_reader)
1131 : : debug_reader = XLogReaderAllocate(wal_segment_size, NULL,
1132 : : XL_ROUTINE(.page_read = NULL,
1133 : : .segment_open = NULL,
1134 : : .segment_close = NULL),
1135 : : NULL);
1136 : : if (!debug_reader)
1137 : : {
1138 : : appendStringInfoString(&buf, "error decoding record: out of memory while allocating a WAL reading processor");
1139 : : }
1140 : : else if (!DecodeXLogRecord(debug_reader,
1141 : : decoded,
1142 : : record,
1143 : : EndPos,
1144 : : &errormsg))
1145 : : {
1146 : : appendStringInfo(&buf, "error decoding record: %s",
1147 : : errormsg ? errormsg : "no error message");
1148 : : }
1149 : : else
1150 : : {
1151 : : appendStringInfoString(&buf, " - ");
1152 : :
1153 : : debug_reader->record = decoded;
1154 : : xlog_outdesc(&buf, debug_reader);
1155 : : debug_reader->record = NULL;
1156 : : }
1157 : : elog(LOG, "%s", buf.data);
1158 : :
1159 : : pfree(decoded);
1160 : : pfree(buf.data);
1161 : : pfree(recordBuf.data);
1162 : : MemoryContextSwitchTo(oldCxt);
1163 : : }
1164 : : #endif
1165 : :
1166 : : /*
1167 : : * Update our global variables
1168 : : */
1169 : 25216470 : ProcLastRecPtr = StartPos;
1170 : 25216470 : XactLastRecEnd = EndPos;
1171 : :
1172 : : /* Report WAL traffic to the instrumentation. */
1173 [ + + ]: 25216470 : if (inserted)
1174 : : {
1175 : 25216405 : pgWalUsage.wal_bytes += rechdr->xl_tot_len;
1176 : 25216405 : pgWalUsage.wal_records++;
1177 : 25216405 : pgWalUsage.wal_fpi += num_fpi;
1178 : 25216405 : pgWalUsage.wal_fpi_bytes += fpi_bytes;
1179 : :
1180 : : /* Required for the flush of pending stats WAL data */
1181 : 25216405 : pgstat_report_fixed = true;
1182 : : }
1183 : :
1184 : 25216470 : return EndPos;
1185 : : }
1186 : :
1187 : : /*
1188 : : * Reserves the right amount of space for a record of given size from the WAL.
1189 : : * *StartPos is set to the beginning of the reserved section, *EndPos to
1190 : : * its end+1. *PrevPtr is set to the beginning of the previous record; it is
1191 : : * used to set the xl_prev of this record.
1192 : : *
1193 : : * This is the performance critical part of XLogInsert that must be serialized
1194 : : * across backends. The rest can happen mostly in parallel. Try to keep this
1195 : : * section as short as possible, insertpos_lck can be heavily contended on a
1196 : : * busy system.
1197 : : *
1198 : : * NB: The space calculation here must match the code in CopyXLogRecordToWAL,
1199 : : * where we actually copy the record to the reserved space.
1200 : : *
1201 : : * NB: Testing shows that XLogInsertRecord runs faster if this code is inlined;
1202 : : * however, because there are two call sites, the compiler is reluctant to
1203 : : * inline. We use pg_always_inline here to try to convince it.
1204 : : */
1205 : : static pg_always_inline void
1206 : 25215608 : ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos, XLogRecPtr *EndPos,
1207 : : XLogRecPtr *PrevPtr)
1208 : : {
1209 : 25215608 : XLogCtlInsert *Insert = &XLogCtl->Insert;
1210 : : uint64 startbytepos;
1211 : : uint64 endbytepos;
1212 : : uint64 prevbytepos;
1213 : :
1214 : 25215608 : size = MAXALIGN(size);
1215 : :
1216 : : /* All (non xlog-switch) records should contain data. */
1217 : : Assert(size > SizeOfXLogRecord);
1218 : :
1219 : : /*
1220 : : * The duration the spinlock needs to be held is minimized by minimizing
1221 : : * the calculations that have to be done while holding the lock. The
1222 : : * current tip of reserved WAL is kept in CurrBytePos, as a byte position
1223 : : * that only counts "usable" bytes in WAL, that is, it excludes all WAL
1224 : : * page headers. The mapping between "usable" byte positions and physical
1225 : : * positions (XLogRecPtrs) can be done outside the locked region, and
1226 : : * because the usable byte position doesn't include any headers, reserving
1227 : : * X bytes from WAL is almost as simple as "CurrBytePos += X".
1228 : : */
1229 : 25215608 : SpinLockAcquire(&Insert->insertpos_lck);
1230 : :
1231 : 25215608 : startbytepos = Insert->CurrBytePos;
1232 : 25215608 : endbytepos = startbytepos + size;
1233 : 25215608 : prevbytepos = Insert->PrevBytePos;
1234 : 25215608 : Insert->CurrBytePos = endbytepos;
1235 : 25215608 : Insert->PrevBytePos = startbytepos;
1236 : :
1237 : 25215608 : SpinLockRelease(&Insert->insertpos_lck);
1238 : :
1239 : 25215608 : *StartPos = XLogBytePosToRecPtr(startbytepos);
1240 : 25215608 : *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1241 : 25215608 : *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1242 : :
1243 : : /*
1244 : : * Check that the conversions between "usable byte positions" and
1245 : : * XLogRecPtrs work consistently in both directions.
1246 : : */
1247 : : Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1248 : : Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1249 : : Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1250 : 25215608 : }
1251 : :
1252 : : /*
1253 : : * Like ReserveXLogInsertLocation(), but for an xlog-switch record.
1254 : : *
1255 : : * A log-switch record is handled slightly differently. The rest of the
1256 : : * segment will be reserved for this insertion, as indicated by the returned
1257 : : * *EndPos value. However, if we are already at the beginning of the current
1258 : : * segment, *StartPos and *EndPos are set to the current location without
1259 : : * reserving any space, and the function returns false.
1260 : : */
1261 : : static bool
1262 : 862 : ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
1263 : : {
1264 : 862 : XLogCtlInsert *Insert = &XLogCtl->Insert;
1265 : : uint64 startbytepos;
1266 : : uint64 endbytepos;
1267 : : uint64 prevbytepos;
1268 : 862 : uint32 size = MAXALIGN(SizeOfXLogRecord);
1269 : : XLogRecPtr ptr;
1270 : : uint32 segleft;
1271 : :
1272 : : /*
1273 : : * These calculations are a bit heavy-weight to be done while holding a
1274 : : * spinlock, but since we're holding all the WAL insertion locks, there
1275 : : * are no other inserters competing for it. GetXLogInsertRecPtr() does
1276 : : * compete for it, but that's not called very frequently.
1277 : : */
1278 : 862 : SpinLockAcquire(&Insert->insertpos_lck);
1279 : :
1280 : 862 : startbytepos = Insert->CurrBytePos;
1281 : :
1282 : 862 : ptr = XLogBytePosToEndRecPtr(startbytepos);
1283 [ + + ]: 862 : if (XLogSegmentOffset(ptr, wal_segment_size) == 0)
1284 : : {
1285 : 65 : SpinLockRelease(&Insert->insertpos_lck);
1286 : 65 : *EndPos = *StartPos = ptr;
1287 : 65 : return false;
1288 : : }
1289 : :
1290 : 797 : endbytepos = startbytepos + size;
1291 : 797 : prevbytepos = Insert->PrevBytePos;
1292 : :
1293 : 797 : *StartPos = XLogBytePosToRecPtr(startbytepos);
1294 : 797 : *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1295 : :
1296 : 797 : segleft = wal_segment_size - XLogSegmentOffset(*EndPos, wal_segment_size);
1297 [ + - ]: 797 : if (segleft != wal_segment_size)
1298 : : {
1299 : : /* consume the rest of the segment */
1300 : 797 : *EndPos += segleft;
1301 : 797 : endbytepos = XLogRecPtrToBytePos(*EndPos);
1302 : : }
1303 : 797 : Insert->CurrBytePos = endbytepos;
1304 : 797 : Insert->PrevBytePos = startbytepos;
1305 : :
1306 : 797 : SpinLockRelease(&Insert->insertpos_lck);
1307 : :
1308 : 797 : *PrevPtr = XLogBytePosToRecPtr(prevbytepos);
1309 : :
1310 : : Assert(XLogSegmentOffset(*EndPos, wal_segment_size) == 0);
1311 : : Assert(XLogRecPtrToBytePos(*EndPos) == endbytepos);
1312 : : Assert(XLogRecPtrToBytePos(*StartPos) == startbytepos);
1313 : : Assert(XLogRecPtrToBytePos(*PrevPtr) == prevbytepos);
1314 : :
1315 : 797 : return true;
1316 : : }
1317 : :
1318 : : /*
1319 : : * Subroutine of XLogInsertRecord. Copies a WAL record to an already-reserved
1320 : : * area in the WAL.
1321 : : */
1322 : : static void
1323 : 25216405 : CopyXLogRecordToWAL(int write_len, bool isLogSwitch, XLogRecData *rdata,
1324 : : XLogRecPtr StartPos, XLogRecPtr EndPos, TimeLineID tli)
1325 : : {
1326 : : char *currpos;
1327 : : int freespace;
1328 : : int written;
1329 : : XLogRecPtr CurrPos;
1330 : : XLogPageHeader pagehdr;
1331 : :
1332 : : /*
1333 : : * Get a pointer to the right place in the right WAL buffer to start
1334 : : * inserting to.
1335 : : */
1336 : 25216405 : CurrPos = StartPos;
1337 : 25216405 : currpos = GetXLogBuffer(CurrPos, tli);
1338 [ + - ]: 25216405 : freespace = INSERT_FREESPACE(CurrPos);
1339 : :
1340 : : /*
1341 : : * there should be enough space for at least the first field (xl_tot_len)
1342 : : * on this page.
1343 : : */
1344 : : Assert(freespace >= sizeof(uint32));
1345 : :
1346 : : /* Copy record data */
1347 : 25216405 : written = 0;
1348 [ + + ]: 115085987 : while (rdata != NULL)
1349 : : {
1350 : 89869582 : const char *rdata_data = rdata->data;
1351 : 89869582 : int rdata_len = rdata->len;
1352 : :
1353 [ + + ]: 91884742 : while (rdata_len > freespace)
1354 : : {
1355 : : /*
1356 : : * Write what fits on this page, and continue on the next page.
1357 : : */
1358 : : Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || freespace == 0);
1359 : 2015160 : memcpy(currpos, rdata_data, freespace);
1360 : 2015160 : rdata_data += freespace;
1361 : 2015160 : rdata_len -= freespace;
1362 : 2015160 : written += freespace;
1363 : 2015160 : CurrPos += freespace;
1364 : :
1365 : : /*
1366 : : * Get pointer to beginning of next page, and set the xlp_rem_len
1367 : : * in the page header. Set XLP_FIRST_IS_CONTRECORD.
1368 : : *
1369 : : * It's safe to set the contrecord flag and xlp_rem_len without a
1370 : : * lock on the page. All the other flags were already set when the
1371 : : * page was initialized, in AdvanceXLInsertBuffer, and we're the
1372 : : * only backend that needs to set the contrecord flag.
1373 : : */
1374 : 2015160 : currpos = GetXLogBuffer(CurrPos, tli);
1375 : 2015160 : pagehdr = (XLogPageHeader) currpos;
1376 : 2015160 : pagehdr->xlp_rem_len = write_len - written;
1377 : 2015160 : pagehdr->xlp_info |= XLP_FIRST_IS_CONTRECORD;
1378 : :
1379 : : /* skip over the page header */
1380 [ + + ]: 2015160 : if (XLogSegmentOffset(CurrPos, wal_segment_size) == 0)
1381 : : {
1382 : 1291 : CurrPos += SizeOfXLogLongPHD;
1383 : 1291 : currpos += SizeOfXLogLongPHD;
1384 : : }
1385 : : else
1386 : : {
1387 : 2013869 : CurrPos += SizeOfXLogShortPHD;
1388 : 2013869 : currpos += SizeOfXLogShortPHD;
1389 : : }
1390 [ + - ]: 2015160 : freespace = INSERT_FREESPACE(CurrPos);
1391 : : }
1392 : :
1393 : : Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || rdata_len == 0);
1394 : 89869582 : memcpy(currpos, rdata_data, rdata_len);
1395 : 89869582 : currpos += rdata_len;
1396 : 89869582 : CurrPos += rdata_len;
1397 : 89869582 : freespace -= rdata_len;
1398 : 89869582 : written += rdata_len;
1399 : :
1400 : 89869582 : rdata = rdata->next;
1401 : : }
1402 : : Assert(written == write_len);
1403 : :
1404 : : /*
1405 : : * If this was an xlog-switch, it's not enough to write the switch record,
1406 : : * we also have to consume all the remaining space in the WAL segment. We
1407 : : * have already reserved that space, but we need to actually fill it.
1408 : : */
1409 [ + + + - ]: 25216405 : if (isLogSwitch && XLogSegmentOffset(CurrPos, wal_segment_size) != 0)
1410 : : {
1411 : : /* An xlog-switch record doesn't contain any data besides the header */
1412 : : Assert(write_len == SizeOfXLogRecord);
1413 : :
1414 : : /* Assert that we did reserve the right amount of space */
1415 : : Assert(XLogSegmentOffset(EndPos, wal_segment_size) == 0);
1416 : :
1417 : : /* Use up all the remaining space on the current page */
1418 : 797 : CurrPos += freespace;
1419 : :
1420 : : /*
1421 : : * Cause all remaining pages in the segment to be flushed, leaving the
1422 : : * XLog position where it should be, at the start of the next segment.
1423 : : * We do this one page at a time, to make sure we don't deadlock
1424 : : * against ourselves if wal_buffers < wal_segment_size.
1425 : : */
1426 [ + + ]: 824315 : while (CurrPos < EndPos)
1427 : : {
1428 : : /*
1429 : : * The minimal action to flush the page would be to call
1430 : : * WALInsertLockUpdateInsertingAt(CurrPos) followed by
1431 : : * AdvanceXLInsertBuffer(...). The page would be left initialized
1432 : : * mostly to zeros, except for the page header (always the short
1433 : : * variant, as this is never a segment's first page).
1434 : : *
1435 : : * The large vistas of zeros are good for compressibility, but the
1436 : : * headers interrupting them every XLOG_BLCKSZ (with values that
1437 : : * differ from page to page) are not. The effect varies with
1438 : : * compression tool, but bzip2 for instance compresses about an
1439 : : * order of magnitude worse if those headers are left in place.
1440 : : *
1441 : : * Rather than complicating AdvanceXLInsertBuffer itself (which is
1442 : : * called in heavily-loaded circumstances as well as this lightly-
1443 : : * loaded one) with variant behavior, we just use GetXLogBuffer
1444 : : * (which itself calls the two methods we need) to get the pointer
1445 : : * and zero most of the page. Then we just zero the page header.
1446 : : */
1447 : 823518 : currpos = GetXLogBuffer(CurrPos, tli);
1448 [ + - + - : 3294072 : MemSet(currpos, 0, SizeOfXLogShortPHD);
+ - + - +
+ ]
1449 : :
1450 : 823518 : CurrPos += XLOG_BLCKSZ;
1451 : : }
1452 : : }
1453 : : else
1454 : : {
1455 : : /* Align the end position, so that the next record starts aligned */
1456 : 25215608 : CurrPos = MAXALIGN64(CurrPos);
1457 : : }
1458 : :
1459 [ - + ]: 25216405 : if (CurrPos != EndPos)
1460 [ # # ]: 0 : ereport(PANIC,
1461 : : errcode(ERRCODE_DATA_CORRUPTED),
1462 : : errmsg_internal("space reserved for WAL record does not match what was written"));
1463 : 25216405 : }
1464 : :
1465 : : /*
1466 : : * Acquire a WAL insertion lock, for inserting to WAL.
1467 : : */
1468 : : static void
1469 : 25224912 : WALInsertLockAcquire(void)
1470 : : {
1471 : : bool immed;
1472 : :
1473 : : /*
1474 : : * It doesn't matter which of the WAL insertion locks we acquire, so try
1475 : : * the one we used last time. If the system isn't particularly busy, it's
1476 : : * a good bet that it's still available, and it's good to have some
1477 : : * affinity to a particular lock so that you don't unnecessarily bounce
1478 : : * cache lines between processes when there's no contention.
1479 : : *
1480 : : * If this is the first time through in this backend, pick a lock
1481 : : * (semi-)randomly. This allows the locks to be used evenly if you have a
1482 : : * lot of very short connections.
1483 : : */
1484 : : static int lockToTry = -1;
1485 : :
1486 [ + + ]: 25224912 : if (lockToTry == -1)
1487 : 9799 : lockToTry = MyProcNumber % NUM_XLOGINSERT_LOCKS;
1488 : 25224912 : MyLockNo = lockToTry;
1489 : :
1490 : : /*
1491 : : * The insertingAt value is initially set to 0, as we don't know our
1492 : : * insert location yet.
1493 : : */
1494 : 25224912 : immed = LWLockAcquire(&WALInsertLocks[MyLockNo].l.lock, LW_EXCLUSIVE);
1495 [ + + ]: 25224912 : if (!immed)
1496 : : {
1497 : : /*
1498 : : * If we couldn't get the lock immediately, try another lock next
1499 : : * time. On a system with more insertion locks than concurrent
1500 : : * inserters, this causes all the inserters to eventually migrate to a
1501 : : * lock that no-one else is using. On a system with more inserters
1502 : : * than locks, it still helps to distribute the inserters evenly
1503 : : * across the locks.
1504 : : */
1505 : 17467 : lockToTry = (lockToTry + 1) % NUM_XLOGINSERT_LOCKS;
1506 : : }
1507 : 25224912 : }
1508 : :
1509 : : /*
1510 : : * Acquire all WAL insertion locks, to prevent other backends from inserting
1511 : : * to WAL.
1512 : : */
1513 : : static void
1514 : 5078 : WALInsertLockAcquireExclusive(void)
1515 : : {
1516 : : int i;
1517 : :
1518 : : /*
1519 : : * When holding all the locks, all but the last lock's insertingAt
1520 : : * indicator is set to 0xFFFFFFFFFFFFFFFF, which is higher than any real
1521 : : * XLogRecPtr value, to make sure that no-one blocks waiting on those.
1522 : : */
1523 [ + + ]: 40624 : for (i = 0; i < NUM_XLOGINSERT_LOCKS - 1; i++)
1524 : : {
1525 : 35546 : LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
1526 : 35546 : LWLockUpdateVar(&WALInsertLocks[i].l.lock,
1527 : 35546 : &WALInsertLocks[i].l.insertingAt,
1528 : : PG_UINT64_MAX);
1529 : : }
1530 : : /* Variable value reset to 0 at release */
1531 : 5078 : LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
1532 : :
1533 : 5078 : holdingAllLocks = true;
1534 : 5078 : }
1535 : :
1536 : : /*
1537 : : * Release our insertion lock (or locks, if we're holding them all).
1538 : : *
1539 : : * NB: Reset all variables to 0, so they cause LWLockWaitForVar to block the
1540 : : * next time the lock is acquired.
1541 : : */
1542 : : static void
1543 : 25229990 : WALInsertLockRelease(void)
1544 : : {
1545 [ + + ]: 25229990 : if (holdingAllLocks)
1546 : : {
1547 : : int i;
1548 : :
1549 [ + + ]: 45702 : for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1550 : 40624 : LWLockReleaseClearVar(&WALInsertLocks[i].l.lock,
1551 : 40624 : &WALInsertLocks[i].l.insertingAt,
1552 : : 0);
1553 : :
1554 : 5078 : holdingAllLocks = false;
1555 : : }
1556 : : else
1557 : : {
1558 : 25224912 : LWLockReleaseClearVar(&WALInsertLocks[MyLockNo].l.lock,
1559 : 25224912 : &WALInsertLocks[MyLockNo].l.insertingAt,
1560 : : 0);
1561 : : }
1562 : 25229990 : }
1563 : :
1564 : : /*
1565 : : * Update our insertingAt value, to let others know that we've finished
1566 : : * inserting up to that point.
1567 : : */
1568 : : static void
1569 : 2761813 : WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt)
1570 : : {
1571 [ + + ]: 2761813 : if (holdingAllLocks)
1572 : : {
1573 : : /*
1574 : : * We use the last lock to mark our actual position, see comments in
1575 : : * WALInsertLockAcquireExclusive.
1576 : : */
1577 : 821833 : LWLockUpdateVar(&WALInsertLocks[NUM_XLOGINSERT_LOCKS - 1].l.lock,
1578 : 821833 : &WALInsertLocks[NUM_XLOGINSERT_LOCKS - 1].l.insertingAt,
1579 : : insertingAt);
1580 : : }
1581 : : else
1582 : 1939980 : LWLockUpdateVar(&WALInsertLocks[MyLockNo].l.lock,
1583 : 1939980 : &WALInsertLocks[MyLockNo].l.insertingAt,
1584 : : insertingAt);
1585 : 2761813 : }
1586 : :
1587 : : /*
1588 : : * Wait for any WAL insertions < upto to finish.
1589 : : *
1590 : : * Returns the location of the oldest insertion that is still in-progress.
1591 : : * Any WAL prior to that point has been fully copied into WAL buffers, and
1592 : : * can be flushed out to disk. Because this waits for any insertions older
1593 : : * than 'upto' to finish, the return value is always >= 'upto'.
1594 : : *
1595 : : * Note: When you are about to write out WAL, you must call this function
1596 : : * *before* acquiring WALWriteLock, to avoid deadlocks. This function might
1597 : : * need to wait for an insertion to finish (or at least advance to next
1598 : : * uninitialized page), and the inserter might need to evict an old WAL buffer
1599 : : * to make room for a new one, which in turn requires WALWriteLock.
1600 : : */
1601 : : static XLogRecPtr
1602 : 2563297 : WaitXLogInsertionsToFinish(XLogRecPtr upto)
1603 : : {
1604 : : uint64 bytepos;
1605 : : XLogRecPtr inserted;
1606 : : XLogRecPtr reservedUpto;
1607 : : XLogRecPtr finishedUpto;
1608 : 2563297 : XLogCtlInsert *Insert = &XLogCtl->Insert;
1609 : : int i;
1610 : :
1611 [ - + ]: 2563297 : if (MyProc == NULL)
1612 [ # # ]: 0 : elog(PANIC, "cannot wait without a PGPROC structure");
1613 : :
1614 : : /*
1615 : : * Check if there's any work to do. Use a barrier to ensure we get the
1616 : : * freshest value.
1617 : : */
1618 : 2563297 : inserted = pg_atomic_read_membarrier_u64(&XLogCtl->logInsertResult);
1619 [ + + ]: 2563297 : if (upto <= inserted)
1620 : 2051221 : return inserted;
1621 : :
1622 : : /* Read the current insert position */
1623 : 512076 : SpinLockAcquire(&Insert->insertpos_lck);
1624 : 512076 : bytepos = Insert->CurrBytePos;
1625 : 512076 : SpinLockRelease(&Insert->insertpos_lck);
1626 : 512076 : reservedUpto = XLogBytePosToEndRecPtr(bytepos);
1627 : :
1628 : : /*
1629 : : * No-one should request to flush a piece of WAL that hasn't even been
1630 : : * reserved yet. However, it can happen if there is a block with a bogus
1631 : : * LSN on disk, for example. XLogFlush checks for that situation and
1632 : : * complains, but only after the flush. Here we just assume that to mean
1633 : : * that all WAL that has been reserved needs to be finished. In this
1634 : : * corner-case, the return value can be smaller than 'upto' argument.
1635 : : */
1636 [ - + ]: 512076 : if (upto > reservedUpto)
1637 : : {
1638 [ # # ]: 0 : ereport(LOG,
1639 : : errmsg("request to flush past end of generated WAL; request %X/%08X, current position %X/%08X",
1640 : : LSN_FORMAT_ARGS(upto), LSN_FORMAT_ARGS(reservedUpto)));
1641 : 0 : upto = reservedUpto;
1642 : : }
1643 : :
1644 : : /*
1645 : : * Loop through all the locks, sleeping on any in-progress insert older
1646 : : * than 'upto'.
1647 : : *
1648 : : * finishedUpto is our return value, indicating the point upto which all
1649 : : * the WAL insertions have been finished. Initialize it to the head of
1650 : : * reserved WAL, and as we iterate through the insertion locks, back it
1651 : : * out for any insertion that's still in progress.
1652 : : */
1653 : 512076 : finishedUpto = reservedUpto;
1654 [ + + ]: 4608684 : for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1655 : : {
1656 : 4096608 : XLogRecPtr insertingat = InvalidXLogRecPtr;
1657 : :
1658 : : do
1659 : : {
1660 : : /*
1661 : : * See if this insertion is in progress. LWLockWaitForVar will
1662 : : * wait for the lock to be released, or for the 'value' to be set
1663 : : * by a LWLockUpdateVar call. When a lock is initially acquired,
1664 : : * its value is 0 (InvalidXLogRecPtr), which means that we don't
1665 : : * know where it's inserting yet. We will have to wait for it. If
1666 : : * it's a small insertion, the record will most likely fit on the
1667 : : * same page and the inserter will release the lock without ever
1668 : : * calling LWLockUpdateVar. But if it has to sleep, it will
1669 : : * advertise the insertion point with LWLockUpdateVar before
1670 : : * sleeping.
1671 : : *
1672 : : * In this loop we are only waiting for insertions that started
1673 : : * before WaitXLogInsertionsToFinish was called. The lack of
1674 : : * memory barriers in the loop means that we might see locks as
1675 : : * "unused" that have since become used. This is fine because
1676 : : * they only can be used for later insertions that we would not
1677 : : * want to wait on anyway. Not taking a lock to acquire the
1678 : : * current insertingAt value means that we might see older
1679 : : * insertingAt values. This is also fine, because if we read a
1680 : : * value too old, we will add ourselves to the wait queue, which
1681 : : * contains atomic operations.
1682 : : */
1683 [ + + ]: 4190858 : if (LWLockWaitForVar(&WALInsertLocks[i].l.lock,
1684 : 4190858 : &WALInsertLocks[i].l.insertingAt,
1685 : : insertingat, &insertingat))
1686 : : {
1687 : : /* the lock was free, so no insertion in progress */
1688 : 2925115 : insertingat = InvalidXLogRecPtr;
1689 : 2925115 : break;
1690 : : }
1691 : :
1692 : : /*
1693 : : * This insertion is still in progress. Have to wait, unless the
1694 : : * inserter has proceeded past 'upto'.
1695 : : */
1696 [ + + ]: 1265743 : } while (insertingat < upto);
1697 : :
1698 [ + + + + ]: 4096608 : if (XLogRecPtrIsValid(insertingat) && insertingat < finishedUpto)
1699 : 407328 : finishedUpto = insertingat;
1700 : : }
1701 : :
1702 : : /*
1703 : : * Advance the limit we know to have been inserted and return the freshest
1704 : : * value we know of, which might be beyond what we requested if somebody
1705 : : * is concurrently doing this with an 'upto' pointer ahead of us.
1706 : : */
1707 : 512076 : finishedUpto = pg_atomic_monotonic_advance_u64(&XLogCtl->logInsertResult,
1708 : : finishedUpto);
1709 : :
1710 : 512076 : return finishedUpto;
1711 : : }
1712 : :
1713 : : /*
1714 : : * Get a pointer to the right location in the WAL buffer containing the
1715 : : * given XLogRecPtr.
1716 : : *
1717 : : * If the page is not initialized yet, it is initialized. That might require
1718 : : * evicting an old dirty buffer from the buffer cache, which means I/O.
1719 : : *
1720 : : * The caller must ensure that the page containing the requested location
1721 : : * isn't evicted yet, and won't be evicted. The way to ensure that is to
1722 : : * hold onto a WAL insertion lock with the insertingAt position set to
1723 : : * something <= ptr. GetXLogBuffer() will update insertingAt if it needs
1724 : : * to evict an old page from the buffer. (This means that once you call
1725 : : * GetXLogBuffer() with a given 'ptr', you must not access anything before
1726 : : * that point anymore, and must not call GetXLogBuffer() with an older 'ptr'
1727 : : * later, because older buffers might be recycled already)
1728 : : */
1729 : : static char *
1730 : 28055093 : GetXLogBuffer(XLogRecPtr ptr, TimeLineID tli)
1731 : : {
1732 : : int idx;
1733 : : XLogRecPtr endptr;
1734 : : static uint64 cachedPage = 0;
1735 : : static char *cachedPos = NULL;
1736 : : XLogRecPtr expectedEndPtr;
1737 : :
1738 : : /*
1739 : : * Fast path for the common case that we need to access again the same
1740 : : * page as last time.
1741 : : */
1742 [ + + ]: 28055093 : if (ptr / XLOG_BLCKSZ == cachedPage)
1743 : : {
1744 : : Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1745 : : Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1746 : 24780840 : return cachedPos + ptr % XLOG_BLCKSZ;
1747 : : }
1748 : :
1749 : : /*
1750 : : * The XLog buffer cache is organized so that a page is always loaded to a
1751 : : * particular buffer. That way we can easily calculate the buffer a given
1752 : : * page must be loaded into, from the XLogRecPtr alone.
1753 : : */
1754 : 3274253 : idx = XLogRecPtrToBufIdx(ptr);
1755 : :
1756 : : /*
1757 : : * See what page is loaded in the buffer at the moment. It could be the
1758 : : * page we're looking for, or something older. It can't be anything newer
1759 : : * - that would imply the page we're looking for has already been written
1760 : : * out to disk and evicted, and the caller is responsible for making sure
1761 : : * that doesn't happen.
1762 : : *
1763 : : * We don't hold a lock while we read the value. If someone is just about
1764 : : * to initialize or has just initialized the page, it's possible that we
1765 : : * get InvalidXLogRecPtr. That's ok, we'll grab the mapping lock (in
1766 : : * AdvanceXLInsertBuffer) and retry if we see anything other than the page
1767 : : * we're looking for.
1768 : : */
1769 : 3274253 : expectedEndPtr = ptr;
1770 : 3274253 : expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
1771 : :
1772 : 3274253 : endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1773 [ + + ]: 3274253 : if (expectedEndPtr != endptr)
1774 : : {
1775 : : XLogRecPtr initializedUpto;
1776 : :
1777 : : /*
1778 : : * Before calling AdvanceXLInsertBuffer(), which can block, let others
1779 : : * know how far we're finished with inserting the record.
1780 : : *
1781 : : * NB: If 'ptr' points to just after the page header, advertise a
1782 : : * position at the beginning of the page rather than 'ptr' itself. If
1783 : : * there are no other insertions running, someone might try to flush
1784 : : * up to our advertised location. If we advertised a position after
1785 : : * the page header, someone might try to flush the page header, even
1786 : : * though page might actually not be initialized yet. As the first
1787 : : * inserter on the page, we are effectively responsible for making
1788 : : * sure that it's initialized, before we let insertingAt to move past
1789 : : * the page header.
1790 : : */
1791 [ + + ]: 2761813 : if (ptr % XLOG_BLCKSZ == SizeOfXLogShortPHD &&
1792 [ + - ]: 12096 : XLogSegmentOffset(ptr, wal_segment_size) > XLOG_BLCKSZ)
1793 : 12096 : initializedUpto = ptr - SizeOfXLogShortPHD;
1794 [ + + ]: 2749717 : else if (ptr % XLOG_BLCKSZ == SizeOfXLogLongPHD &&
1795 [ + + ]: 1042 : XLogSegmentOffset(ptr, wal_segment_size) < XLOG_BLCKSZ)
1796 : 660 : initializedUpto = ptr - SizeOfXLogLongPHD;
1797 : : else
1798 : 2749057 : initializedUpto = ptr;
1799 : :
1800 : 2761813 : WALInsertLockUpdateInsertingAt(initializedUpto);
1801 : :
1802 : 2761813 : AdvanceXLInsertBuffer(ptr, tli, false);
1803 : 2761813 : endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1804 : :
1805 [ - + ]: 2761813 : if (expectedEndPtr != endptr)
1806 [ # # ]: 0 : elog(PANIC, "could not find WAL buffer for %X/%08X",
1807 : : LSN_FORMAT_ARGS(ptr));
1808 : : }
1809 : : else
1810 : : {
1811 : : /*
1812 : : * Make sure the initialization of the page is visible to us, and
1813 : : * won't arrive later to overwrite the WAL data we write on the page.
1814 : : */
1815 : 512440 : pg_memory_barrier();
1816 : : }
1817 : :
1818 : : /*
1819 : : * Found the buffer holding this page. Return a pointer to the right
1820 : : * offset within the page.
1821 : : */
1822 : 3274253 : cachedPage = ptr / XLOG_BLCKSZ;
1823 : 3274253 : cachedPos = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
1824 : :
1825 : : Assert(((XLogPageHeader) cachedPos)->xlp_magic == XLOG_PAGE_MAGIC);
1826 : : Assert(((XLogPageHeader) cachedPos)->xlp_pageaddr == ptr - (ptr % XLOG_BLCKSZ));
1827 : :
1828 : 3274253 : return cachedPos + ptr % XLOG_BLCKSZ;
1829 : : }
1830 : :
1831 : : /*
1832 : : * Read WAL data directly from WAL buffers, if available. Returns the number
1833 : : * of bytes read successfully.
1834 : : *
1835 : : * Fewer than 'count' bytes may be read if some of the requested WAL data has
1836 : : * already been evicted.
1837 : : *
1838 : : * No locks are taken.
1839 : : *
1840 : : * Caller should ensure that it reads no further than LogwrtResult.Write
1841 : : * (which should have been updated by the caller when determining how far to
1842 : : * read). The 'tli' argument is only used as a convenient safety check so that
1843 : : * callers do not read from WAL buffers on a historical timeline.
1844 : : */
1845 : : Size
1846 : 107210 : WALReadFromBuffers(char *dstbuf, XLogRecPtr startptr, Size count,
1847 : : TimeLineID tli)
1848 : : {
1849 : 107210 : char *pdst = dstbuf;
1850 : 107210 : XLogRecPtr recptr = startptr;
1851 : : XLogRecPtr inserted;
1852 : 107210 : Size nbytes = count;
1853 : :
1854 [ + + + + ]: 107210 : if (RecoveryInProgress() || tli != GetWALInsertionTimeLine())
1855 : 1376 : return 0;
1856 : :
1857 : : Assert(XLogRecPtrIsValid(startptr));
1858 : :
1859 : : /*
1860 : : * Caller should ensure that the requested data has been inserted into WAL
1861 : : * buffers before we try to read it.
1862 : : */
1863 : 105834 : inserted = pg_atomic_read_u64(&XLogCtl->logInsertResult);
1864 [ - + ]: 105834 : if (startptr + count > inserted)
1865 [ # # ]: 0 : ereport(ERROR,
1866 : : errmsg("cannot read past end of generated WAL: requested %X/%08X, current position %X/%08X",
1867 : : LSN_FORMAT_ARGS(startptr + count),
1868 : : LSN_FORMAT_ARGS(inserted)));
1869 : :
1870 : : /*
1871 : : * Loop through the buffers without a lock. For each buffer, atomically
1872 : : * read and verify the end pointer, then copy the data out, and finally
1873 : : * re-read and re-verify the end pointer.
1874 : : *
1875 : : * Once a page is evicted, it never returns to the WAL buffers, so if the
1876 : : * end pointer matches the expected end pointer before and after we copy
1877 : : * the data, then the right page must have been present during the data
1878 : : * copy. Read barriers are necessary to ensure that the data copy actually
1879 : : * happens between the two verification steps.
1880 : : *
1881 : : * If either verification fails, we simply terminate the loop and return
1882 : : * with the data that had been already copied out successfully.
1883 : : */
1884 [ + + ]: 136713 : while (nbytes > 0)
1885 : : {
1886 : 127667 : uint32 offset = recptr % XLOG_BLCKSZ;
1887 : 127667 : int idx = XLogRecPtrToBufIdx(recptr);
1888 : : XLogRecPtr expectedEndPtr;
1889 : : XLogRecPtr endptr;
1890 : : const char *page;
1891 : : const char *psrc;
1892 : : Size npagebytes;
1893 : :
1894 : : /*
1895 : : * Calculate the end pointer we expect in the xlblocks array if the
1896 : : * correct page is present.
1897 : : */
1898 : 127667 : expectedEndPtr = recptr + (XLOG_BLCKSZ - offset);
1899 : :
1900 : : /*
1901 : : * First verification step: check that the correct page is present in
1902 : : * the WAL buffers.
1903 : : */
1904 : 127667 : endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1905 [ + + ]: 127667 : if (expectedEndPtr != endptr)
1906 : 96784 : break;
1907 : :
1908 : : /*
1909 : : * The correct page is present (or was at the time the endptr was
1910 : : * read; must re-verify later). Calculate pointer to source data and
1911 : : * determine how much data to read from this page.
1912 : : */
1913 : 30883 : page = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
1914 : 30883 : psrc = page + offset;
1915 : 30883 : npagebytes = Min(nbytes, XLOG_BLCKSZ - offset);
1916 : :
1917 : : /*
1918 : : * Ensure that the data copy and the first verification step are not
1919 : : * reordered.
1920 : : */
1921 : 30883 : pg_read_barrier();
1922 : :
1923 : : /* data copy */
1924 : 30883 : memcpy(pdst, psrc, npagebytes);
1925 : :
1926 : : /*
1927 : : * Ensure that the data copy and the second verification step are not
1928 : : * reordered.
1929 : : */
1930 : 30883 : pg_read_barrier();
1931 : :
1932 : : /*
1933 : : * Second verification step: check that the page we read from wasn't
1934 : : * evicted while we were copying the data.
1935 : : */
1936 : 30883 : endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1937 [ + + ]: 30883 : if (expectedEndPtr != endptr)
1938 : 4 : break;
1939 : :
1940 : 30879 : pdst += npagebytes;
1941 : 30879 : recptr += npagebytes;
1942 : 30879 : nbytes -= npagebytes;
1943 : : }
1944 : :
1945 : : Assert(pdst - dstbuf <= count);
1946 : :
1947 : 105834 : return pdst - dstbuf;
1948 : : }
1949 : :
1950 : : /*
1951 : : * Converts a "usable byte position" to XLogRecPtr. A usable byte position
1952 : : * is the position starting from the beginning of WAL, excluding all WAL
1953 : : * page headers.
1954 : : */
1955 : : static XLogRecPtr
1956 : 50435839 : XLogBytePosToRecPtr(uint64 bytepos)
1957 : : {
1958 : : uint64 fullsegs;
1959 : : uint64 fullpages;
1960 : : uint64 bytesleft;
1961 : : uint32 seg_offset;
1962 : : XLogRecPtr result;
1963 : :
1964 : 50435839 : fullsegs = bytepos / UsableBytesInSegment;
1965 : 50435839 : bytesleft = bytepos % UsableBytesInSegment;
1966 : :
1967 [ + + ]: 50435839 : if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
1968 : : {
1969 : : /* fits on first page of segment */
1970 : 73397 : seg_offset = bytesleft + SizeOfXLogLongPHD;
1971 : : }
1972 : : else
1973 : : {
1974 : : /* account for the first page on segment with long header */
1975 : 50362442 : seg_offset = XLOG_BLCKSZ;
1976 : 50362442 : bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
1977 : :
1978 : 50362442 : fullpages = bytesleft / UsableBytesInPage;
1979 : 50362442 : bytesleft = bytesleft % UsableBytesInPage;
1980 : :
1981 : 50362442 : seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
1982 : : }
1983 : :
1984 : 50435839 : XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
1985 : :
1986 : 50435839 : return result;
1987 : : }
1988 : :
1989 : : /*
1990 : : * Like XLogBytePosToRecPtr, but if the position is at a page boundary,
1991 : : * returns a pointer to the beginning of the page (ie. before page header),
1992 : : * not to where the first xlog record on that page would go to. This is used
1993 : : * when converting a pointer to the end of a record.
1994 : : */
1995 : : static XLogRecPtr
1996 : 25739942 : XLogBytePosToEndRecPtr(uint64 bytepos)
1997 : : {
1998 : : uint64 fullsegs;
1999 : : uint64 fullpages;
2000 : : uint64 bytesleft;
2001 : : uint32 seg_offset;
2002 : : XLogRecPtr result;
2003 : :
2004 : 25739942 : fullsegs = bytepos / UsableBytesInSegment;
2005 : 25739942 : bytesleft = bytepos % UsableBytesInSegment;
2006 : :
2007 [ + + ]: 25739942 : if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
2008 : : {
2009 : : /* fits on first page of segment */
2010 [ + + ]: 118875 : if (bytesleft == 0)
2011 : 80677 : seg_offset = 0;
2012 : : else
2013 : 38198 : seg_offset = bytesleft + SizeOfXLogLongPHD;
2014 : : }
2015 : : else
2016 : : {
2017 : : /* account for the first page on segment with long header */
2018 : 25621067 : seg_offset = XLOG_BLCKSZ;
2019 : 25621067 : bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2020 : :
2021 : 25621067 : fullpages = bytesleft / UsableBytesInPage;
2022 : 25621067 : bytesleft = bytesleft % UsableBytesInPage;
2023 : :
2024 [ + + ]: 25621067 : if (bytesleft == 0)
2025 : 24665 : seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
2026 : : else
2027 : 25596402 : seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2028 : : }
2029 : :
2030 : 25739942 : XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
2031 : :
2032 : 25739942 : return result;
2033 : : }
2034 : :
2035 : : /*
2036 : : * Convert an XLogRecPtr to a "usable byte position".
2037 : : */
2038 : : static uint64
2039 : 2929 : XLogRecPtrToBytePos(XLogRecPtr ptr)
2040 : : {
2041 : : uint64 fullsegs;
2042 : : uint32 fullpages;
2043 : : uint32 offset;
2044 : : uint64 result;
2045 : :
2046 : 2929 : XLByteToSeg(ptr, fullsegs, wal_segment_size);
2047 : :
2048 : 2929 : fullpages = (XLogSegmentOffset(ptr, wal_segment_size)) / XLOG_BLCKSZ;
2049 : 2929 : offset = ptr % XLOG_BLCKSZ;
2050 : :
2051 [ + + ]: 2929 : if (fullpages == 0)
2052 : : {
2053 : 1120 : result = fullsegs * UsableBytesInSegment;
2054 [ + + ]: 1120 : if (offset > 0)
2055 : : {
2056 : : Assert(offset >= SizeOfXLogLongPHD);
2057 : 304 : result += offset - SizeOfXLogLongPHD;
2058 : : }
2059 : : }
2060 : : else
2061 : : {
2062 : 1809 : result = fullsegs * UsableBytesInSegment +
2063 : 1809 : (XLOG_BLCKSZ - SizeOfXLogLongPHD) + /* account for first page */
2064 : 1809 : (fullpages - 1) * UsableBytesInPage; /* full pages */
2065 [ + + ]: 1809 : if (offset > 0)
2066 : : {
2067 : : Assert(offset >= SizeOfXLogShortPHD);
2068 : 1800 : result += offset - SizeOfXLogShortPHD;
2069 : : }
2070 : : }
2071 : :
2072 : 2929 : return result;
2073 : : }
2074 : :
2075 : : /*
2076 : : * Initialize XLOG buffers, writing out old buffers if they still contain
2077 : : * unwritten data, upto the page containing 'upto'. Or if 'opportunistic' is
2078 : : * true, initialize as many pages as we can without having to write out
2079 : : * unwritten data. Any new pages are initialized to zeros, with pages headers
2080 : : * initialized properly.
2081 : : */
2082 : : static void
2083 : 2766960 : AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli, bool opportunistic)
2084 : : {
2085 : : int nextidx;
2086 : : XLogRecPtr OldPageRqstPtr;
2087 : : XLogwrtRqst WriteRqst;
2088 : 2766960 : XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
2089 : : XLogRecPtr NewPageBeginPtr;
2090 : : XLogPageHeader NewPage;
2091 : 2766960 : int npages pg_attribute_unused() = 0;
2092 : :
2093 : 2766960 : LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2094 : :
2095 : : /*
2096 : : * Now that we have the lock, check if someone initialized the page
2097 : : * already.
2098 : : */
2099 [ + + + + ]: 8060648 : while (upto >= XLogCtl->InitializedUpTo || opportunistic)
2100 : : {
2101 : 5298835 : nextidx = XLogRecPtrToBufIdx(XLogCtl->InitializedUpTo);
2102 : :
2103 : : /*
2104 : : * Get ending-offset of the buffer page we need to replace (this may
2105 : : * be zero if the buffer hasn't been used yet). Fall through if it's
2106 : : * already written out.
2107 : : */
2108 : 5298835 : OldPageRqstPtr = pg_atomic_read_u64(&XLogCtl->xlblocks[nextidx]);
2109 [ + + ]: 5298835 : if (LogwrtResult.Write < OldPageRqstPtr)
2110 : : {
2111 : : /*
2112 : : * Nope, got work to do. If we just want to pre-initialize as much
2113 : : * as we can without flushing, give up now.
2114 : : */
2115 [ + + ]: 2416084 : if (opportunistic)
2116 : 5147 : break;
2117 : :
2118 : : /* Advance shared memory write request position */
2119 : 2410937 : SpinLockAcquire(&XLogCtl->info_lck);
2120 [ + + ]: 2410937 : if (XLogCtl->LogwrtRqst.Write < OldPageRqstPtr)
2121 : 773513 : XLogCtl->LogwrtRqst.Write = OldPageRqstPtr;
2122 : 2410937 : SpinLockRelease(&XLogCtl->info_lck);
2123 : :
2124 : : /*
2125 : : * Acquire an up-to-date LogwrtResult value and see if we still
2126 : : * need to write it or if someone else already did.
2127 : : */
2128 : 2410937 : RefreshXLogWriteResult(LogwrtResult);
2129 [ + + ]: 2410937 : if (LogwrtResult.Write < OldPageRqstPtr)
2130 : : {
2131 : : /*
2132 : : * Must acquire write lock. Release WALBufMappingLock first,
2133 : : * to make sure that all insertions that we need to wait for
2134 : : * can finish (up to this same position). Otherwise we risk
2135 : : * deadlock.
2136 : : */
2137 : 2392609 : LWLockRelease(WALBufMappingLock);
2138 : :
2139 : 2392609 : WaitXLogInsertionsToFinish(OldPageRqstPtr);
2140 : :
2141 : 2392609 : LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2142 : :
2143 : 2392609 : RefreshXLogWriteResult(LogwrtResult);
2144 [ + + ]: 2392609 : if (LogwrtResult.Write >= OldPageRqstPtr)
2145 : : {
2146 : : /* OK, someone wrote it already */
2147 : 143940 : LWLockRelease(WALWriteLock);
2148 : : }
2149 : : else
2150 : : {
2151 : : /* Have to write it ourselves */
2152 : : TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2153 : 2248669 : WriteRqst.Write = OldPageRqstPtr;
2154 : 2248669 : WriteRqst.Flush = InvalidXLogRecPtr;
2155 : 2248669 : XLogWrite(WriteRqst, tli, false);
2156 : 2248669 : LWLockRelease(WALWriteLock);
2157 : 2248669 : pgWalUsage.wal_buffers_full++;
2158 : : TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
2159 : :
2160 : : /*
2161 : : * Required for the flush of pending stats WAL data, per
2162 : : * update of pgWalUsage.
2163 : : */
2164 : 2248669 : pgstat_report_fixed = true;
2165 : : }
2166 : : /* Re-acquire WALBufMappingLock and retry */
2167 : 2392609 : LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2168 : 2392609 : continue;
2169 : : }
2170 : : }
2171 : :
2172 : : /*
2173 : : * Now the next buffer slot is free and we can set it up to be the
2174 : : * next output page.
2175 : : */
2176 : 2901079 : NewPageBeginPtr = XLogCtl->InitializedUpTo;
2177 : 2901079 : NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2178 : :
2179 : : Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
2180 : :
2181 : 2901079 : NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
2182 : :
2183 : : /*
2184 : : * Mark the xlblock with InvalidXLogRecPtr and issue a write barrier
2185 : : * before initializing. Otherwise, the old page may be partially
2186 : : * zeroed but look valid.
2187 : : */
2188 : 2901079 : pg_atomic_write_u64(&XLogCtl->xlblocks[nextidx], InvalidXLogRecPtr);
2189 : 2901079 : pg_write_barrier();
2190 : :
2191 : : /*
2192 : : * Be sure to re-zero the buffer so that bytes beyond what we've
2193 : : * written will look like zeroes and not valid XLOG records...
2194 : : */
2195 [ + - + - : 2901079 : MemSet(NewPage, 0, XLOG_BLCKSZ);
+ - - + -
- ]
2196 : :
2197 : : /*
2198 : : * Fill the new page's header
2199 : : */
2200 : 2901079 : NewPage->xlp_magic = XLOG_PAGE_MAGIC;
2201 : :
2202 : : /* NewPage->xlp_info = 0; */ /* done by memset */
2203 : 2901079 : NewPage->xlp_tli = tli;
2204 : 2901079 : NewPage->xlp_pageaddr = NewPageBeginPtr;
2205 : :
2206 : : /* NewPage->xlp_rem_len = 0; */ /* done by memset */
2207 : :
2208 : : /*
2209 : : * If first page of an XLOG segment file, make it a long header.
2210 : : */
2211 [ + + ]: 2901079 : if ((XLogSegmentOffset(NewPage->xlp_pageaddr, wal_segment_size)) == 0)
2212 : : {
2213 : 1963 : XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
2214 : :
2215 : 1963 : NewLongPage->xlp_sysid = ControlFile->system_identifier;
2216 : 1963 : NewLongPage->xlp_seg_size = wal_segment_size;
2217 : 1963 : NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
2218 : 1963 : NewPage->xlp_info |= XLP_LONG_HEADER;
2219 : : }
2220 : :
2221 : : /*
2222 : : * Make sure the initialization of the page becomes visible to others
2223 : : * before the xlblocks update. GetXLogBuffer() reads xlblocks without
2224 : : * holding a lock.
2225 : : */
2226 : 2901079 : pg_write_barrier();
2227 : :
2228 : 2901079 : pg_atomic_write_u64(&XLogCtl->xlblocks[nextidx], NewPageEndPtr);
2229 : 2901079 : XLogCtl->InitializedUpTo = NewPageEndPtr;
2230 : :
2231 : 2901079 : npages++;
2232 : : }
2233 : 2766960 : LWLockRelease(WALBufMappingLock);
2234 : :
2235 : : #ifdef WAL_DEBUG
2236 : : if (XLOG_DEBUG && npages > 0)
2237 : : {
2238 : : elog(DEBUG1, "initialized %d pages, up to %X/%08X",
2239 : : npages, LSN_FORMAT_ARGS(NewPageEndPtr));
2240 : : }
2241 : : #endif
2242 : 2766960 : }
2243 : :
2244 : : /*
2245 : : * Calculate CheckPointSegments based on max_wal_size_mb and
2246 : : * checkpoint_completion_target.
2247 : : */
2248 : : static void
2249 : 10070 : CalculateCheckpointSegments(void)
2250 : : {
2251 : : double target;
2252 : :
2253 : : /*-------
2254 : : * Calculate the distance at which to trigger a checkpoint, to avoid
2255 : : * exceeding max_wal_size_mb. This is based on two assumptions:
2256 : : *
2257 : : * a) we keep WAL for only one checkpoint cycle (prior to PG11 we kept
2258 : : * WAL for two checkpoint cycles to allow us to recover from the
2259 : : * secondary checkpoint if the first checkpoint failed, though we
2260 : : * only did this on the primary anyway, not on standby. Keeping just
2261 : : * one checkpoint simplifies processing and reduces disk space in
2262 : : * many smaller databases.)
2263 : : * b) during checkpoint, we consume checkpoint_completion_target *
2264 : : * number of segments consumed between checkpoints.
2265 : : *-------
2266 : : */
2267 : 10070 : target = (double) ConvertToXSegs(max_wal_size_mb, wal_segment_size) /
2268 : 10070 : (1.0 + CheckPointCompletionTarget);
2269 : :
2270 : : /* round down */
2271 : 10070 : CheckPointSegments = (int) target;
2272 : :
2273 [ + + ]: 10070 : if (CheckPointSegments < 1)
2274 : 8 : CheckPointSegments = 1;
2275 : 10070 : }
2276 : :
2277 : : void
2278 : 7492 : assign_max_wal_size(int newval, void *extra)
2279 : : {
2280 : 7492 : max_wal_size_mb = newval;
2281 : 7492 : CalculateCheckpointSegments();
2282 : 7492 : }
2283 : :
2284 : : void
2285 : 1362 : assign_checkpoint_completion_target(double newval, void *extra)
2286 : : {
2287 : 1362 : CheckPointCompletionTarget = newval;
2288 : 1362 : CalculateCheckpointSegments();
2289 : 1362 : }
2290 : :
2291 : : bool
2292 : 2638 : check_wal_segment_size(int *newval, void **extra, GucSource source)
2293 : : {
2294 [ + - + - : 2638 : if (!IsValidWalSegSize(*newval))
+ - - + ]
2295 : : {
2296 : 0 : GUC_check_errdetail("The WAL segment size must be a power of two between 1 MB and 1 GB.");
2297 : 0 : return false;
2298 : : }
2299 : :
2300 : 2638 : return true;
2301 : : }
2302 : :
2303 : : /*
2304 : : * At a checkpoint, how many WAL segments to recycle as preallocated future
2305 : : * XLOG segments? Returns the highest segment that should be preallocated.
2306 : : */
2307 : : static XLogSegNo
2308 : 2027 : XLOGfileslop(XLogRecPtr lastredoptr)
2309 : : {
2310 : : XLogSegNo minSegNo;
2311 : : XLogSegNo maxSegNo;
2312 : : double distance;
2313 : : XLogSegNo recycleSegNo;
2314 : :
2315 : : /*
2316 : : * Calculate the segment numbers that min_wal_size_mb and max_wal_size_mb
2317 : : * correspond to. Always recycle enough segments to meet the minimum, and
2318 : : * remove enough segments to stay below the maximum.
2319 : : */
2320 : 2027 : minSegNo = lastredoptr / wal_segment_size +
2321 : 2027 : ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
2322 : 2027 : maxSegNo = lastredoptr / wal_segment_size +
2323 : 2027 : ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
2324 : :
2325 : : /*
2326 : : * Between those limits, recycle enough segments to get us through to the
2327 : : * estimated end of next checkpoint.
2328 : : *
2329 : : * To estimate where the next checkpoint will finish, assume that the
2330 : : * system runs steadily consuming CheckPointDistanceEstimate bytes between
2331 : : * every checkpoint.
2332 : : */
2333 : 2027 : distance = (1.0 + CheckPointCompletionTarget) * CheckPointDistanceEstimate;
2334 : : /* add 10% for good measure. */
2335 : 2027 : distance *= 1.10;
2336 : :
2337 : 2027 : recycleSegNo = (XLogSegNo) ceil(((double) lastredoptr + distance) /
2338 : : wal_segment_size);
2339 : :
2340 [ + + ]: 2027 : if (recycleSegNo < minSegNo)
2341 : 1437 : recycleSegNo = minSegNo;
2342 [ + + ]: 2027 : if (recycleSegNo > maxSegNo)
2343 : 419 : recycleSegNo = maxSegNo;
2344 : :
2345 : 2027 : return recycleSegNo;
2346 : : }
2347 : :
2348 : : /*
2349 : : * Check whether we've consumed enough xlog space that a checkpoint is needed.
2350 : : *
2351 : : * new_segno indicates a log file that has just been filled up (or read
2352 : : * during recovery). We measure the distance from RedoRecPtr to new_segno
2353 : : * and see if that exceeds CheckPointSegments.
2354 : : *
2355 : : * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
2356 : : */
2357 : : bool
2358 : 5097 : XLogCheckpointNeeded(XLogSegNo new_segno)
2359 : : {
2360 : : XLogSegNo old_segno;
2361 : :
2362 : 5097 : XLByteToSeg(RedoRecPtr, old_segno, wal_segment_size);
2363 : :
2364 [ + + ]: 5097 : if (new_segno >= old_segno + (uint64) (CheckPointSegments - 1))
2365 : 3107 : return true;
2366 : 1990 : return false;
2367 : : }
2368 : :
2369 : : /*
2370 : : * Write and/or fsync the log at least as far as WriteRqst indicates.
2371 : : *
2372 : : * If flexible == true, we don't have to write as far as WriteRqst, but
2373 : : * may stop at any convenient boundary (such as a cache or logfile boundary).
2374 : : * This option allows us to avoid uselessly issuing multiple writes when a
2375 : : * single one would do.
2376 : : *
2377 : : * Must be called with WALWriteLock held. WaitXLogInsertionsToFinish(WriteRqst)
2378 : : * must be called before grabbing the lock, to make sure the data is ready to
2379 : : * write.
2380 : : */
2381 : : static void
2382 : 2414644 : XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible)
2383 : : {
2384 : : bool ispartialpage;
2385 : : bool last_iteration;
2386 : : bool finishing_seg;
2387 : : XLogRecPtr oldFlush;
2388 : : int curridx;
2389 : : int npages;
2390 : : int startidx;
2391 : : uint32 startoffset;
2392 : :
2393 : : /* We should always be inside a critical section here */
2394 : : Assert(CritSectionCount > 0);
2395 : :
2396 : : /*
2397 : : * Update local LogwrtResult (caller probably did this already, but...)
2398 : : */
2399 : 2414644 : RefreshXLogWriteResult(LogwrtResult);
2400 : 2414644 : oldFlush = LogwrtResult.Flush;
2401 : :
2402 : : /*
2403 : : * Since successive pages in the xlog cache are consecutively allocated,
2404 : : * we can usually gather multiple pages together and issue just one
2405 : : * write() call. npages is the number of pages we have determined can be
2406 : : * written together; startidx is the cache block index of the first one,
2407 : : * and startoffset is the file offset at which it should go. The latter
2408 : : * two variables are only valid when npages > 0, but we must initialize
2409 : : * all of them to keep the compiler quiet.
2410 : : */
2411 : 2414644 : npages = 0;
2412 : 2414644 : startidx = 0;
2413 : 2414644 : startoffset = 0;
2414 : :
2415 : : /*
2416 : : * Within the loop, curridx is the cache block index of the page to
2417 : : * consider writing. Begin at the buffer containing the next unwritten
2418 : : * page, or last partially written page.
2419 : : */
2420 : 2414644 : curridx = XLogRecPtrToBufIdx(LogwrtResult.Write);
2421 : :
2422 [ + + ]: 5265335 : while (LogwrtResult.Write < WriteRqst.Write)
2423 : : {
2424 : : /*
2425 : : * Make sure we're not ahead of the insert process. This could happen
2426 : : * if we're passed a bogus WriteRqst.Write that is past the end of the
2427 : : * last page that's been initialized by AdvanceXLInsertBuffer.
2428 : : */
2429 : 3012592 : XLogRecPtr EndPtr = pg_atomic_read_u64(&XLogCtl->xlblocks[curridx]);
2430 : :
2431 [ - + ]: 3012592 : if (LogwrtResult.Write >= EndPtr)
2432 [ # # ]: 0 : elog(PANIC, "xlog write request %X/%08X is past end of log %X/%08X",
2433 : : LSN_FORMAT_ARGS(LogwrtResult.Write),
2434 : : LSN_FORMAT_ARGS(EndPtr));
2435 : :
2436 : : /* Advance LogwrtResult.Write to end of current buffer page */
2437 : 3012592 : LogwrtResult.Write = EndPtr;
2438 : 3012592 : ispartialpage = WriteRqst.Write < LogwrtResult.Write;
2439 : :
2440 [ + + ]: 3012592 : if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
2441 : : wal_segment_size))
2442 : : {
2443 : : /*
2444 : : * Switch to new logfile segment. We cannot have any pending
2445 : : * pages here (since we dump what we have at segment end).
2446 : : */
2447 : : Assert(npages == 0);
2448 [ + + ]: 15233 : if (openLogFile >= 0)
2449 : 6504 : XLogFileClose();
2450 : 15233 : XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2451 : : wal_segment_size);
2452 : 15233 : openLogTLI = tli;
2453 : :
2454 : : /* create/use new log file */
2455 : 15233 : openLogFile = XLogFileInit(openLogSegNo, tli);
2456 : 15233 : ReserveExternalFD();
2457 : : }
2458 : :
2459 : : /* Make sure we have the current logfile open */
2460 [ - + ]: 3012592 : if (openLogFile < 0)
2461 : : {
2462 : 0 : XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2463 : : wal_segment_size);
2464 : 0 : openLogTLI = tli;
2465 : 0 : openLogFile = XLogFileOpen(openLogSegNo, tli);
2466 : 0 : ReserveExternalFD();
2467 : : }
2468 : :
2469 : : /* Add current page to the set of pending pages-to-dump */
2470 [ + + ]: 3012592 : if (npages == 0)
2471 : : {
2472 : : /* first of group */
2473 : 2432087 : startidx = curridx;
2474 : 2432087 : startoffset = XLogSegmentOffset(LogwrtResult.Write - XLOG_BLCKSZ,
2475 : : wal_segment_size);
2476 : : }
2477 : 3012592 : npages++;
2478 : :
2479 : : /*
2480 : : * Dump the set if this will be the last loop iteration, or if we are
2481 : : * at the last page of the cache area (since the next page won't be
2482 : : * contiguous in memory), or if we are at the end of the logfile
2483 : : * segment.
2484 : : */
2485 : 3012592 : last_iteration = WriteRqst.Write <= LogwrtResult.Write;
2486 : :
2487 [ + + ]: 5867425 : finishing_seg = !ispartialpage &&
2488 [ + + ]: 2854833 : (startoffset + npages * XLOG_BLCKSZ) >= wal_segment_size;
2489 : :
2490 [ + + ]: 3012592 : if (last_iteration ||
2491 [ + + - + ]: 599361 : curridx == XLogCtl->XLogCacheBlck ||
2492 : : finishing_seg)
2493 : : {
2494 : : char *from;
2495 : : Size nbytes;
2496 : : Size nleft;
2497 : : ssize_t written;
2498 : : instr_time start;
2499 : :
2500 : : /* OK to write the page(s) */
2501 : 2432087 : from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
2502 : 2432087 : nbytes = npages * (Size) XLOG_BLCKSZ;
2503 : 2432087 : nleft = nbytes;
2504 : : do
2505 : : {
2506 : 2432087 : errno = 0;
2507 : :
2508 : : /*
2509 : : * Measure I/O timing to write WAL data, for pg_stat_io.
2510 : : */
2511 : 2432087 : start = pgstat_prepare_io_time(track_wal_io_timing);
2512 : :
2513 : 2432087 : pgstat_report_wait_start(WAIT_EVENT_WAL_WRITE);
2514 : 2432087 : written = pg_pwrite(openLogFile, from, nleft, startoffset);
2515 : 2432087 : pgstat_report_wait_end();
2516 : :
2517 [ - + ]: 2432087 : if (written <= 0)
2518 : : {
2519 : : char xlogfname[MAXFNAMELEN];
2520 : : int save_errno;
2521 : :
2522 [ # # ]: 0 : if (errno == EINTR)
2523 : 0 : continue;
2524 : :
2525 : 0 : save_errno = errno;
2526 : 0 : XLogFileName(xlogfname, tli, openLogSegNo,
2527 : : wal_segment_size);
2528 : 0 : errno = save_errno;
2529 [ # # ]: 0 : ereport(PANIC,
2530 : : (errcode_for_file_access(),
2531 : : errmsg("could not write to log file \"%s\" at offset %u, length %zu: %m",
2532 : : xlogfname, startoffset, nleft)));
2533 : : }
2534 : :
2535 : 2432087 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL,
2536 : : IOOP_WRITE, start, 1, written);
2537 : 2432087 : nleft -= written;
2538 : 2432087 : from += written;
2539 : 2432087 : startoffset += written;
2540 [ - + ]: 2432087 : } while (nleft > 0);
2541 : :
2542 : 2432087 : npages = 0;
2543 : :
2544 : : /*
2545 : : * If we just wrote the whole last page of a logfile segment,
2546 : : * fsync the segment immediately. This avoids having to go back
2547 : : * and re-open prior segments when an fsync request comes along
2548 : : * later. Doing it here ensures that one and only one backend will
2549 : : * perform this fsync.
2550 : : *
2551 : : * This is also the right place to notify the Archiver that the
2552 : : * segment is ready to copy to archival storage, and to update the
2553 : : * timer for archive_timeout, and to signal for a checkpoint if
2554 : : * too many logfile segments have been used since the last
2555 : : * checkpoint.
2556 : : */
2557 [ + + ]: 2432087 : if (finishing_seg)
2558 : : {
2559 : 2106 : issue_xlog_fsync(openLogFile, openLogSegNo, tli);
2560 : :
2561 : : /* signal that we need to wakeup walsenders later */
2562 : 2106 : WalSndWakeupRequest();
2563 : :
2564 : 2106 : LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
2565 : :
2566 [ + + ]: 2106 : if (XLogArchivingActive())
2567 : 422 : XLogArchiveNotifySeg(openLogSegNo, tli);
2568 : :
2569 : 2106 : XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
2570 : 2106 : XLogCtl->lastSegSwitchLSN = LogwrtResult.Flush;
2571 : :
2572 : : /*
2573 : : * Request a checkpoint if we've consumed too much xlog since
2574 : : * the last one. For speed, we first check using the local
2575 : : * copy of RedoRecPtr, which might be out of date; if it looks
2576 : : * like a checkpoint is needed, forcibly update RedoRecPtr and
2577 : : * recheck.
2578 : : */
2579 [ + + + + ]: 2106 : if (IsUnderPostmaster && XLogCheckpointNeeded(openLogSegNo))
2580 : : {
2581 : 277 : (void) GetRedoRecPtr();
2582 [ + + ]: 277 : if (XLogCheckpointNeeded(openLogSegNo))
2583 : 215 : RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
2584 : : }
2585 : : }
2586 : : }
2587 : :
2588 [ + + ]: 3012592 : if (ispartialpage)
2589 : : {
2590 : : /* Only asked to write a partial page */
2591 : 157759 : LogwrtResult.Write = WriteRqst.Write;
2592 : 157759 : break;
2593 : : }
2594 [ + + ]: 2854833 : curridx = NextBufIdx(curridx);
2595 : :
2596 : : /* If flexible, break out of loop as soon as we wrote something */
2597 [ + + + + ]: 2854833 : if (flexible && npages == 0)
2598 : 4142 : break;
2599 : : }
2600 : :
2601 : : Assert(npages == 0);
2602 : :
2603 : : /*
2604 : : * If asked to flush, do so
2605 : : */
2606 [ + + ]: 2414644 : if (LogwrtResult.Flush < WriteRqst.Flush &&
2607 [ + + ]: 165086 : LogwrtResult.Flush < LogwrtResult.Write)
2608 : : {
2609 : : /*
2610 : : * Could get here without iterating above loop, in which case we might
2611 : : * have no open file or the wrong one. However, we do not need to
2612 : : * fsync more than one file.
2613 : : */
2614 [ + - ]: 165006 : if (wal_sync_method != WAL_SYNC_METHOD_OPEN &&
2615 [ + - ]: 165006 : wal_sync_method != WAL_SYNC_METHOD_OPEN_DSYNC)
2616 : : {
2617 [ + + ]: 165006 : if (openLogFile >= 0 &&
2618 [ + + ]: 164995 : !XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
2619 : : wal_segment_size))
2620 : 91 : XLogFileClose();
2621 [ + + ]: 165006 : if (openLogFile < 0)
2622 : : {
2623 : 102 : XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2624 : : wal_segment_size);
2625 : 102 : openLogTLI = tli;
2626 : 102 : openLogFile = XLogFileOpen(openLogSegNo, tli);
2627 : 102 : ReserveExternalFD();
2628 : : }
2629 : :
2630 : 165006 : issue_xlog_fsync(openLogFile, openLogSegNo, tli);
2631 : : }
2632 : :
2633 : : /* signal that we need to wakeup walsenders later */
2634 : 165006 : WalSndWakeupRequest();
2635 : :
2636 : 165006 : LogwrtResult.Flush = LogwrtResult.Write;
2637 : : }
2638 : :
2639 : : /*
2640 : : * Update shared-memory status
2641 : : *
2642 : : * We make sure that the shared 'request' values do not fall behind the
2643 : : * 'result' values. This is not absolutely essential, but it saves some
2644 : : * code in a couple of places.
2645 : : */
2646 : 2414644 : SpinLockAcquire(&XLogCtl->info_lck);
2647 [ + + ]: 2414644 : if (XLogCtl->LogwrtRqst.Write < LogwrtResult.Write)
2648 : 145214 : XLogCtl->LogwrtRqst.Write = LogwrtResult.Write;
2649 [ + + ]: 2414644 : if (XLogCtl->LogwrtRqst.Flush < LogwrtResult.Flush)
2650 : 166661 : XLogCtl->LogwrtRqst.Flush = LogwrtResult.Flush;
2651 : 2414644 : SpinLockRelease(&XLogCtl->info_lck);
2652 : :
2653 : : /*
2654 : : * We write Write first, bar, then Flush. When reading, the opposite must
2655 : : * be done (with a matching barrier in between), so that we always see a
2656 : : * Flush value that trails behind the Write value seen.
2657 : : */
2658 : 2414644 : pg_atomic_write_u64(&XLogCtl->logWriteResult, LogwrtResult.Write);
2659 : 2414644 : pg_write_barrier();
2660 : 2414644 : pg_atomic_write_u64(&XLogCtl->logFlushResult, LogwrtResult.Flush);
2661 : :
2662 : : /* Defer notification until the caller has released its WAL locks. */
2663 [ + + ]: 2414644 : if (LogwrtResult.Flush > oldFlush)
2664 : 166661 : primaryFlushWakeupPending = true;
2665 : :
2666 : : #ifdef USE_ASSERT_CHECKING
2667 : : {
2668 : : XLogRecPtr Flush;
2669 : : XLogRecPtr Write;
2670 : : XLogRecPtr Insert;
2671 : :
2672 : : Flush = pg_atomic_read_u64(&XLogCtl->logFlushResult);
2673 : : pg_read_barrier();
2674 : : Write = pg_atomic_read_u64(&XLogCtl->logWriteResult);
2675 : : pg_read_barrier();
2676 : : Insert = pg_atomic_read_u64(&XLogCtl->logInsertResult);
2677 : :
2678 : : /* WAL written to disk is always ahead of WAL flushed */
2679 : : Assert(Write >= Flush);
2680 : :
2681 : : /* WAL inserted to buffers is always ahead of WAL written */
2682 : : Assert(Insert >= Write);
2683 : : }
2684 : : #endif
2685 : 2414644 : }
2686 : :
2687 : : /*
2688 : : * Record the LSN for an asynchronous transaction commit/abort
2689 : : * and nudge the WALWriter if there is work for it to do.
2690 : : * (This should not be called for synchronous commits.)
2691 : : */
2692 : : void
2693 : 63682 : XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
2694 : : {
2695 : 63682 : XLogRecPtr WriteRqstPtr = asyncXactLSN;
2696 : : bool sleeping;
2697 : 63682 : bool wakeup = false;
2698 : : XLogRecPtr prevAsyncXactLSN;
2699 : :
2700 : 63682 : SpinLockAcquire(&XLogCtl->info_lck);
2701 : 63682 : sleeping = XLogCtl->WalWriterSleeping;
2702 : 63682 : prevAsyncXactLSN = XLogCtl->asyncXactLSN;
2703 [ + + ]: 63682 : if (XLogCtl->asyncXactLSN < asyncXactLSN)
2704 : 63125 : XLogCtl->asyncXactLSN = asyncXactLSN;
2705 : 63682 : SpinLockRelease(&XLogCtl->info_lck);
2706 : :
2707 : : /*
2708 : : * If somebody else already called this function with a more aggressive
2709 : : * LSN, they will have done what we needed (and perhaps more).
2710 : : */
2711 [ + + ]: 63682 : if (asyncXactLSN <= prevAsyncXactLSN)
2712 : 557 : return;
2713 : :
2714 : : /*
2715 : : * If the WALWriter is sleeping, kick it to make it come out of low-power
2716 : : * mode, so that this async commit will reach disk within the expected
2717 : : * amount of time. Otherwise, determine whether it has enough WAL
2718 : : * available to flush, the same way that XLogBackgroundFlush() does.
2719 : : */
2720 [ + + ]: 63125 : if (sleeping)
2721 : 42 : wakeup = true;
2722 : : else
2723 : : {
2724 : : int flushblocks;
2725 : :
2726 : 63083 : RefreshXLogWriteResult(LogwrtResult);
2727 : :
2728 : 63083 : flushblocks =
2729 : 63083 : WriteRqstPtr / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
2730 : :
2731 [ + - + + ]: 63083 : if (WalWriterFlushAfter == 0 || flushblocks >= WalWriterFlushAfter)
2732 : 5720 : wakeup = true;
2733 : : }
2734 : :
2735 [ + + ]: 63125 : if (wakeup)
2736 : : {
2737 : 5762 : ProcNumber walwriterProc = pg_atomic_read_u32(&ProcGlobal->walwriterProc);
2738 : :
2739 [ + + ]: 5762 : if (walwriterProc != INVALID_PROC_NUMBER)
2740 : 1758 : SetLatch(&GetPGProcByNumber(walwriterProc)->procLatch);
2741 : : }
2742 : : }
2743 : :
2744 : : /*
2745 : : * Record the LSN up to which we can remove WAL because it's not required by
2746 : : * any replication slot.
2747 : : */
2748 : : void
2749 : 43523 : XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
2750 : : {
2751 : 43523 : SpinLockAcquire(&XLogCtl->info_lck);
2752 : 43523 : XLogCtl->replicationSlotMinLSN = lsn;
2753 : 43523 : SpinLockRelease(&XLogCtl->info_lck);
2754 : 43523 : }
2755 : :
2756 : :
2757 : : /*
2758 : : * Return the oldest LSN we must retain to satisfy the needs of some
2759 : : * replication slot.
2760 : : */
2761 : : XLogRecPtr
2762 : 2655 : XLogGetReplicationSlotMinimumLSN(void)
2763 : : {
2764 : : XLogRecPtr retval;
2765 : :
2766 : 2655 : SpinLockAcquire(&XLogCtl->info_lck);
2767 : 2655 : retval = XLogCtl->replicationSlotMinLSN;
2768 : 2655 : SpinLockRelease(&XLogCtl->info_lck);
2769 : :
2770 : 2655 : return retval;
2771 : : }
2772 : :
2773 : : /*
2774 : : * Advance minRecoveryPoint in control file.
2775 : : *
2776 : : * If we crash during recovery, we must reach this point again before the
2777 : : * database is consistent.
2778 : : *
2779 : : * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
2780 : : * is only updated if it's not already greater than or equal to 'lsn'.
2781 : : */
2782 : : static void
2783 : 122711 : UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
2784 : : {
2785 : : /* Quick check using our local copy of the variable */
2786 [ + + + + : 122711 : if (!updateMinRecoveryPoint || (!force && lsn <= LocalMinRecoveryPoint))
+ + ]
2787 : 115365 : return;
2788 : :
2789 : : /*
2790 : : * An invalid minRecoveryPoint means that we need to recover all the WAL,
2791 : : * i.e., we're doing crash recovery. We never modify the control file's
2792 : : * value in that case, so we can short-circuit future checks here too. The
2793 : : * local values of minRecoveryPoint and minRecoveryPointTLI should not be
2794 : : * updated until crash recovery finishes. We only do this for the startup
2795 : : * process as it should not update its own reference of minRecoveryPoint
2796 : : * until it has finished crash recovery to make sure that all WAL
2797 : : * available is replayed in this case. This also saves from extra locks
2798 : : * taken on the control file from the startup process.
2799 : : */
2800 [ + + + + ]: 7346 : if (!XLogRecPtrIsValid(LocalMinRecoveryPoint) && InRecovery)
2801 : : {
2802 : 32 : updateMinRecoveryPoint = false;
2803 : 32 : return;
2804 : : }
2805 : :
2806 : 7314 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2807 : :
2808 : : /* update local copy */
2809 : 7314 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
2810 : :
2811 [ + + ]: 7314 : if (!XLogRecPtrIsValid(LocalMinRecoveryPoint))
2812 : 3 : updateMinRecoveryPoint = false;
2813 [ + + + + ]: 7311 : else if (force || LocalMinRecoveryPoint < lsn)
2814 : : {
2815 : : XLogRecPtr newMinRecoveryPoint;
2816 : : TimeLineID newMinRecoveryPointTLI;
2817 : :
2818 : : /*
2819 : : * To avoid having to update the control file too often, we update it
2820 : : * all the way to the last record being replayed, even though 'lsn'
2821 : : * would suffice for correctness. This also allows the 'force' case
2822 : : * to not need a valid 'lsn' value.
2823 : : *
2824 : : * Another important reason for doing it this way is that the passed
2825 : : * 'lsn' value could be bogus, i.e., past the end of available WAL, if
2826 : : * the caller got it from a corrupted heap page. Accepting such a
2827 : : * value as the min recovery point would prevent us from coming up at
2828 : : * all. Instead, we just log a warning and continue with recovery.
2829 : : * (See also the comments about corrupt LSNs in XLogFlush.)
2830 : : */
2831 : 5846 : newMinRecoveryPoint = GetCurrentReplayRecPtr(&newMinRecoveryPointTLI);
2832 [ + + - + ]: 5846 : if (!force && newMinRecoveryPoint < lsn)
2833 [ # # ]: 0 : elog(WARNING,
2834 : : "xlog min recovery request %X/%08X is past current point %X/%08X",
2835 : : LSN_FORMAT_ARGS(lsn), LSN_FORMAT_ARGS(newMinRecoveryPoint));
2836 : :
2837 : : /* update control file */
2838 [ + + ]: 5846 : if (ControlFile->minRecoveryPoint < newMinRecoveryPoint)
2839 : : {
2840 : 5487 : ControlFile->minRecoveryPoint = newMinRecoveryPoint;
2841 : 5487 : ControlFile->minRecoveryPointTLI = newMinRecoveryPointTLI;
2842 : 5487 : UpdateControlFile();
2843 : 5487 : LocalMinRecoveryPoint = newMinRecoveryPoint;
2844 : :
2845 [ + + ]: 5487 : ereport(DEBUG2,
2846 : : errmsg_internal("updated min recovery point to %X/%08X on timeline %u",
2847 : : LSN_FORMAT_ARGS(newMinRecoveryPoint),
2848 : : newMinRecoveryPointTLI));
2849 : : }
2850 : : }
2851 : 7314 : LWLockRelease(ControlFileLock);
2852 : : }
2853 : :
2854 : : /*
2855 : : * Ensure that all XLOG data through the given position is flushed to disk.
2856 : : *
2857 : : * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
2858 : : * already held, and we try to avoid acquiring it if possible.
2859 : : */
2860 : : void
2861 : 868227 : XLogFlush(XLogRecPtr record)
2862 : : {
2863 : : XLogRecPtr WriteRqstPtr;
2864 : : XLogwrtRqst WriteRqst;
2865 : 868227 : TimeLineID insertTLI = XLogCtl->InsertTimeLineID;
2866 : :
2867 : : /*
2868 : : * During REDO, we are reading not writing WAL. Therefore, instead of
2869 : : * trying to flush the WAL, we should update minRecoveryPoint instead. We
2870 : : * test XLogInsertAllowed(), not InRecovery, because we need checkpointer
2871 : : * to act this way too, and because when it tries to write the
2872 : : * end-of-recovery checkpoint, it should indeed flush.
2873 : : */
2874 [ + + ]: 868227 : if (!XLogInsertAllowed())
2875 : : {
2876 : 122232 : UpdateMinRecoveryPoint(record, false);
2877 : 693885 : return;
2878 : : }
2879 : :
2880 : : /* Quick exit if already known flushed */
2881 [ + + ]: 745995 : if (record <= LogwrtResult.Flush)
2882 : 571653 : return;
2883 : :
2884 : : #ifdef WAL_DEBUG
2885 : : if (XLOG_DEBUG)
2886 : : elog(LOG, "xlog flush request %X/%08X; write %X/%08X; flush %X/%08X",
2887 : : LSN_FORMAT_ARGS(record),
2888 : : LSN_FORMAT_ARGS(LogwrtResult.Write),
2889 : : LSN_FORMAT_ARGS(LogwrtResult.Flush));
2890 : : #endif
2891 : :
2892 : 174342 : START_CRIT_SECTION();
2893 : :
2894 : : /*
2895 : : * Since fsync is usually a horribly expensive operation, we try to
2896 : : * piggyback as much data as we can on each fsync: if we see any more data
2897 : : * entered into the xlog buffer, we'll write and fsync that too, so that
2898 : : * the final value of LogwrtResult.Flush is as large as possible. This
2899 : : * gives us some chance of avoiding another fsync immediately after.
2900 : : */
2901 : :
2902 : : /* initialize to given target; may increase below */
2903 : 174342 : WriteRqstPtr = record;
2904 : :
2905 : : /*
2906 : : * Now wait until we get the write lock, or someone else does the flush
2907 : : * for us.
2908 : : */
2909 : : for (;;)
2910 : 2823 : {
2911 : : XLogRecPtr insertpos;
2912 : :
2913 : : /* done already? */
2914 : 177165 : RefreshXLogWriteResult(LogwrtResult);
2915 [ + + ]: 177165 : if (record <= LogwrtResult.Flush)
2916 : 11624 : break;
2917 : :
2918 : : /*
2919 : : * Before actually performing the write, wait for all in-flight
2920 : : * insertions to the pages we're about to write to finish.
2921 : : */
2922 : 165541 : SpinLockAcquire(&XLogCtl->info_lck);
2923 [ + + ]: 165541 : if (WriteRqstPtr < XLogCtl->LogwrtRqst.Write)
2924 : 10412 : WriteRqstPtr = XLogCtl->LogwrtRqst.Write;
2925 : 165541 : SpinLockRelease(&XLogCtl->info_lck);
2926 : 165541 : insertpos = WaitXLogInsertionsToFinish(WriteRqstPtr);
2927 : :
2928 : : /*
2929 : : * Try to get the write lock. If we can't get it immediately, wait
2930 : : * until it's released, and recheck if we still need to do the flush
2931 : : * or if the backend that held the lock did it for us already. This
2932 : : * helps to maintain a good rate of group committing when the system
2933 : : * is bottlenecked by the speed of fsyncing.
2934 : : */
2935 [ + + ]: 165541 : if (!LWLockAcquireOrWait(WALWriteLock, LW_EXCLUSIVE))
2936 : : {
2937 : : /*
2938 : : * The lock is now free, but we didn't acquire it yet. Before we
2939 : : * do, loop back to check if someone else flushed the record for
2940 : : * us already.
2941 : : */
2942 : 2823 : continue;
2943 : : }
2944 : :
2945 : : /* Got the lock; recheck whether request is satisfied */
2946 : 162718 : RefreshXLogWriteResult(LogwrtResult);
2947 [ + + ]: 162718 : if (record <= LogwrtResult.Flush)
2948 : : {
2949 : 1807 : LWLockRelease(WALWriteLock);
2950 : 1807 : break;
2951 : : }
2952 : :
2953 : : /*
2954 : : * Sleep before flush! By adding a delay here, we may give further
2955 : : * backends the opportunity to join the backlog of group commit
2956 : : * followers; this can significantly improve transaction throughput,
2957 : : * at the risk of increasing transaction latency.
2958 : : *
2959 : : * We do not sleep if enableFsync is not turned on, nor if there are
2960 : : * fewer than CommitSiblings other backends with active transactions.
2961 : : */
2962 [ - + - - : 160911 : if (CommitDelay > 0 && enableFsync &&
- - ]
2963 : 0 : MinimumActiveBackends(CommitSiblings))
2964 : : {
2965 : 0 : pgstat_report_wait_start(WAIT_EVENT_COMMIT_DELAY);
2966 : 0 : pg_usleep(CommitDelay);
2967 : 0 : pgstat_report_wait_end();
2968 : :
2969 : : /*
2970 : : * Re-check how far we can now flush the WAL. It's generally not
2971 : : * safe to call WaitXLogInsertionsToFinish while holding
2972 : : * WALWriteLock, because an in-progress insertion might need to
2973 : : * also grab WALWriteLock to make progress. But we know that all
2974 : : * the insertions up to insertpos have already finished, because
2975 : : * that's what the earlier WaitXLogInsertionsToFinish() returned.
2976 : : * We're only calling it again to allow insertpos to be moved
2977 : : * further forward, not to actually wait for anyone.
2978 : : */
2979 : 0 : insertpos = WaitXLogInsertionsToFinish(insertpos);
2980 : : }
2981 : :
2982 : : /* try to write/flush later additions to XLOG as well */
2983 : 160911 : WriteRqst.Write = insertpos;
2984 : 160911 : WriteRqst.Flush = insertpos;
2985 : :
2986 : 160911 : XLogWrite(WriteRqst, insertTLI, false);
2987 : :
2988 : 160911 : LWLockRelease(WALWriteLock);
2989 : : /* done */
2990 : 160911 : break;
2991 : : }
2992 : :
2993 : 174342 : END_CRIT_SECTION();
2994 : :
2995 : : /* wake up walsenders now that we've released heavily contended locks */
2996 : 174342 : WalSndWakeupProcessRequests(true, !RecoveryInProgress());
2997 : :
2998 : : /*
2999 : : * Wake up processes waiting for primary flush LSN to reach current flush
3000 : : * position.
3001 : : */
3002 : 174342 : primaryFlushWakeupPending = false;
3003 : 174342 : WaitLSNWakeup(WAIT_LSN_TYPE_PRIMARY_FLUSH, LogwrtResult.Flush);
3004 : :
3005 : : /*
3006 : : * If we still haven't flushed to the request point then we have a
3007 : : * problem; most likely, the requested flush point is past end of XLOG.
3008 : : * This has been seen to occur when a disk page has a corrupted LSN.
3009 : : *
3010 : : * Formerly we treated this as a PANIC condition, but that hurts the
3011 : : * system's robustness rather than helping it: we do not want to take down
3012 : : * the whole system due to corruption on one data page. In particular, if
3013 : : * the bad page is encountered again during recovery then we would be
3014 : : * unable to restart the database at all! (This scenario actually
3015 : : * happened in the field several times with 7.1 releases.) As of 8.4, bad
3016 : : * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem;
3017 : : * the only time we can reach here during recovery is while flushing the
3018 : : * end-of-recovery checkpoint record, and we don't expect that to have a
3019 : : * bad LSN.
3020 : : *
3021 : : * Note that for calls from xact.c, the ERROR will be promoted to PANIC
3022 : : * since xact.c calls this routine inside a critical section. However,
3023 : : * calls from bufmgr.c are not within critical sections and so we will not
3024 : : * force a restart for a bad LSN on a data page.
3025 : : */
3026 [ - + ]: 174342 : if (LogwrtResult.Flush < record)
3027 [ # # ]: 0 : elog(ERROR,
3028 : : "xlog flush request %X/%08X is not satisfied --- flushed only to %X/%08X",
3029 : : LSN_FORMAT_ARGS(record),
3030 : : LSN_FORMAT_ARGS(LogwrtResult.Flush));
3031 : :
3032 : : /*
3033 : : * Cross-check XLogNeedsFlush(). Some of the checks of XLogFlush() and
3034 : : * XLogNeedsFlush() are duplicated, and this assertion ensures that these
3035 : : * remain consistent.
3036 : : */
3037 : : Assert(!XLogNeedsFlush(record));
3038 : : }
3039 : :
3040 : : /*
3041 : : * Write & flush xlog, but without specifying exactly where to.
3042 : : *
3043 : : * We normally write only completed blocks; but if there is nothing to do on
3044 : : * that basis, we check for unwritten async commits in the current incomplete
3045 : : * block, and write through the latest one of those. Thus, if async commits
3046 : : * are not being used, we will write complete blocks only.
3047 : : *
3048 : : * If, based on the above, there's anything to write we do so immediately. But
3049 : : * to avoid calling fsync, fdatasync et. al. at a rate that'd impact
3050 : : * concurrent IO, we only flush WAL every wal_writer_delay ms, or if there's
3051 : : * more than wal_writer_flush_after unflushed blocks.
3052 : : *
3053 : : * We can guarantee that async commits reach disk after at most three
3054 : : * wal_writer_delay cycles. (When flushing complete blocks, we allow XLogWrite
3055 : : * to write "flexibly", meaning it can stop at the end of the buffer ring;
3056 : : * this makes a difference only with very high load or long wal_writer_delay,
3057 : : * but imposes one extra cycle for the worst case for async commits.)
3058 : : *
3059 : : * This routine is invoked periodically by the background walwriter process.
3060 : : *
3061 : : * Returns true if there was any work to do, even if we skipped flushing due
3062 : : * to wal_writer_delay/wal_writer_flush_after.
3063 : : */
3064 : : bool
3065 : 16671 : XLogBackgroundFlush(void)
3066 : : {
3067 : : XLogwrtRqst WriteRqst;
3068 : 16671 : bool flexible = true;
3069 : : static TimestampTz lastflush;
3070 : : TimestampTz now;
3071 : : int flushblocks;
3072 : : TimeLineID insertTLI;
3073 : :
3074 : : /* XLOG doesn't need flushing during recovery */
3075 [ - + ]: 16671 : if (RecoveryInProgress())
3076 : 0 : return false;
3077 : :
3078 : : /*
3079 : : * Since we're not in recovery, InsertTimeLineID is set and can't change,
3080 : : * so we can read it without a lock.
3081 : : */
3082 : 16671 : insertTLI = XLogCtl->InsertTimeLineID;
3083 : :
3084 : : /* read updated LogwrtRqst */
3085 : 16671 : SpinLockAcquire(&XLogCtl->info_lck);
3086 : 16671 : WriteRqst = XLogCtl->LogwrtRqst;
3087 : 16671 : SpinLockRelease(&XLogCtl->info_lck);
3088 : :
3089 : : /* back off to last completed page boundary */
3090 : 16671 : WriteRqst.Write -= WriteRqst.Write % XLOG_BLCKSZ;
3091 : :
3092 : : /* if we have already flushed that far, consider async commit records */
3093 : 16671 : RefreshXLogWriteResult(LogwrtResult);
3094 [ + + ]: 16671 : if (WriteRqst.Write <= LogwrtResult.Flush)
3095 : : {
3096 : 12399 : SpinLockAcquire(&XLogCtl->info_lck);
3097 : 12399 : WriteRqst.Write = XLogCtl->asyncXactLSN;
3098 : 12399 : SpinLockRelease(&XLogCtl->info_lck);
3099 : 12399 : flexible = false; /* ensure it all gets written */
3100 : : }
3101 : :
3102 : : /*
3103 : : * If already known flushed, we're done. Just need to check if we are
3104 : : * holding an open file handle to a logfile that's no longer in use,
3105 : : * preventing the file from being deleted.
3106 : : */
3107 [ + + ]: 16671 : if (WriteRqst.Write <= LogwrtResult.Flush)
3108 : : {
3109 [ + + ]: 11524 : if (openLogFile >= 0)
3110 : : {
3111 [ + + ]: 7266 : if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
3112 : : wal_segment_size))
3113 : : {
3114 : 206 : XLogFileClose();
3115 : : }
3116 : : }
3117 : 11524 : return false;
3118 : : }
3119 : :
3120 : : /*
3121 : : * Determine how far to flush WAL, based on the wal_writer_delay and
3122 : : * wal_writer_flush_after GUCs.
3123 : : *
3124 : : * Note that XLogSetAsyncXactLSN() performs similar calculation based on
3125 : : * wal_writer_flush_after, to decide when to wake us up. Make sure the
3126 : : * logic is the same in both places if you change this.
3127 : : */
3128 : 5147 : now = GetCurrentTimestamp();
3129 : 5147 : flushblocks =
3130 : 5147 : WriteRqst.Write / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
3131 : :
3132 [ + - + + ]: 5147 : if (WalWriterFlushAfter == 0 || lastflush == 0)
3133 : : {
3134 : : /* first call, or block based limits disabled */
3135 : 315 : WriteRqst.Flush = WriteRqst.Write;
3136 : 315 : lastflush = now;
3137 : : }
3138 [ + + ]: 4832 : else if (TimestampDifferenceExceeds(lastflush, now, WalWriterDelay))
3139 : : {
3140 : : /*
3141 : : * Flush the writes at least every WalWriterDelay ms. This is
3142 : : * important to bound the amount of time it takes for an asynchronous
3143 : : * commit to hit disk.
3144 : : */
3145 : 4418 : WriteRqst.Flush = WriteRqst.Write;
3146 : 4418 : lastflush = now;
3147 : : }
3148 [ + + ]: 414 : else if (flushblocks >= WalWriterFlushAfter)
3149 : : {
3150 : : /* exceeded wal_writer_flush_after blocks, flush */
3151 : 323 : WriteRqst.Flush = WriteRqst.Write;
3152 : 323 : lastflush = now;
3153 : : }
3154 : : else
3155 : : {
3156 : : /* no flushing, this time round */
3157 : 91 : WriteRqst.Flush = InvalidXLogRecPtr;
3158 : : }
3159 : :
3160 : : #ifdef WAL_DEBUG
3161 : : if (XLOG_DEBUG)
3162 : : elog(LOG, "xlog bg flush request write %X/%08X; flush: %X/%08X, current is write %X/%08X; flush %X/%08X",
3163 : : LSN_FORMAT_ARGS(WriteRqst.Write),
3164 : : LSN_FORMAT_ARGS(WriteRqst.Flush),
3165 : : LSN_FORMAT_ARGS(LogwrtResult.Write),
3166 : : LSN_FORMAT_ARGS(LogwrtResult.Flush));
3167 : : #endif
3168 : :
3169 : 5147 : START_CRIT_SECTION();
3170 : :
3171 : : /* now wait for any in-progress insertions to finish and get write lock */
3172 : 5147 : WaitXLogInsertionsToFinish(WriteRqst.Write);
3173 : 5147 : LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
3174 : 5147 : RefreshXLogWriteResult(LogwrtResult);
3175 [ + + ]: 5147 : if (WriteRqst.Write > LogwrtResult.Write ||
3176 [ + + ]: 136 : WriteRqst.Flush > LogwrtResult.Flush)
3177 : : {
3178 : 5064 : XLogWrite(WriteRqst, insertTLI, flexible);
3179 : : }
3180 : 5147 : LWLockRelease(WALWriteLock);
3181 : :
3182 : 5147 : END_CRIT_SECTION();
3183 : :
3184 : : /* wake up walsenders now that we've released heavily contended locks */
3185 : 5147 : WalSndWakeupProcessRequests(true, !RecoveryInProgress());
3186 : :
3187 : : /*
3188 : : * Wake up processes waiting for primary flush LSN to reach current flush
3189 : : * position.
3190 : : */
3191 : 5147 : primaryFlushWakeupPending = false;
3192 : 5147 : WaitLSNWakeup(WAIT_LSN_TYPE_PRIMARY_FLUSH, LogwrtResult.Flush);
3193 : :
3194 : : /*
3195 : : * Great, done. To take some work off the critical path, try to initialize
3196 : : * as many of the no-longer-needed WAL buffers for future use as we can.
3197 : : */
3198 : 5147 : AdvanceXLInsertBuffer(InvalidXLogRecPtr, insertTLI, true);
3199 : :
3200 : : /*
3201 : : * If we determined that we need to write data, but somebody else
3202 : : * wrote/flushed already, it should be considered as being active, to
3203 : : * avoid hibernating too early.
3204 : : */
3205 : 5147 : return true;
3206 : : }
3207 : :
3208 : : /*
3209 : : * Test whether XLOG data has been flushed up to (at least) the given
3210 : : * position, or whether the minimum recovery point has been updated past
3211 : : * the given position.
3212 : : *
3213 : : * Returns true if a flush is still needed, or if the minimum recovery point
3214 : : * must be updated.
3215 : : *
3216 : : * It is possible that someone else is already in the process of flushing
3217 : : * that far, or has updated the minimum recovery point up to the given
3218 : : * position.
3219 : : */
3220 : : bool
3221 : 16791118 : XLogNeedsFlush(XLogRecPtr record)
3222 : : {
3223 : : /*
3224 : : * During recovery, we don't flush WAL but update minRecoveryPoint
3225 : : * instead. So "needs flush" is taken to mean whether minRecoveryPoint
3226 : : * would need to be updated.
3227 : : *
3228 : : * Using XLogInsertAllowed() rather than RecoveryInProgress() matters for
3229 : : * the case of an end-of-recovery checkpoint, where WAL data is flushed.
3230 : : * This check should be consistent with the one in XLogFlush().
3231 : : */
3232 [ + + ]: 16791118 : if (!XLogInsertAllowed())
3233 : : {
3234 : : /* Quick exit if already known to be updated or cannot be updated */
3235 [ + - + + ]: 637031 : if (!updateMinRecoveryPoint || record <= LocalMinRecoveryPoint)
3236 : 602074 : return false;
3237 : :
3238 : : /*
3239 : : * An invalid minRecoveryPoint means that we need to recover all the
3240 : : * WAL, i.e., we're doing crash recovery. We never modify the control
3241 : : * file's value in that case, so we can short-circuit future checks
3242 : : * here too. This triggers a quick exit path for the startup process,
3243 : : * which cannot update its local copy of minRecoveryPoint as long as
3244 : : * it has not replayed all WAL available when doing crash recovery.
3245 : : */
3246 [ + + - + ]: 34957 : if (!XLogRecPtrIsValid(LocalMinRecoveryPoint) && InRecovery)
3247 : : {
3248 : 0 : updateMinRecoveryPoint = false;
3249 : 0 : return false;
3250 : : }
3251 : :
3252 : : /*
3253 : : * Update local copy of minRecoveryPoint. But if the lock is busy,
3254 : : * just return a conservative guess.
3255 : : */
3256 [ - + ]: 34957 : if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
3257 : 0 : return true;
3258 : 34957 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
3259 : 34957 : LWLockRelease(ControlFileLock);
3260 : :
3261 : : /*
3262 : : * Check minRecoveryPoint for any other process than the startup
3263 : : * process doing crash recovery, which should not update the control
3264 : : * file value if crash recovery is still running.
3265 : : */
3266 [ - + ]: 34957 : if (!XLogRecPtrIsValid(LocalMinRecoveryPoint))
3267 : 0 : updateMinRecoveryPoint = false;
3268 : :
3269 : : /* check again */
3270 [ + + - + ]: 34957 : if (record <= LocalMinRecoveryPoint || !updateMinRecoveryPoint)
3271 : 121 : return false;
3272 : : else
3273 : 34836 : return true;
3274 : : }
3275 : :
3276 : : /* Quick exit if already known flushed */
3277 [ + + ]: 16154087 : if (record <= LogwrtResult.Flush)
3278 : 15918003 : return false;
3279 : :
3280 : : /* read LogwrtResult and update local state */
3281 : 236084 : RefreshXLogWriteResult(LogwrtResult);
3282 : :
3283 : : /* check again */
3284 [ + + ]: 236084 : if (record <= LogwrtResult.Flush)
3285 : 2783 : return false;
3286 : :
3287 : 233301 : return true;
3288 : : }
3289 : :
3290 : : /*
3291 : : * Try to make a given XLOG file segment exist.
3292 : : *
3293 : : * logsegno: identify segment.
3294 : : *
3295 : : * *added: on return, true if this call raised the number of extant segments.
3296 : : *
3297 : : * path: on return, this char[MAXPGPATH] has the path to the logsegno file.
3298 : : *
3299 : : * Returns -1 or FD of opened file. A -1 here is not an error; a caller
3300 : : * wanting an open segment should attempt to open "path", which usually will
3301 : : * succeed. (This is weird, but it's efficient for the callers.)
3302 : : */
3303 : : static int
3304 : 16430 : XLogFileInitInternal(XLogSegNo logsegno, TimeLineID logtli,
3305 : : bool *added, char *path)
3306 : : {
3307 : : char tmppath[MAXPGPATH];
3308 : : XLogSegNo installed_segno;
3309 : : XLogSegNo max_segno;
3310 : : int fd;
3311 : : int save_errno;
3312 : 16430 : int open_flags = O_RDWR | O_CREAT | O_EXCL | PG_BINARY;
3313 : : instr_time io_start;
3314 : :
3315 : : Assert(logtli != 0);
3316 : :
3317 : 16430 : XLogFilePath(path, logtli, logsegno, wal_segment_size);
3318 : :
3319 : : /*
3320 : : * Try to use existent file (checkpoint maker may have created it already)
3321 : : */
3322 : 16430 : *added = false;
3323 : 16430 : fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3324 : 16430 : get_sync_bit(wal_sync_method));
3325 [ + + ]: 16430 : if (fd < 0)
3326 : : {
3327 [ - + ]: 1484 : if (errno != ENOENT)
3328 [ # # ]: 0 : ereport(ERROR,
3329 : : (errcode_for_file_access(),
3330 : : errmsg("could not open file \"%s\": %m", path)));
3331 : : }
3332 : : else
3333 : 14946 : return fd;
3334 : :
3335 : : /*
3336 : : * Initialize an empty (all zeroes) segment. NOTE: it is possible that
3337 : : * another process is doing the same thing. If so, we will end up
3338 : : * pre-creating an extra log segment. That seems OK, and better than
3339 : : * holding the lock throughout this lengthy process.
3340 : : */
3341 [ + + ]: 1484 : elog(DEBUG2, "creating and filling new WAL file");
3342 : :
3343 : 1484 : snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3344 : :
3345 : 1484 : unlink(tmppath);
3346 : :
3347 [ - + ]: 1484 : if (io_direct_flags & IO_DIRECT_WAL_INIT)
3348 : 0 : open_flags |= PG_O_DIRECT;
3349 : :
3350 : : /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3351 : 1484 : fd = BasicOpenFile(tmppath, open_flags);
3352 [ - + ]: 1484 : if (fd < 0)
3353 [ # # ]: 0 : ereport(ERROR,
3354 : : (errcode_for_file_access(),
3355 : : errmsg("could not create file \"%s\": %m", tmppath)));
3356 : :
3357 : : /* Measure I/O timing when initializing segment */
3358 : 1484 : io_start = pgstat_prepare_io_time(track_wal_io_timing);
3359 : :
3360 : 1484 : pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_WRITE);
3361 : 1484 : save_errno = 0;
3362 [ + - ]: 1484 : if (wal_init_zero)
3363 : : {
3364 : : ssize_t rc;
3365 : :
3366 : : /*
3367 : : * Zero-fill the file. With this setting, we do this the hard way to
3368 : : * ensure that all the file space has really been allocated. On
3369 : : * platforms that allow "holes" in files, just seeking to the end
3370 : : * doesn't allocate intermediate space. This way, we know that we
3371 : : * have all the space and (after the fsync below) that all the
3372 : : * indirect blocks are down on disk. Therefore, fdatasync(2) or
3373 : : * O_DSYNC will be sufficient to sync future writes to the log file.
3374 : : */
3375 : 1484 : rc = pg_pwrite_zeros(fd, wal_segment_size, 0);
3376 : :
3377 [ - + ]: 1484 : if (rc < 0)
3378 : 0 : save_errno = errno;
3379 : : }
3380 : : else
3381 : : {
3382 : : /*
3383 : : * Otherwise, seeking to the end and writing a solitary byte is
3384 : : * enough.
3385 : : */
3386 : 0 : errno = 0;
3387 [ # # ]: 0 : if (pg_pwrite(fd, "\0", 1, wal_segment_size - 1) != 1)
3388 : : {
3389 : : /* if write didn't set errno, assume no disk space */
3390 [ # # ]: 0 : save_errno = errno ? errno : ENOSPC;
3391 : : }
3392 : : }
3393 : 1484 : pgstat_report_wait_end();
3394 : :
3395 [ - + ]: 1484 : if (save_errno)
3396 : : {
3397 : : /*
3398 : : * If we fail to make the file, delete it to release disk space
3399 : : */
3400 : 0 : unlink(tmppath);
3401 : :
3402 : 0 : close(fd);
3403 : :
3404 : 0 : errno = save_errno;
3405 : :
3406 [ # # ]: 0 : ereport(ERROR,
3407 : : (errcode_for_file_access(),
3408 : : errmsg("could not write to file \"%s\": %m", tmppath)));
3409 : : }
3410 : :
3411 : : /*
3412 : : * A full segment worth of data is written when using wal_init_zero. One
3413 : : * byte is written when not using it.
3414 : : */
3415 : 1484 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_INIT, IOOP_WRITE,
3416 : : io_start, 1,
3417 [ + - ]: 1484 : wal_init_zero ? wal_segment_size : 1);
3418 : :
3419 : : /* Measure I/O timing when flushing segment */
3420 : 1484 : io_start = pgstat_prepare_io_time(track_wal_io_timing);
3421 : :
3422 : 1484 : pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_SYNC);
3423 [ - + ]: 1484 : if (pg_fsync(fd) != 0)
3424 : : {
3425 : 0 : save_errno = errno;
3426 : 0 : close(fd);
3427 : 0 : errno = save_errno;
3428 [ # # ]: 0 : ereport(ERROR,
3429 : : (errcode_for_file_access(),
3430 : : errmsg("could not fsync file \"%s\": %m", tmppath)));
3431 : : }
3432 : 1484 : pgstat_report_wait_end();
3433 : :
3434 : 1484 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_INIT,
3435 : : IOOP_FSYNC, io_start, 1, 0);
3436 : :
3437 [ - + ]: 1484 : if (close(fd) != 0)
3438 [ # # ]: 0 : ereport(ERROR,
3439 : : (errcode_for_file_access(),
3440 : : errmsg("could not close file \"%s\": %m", tmppath)));
3441 : :
3442 : : /*
3443 : : * Now move the segment into place with its final name. Cope with
3444 : : * possibility that someone else has created the file while we were
3445 : : * filling ours: if so, use ours to pre-create a future log segment.
3446 : : */
3447 : 1484 : installed_segno = logsegno;
3448 : :
3449 : : /*
3450 : : * XXX: What should we use as max_segno? We used to use XLOGfileslop when
3451 : : * that was a constant, but that was always a bit dubious: normally, at a
3452 : : * checkpoint, XLOGfileslop was the offset from the checkpoint record, but
3453 : : * here, it was the offset from the insert location. We can't do the
3454 : : * normal XLOGfileslop calculation here because we don't have access to
3455 : : * the prior checkpoint's redo location. So somewhat arbitrarily, just use
3456 : : * CheckPointSegments.
3457 : : */
3458 : 1484 : max_segno = logsegno + CheckPointSegments;
3459 [ + - ]: 1484 : if (InstallXLogFileSegment(&installed_segno, tmppath, true, max_segno,
3460 : : logtli))
3461 : : {
3462 : 1484 : *added = true;
3463 [ + + ]: 1484 : elog(DEBUG2, "done creating and filling new WAL file");
3464 : : }
3465 : : else
3466 : : {
3467 : : /*
3468 : : * No need for any more future segments, or InstallXLogFileSegment()
3469 : : * failed to rename the file into place. If the rename failed, a
3470 : : * caller opening the file may fail.
3471 : : */
3472 : 0 : unlink(tmppath);
3473 [ # # ]: 0 : elog(DEBUG2, "abandoned new WAL file");
3474 : : }
3475 : :
3476 : 1484 : return -1;
3477 : : }
3478 : :
3479 : : /*
3480 : : * Create a new XLOG file segment, or open a pre-existing one.
3481 : : *
3482 : : * logsegno: identify segment to be created/opened.
3483 : : *
3484 : : * Returns FD of opened file.
3485 : : *
3486 : : * Note: errors here are ERROR not PANIC because we might or might not be
3487 : : * inside a critical section (eg, during checkpoint there is no reason to
3488 : : * take down the system on failure). They will promote to PANIC if we are
3489 : : * in a critical section.
3490 : : */
3491 : : int
3492 : 16209 : XLogFileInit(XLogSegNo logsegno, TimeLineID logtli)
3493 : : {
3494 : : bool ignore_added;
3495 : : char path[MAXPGPATH];
3496 : : int fd;
3497 : :
3498 : : Assert(logtli != 0);
3499 : :
3500 : 16209 : fd = XLogFileInitInternal(logsegno, logtli, &ignore_added, path);
3501 [ + + ]: 16209 : if (fd >= 0)
3502 : 14783 : return fd;
3503 : :
3504 : : /* Now open original target segment (might not be file I just made) */
3505 : 1426 : fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3506 : 1426 : get_sync_bit(wal_sync_method));
3507 [ - + ]: 1426 : if (fd < 0)
3508 [ # # ]: 0 : ereport(ERROR,
3509 : : (errcode_for_file_access(),
3510 : : errmsg("could not open file \"%s\": %m", path)));
3511 : 1426 : return fd;
3512 : : }
3513 : :
3514 : : /*
3515 : : * Create a new XLOG file segment by copying a pre-existing one.
3516 : : *
3517 : : * destsegno: identify segment to be created.
3518 : : *
3519 : : * srcTLI, srcsegno: identify segment to be copied (could be from
3520 : : * a different timeline)
3521 : : *
3522 : : * upto: how much of the source file to copy (the rest is filled with
3523 : : * zeros)
3524 : : *
3525 : : * Currently this is only used during recovery, and so there are no locking
3526 : : * considerations. But we should be just as tense as XLogFileInit to avoid
3527 : : * emplacing a bogus file.
3528 : : */
3529 : : static void
3530 : 56 : XLogFileCopy(TimeLineID destTLI, XLogSegNo destsegno,
3531 : : TimeLineID srcTLI, XLogSegNo srcsegno,
3532 : : int upto)
3533 : : {
3534 : : char path[MAXPGPATH];
3535 : : char tmppath[MAXPGPATH];
3536 : : PGAlignedXLogBlock buffer;
3537 : : int srcfd;
3538 : : int fd;
3539 : : int nbytes;
3540 : :
3541 : : /*
3542 : : * Open the source file
3543 : : */
3544 : 56 : XLogFilePath(path, srcTLI, srcsegno, wal_segment_size);
3545 : 56 : srcfd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3546 [ - + ]: 56 : if (srcfd < 0)
3547 [ # # ]: 0 : ereport(ERROR,
3548 : : (errcode_for_file_access(),
3549 : : errmsg("could not open file \"%s\": %m", path)));
3550 : :
3551 : : /*
3552 : : * Copy into a temp file name.
3553 : : */
3554 : 56 : snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3555 : :
3556 : 56 : unlink(tmppath);
3557 : :
3558 : : /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3559 : 56 : fd = OpenTransientFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3560 [ - + ]: 56 : if (fd < 0)
3561 [ # # ]: 0 : ereport(ERROR,
3562 : : (errcode_for_file_access(),
3563 : : errmsg("could not create file \"%s\": %m", tmppath)));
3564 : :
3565 : : /*
3566 : : * Do the data copying.
3567 : : */
3568 [ + + ]: 114744 : for (nbytes = 0; nbytes < wal_segment_size; nbytes += sizeof(buffer))
3569 : : {
3570 : : ssize_t nread;
3571 : :
3572 : 114688 : nread = upto - nbytes;
3573 : :
3574 : : /*
3575 : : * The part that is not read from the source file is filled with
3576 : : * zeros.
3577 : : */
3578 [ + + ]: 114688 : if (nread < sizeof(buffer))
3579 : 56 : memset(buffer.data, 0, sizeof(buffer));
3580 : :
3581 [ + + ]: 114688 : if (nread > 0)
3582 : : {
3583 : : ssize_t r;
3584 : :
3585 [ + + ]: 4862 : if (nread > sizeof(buffer))
3586 : 4806 : nread = sizeof(buffer);
3587 : 4862 : pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_READ);
3588 : 4862 : r = read(srcfd, buffer.data, nread);
3589 [ - + ]: 4862 : if (r != nread)
3590 : : {
3591 [ # # ]: 0 : if (r < 0)
3592 [ # # ]: 0 : ereport(ERROR,
3593 : : (errcode_for_file_access(),
3594 : : errmsg("could not read file \"%s\": %m",
3595 : : path)));
3596 : : else
3597 [ # # ]: 0 : ereport(ERROR,
3598 : : (errcode(ERRCODE_DATA_CORRUPTED),
3599 : : errmsg("could not read file \"%s\": read %zd of %zu",
3600 : : path, r, nread)));
3601 : : }
3602 : 4862 : pgstat_report_wait_end();
3603 : : }
3604 : 114688 : errno = 0;
3605 : 114688 : pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_WRITE);
3606 [ - + ]: 114688 : if (write(fd, buffer.data, sizeof(buffer)) != sizeof(buffer))
3607 : : {
3608 : 0 : int save_errno = errno;
3609 : :
3610 : : /*
3611 : : * If we fail to make the file, delete it to release disk space
3612 : : */
3613 : 0 : unlink(tmppath);
3614 : : /* if write didn't set errno, assume problem is no disk space */
3615 [ # # ]: 0 : errno = save_errno ? save_errno : ENOSPC;
3616 : :
3617 [ # # ]: 0 : ereport(ERROR,
3618 : : (errcode_for_file_access(),
3619 : : errmsg("could not write to file \"%s\": %m", tmppath)));
3620 : : }
3621 : 114688 : pgstat_report_wait_end();
3622 : : }
3623 : :
3624 : 56 : pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_SYNC);
3625 [ - + ]: 56 : if (pg_fsync(fd) != 0)
3626 [ # # ]: 0 : ereport(data_sync_elevel(ERROR),
3627 : : (errcode_for_file_access(),
3628 : : errmsg("could not fsync file \"%s\": %m", tmppath)));
3629 : 56 : pgstat_report_wait_end();
3630 : :
3631 [ - + ]: 56 : if (CloseTransientFile(fd) != 0)
3632 [ # # ]: 0 : ereport(ERROR,
3633 : : (errcode_for_file_access(),
3634 : : errmsg("could not close file \"%s\": %m", tmppath)));
3635 : :
3636 [ - + ]: 56 : if (CloseTransientFile(srcfd) != 0)
3637 [ # # ]: 0 : ereport(ERROR,
3638 : : (errcode_for_file_access(),
3639 : : errmsg("could not close file \"%s\": %m", path)));
3640 : :
3641 : : /*
3642 : : * Now move the segment into place with its final name.
3643 : : */
3644 [ - + ]: 56 : if (!InstallXLogFileSegment(&destsegno, tmppath, false, 0, destTLI))
3645 [ # # ]: 0 : elog(ERROR, "InstallXLogFileSegment should not have failed");
3646 : 56 : }
3647 : :
3648 : : /*
3649 : : * Install a new XLOG segment file as a current or future log segment.
3650 : : *
3651 : : * This is used both to install a newly-created segment (which has a temp
3652 : : * filename while it's being created) and to recycle an old segment.
3653 : : *
3654 : : * *segno: identify segment to install as (or first possible target).
3655 : : * When find_free is true, this is modified on return to indicate the
3656 : : * actual installation location or last segment searched.
3657 : : *
3658 : : * tmppath: initial name of file to install. It will be renamed into place.
3659 : : *
3660 : : * find_free: if true, install the new segment at the first empty segno
3661 : : * number at or after the passed numbers. If false, install the new segment
3662 : : * exactly where specified, deleting any existing segment file there.
3663 : : *
3664 : : * max_segno: maximum segment number to install the new file as. Fail if no
3665 : : * free slot is found between *segno and max_segno. (Ignored when find_free
3666 : : * is false.)
3667 : : *
3668 : : * tli: The timeline on which the new segment should be installed.
3669 : : *
3670 : : * Returns true if the file was installed successfully. false indicates that
3671 : : * max_segno limit was exceeded, the startup process has disabled this
3672 : : * function for now, or an error occurred while renaming the file into place.
3673 : : */
3674 : : static bool
3675 : 3355 : InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
3676 : : bool find_free, XLogSegNo max_segno, TimeLineID tli)
3677 : : {
3678 : : char path[MAXPGPATH];
3679 : : struct stat stat_buf;
3680 : :
3681 : : Assert(tli != 0);
3682 : :
3683 : 3355 : XLogFilePath(path, tli, *segno, wal_segment_size);
3684 : :
3685 : 3355 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3686 [ - + ]: 3355 : if (!XLogCtl->InstallXLogFileSegmentActive)
3687 : : {
3688 : 0 : LWLockRelease(ControlFileLock);
3689 : 0 : return false;
3690 : : }
3691 : :
3692 [ + + ]: 3355 : if (!find_free)
3693 : : {
3694 : : /* Force installation: get rid of any pre-existing segment file */
3695 : 56 : durable_unlink(path, DEBUG1);
3696 : : }
3697 : : else
3698 : : {
3699 : : /* Find a free slot to put it in */
3700 [ + + ]: 4682 : while (stat(path, &stat_buf) == 0)
3701 : : {
3702 [ + + ]: 1557 : if ((*segno) >= max_segno)
3703 : : {
3704 : : /* Failed to find a free slot within specified range */
3705 : 174 : LWLockRelease(ControlFileLock);
3706 : 174 : return false;
3707 : : }
3708 : 1383 : (*segno)++;
3709 : 1383 : XLogFilePath(path, tli, *segno, wal_segment_size);
3710 : : }
3711 : : }
3712 : :
3713 : : Assert(access(path, F_OK) != 0 && errno == ENOENT);
3714 [ - + ]: 3181 : if (durable_rename(tmppath, path, LOG) != 0)
3715 : : {
3716 : 0 : LWLockRelease(ControlFileLock);
3717 : : /* durable_rename already emitted log message */
3718 : 0 : return false;
3719 : : }
3720 : :
3721 : 3181 : LWLockRelease(ControlFileLock);
3722 : :
3723 : 3181 : return true;
3724 : : }
3725 : :
3726 : : /*
3727 : : * Open a pre-existing logfile segment for writing.
3728 : : */
3729 : : int
3730 : 102 : XLogFileOpen(XLogSegNo segno, TimeLineID tli)
3731 : : {
3732 : : char path[MAXPGPATH];
3733 : : int fd;
3734 : :
3735 : 102 : XLogFilePath(path, tli, segno, wal_segment_size);
3736 : :
3737 : 102 : fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3738 : 102 : get_sync_bit(wal_sync_method));
3739 [ - + ]: 102 : if (fd < 0)
3740 [ # # ]: 0 : ereport(PANIC,
3741 : : (errcode_for_file_access(),
3742 : : errmsg("could not open file \"%s\": %m", path)));
3743 : :
3744 : 102 : return fd;
3745 : : }
3746 : :
3747 : : /*
3748 : : * Close the current logfile segment for writing.
3749 : : */
3750 : : static void
3751 : 6801 : XLogFileClose(void)
3752 : : {
3753 : : Assert(openLogFile >= 0);
3754 : :
3755 : : /*
3756 : : * WAL segment files will not be re-read in normal operation, so we advise
3757 : : * the OS to release any cached pages. But do not do so if WAL archiving
3758 : : * or streaming is active, because archiver and walsender process could
3759 : : * use the cache to read the WAL segment.
3760 : : */
3761 : : #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3762 [ + + + - ]: 6801 : if (!XLogIsNeeded() && (io_direct_flags & IO_DIRECT_WAL) == 0)
3763 : 163 : (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3764 : : #endif
3765 : :
3766 [ - + ]: 6801 : if (close(openLogFile) != 0)
3767 : : {
3768 : : char xlogfname[MAXFNAMELEN];
3769 : 0 : int save_errno = errno;
3770 : :
3771 : 0 : XLogFileName(xlogfname, openLogTLI, openLogSegNo, wal_segment_size);
3772 : 0 : errno = save_errno;
3773 [ # # ]: 0 : ereport(PANIC,
3774 : : (errcode_for_file_access(),
3775 : : errmsg("could not close file \"%s\": %m", xlogfname)));
3776 : : }
3777 : :
3778 : 6801 : openLogFile = -1;
3779 : 6801 : ReleaseExternalFD();
3780 : 6801 : }
3781 : :
3782 : : /*
3783 : : * Preallocate log files beyond the specified log endpoint.
3784 : : *
3785 : : * XXX this is currently extremely conservative, since it forces only one
3786 : : * future log segment to exist, and even that only if we are 75% done with
3787 : : * the current one. This is only appropriate for very low-WAL-volume systems.
3788 : : * High-volume systems will be OK once they've built up a sufficient set of
3789 : : * recycled log segments, but the startup transient is likely to include
3790 : : * a lot of segment creations by foreground processes, which is not so good.
3791 : : *
3792 : : * XLogFileInitInternal() can ereport(ERROR). All known causes indicate big
3793 : : * trouble; for example, a full filesystem is one cause. The checkpoint WAL
3794 : : * and/or ControlFile updates already completed. If a RequestCheckpoint()
3795 : : * initiated the present checkpoint and an ERROR ends this function, the
3796 : : * command that called RequestCheckpoint() fails. That's not ideal, but it's
3797 : : * not worth contorting more functions to use caller-specified elevel values.
3798 : : * (With or without RequestCheckpoint(), an ERROR forestalls some inessential
3799 : : * reporting and resource reclamation.)
3800 : : */
3801 : : static void
3802 : 2317 : PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli)
3803 : : {
3804 : : XLogSegNo _logSegNo;
3805 : : int lf;
3806 : : bool added;
3807 : : char path[MAXPGPATH];
3808 : : uint64 offset;
3809 : :
3810 [ + + ]: 2317 : if (!XLogCtl->InstallXLogFileSegmentActive)
3811 : 10 : return; /* unlocked check says no */
3812 : :
3813 : 2307 : XLByteToPrevSeg(endptr, _logSegNo, wal_segment_size);
3814 : 2307 : offset = XLogSegmentOffset(endptr - 1, wal_segment_size);
3815 [ + + ]: 2307 : if (offset >= (uint32) (0.75 * wal_segment_size))
3816 : : {
3817 : 221 : _logSegNo++;
3818 : 221 : lf = XLogFileInitInternal(_logSegNo, tli, &added, path);
3819 [ + + ]: 221 : if (lf >= 0)
3820 : 163 : close(lf);
3821 [ + + ]: 221 : if (added)
3822 : 58 : CheckpointStats.ckpt_segs_added++;
3823 : : }
3824 : : }
3825 : :
3826 : : /*
3827 : : * Throws an error if the given log segment has already been removed or
3828 : : * recycled. The caller should only pass a segment that it knows to have
3829 : : * existed while the server has been running, as this function always
3830 : : * succeeds if no WAL segments have been removed since startup.
3831 : : * 'tli' is only used in the error message.
3832 : : *
3833 : : * Note: this function guarantees to keep errno unchanged on return.
3834 : : * This supports callers that use this to possibly deliver a better
3835 : : * error message about a missing file, while still being able to throw
3836 : : * a normal file-access error afterwards, if this does return.
3837 : : */
3838 : : void
3839 : 133094 : CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
3840 : : {
3841 : 133094 : int save_errno = errno;
3842 : : XLogSegNo lastRemovedSegNo;
3843 : :
3844 : 133094 : SpinLockAcquire(&XLogCtl->info_lck);
3845 : 133094 : lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3846 : 133094 : SpinLockRelease(&XLogCtl->info_lck);
3847 : :
3848 [ - + ]: 133094 : if (segno <= lastRemovedSegNo)
3849 : : {
3850 : : char filename[MAXFNAMELEN];
3851 : :
3852 : 0 : XLogFileName(filename, tli, segno, wal_segment_size);
3853 : 0 : errno = save_errno;
3854 [ # # ]: 0 : ereport(ERROR,
3855 : : (errcode_for_file_access(),
3856 : : errmsg("requested WAL segment %s has already been removed",
3857 : : filename)));
3858 : : }
3859 : 133094 : errno = save_errno;
3860 : 133094 : }
3861 : :
3862 : : /*
3863 : : * Return the last WAL segment removed, or 0 if no segment has been removed
3864 : : * since startup.
3865 : : *
3866 : : * NB: the result can be out of date arbitrarily fast, the caller has to deal
3867 : : * with that.
3868 : : */
3869 : : XLogSegNo
3870 : 1342 : XLogGetLastRemovedSegno(void)
3871 : : {
3872 : : XLogSegNo lastRemovedSegNo;
3873 : :
3874 : 1342 : SpinLockAcquire(&XLogCtl->info_lck);
3875 : 1342 : lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3876 : 1342 : SpinLockRelease(&XLogCtl->info_lck);
3877 : :
3878 : 1342 : return lastRemovedSegNo;
3879 : : }
3880 : :
3881 : : /*
3882 : : * Return the oldest WAL segment on the given TLI that still exists in
3883 : : * XLOGDIR, or 0 if none.
3884 : : */
3885 : : XLogSegNo
3886 : 12 : XLogGetOldestSegno(TimeLineID tli)
3887 : : {
3888 : : DIR *xldir;
3889 : : struct dirent *xlde;
3890 : 12 : XLogSegNo oldest_segno = 0;
3891 : :
3892 : 12 : xldir = AllocateDir(XLOGDIR);
3893 [ + + ]: 86 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3894 : : {
3895 : : TimeLineID file_tli;
3896 : : XLogSegNo file_segno;
3897 : :
3898 : : /* Ignore files that are not XLOG segments. */
3899 [ + + ]: 74 : if (!IsXLogFileName(xlde->d_name))
3900 : 49 : continue;
3901 : :
3902 : : /* Parse filename to get TLI and segno. */
3903 : 25 : XLogFromFileName(xlde->d_name, &file_tli, &file_segno,
3904 : : wal_segment_size);
3905 : :
3906 : : /* Ignore anything that's not from the TLI of interest. */
3907 [ - + ]: 25 : if (tli != file_tli)
3908 : 0 : continue;
3909 : :
3910 : : /* If it's the oldest so far, update oldest_segno. */
3911 [ + + + + ]: 25 : if (oldest_segno == 0 || file_segno < oldest_segno)
3912 : 16 : oldest_segno = file_segno;
3913 : : }
3914 : :
3915 : 12 : FreeDir(xldir);
3916 : 12 : return oldest_segno;
3917 : : }
3918 : :
3919 : : /*
3920 : : * Update the last removed segno pointer in shared memory, to reflect that the
3921 : : * given XLOG file has been removed.
3922 : : */
3923 : : static void
3924 : 2803 : UpdateLastRemovedPtr(char *filename)
3925 : : {
3926 : : uint32 tli;
3927 : : XLogSegNo segno;
3928 : :
3929 : 2803 : XLogFromFileName(filename, &tli, &segno, wal_segment_size);
3930 : :
3931 : 2803 : SpinLockAcquire(&XLogCtl->info_lck);
3932 [ + + ]: 2803 : if (segno > XLogCtl->lastRemovedSegNo)
3933 : 1248 : XLogCtl->lastRemovedSegNo = segno;
3934 : 2803 : SpinLockRelease(&XLogCtl->info_lck);
3935 : 2803 : }
3936 : :
3937 : : /*
3938 : : * Remove all temporary log files in pg_wal
3939 : : *
3940 : : * This is called at the beginning of recovery after a previous crash,
3941 : : * at a point where no other processes write fresh WAL data.
3942 : : */
3943 : : static void
3944 : 212 : RemoveTempXlogFiles(void)
3945 : : {
3946 : : DIR *xldir;
3947 : : struct dirent *xlde;
3948 : :
3949 [ + + ]: 212 : elog(DEBUG2, "removing all temporary WAL segments");
3950 : :
3951 : 212 : xldir = AllocateDir(XLOGDIR);
3952 [ + + ]: 1426 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3953 : : {
3954 : : char path[MAXPGPATH];
3955 : :
3956 [ + - ]: 1214 : if (strncmp(xlde->d_name, "xlogtemp.", 9) != 0)
3957 : 1214 : continue;
3958 : :
3959 : 0 : snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3960 : 0 : unlink(path);
3961 [ # # ]: 0 : elog(DEBUG2, "removed temporary WAL segment \"%s\"", path);
3962 : : }
3963 : 212 : FreeDir(xldir);
3964 : 212 : }
3965 : :
3966 : : /*
3967 : : * Recycle or remove all log files older or equal to passed segno.
3968 : : *
3969 : : * endptr is current (or recent) end of xlog, and lastredoptr is the
3970 : : * redo pointer of the last checkpoint. These are used to determine
3971 : : * whether we want to recycle rather than delete no-longer-wanted log files.
3972 : : *
3973 : : * insertTLI is the current timeline for XLOG insertion. Any recycled
3974 : : * segments should be reused for this timeline.
3975 : : */
3976 : : static void
3977 : 2027 : RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr,
3978 : : TimeLineID insertTLI)
3979 : : {
3980 : : DIR *xldir;
3981 : : struct dirent *xlde;
3982 : : char lastoff[MAXFNAMELEN];
3983 : : XLogSegNo endlogSegNo;
3984 : : XLogSegNo recycleSegNo;
3985 : :
3986 : : /* Initialize info about where to try to recycle to */
3987 : 2027 : XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
3988 : 2027 : recycleSegNo = XLOGfileslop(lastredoptr);
3989 : :
3990 : : /*
3991 : : * Construct a filename of the last segment to be kept. The timeline ID
3992 : : * doesn't matter, we ignore that in the comparison. (During recovery,
3993 : : * InsertTimeLineID isn't set, so we can't use that.)
3994 : : */
3995 : 2027 : XLogFileName(lastoff, 0, segno, wal_segment_size);
3996 : :
3997 [ + + ]: 2027 : elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
3998 : : lastoff);
3999 : :
4000 : 2027 : xldir = AllocateDir(XLOGDIR);
4001 : :
4002 [ + + ]: 36697 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4003 : : {
4004 : : /* Ignore files that are not XLOG segments */
4005 [ + + ]: 34670 : if (!IsXLogFileName(xlde->d_name) &&
4006 [ + + ]: 8581 : !IsPartialXLogFileName(xlde->d_name))
4007 : 8577 : continue;
4008 : :
4009 : : /*
4010 : : * We ignore the timeline part of the XLOG segment identifiers in
4011 : : * deciding whether a segment is still needed. This ensures that we
4012 : : * won't prematurely remove a segment from a parent timeline. We could
4013 : : * probably be a little more proactive about removing segments of
4014 : : * non-parent timelines, but that would be a whole lot more
4015 : : * complicated.
4016 : : *
4017 : : * We use the alphanumeric sorting property of the filenames to decide
4018 : : * which ones are earlier than the lastoff segment.
4019 : : */
4020 [ + + ]: 26093 : if (strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
4021 : : {
4022 [ + + ]: 19215 : if (XLogArchiveCheckDone(xlde->d_name))
4023 : : {
4024 : : /* Update the last removed location in shared memory first */
4025 : 2803 : UpdateLastRemovedPtr(xlde->d_name);
4026 : :
4027 : 2803 : RemoveXlogFile(xlde, recycleSegNo, &endlogSegNo, insertTLI);
4028 : : }
4029 : : }
4030 : : }
4031 : :
4032 : 2027 : FreeDir(xldir);
4033 : 2027 : }
4034 : :
4035 : : /*
4036 : : * Recycle or remove WAL files that are not part of the given timeline's
4037 : : * history.
4038 : : *
4039 : : * This is called during recovery, whenever we switch to follow a new
4040 : : * timeline, and at the end of recovery when we create a new timeline. We
4041 : : * wouldn't otherwise care about extra WAL files lying in pg_wal, but they
4042 : : * might be leftover pre-allocated or recycled WAL segments on the old timeline
4043 : : * that we haven't used yet, and contain garbage. If we just leave them in
4044 : : * pg_wal, they will eventually be archived, and we can't let that happen.
4045 : : * Files that belong to our timeline history are valid, because we have
4046 : : * successfully replayed them, but from others we can't be sure.
4047 : : *
4048 : : * 'switchpoint' is the current point in WAL where we switch to new timeline,
4049 : : * and 'newTLI' is the new timeline we switch to.
4050 : : */
4051 : : void
4052 : 81 : RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
4053 : : {
4054 : : DIR *xldir;
4055 : : struct dirent *xlde;
4056 : : char switchseg[MAXFNAMELEN];
4057 : : XLogSegNo endLogSegNo;
4058 : : XLogSegNo switchLogSegNo;
4059 : : XLogSegNo recycleSegNo;
4060 : :
4061 : : /*
4062 : : * Initialize info about where to begin the work. This will recycle,
4063 : : * somewhat arbitrarily, 10 future segments.
4064 : : */
4065 : 81 : XLByteToPrevSeg(switchpoint, switchLogSegNo, wal_segment_size);
4066 : 81 : XLByteToSeg(switchpoint, endLogSegNo, wal_segment_size);
4067 : 81 : recycleSegNo = endLogSegNo + 10;
4068 : :
4069 : : /*
4070 : : * Construct a filename of the last segment to be kept.
4071 : : */
4072 : 81 : XLogFileName(switchseg, newTLI, switchLogSegNo, wal_segment_size);
4073 : :
4074 [ + + ]: 81 : elog(DEBUG2, "attempting to remove WAL segments newer than log file %s",
4075 : : switchseg);
4076 : :
4077 : 81 : xldir = AllocateDir(XLOGDIR);
4078 : :
4079 [ + + ]: 768 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4080 : : {
4081 : : /* Ignore files that are not XLOG segments */
4082 [ + + ]: 687 : if (!IsXLogFileName(xlde->d_name))
4083 : 424 : continue;
4084 : :
4085 : : /*
4086 : : * Remove files that are on a timeline older than the new one we're
4087 : : * switching to, but with a segment number >= the first segment on the
4088 : : * new timeline.
4089 : : */
4090 [ + + ]: 263 : if (strncmp(xlde->d_name, switchseg, 8) < 0 &&
4091 [ + + ]: 170 : strcmp(xlde->d_name + 8, switchseg + 8) > 0)
4092 : : {
4093 : : /*
4094 : : * If the file has already been marked as .ready, however, don't
4095 : : * remove it yet. It should be OK to remove it - files that are
4096 : : * not part of our timeline history are not required for recovery
4097 : : * - but seems safer to let them be archived and removed later.
4098 : : */
4099 [ + - ]: 19 : if (!XLogArchiveIsReady(xlde->d_name))
4100 : 19 : RemoveXlogFile(xlde, recycleSegNo, &endLogSegNo, newTLI);
4101 : : }
4102 : : }
4103 : :
4104 : 81 : FreeDir(xldir);
4105 : 81 : }
4106 : :
4107 : : /*
4108 : : * Recycle or remove a log file that's no longer needed.
4109 : : *
4110 : : * segment_de is the dirent structure of the segment to recycle or remove.
4111 : : * recycleSegNo is the segment number to recycle up to. endlogSegNo is
4112 : : * the segment number of the current (or recent) end of WAL.
4113 : : *
4114 : : * endlogSegNo gets incremented if the segment is recycled so as it is not
4115 : : * checked again with future callers of this function.
4116 : : *
4117 : : * insertTLI is the current timeline for XLOG insertion. Any recycled segments
4118 : : * should be used for this timeline.
4119 : : */
4120 : : static void
4121 : 2822 : RemoveXlogFile(const struct dirent *segment_de,
4122 : : XLogSegNo recycleSegNo, XLogSegNo *endlogSegNo,
4123 : : TimeLineID insertTLI)
4124 : : {
4125 : : char path[MAXPGPATH];
4126 : : #ifdef WIN32
4127 : : char newpath[MAXPGPATH];
4128 : : #endif
4129 : 2822 : const char *segname = segment_de->d_name;
4130 : :
4131 : 2822 : snprintf(path, MAXPGPATH, XLOGDIR "/%s", segname);
4132 : :
4133 : : /*
4134 : : * Before deleting the file, see if it can be recycled as a future log
4135 : : * segment. Only recycle normal files, because we don't want to recycle
4136 : : * symbolic links pointing to a separate archive directory.
4137 : : */
4138 [ + - ]: 2822 : if (wal_recycle &&
4139 [ + + ]: 2822 : *endlogSegNo <= recycleSegNo &&
4140 [ + + + - ]: 3958 : XLogCtl->InstallXLogFileSegmentActive && /* callee rechecks this */
4141 [ + + ]: 3630 : get_dirent_type(path, segment_de, false, DEBUG2) == PGFILETYPE_REG &&
4142 : 1815 : InstallXLogFileSegment(endlogSegNo, path,
4143 : : true, recycleSegNo, insertTLI))
4144 : : {
4145 [ + + ]: 1641 : ereport(DEBUG2,
4146 : : (errmsg_internal("recycled write-ahead log file \"%s\"",
4147 : : segname)));
4148 : 1641 : CheckpointStats.ckpt_segs_recycled++;
4149 : : /* Needn't recheck that slot on future iterations */
4150 : 1641 : (*endlogSegNo)++;
4151 : : }
4152 : : else
4153 : : {
4154 : : /* No need for any more future segments, or recycling failed ... */
4155 : : int rc;
4156 : :
4157 [ + + ]: 1181 : ereport(DEBUG2,
4158 : : (errmsg_internal("removing write-ahead log file \"%s\"",
4159 : : segname)));
4160 : :
4161 : : #ifdef WIN32
4162 : :
4163 : : /*
4164 : : * On Windows, if another process (e.g another backend) holds the file
4165 : : * open in FILE_SHARE_DELETE mode, unlink will succeed, but the file
4166 : : * will still show up in directory listing until the last handle is
4167 : : * closed. To avoid confusing the lingering deleted file for a live
4168 : : * WAL file that needs to be archived, rename it before deleting it.
4169 : : *
4170 : : * If another process holds the file open without FILE_SHARE_DELETE
4171 : : * flag, rename will fail. We'll try again at the next checkpoint.
4172 : : */
4173 : : snprintf(newpath, MAXPGPATH, "%s.deleted", path);
4174 : : if (rename(path, newpath) != 0)
4175 : : {
4176 : : ereport(LOG,
4177 : : (errcode_for_file_access(),
4178 : : errmsg("could not rename file \"%s\": %m",
4179 : : path)));
4180 : : return;
4181 : : }
4182 : : rc = durable_unlink(newpath, LOG);
4183 : : #else
4184 : 1181 : rc = durable_unlink(path, LOG);
4185 : : #endif
4186 [ - + ]: 1181 : if (rc != 0)
4187 : : {
4188 : : /* Message already logged by durable_unlink() */
4189 : 0 : return;
4190 : : }
4191 : 1181 : CheckpointStats.ckpt_segs_removed++;
4192 : : }
4193 : :
4194 : 2822 : XLogArchiveCleanup(segname);
4195 : : }
4196 : :
4197 : : /*
4198 : : * Verify whether pg_wal, pg_wal/archive_status, and pg_wal/summaries exist.
4199 : : * If the latter do not exist, recreate them.
4200 : : *
4201 : : * It is not the goal of this function to verify the contents of these
4202 : : * directories, but to help in cases where someone has performed a cluster
4203 : : * copy for PITR purposes but omitted pg_wal from the copy.
4204 : : *
4205 : : * We could also recreate pg_wal if it doesn't exist, but a deliberate
4206 : : * policy decision was made not to. It is fairly common for pg_wal to be
4207 : : * a symlink, and if that was the DBA's intent then automatically making a
4208 : : * plain directory would result in degraded performance with no notice.
4209 : : */
4210 : : static void
4211 : 1148 : ValidateXLOGDirectoryStructure(void)
4212 : : {
4213 : : char path[MAXPGPATH];
4214 : : struct stat stat_buf;
4215 : :
4216 : : /* Check for pg_wal; if it doesn't exist, error out */
4217 [ + - ]: 1148 : if (stat(XLOGDIR, &stat_buf) != 0 ||
4218 [ - + ]: 1148 : !S_ISDIR(stat_buf.st_mode))
4219 [ # # ]: 0 : ereport(FATAL,
4220 : : (errcode_for_file_access(),
4221 : : errmsg("required WAL directory \"%s\" does not exist",
4222 : : XLOGDIR)));
4223 : :
4224 : : /* Check for archive_status */
4225 : 1148 : snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
4226 [ + + ]: 1148 : if (stat(path, &stat_buf) == 0)
4227 : : {
4228 : : /* Check for weird cases where it exists but isn't a directory */
4229 [ - + ]: 1146 : if (!S_ISDIR(stat_buf.st_mode))
4230 [ # # ]: 0 : ereport(FATAL,
4231 : : (errcode_for_file_access(),
4232 : : errmsg("required WAL directory \"%s\" does not exist",
4233 : : path)));
4234 : : }
4235 : : else
4236 : : {
4237 [ + - ]: 2 : ereport(LOG,
4238 : : (errmsg("creating missing WAL directory \"%s\"", path)));
4239 [ - + ]: 2 : if (MakePGDirectory(path) < 0)
4240 [ # # ]: 0 : ereport(FATAL,
4241 : : (errcode_for_file_access(),
4242 : : errmsg("could not create missing directory \"%s\": %m",
4243 : : path)));
4244 : : }
4245 : :
4246 : : /* Check for summaries */
4247 : 1148 : snprintf(path, MAXPGPATH, XLOGDIR "/summaries");
4248 [ + + ]: 1148 : if (stat(path, &stat_buf) == 0)
4249 : : {
4250 : : /* Check for weird cases where it exists but isn't a directory */
4251 [ - + ]: 1146 : if (!S_ISDIR(stat_buf.st_mode))
4252 [ # # ]: 0 : ereport(FATAL,
4253 : : (errmsg("required WAL directory \"%s\" does not exist",
4254 : : path)));
4255 : : }
4256 : : else
4257 : : {
4258 [ + - ]: 2 : ereport(LOG,
4259 : : (errmsg("creating missing WAL directory \"%s\"", path)));
4260 [ - + ]: 2 : if (MakePGDirectory(path) < 0)
4261 [ # # ]: 0 : ereport(FATAL,
4262 : : (errmsg("could not create missing directory \"%s\": %m",
4263 : : path)));
4264 : : }
4265 : 1148 : }
4266 : :
4267 : : /*
4268 : : * Remove previous backup history files. This also retries creation of
4269 : : * .ready files for any backup history files for which XLogArchiveNotify
4270 : : * failed earlier.
4271 : : */
4272 : : static void
4273 : 180 : CleanupBackupHistory(void)
4274 : : {
4275 : : DIR *xldir;
4276 : : struct dirent *xlde;
4277 : : char path[MAXPGPATH + sizeof(XLOGDIR)];
4278 : :
4279 : 180 : xldir = AllocateDir(XLOGDIR);
4280 : :
4281 [ + + ]: 1834 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4282 : : {
4283 [ + + ]: 1474 : if (IsBackupHistoryFileName(xlde->d_name))
4284 : : {
4285 [ + + ]: 190 : if (XLogArchiveCheckDone(xlde->d_name))
4286 : : {
4287 [ + + ]: 152 : elog(DEBUG2, "removing WAL backup history file \"%s\"",
4288 : : xlde->d_name);
4289 : 152 : snprintf(path, sizeof(path), XLOGDIR "/%s", xlde->d_name);
4290 : 152 : unlink(path);
4291 : 152 : XLogArchiveCleanup(xlde->d_name);
4292 : : }
4293 : : }
4294 : : }
4295 : :
4296 : 180 : FreeDir(xldir);
4297 : 180 : }
4298 : :
4299 : : /*
4300 : : * I/O routines for pg_control
4301 : : *
4302 : : * *ControlFile is a buffer in shared memory that holds an image of the
4303 : : * contents of pg_control. WriteControlFile() initializes pg_control
4304 : : * given a preloaded buffer, ReadControlFile() loads the buffer from
4305 : : * the pg_control file (during postmaster or standalone-backend startup),
4306 : : * and UpdateControlFile() rewrites pg_control after we modify xlog state.
4307 : : * InitControlFile() fills the buffer with initial values.
4308 : : *
4309 : : * For simplicity, WriteControlFile() initializes the fields of pg_control
4310 : : * that are related to checking backend/database compatibility, and
4311 : : * ReadControlFile() verifies they are correct. We could split out the
4312 : : * I/O and compatibility-check functions, but there seems no need currently.
4313 : : */
4314 : :
4315 : : static void
4316 : 59 : InitControlFile(uint64 sysidentifier, uint32 data_checksum_version)
4317 : : {
4318 : : char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
4319 : :
4320 : : /*
4321 : : * Generate a random nonce. This is used for authentication requests that
4322 : : * will fail because the user does not exist. The nonce is used to create
4323 : : * a genuine-looking password challenge for the non-existent user, in lieu
4324 : : * of an actual stored password.
4325 : : */
4326 [ - + ]: 59 : if (!pg_strong_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
4327 [ # # ]: 0 : ereport(PANIC,
4328 : : (errcode(ERRCODE_INTERNAL_ERROR),
4329 : : errmsg("could not generate secret authorization token")));
4330 : :
4331 : 59 : memset(ControlFile, 0, sizeof(ControlFileData));
4332 : : /* Initialize pg_control status fields */
4333 : 59 : ControlFile->system_identifier = sysidentifier;
4334 : 59 : memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
4335 : 59 : ControlFile->state = DB_SHUTDOWNED;
4336 : 59 : ControlFile->unloggedLSN = FirstNormalUnloggedLSN;
4337 : :
4338 : : /* Set important parameter values for use when replaying WAL */
4339 : 59 : ControlFile->MaxConnections = MaxConnections;
4340 : 59 : ControlFile->max_worker_processes = max_worker_processes;
4341 : 59 : ControlFile->max_wal_senders = max_wal_senders;
4342 : 59 : ControlFile->max_prepared_xacts = max_prepared_xacts;
4343 : 59 : ControlFile->max_locks_per_xact = max_locks_per_xact;
4344 : 59 : ControlFile->wal_level = wal_level;
4345 : 59 : ControlFile->wal_log_hints = wal_log_hints;
4346 : 59 : ControlFile->track_commit_timestamp = track_commit_timestamp;
4347 : 59 : ControlFile->data_checksum_version = data_checksum_version;
4348 : 59 : ControlFile->data_checksum_version_init = data_checksum_version;
4349 : 59 : ControlFile->data_checksum_is_local = false;
4350 : 59 : ControlFile->data_checksum_lsn = InvalidXLogRecPtr;
4351 : :
4352 : : /*
4353 : : * Set the data_checksum_version value into XLogCtl, which is where all
4354 : : * processes get the current value from.
4355 : : */
4356 : 59 : XLogCtl->data_checksum_version = data_checksum_version;
4357 : 59 : }
4358 : :
4359 : : static void
4360 : 59 : WriteControlFile(void)
4361 : : {
4362 : : int fd;
4363 : : char buffer[PG_CONTROL_FILE_SIZE]; /* need not be aligned */
4364 : :
4365 : : /*
4366 : : * Initialize version and compatibility-check fields
4367 : : */
4368 : 59 : ControlFile->pg_control_version = PG_CONTROL_VERSION;
4369 : 59 : ControlFile->catalog_version_no = CATALOG_VERSION_NO;
4370 : :
4371 : 59 : ControlFile->maxAlign = MAXIMUM_ALIGNOF;
4372 : 59 : ControlFile->floatFormat = FLOATFORMAT_VALUE;
4373 : :
4374 : 59 : ControlFile->blcksz = BLCKSZ;
4375 : 59 : ControlFile->relseg_size = RELSEG_SIZE;
4376 : 59 : ControlFile->slru_pages_per_segment = SLRU_PAGES_PER_SEGMENT;
4377 : 59 : ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4378 : 59 : ControlFile->xlog_seg_size = wal_segment_size;
4379 : :
4380 : 59 : ControlFile->nameDataLen = NAMEDATALEN;
4381 : 59 : ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
4382 : :
4383 : 59 : ControlFile->toast_max_chunk_size = TOAST_OID_MAX_CHUNK_SIZE;
4384 : 59 : ControlFile->loblksize = LOBLKSIZE;
4385 : :
4386 : 59 : ControlFile->float8ByVal = true; /* vestigial */
4387 : :
4388 : : /*
4389 : : * Initialize the default 'char' signedness.
4390 : : *
4391 : : * The signedness of the char type is implementation-defined. For instance
4392 : : * on x86 architecture CPUs, the char data type is typically treated as
4393 : : * signed by default, whereas on aarch architecture CPUs, it is typically
4394 : : * treated as unsigned by default. In v17 or earlier, we accidentally let
4395 : : * C implementation signedness affect persistent data. This led to
4396 : : * inconsistent results when comparing char data across different
4397 : : * platforms.
4398 : : *
4399 : : * This flag can be used as a hint to ensure consistent behavior for
4400 : : * pre-v18 data files that store data sorted by the 'char' type on disk,
4401 : : * especially in cross-platform replication scenarios.
4402 : : *
4403 : : * Newly created database clusters unconditionally set the default char
4404 : : * signedness to true. pg_upgrade changes this flag for clusters that were
4405 : : * initialized on signedness=false platforms. As a result,
4406 : : * signedness=false setting will become rare over time. If we had known
4407 : : * about this problem during the last development cycle that forced initdb
4408 : : * (v8.3), we would have made all clusters signed or all clusters
4409 : : * unsigned. Making pg_upgrade the only source of signedness=false will
4410 : : * cause the population of database clusters to converge toward that
4411 : : * retrospective ideal.
4412 : : */
4413 : 59 : ControlFile->default_char_signedness = true;
4414 : :
4415 : : /* Contents are protected with a CRC */
4416 : 59 : INIT_CRC32C(ControlFile->crc);
4417 : 59 : COMP_CRC32C(ControlFile->crc,
4418 : : ControlFile,
4419 : : offsetof(ControlFileData, crc));
4420 : 59 : FIN_CRC32C(ControlFile->crc);
4421 : :
4422 : : /*
4423 : : * We write out PG_CONTROL_FILE_SIZE bytes into pg_control, zero-padding
4424 : : * the excess over sizeof(ControlFileData). This reduces the odds of
4425 : : * premature-EOF errors when reading pg_control. We'll still fail when we
4426 : : * check the contents of the file, but hopefully with a more specific
4427 : : * error than "couldn't read pg_control".
4428 : : */
4429 : 59 : memset(buffer, 0, PG_CONTROL_FILE_SIZE);
4430 : 59 : memcpy(buffer, ControlFile, sizeof(ControlFileData));
4431 : :
4432 : 59 : fd = BasicOpenFile(XLOG_CONTROL_FILE,
4433 : : O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
4434 [ - + ]: 59 : if (fd < 0)
4435 [ # # ]: 0 : ereport(PANIC,
4436 : : (errcode_for_file_access(),
4437 : : errmsg("could not create file \"%s\": %m",
4438 : : XLOG_CONTROL_FILE)));
4439 : :
4440 : 59 : errno = 0;
4441 : 59 : pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_WRITE);
4442 [ - + ]: 59 : if (write(fd, buffer, PG_CONTROL_FILE_SIZE) != PG_CONTROL_FILE_SIZE)
4443 : : {
4444 : : /* if write didn't set errno, assume problem is no disk space */
4445 [ # # ]: 0 : if (errno == 0)
4446 : 0 : errno = ENOSPC;
4447 [ # # ]: 0 : ereport(PANIC,
4448 : : (errcode_for_file_access(),
4449 : : errmsg("could not write to file \"%s\": %m",
4450 : : XLOG_CONTROL_FILE)));
4451 : : }
4452 : 59 : pgstat_report_wait_end();
4453 : :
4454 : 59 : pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_SYNC);
4455 [ - + ]: 59 : if (pg_fsync(fd) != 0)
4456 [ # # ]: 0 : ereport(PANIC,
4457 : : (errcode_for_file_access(),
4458 : : errmsg("could not fsync file \"%s\": %m",
4459 : : XLOG_CONTROL_FILE)));
4460 : 59 : pgstat_report_wait_end();
4461 : :
4462 [ - + ]: 59 : if (close(fd) != 0)
4463 [ # # ]: 0 : ereport(PANIC,
4464 : : (errcode_for_file_access(),
4465 : : errmsg("could not close file \"%s\": %m",
4466 : : XLOG_CONTROL_FILE)));
4467 : 59 : }
4468 : :
4469 : : static void
4470 : 1216 : ReadControlFile(void)
4471 : : {
4472 : : pg_crc32c crc;
4473 : : int fd;
4474 : : char wal_segsz_str[20];
4475 : : ssize_t r;
4476 : :
4477 : : /*
4478 : : * Read data...
4479 : : */
4480 : 1216 : fd = BasicOpenFile(XLOG_CONTROL_FILE,
4481 : : O_RDWR | PG_BINARY);
4482 [ - + ]: 1216 : if (fd < 0)
4483 [ # # ]: 0 : ereport(PANIC,
4484 : : (errcode_for_file_access(),
4485 : : errmsg("could not open file \"%s\": %m",
4486 : : XLOG_CONTROL_FILE)));
4487 : :
4488 : 1216 : pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_READ);
4489 : 1216 : r = read(fd, ControlFile, sizeof(ControlFileData));
4490 [ - + ]: 1216 : if (r != sizeof(ControlFileData))
4491 : : {
4492 [ # # ]: 0 : if (r < 0)
4493 [ # # ]: 0 : ereport(PANIC,
4494 : : (errcode_for_file_access(),
4495 : : errmsg("could not read file \"%s\": %m",
4496 : : XLOG_CONTROL_FILE)));
4497 : : else
4498 [ # # ]: 0 : ereport(PANIC,
4499 : : (errcode(ERRCODE_DATA_CORRUPTED),
4500 : : errmsg("could not read file \"%s\": read %zd of %zu",
4501 : : XLOG_CONTROL_FILE, r, sizeof(ControlFileData))));
4502 : : }
4503 : 1216 : pgstat_report_wait_end();
4504 : :
4505 : 1216 : close(fd);
4506 : :
4507 : : /*
4508 : : * Check for expected pg_control format version. If this is wrong, the
4509 : : * CRC check will likely fail because we'll be checking the wrong number
4510 : : * of bytes. Complaining about wrong version will probably be more
4511 : : * enlightening than complaining about wrong CRC.
4512 : : */
4513 : :
4514 [ - + - - : 1216 : if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
- - ]
4515 [ # # ]: 0 : ereport(FATAL,
4516 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4517 : : errmsg("database files are incompatible with server"),
4518 : : errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4519 : : " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4520 : : ControlFile->pg_control_version, ControlFile->pg_control_version,
4521 : : PG_CONTROL_VERSION, PG_CONTROL_VERSION),
4522 : : errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4523 : :
4524 [ - + ]: 1216 : if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
4525 [ # # ]: 0 : ereport(FATAL,
4526 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4527 : : errmsg("database files are incompatible with server"),
4528 : : errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4529 : : " but the server was compiled with PG_CONTROL_VERSION %d.",
4530 : : ControlFile->pg_control_version, PG_CONTROL_VERSION),
4531 : : errhint("It looks like you need to initdb.")));
4532 : :
4533 : : /* Now check the CRC. */
4534 : 1216 : INIT_CRC32C(crc);
4535 : 1216 : COMP_CRC32C(crc,
4536 : : ControlFile,
4537 : : offsetof(ControlFileData, crc));
4538 : 1216 : FIN_CRC32C(crc);
4539 : :
4540 [ - + ]: 1216 : if (!EQ_CRC32C(crc, ControlFile->crc))
4541 [ # # ]: 0 : ereport(FATAL,
4542 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4543 : : errmsg("incorrect checksum in control file")));
4544 : :
4545 : : /*
4546 : : * Do compatibility checking immediately. If the database isn't
4547 : : * compatible with the backend executable, we want to abort before we can
4548 : : * possibly do any damage.
4549 : : */
4550 [ - + ]: 1216 : if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
4551 [ # # ]: 0 : ereport(FATAL,
4552 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4553 : : errmsg("database files are incompatible with server"),
4554 : : /* translator: %s is a variable name and %d is its value */
4555 : : errdetail("The database cluster was initialized with %s %d,"
4556 : : " but the server was compiled with %s %d.",
4557 : : "CATALOG_VERSION_NO", ControlFile->catalog_version_no,
4558 : : "CATALOG_VERSION_NO", CATALOG_VERSION_NO),
4559 : : errhint("It looks like you need to initdb.")));
4560 [ - + ]: 1216 : if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4561 [ # # ]: 0 : ereport(FATAL,
4562 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4563 : : errmsg("database files are incompatible with server"),
4564 : : /* translator: %s is a variable name and %d is its value */
4565 : : errdetail("The database cluster was initialized with %s %d,"
4566 : : " but the server was compiled with %s %d.",
4567 : : "MAXALIGN", ControlFile->maxAlign,
4568 : : "MAXALIGN", MAXIMUM_ALIGNOF),
4569 : : errhint("It looks like you need to initdb.")));
4570 [ - + ]: 1216 : if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
4571 [ # # ]: 0 : ereport(FATAL,
4572 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4573 : : errmsg("database files are incompatible with server"),
4574 : : errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4575 : : errhint("It looks like you need to initdb.")));
4576 [ - + ]: 1216 : if (ControlFile->blcksz != BLCKSZ)
4577 [ # # ]: 0 : ereport(FATAL,
4578 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4579 : : errmsg("database files are incompatible with server"),
4580 : : /* translator: %s is a variable name and %d is its value */
4581 : : errdetail("The database cluster was initialized with %s %d,"
4582 : : " but the server was compiled with %s %d.",
4583 : : "BLCKSZ", ControlFile->blcksz,
4584 : : "BLCKSZ", BLCKSZ),
4585 : : errhint("It looks like you need to recompile or initdb.")));
4586 [ - + ]: 1216 : if (ControlFile->relseg_size != RELSEG_SIZE)
4587 [ # # ]: 0 : ereport(FATAL,
4588 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4589 : : errmsg("database files are incompatible with server"),
4590 : : /* translator: %s is a variable name and %d is its value */
4591 : : errdetail("The database cluster was initialized with %s %d,"
4592 : : " but the server was compiled with %s %d.",
4593 : : "RELSEG_SIZE", ControlFile->relseg_size,
4594 : : "RELSEG_SIZE", RELSEG_SIZE),
4595 : : errhint("It looks like you need to recompile or initdb.")));
4596 [ - + ]: 1216 : if (ControlFile->slru_pages_per_segment != SLRU_PAGES_PER_SEGMENT)
4597 [ # # ]: 0 : ereport(FATAL,
4598 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4599 : : errmsg("database files are incompatible with server"),
4600 : : /* translator: %s is a variable name and %d is its value */
4601 : : errdetail("The database cluster was initialized with %s %d,"
4602 : : " but the server was compiled with %s %d.",
4603 : : "SLRU_PAGES_PER_SEGMENT", ControlFile->slru_pages_per_segment,
4604 : : "SLRU_PAGES_PER_SEGMENT", SLRU_PAGES_PER_SEGMENT),
4605 : : errhint("It looks like you need to recompile or initdb.")));
4606 [ - + ]: 1216 : if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4607 [ # # ]: 0 : ereport(FATAL,
4608 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4609 : : errmsg("database files are incompatible with server"),
4610 : : /* translator: %s is a variable name and %d is its value */
4611 : : errdetail("The database cluster was initialized with %s %d,"
4612 : : " but the server was compiled with %s %d.",
4613 : : "XLOG_BLCKSZ", ControlFile->xlog_blcksz,
4614 : : "XLOG_BLCKSZ", XLOG_BLCKSZ),
4615 : : errhint("It looks like you need to recompile or initdb.")));
4616 [ - + ]: 1216 : if (ControlFile->nameDataLen != NAMEDATALEN)
4617 [ # # ]: 0 : ereport(FATAL,
4618 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4619 : : errmsg("database files are incompatible with server"),
4620 : : /* translator: %s is a variable name and %d is its value */
4621 : : errdetail("The database cluster was initialized with %s %d,"
4622 : : " but the server was compiled with %s %d.",
4623 : : "NAMEDATALEN", ControlFile->nameDataLen,
4624 : : "NAMEDATALEN", NAMEDATALEN),
4625 : : errhint("It looks like you need to recompile or initdb.")));
4626 [ - + ]: 1216 : if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4627 [ # # ]: 0 : ereport(FATAL,
4628 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4629 : : errmsg("database files are incompatible with server"),
4630 : : /* translator: %s is a variable name and %d is its value */
4631 : : errdetail("The database cluster was initialized with %s %d,"
4632 : : " but the server was compiled with %s %d.",
4633 : : "INDEX_MAX_KEYS", ControlFile->indexMaxKeys,
4634 : : "INDEX_MAX_KEYS", INDEX_MAX_KEYS),
4635 : : errhint("It looks like you need to recompile or initdb.")));
4636 [ - + ]: 1216 : if (ControlFile->toast_max_chunk_size != TOAST_OID_MAX_CHUNK_SIZE)
4637 [ # # ]: 0 : ereport(FATAL,
4638 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4639 : : errmsg("database files are incompatible with server"),
4640 : : /* translator: %s is a variable name and %d is its value */
4641 : : errdetail("The database cluster was initialized with %s %d,"
4642 : : " but the server was compiled with %s %d.",
4643 : : "TOAST_OID_MAX_CHUNK_SIZE", ControlFile->toast_max_chunk_size,
4644 : : "TOAST_OID_MAX_CHUNK_SIZE", (int) TOAST_OID_MAX_CHUNK_SIZE),
4645 : : errhint("It looks like you need to recompile or initdb.")));
4646 [ - + ]: 1216 : if (ControlFile->loblksize != LOBLKSIZE)
4647 [ # # ]: 0 : ereport(FATAL,
4648 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4649 : : errmsg("database files are incompatible with server"),
4650 : : /* translator: %s is a variable name and %d is its value */
4651 : : errdetail("The database cluster was initialized with %s %d,"
4652 : : " but the server was compiled with %s %d.",
4653 : : "LOBLKSIZE", ControlFile->loblksize,
4654 : : "LOBLKSIZE", (int) LOBLKSIZE),
4655 : : errhint("It looks like you need to recompile or initdb.")));
4656 : :
4657 : : Assert(ControlFile->float8ByVal); /* vestigial, not worth an error msg */
4658 : :
4659 : 1216 : wal_segment_size = ControlFile->xlog_seg_size;
4660 : :
4661 [ + - + - : 1216 : if (!IsValidWalSegSize(wal_segment_size))
+ - - + ]
4662 [ # # ]: 0 : ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4663 : : errmsg_plural("invalid WAL segment size in control file (%d byte)",
4664 : : "invalid WAL segment size in control file (%d bytes)",
4665 : : wal_segment_size,
4666 : : wal_segment_size),
4667 : : errdetail("The WAL segment size must be a power of two between 1 MB and 1 GB.")));
4668 : :
4669 : 1216 : snprintf(wal_segsz_str, sizeof(wal_segsz_str), "%d", wal_segment_size);
4670 : 1216 : SetConfigOption("wal_segment_size", wal_segsz_str, PGC_INTERNAL,
4671 : : PGC_S_DYNAMIC_DEFAULT);
4672 : :
4673 : : /* check and update variables dependent on wal_segment_size */
4674 [ - + ]: 1216 : if (ConvertToXSegs(min_wal_size_mb, wal_segment_size) < 2)
4675 [ # # ]: 0 : ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4676 : : /* translator: both %s are GUC names */
4677 : : errmsg("\"%s\" must be at least twice \"%s\"",
4678 : : "min_wal_size", "wal_segment_size")));
4679 : :
4680 [ - + ]: 1216 : if (ConvertToXSegs(max_wal_size_mb, wal_segment_size) < 2)
4681 [ # # ]: 0 : ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4682 : : /* translator: both %s are GUC names */
4683 : : errmsg("\"%s\" must be at least twice \"%s\"",
4684 : : "max_wal_size", "wal_segment_size")));
4685 : :
4686 : 1216 : UsableBytesInSegment =
4687 : 1216 : (wal_segment_size / XLOG_BLCKSZ * UsableBytesInPage) -
4688 : : (SizeOfXLogLongPHD - SizeOfXLogShortPHD);
4689 : :
4690 : 1216 : CalculateCheckpointSegments();
4691 : 1216 : }
4692 : :
4693 : : /*
4694 : : * Utility wrapper to update the control file. Note that the control
4695 : : * file gets flushed.
4696 : : */
4697 : : static void
4698 : 10487 : UpdateControlFile(void)
4699 : : {
4700 : 10487 : update_controlfile(DataDir, ControlFile, true);
4701 : 10487 : }
4702 : :
4703 : : /*
4704 : : * Returns the unique system identifier from control file.
4705 : : */
4706 : : uint64
4707 : 1728 : GetSystemIdentifier(void)
4708 : : {
4709 : : Assert(ControlFile != NULL);
4710 : 1728 : return ControlFile->system_identifier;
4711 : : }
4712 : :
4713 : : /*
4714 : : * Returns the random nonce from control file.
4715 : : */
4716 : : char *
4717 : 2 : GetMockAuthenticationNonce(void)
4718 : : {
4719 : : Assert(ControlFile != NULL);
4720 : 2 : return ControlFile->mock_authentication_nonce;
4721 : : }
4722 : :
4723 : : /*
4724 : : * DataChecksumsNeedWrite
4725 : : * Returns whether data checksums must be written or not
4726 : : *
4727 : : * Returns true if data checksums are enabled, or are in the process of being
4728 : : * enabled. During "inprogress-on" and "inprogress-off" states checksums must
4729 : : * be written even though they are not verified (see datachecksum_state.c for
4730 : : * a longer discussion).
4731 : : *
4732 : : * This function is intended for callsites which are about to write a data page
4733 : : * to storage, and need to know whether to re-calculate the checksum for the
4734 : : * page header. Calling this function must be performed as close to the write
4735 : : * operation as possible to keep the critical section short.
4736 : : */
4737 : : bool
4738 : 871951 : DataChecksumsNeedWrite(void)
4739 : : {
4740 : 985145 : return (LocalDataChecksumState == PG_DATA_CHECKSUM_VERSION ||
4741 [ + + + + ]: 931748 : LocalDataChecksumState == PG_DATA_CHECKSUM_INPROGRESS_ON ||
4742 [ + + ]: 59797 : LocalDataChecksumState == PG_DATA_CHECKSUM_INPROGRESS_OFF);
4743 : : }
4744 : :
4745 : :
4746 : : bool
4747 : 12 : DataChecksumsOff(void)
4748 : : {
4749 : : bool ret;
4750 : :
4751 : 12 : SpinLockAcquire(&XLogCtl->info_lck);
4752 : 12 : ret = (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_OFF);
4753 : 12 : SpinLockRelease(&XLogCtl->info_lck);
4754 : :
4755 : 12 : return ret;
4756 : : }
4757 : :
4758 : : bool
4759 : 18 : DataChecksumsOn(void)
4760 : : {
4761 : : bool ret;
4762 : :
4763 : 18 : SpinLockAcquire(&XLogCtl->info_lck);
4764 : 18 : ret = (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_VERSION);
4765 : 18 : SpinLockRelease(&XLogCtl->info_lck);
4766 : :
4767 : 18 : return ret;
4768 : : }
4769 : :
4770 : : bool
4771 : 338 : DataChecksumsInProgressOn(void)
4772 : : {
4773 : : bool ret;
4774 : :
4775 : 338 : SpinLockAcquire(&XLogCtl->info_lck);
4776 : 338 : ret = (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_ON);
4777 : 338 : SpinLockRelease(&XLogCtl->info_lck);
4778 : :
4779 : 338 : return ret;
4780 : : }
4781 : :
4782 : : /*
4783 : : * DataChecksumsNeedVerify
4784 : : * Returns whether data checksums must be verified or not
4785 : : *
4786 : : * Data checksums are only verified if they are fully enabled in the cluster.
4787 : : * During the "inprogress-on" and "inprogress-off" states they are only
4788 : : * updated, not verified (see datachecksum_state.c for a longer discussion).
4789 : : *
4790 : : * This function is intended for callsites which have read data and are about
4791 : : * to perform checksum validation based on the result of this. Calling this
4792 : : * function must be performed as close to the validation call as possible to
4793 : : * keep the critical section short. This is in order to protect against time of
4794 : : * check/time of use situations around data checksum validation.
4795 : : */
4796 : : bool
4797 : 2778147 : DataChecksumsNeedVerify(void)
4798 : : {
4799 : 2778147 : return (LocalDataChecksumState == PG_DATA_CHECKSUM_VERSION);
4800 : : }
4801 : :
4802 : : /*
4803 : : * GetLastChecksumChangeRecPtr
4804 : : * Returns the location of the last data checksum state change
4805 : : *
4806 : : * Offline state changes by pg_checksums leave no trace here; callers must
4807 : : * also inspect the current state.
4808 : : *
4809 : : * No barrier semantics are needed: pages reach disk under a new checksum
4810 : : * state only after their writer absorbed the procsignal barrier for the
4811 : : * change, which is emitted after the new location became visible.
4812 : : */
4813 : : XLogRecPtr
4814 : 1416493 : GetLastChecksumChangeRecPtr(void)
4815 : : {
4816 : 1416493 : return pg_atomic_read_u64(&XLogCtl->lastChecksumChangeRecPtr);
4817 : : }
4818 : :
4819 : : /*
4820 : : * SetDataChecksumsOnInProgress
4821 : : * Sets the data checksum state to "inprogress-on" to enable checksums
4822 : : *
4823 : : * To start the process of enabling data checksums in a running cluster the
4824 : : * data_checksum_version state must be changed to "inprogress-on". See
4825 : : * SetDataChecksumsOn below for a description on how this state change works.
4826 : : * This function blocks until all backends in the cluster have acknowledged the
4827 : : * state transition.
4828 : : */
4829 : : void
4830 : 16 : SetDataChecksumsOnInProgress(void)
4831 : : {
4832 : : uint64 barrier;
4833 : : XLogRecPtr recptr;
4834 : :
4835 : : /*
4836 : : * The state transition is performed in a critical section with
4837 : : * checkpoints held off to provide crash safety.
4838 : : */
4839 : 16 : START_CRIT_SECTION();
4840 : 16 : MyProc->delayChkptFlags |= DELAY_CHKPT_START;
4841 : :
4842 : 16 : recptr = XLogChecksums(PG_DATA_CHECKSUM_INPROGRESS_ON);
4843 : :
4844 : 16 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
4845 : 16 : ControlFile->data_checksum_version = PG_DATA_CHECKSUM_INPROGRESS_ON;
4846 : 16 : ControlFile->data_checksum_lsn = recptr;
4847 : 16 : ControlFile->data_checksum_is_local = false;
4848 : 16 : UpdateControlFile();
4849 : 16 : LWLockRelease(ControlFileLock);
4850 : :
4851 : 16 : barrier = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_INPROGRESS_ON);
4852 : :
4853 : 16 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
4854 : 16 : END_CRIT_SECTION();
4855 : :
4856 : 16 : WaitForProcSignalBarrier(barrier);
4857 : 16 : }
4858 : :
4859 : : /*
4860 : : * SetDataChecksumsOn
4861 : : * Set data checksums state to 'on' cluster-wide
4862 : : *
4863 : : * Enabling data checksums is performed using two barriers, the first one to
4864 : : * set the state to "inprogress-on" (done by SetDataChecksumsOnInProgress())
4865 : : * and the second one to set the state to "on" (done here). Below is a short
4866 : : * description of the processing, a more detailed write-up can be found in
4867 : : * datachecksum_state.c.
4868 : : *
4869 : : * To start the process of enabling data checksums in a running cluster the
4870 : : * data_checksum_version state must be changed to "inprogress-on". This state
4871 : : * requires data checksums to be written but not verified. This ensures that
4872 : : * all data pages can be checksummed without the risk of false negatives in
4873 : : * validation during the process. When all existing pages are guaranteed to
4874 : : * have checksums, and all new pages will be initiated with checksums, the
4875 : : * state can be changed to "on". Once the state is "on" checksums will be both
4876 : : * written and verified.
4877 : : *
4878 : : * This function blocks until all backends in the cluster have acknowledged the
4879 : : * state transition.
4880 : : */
4881 : : void
4882 : 12 : SetDataChecksumsOn(void)
4883 : : {
4884 : : uint64 barrier;
4885 : : bool persist;
4886 : : XLogRecPtr recptr;
4887 : :
4888 : 12 : SpinLockAcquire(&XLogCtl->info_lck);
4889 : :
4890 : : /*
4891 : : * The only allowed state transition to "on" is from "inprogress-on" since
4892 : : * that state ensures that all pages will have data checksums written. Any
4893 : : * other attempted state transition is likely due to a programmer error.
4894 : : */
4895 [ - + ]: 12 : if (XLogCtl->data_checksum_version != PG_DATA_CHECKSUM_INPROGRESS_ON)
4896 : : {
4897 : 0 : SpinLockRelease(&XLogCtl->info_lck);
4898 [ # # ]: 0 : elog(WARNING,
4899 : : "cannot set data checksums to \"on\", current state is not \"inprogress-on\", disabling");
4900 : 0 : SetDataChecksumsOff();
4901 : 0 : return;
4902 : : }
4903 : :
4904 : 12 : SpinLockRelease(&XLogCtl->info_lck);
4905 : :
4906 : 12 : INJECTION_POINT("datachecksums-enable-checksums-delay", NULL);
4907 : 12 : INJECTION_POINT_LOAD("datachecksums-on-before-publish");
4908 : 12 : START_CRIT_SECTION();
4909 : 12 : MyProc->delayChkptFlags |= DELAY_CHKPT_START;
4910 : :
4911 : 12 : recptr = XLogChecksums(PG_DATA_CHECKSUM_VERSION);
4912 : :
4913 : 12 : barrier = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_ON);
4914 : :
4915 : 12 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
4916 : 12 : END_CRIT_SECTION();
4917 : :
4918 : 12 : INJECTION_POINT("datachecksums-on-before-checkpoint", NULL);
4919 : :
4920 : 12 : RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_FAST);
4921 : :
4922 : 12 : INJECTION_POINT("datachecksums-on-after-checkpoint", NULL);
4923 : :
4924 : : /*
4925 : : * Update the controlfile now once all pages are flushed to disk via the
4926 : : * checkpoint. Only update in case the lsn of the checksum record is the
4927 : : * record stored above, else the checkpoint has already updated the
4928 : : * control file. Comparing the watermark and not the state covers the
4929 : : * (unlikely) scenario that checksums went on->off->on in between.
4930 : : */
4931 : 12 : SpinLockAcquire(&XLogCtl->info_lck);
4932 : 12 : persist = (XLogCtl->data_checksum_lsn == recptr);
4933 : 12 : SpinLockRelease(&XLogCtl->info_lck);
4934 : :
4935 [ + - ]: 12 : if (persist)
4936 : : {
4937 : 12 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
4938 : 12 : ControlFile->data_checksum_version = PG_DATA_CHECKSUM_VERSION;
4939 : 12 : ControlFile->data_checksum_lsn = recptr;
4940 : 12 : ControlFile->data_checksum_is_local = false;
4941 : 12 : UpdateControlFile();
4942 : 12 : LWLockRelease(ControlFileLock);
4943 : : }
4944 : :
4945 : 12 : WaitForProcSignalBarrier(barrier);
4946 : : }
4947 : :
4948 : : /*
4949 : : * SetDataChecksumsOff
4950 : : * Disables data checksums cluster-wide
4951 : : *
4952 : : * Disabling data checksums must be performed with two sets of barriers, each
4953 : : * carrying a different state. The state is first set to "inprogress-off"
4954 : : * during which checksums are still written but not verified. This ensures that
4955 : : * backends which have yet to observe the state change from "on" won't get
4956 : : * validation errors on concurrently modified pages. Once all backends have
4957 : : * changed to "inprogress-off", the barrier for moving to "off" can be emitted.
4958 : : * This function blocks until all backends in the cluster have acknowledged the
4959 : : * state transition.
4960 : : */
4961 : : void
4962 : 12 : SetDataChecksumsOff(void)
4963 : : {
4964 : : uint64 barrier;
4965 : : XLogRecPtr recptr;
4966 : :
4967 : 12 : SpinLockAcquire(&XLogCtl->info_lck);
4968 : :
4969 : : /* If data checksums are already disabled there is nothing to do */
4970 [ - + ]: 12 : if (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_OFF)
4971 : : {
4972 : 0 : SpinLockRelease(&XLogCtl->info_lck);
4973 : 0 : return;
4974 : : }
4975 : :
4976 : : /*
4977 : : * If data checksums are currently enabled, or in the process of being
4978 : : * enabled, we first transition to the "inprogress-off" state during which
4979 : : * backends continue to write checksums without verifying them. When all
4980 : : * backends are in "inprogress-off" the next transition to "off" can be
4981 : : * performed, after which all data checksum processing is disabled.
4982 : : */
4983 [ + + ]: 12 : if (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_VERSION ||
4984 [ + - ]: 4 : XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_ON)
4985 : : {
4986 : 12 : SpinLockRelease(&XLogCtl->info_lck);
4987 : :
4988 : 12 : START_CRIT_SECTION();
4989 : 12 : MyProc->delayChkptFlags |= DELAY_CHKPT_START;
4990 : :
4991 : 12 : recptr = XLogChecksums(PG_DATA_CHECKSUM_INPROGRESS_OFF);
4992 : :
4993 : 12 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
4994 : 12 : ControlFile->data_checksum_version = PG_DATA_CHECKSUM_INPROGRESS_OFF;
4995 : 12 : ControlFile->data_checksum_lsn = recptr;
4996 : 12 : ControlFile->data_checksum_is_local = false;
4997 : 12 : UpdateControlFile();
4998 : 12 : LWLockRelease(ControlFileLock);
4999 : :
5000 : 12 : barrier = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_INPROGRESS_OFF);
5001 : :
5002 : 12 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
5003 : 12 : END_CRIT_SECTION();
5004 : :
5005 : 12 : RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_FAST);
5006 : 12 : WaitForProcSignalBarrier(barrier);
5007 : :
5008 : : /*
5009 : : * At this point we know that no backends are verifying data checksums
5010 : : * during reading. Next, we can safely move to state "off" to also
5011 : : * stop writing checksums.
5012 : : */
5013 : : }
5014 : : else
5015 : : {
5016 : : /*
5017 : : * Ending up here implies that the checksums state is "inprogress-off"
5018 : : * and we can transition directly to "off" from there.
5019 : : */
5020 : 0 : SpinLockRelease(&XLogCtl->info_lck);
5021 : : }
5022 : :
5023 : 12 : START_CRIT_SECTION();
5024 : : /* Ensure that we don't incur a checkpoint during disabling checksums */
5025 : 12 : MyProc->delayChkptFlags |= DELAY_CHKPT_START;
5026 : :
5027 : 12 : recptr = XLogChecksums(PG_DATA_CHECKSUM_OFF);
5028 : :
5029 : 12 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5030 : 12 : ControlFile->data_checksum_version = PG_DATA_CHECKSUM_OFF;
5031 : 12 : ControlFile->data_checksum_lsn = recptr;
5032 : 12 : ControlFile->data_checksum_is_local = false;
5033 : 12 : UpdateControlFile();
5034 : 12 : LWLockRelease(ControlFileLock);
5035 : :
5036 : 12 : barrier = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_OFF);
5037 : :
5038 : 12 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
5039 : 12 : END_CRIT_SECTION();
5040 : :
5041 : 12 : RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_FAST);
5042 : 12 : WaitForProcSignalBarrier(barrier);
5043 : : }
5044 : :
5045 : : /*
5046 : : * InitLocalDataChecksumState
5047 : : *
5048 : : * Set up backend local caches of controldata variables which may change at
5049 : : * any point during runtime and thus require special cased locking. So far
5050 : : * this only applies to data_checksum_version, but it's intended to be general
5051 : : * purpose enough to handle future cases.
5052 : : */
5053 : : void
5054 : 25739 : InitLocalDataChecksumState(void)
5055 : : {
5056 : : Assert(InterruptHoldoffCount > 0);
5057 : 25739 : SpinLockAcquire(&XLogCtl->info_lck);
5058 : 25739 : SetLocalDataChecksumState(XLogCtl->data_checksum_version);
5059 : 25739 : SpinLockRelease(&XLogCtl->info_lck);
5060 : 25739 : }
5061 : :
5062 : : void
5063 : 28679 : SetLocalDataChecksumState(uint32 data_checksum_version)
5064 : : {
5065 : 28679 : LocalDataChecksumState = data_checksum_version;
5066 : :
5067 : 28679 : data_checksums = data_checksum_version;
5068 : 28679 : }
5069 : :
5070 : : /*
5071 : : * CheckReplayedDataChecksumState
5072 : : * Cross-check the data checksum state carried by a replayed checkpoint
5073 : : * record against the state of this node.
5074 : : *
5075 : : * The state in the replayed checkpoint is the state of the node which wrote
5076 : : * the WAL, which may differ from the state at this node replaying the WAL.
5077 : : * The mismatch is possible when an offline transition was used on a subset
5078 : : * of nodes in a replication setup. Since the offline transition is not WAL
5079 : : * logged it is local to the node.
5080 : : *
5081 : : * Archive recovery can see a lasting mismatch, since the WAL and the control
5082 : : * file can come from different nodes or different points in time. A mismatch
5083 : : * during crash recovery implies replay from a restartpoint earlier than an
5084 : : * applied XLOG2_CHECKSUMS record. The state will be unified during replay.
5085 : : */
5086 : : static void
5087 : 690 : CheckReplayedDataChecksumState(uint32 replayed_state)
5088 : : {
5089 : : /*
5090 : : * Warn once per remote value, so a lasting mismatch does not flood the
5091 : : * log. Matching states re-arm the warning. Backend-local state is
5092 : : * enough: replay only runs in the startup process, and restarting it
5093 : : * re-arms as well.
5094 : : */
5095 : : static uint32 last_warned_version = NO_WARNING_ISSUED;
5096 : : uint32 local_state;
5097 : :
5098 [ + + ]: 690 : if (!ArchiveRecoveryRequested)
5099 : 28 : return;
5100 : :
5101 : : /*
5102 : : * Re-replayed WAL below the consistency point was already cross-checked
5103 : : * before minRecoveryPoint was last persisted, and the persisted state can
5104 : : * legitimately be newer than what checkpoint records there carry:
5105 : : * XLOG2_CHECKSUMS replay persists most states ahead of the restartpoint
5106 : : * horizon. In particular the checkpoint record recovery restarts from is
5107 : : * such a re-replay.
5108 : : */
5109 [ + + ]: 662 : if (!reachedConsistency)
5110 : 34 : return;
5111 : :
5112 : 628 : SpinLockAcquire(&XLogCtl->info_lck);
5113 : 628 : local_state = XLogCtl->data_checksum_version;
5114 : 628 : SpinLockRelease(&XLogCtl->info_lck);
5115 : :
5116 [ + + ]: 628 : if (replayed_state == local_state)
5117 : : {
5118 : : /*
5119 : : * Report convergence if this process warned before. Nothing else
5120 : : * tells the operator that running pg_checksums on the other nodes, or
5121 : : * a rebuild, took effect.
5122 : : */
5123 [ - + ]: 626 : if (last_warned_version != NO_WARNING_ISSUED)
5124 [ # # ]: 0 : ereport(LOG,
5125 : : errmsg("data checksum state \"%s\" of this node now agrees with the replayed WAL",
5126 : : get_checksum_state_string(local_state)));
5127 : :
5128 : 626 : last_warned_version = NO_WARNING_ISSUED;
5129 : 626 : return;
5130 : : }
5131 : :
5132 : : /* the nodes legitimately differ while an online transition runs */
5133 [ + - + - ]: 2 : if (replayed_state == PG_DATA_CHECKSUM_INPROGRESS_ON ||
5134 [ + - ]: 2 : replayed_state == PG_DATA_CHECKSUM_INPROGRESS_OFF ||
5135 [ - + ]: 2 : local_state == PG_DATA_CHECKSUM_INPROGRESS_ON ||
5136 : : local_state == PG_DATA_CHECKSUM_INPROGRESS_OFF)
5137 : 0 : return;
5138 : :
5139 [ + + ]: 2 : if (replayed_state == last_warned_version)
5140 : 1 : return;
5141 : 1 : last_warned_version = replayed_state;
5142 : :
5143 [ + - ]: 1 : ereport(WARNING,
5144 : : errmsg("data checksum state \"%s\" of this node does not match the state \"%s\" in the replayed WAL",
5145 : : get_checksum_state_string(local_state),
5146 : : get_checksum_state_string(replayed_state)),
5147 : : errdetail("The data checksum state may have been changed with pg_checksums on another node."),
5148 : : errhint("Apply the same change with pg_checksums on the primary and all standby servers, or rebuild this server from a base backup."));
5149 : : }
5150 : :
5151 : : /*
5152 : : * AdoptReplayedDataChecksumState
5153 : : * Adopt the data checksum state at the redo point of backup label
5154 : : * recovery.
5155 : : *
5156 : : * The state is written to the control file immediately so that a crash before
5157 : : * the first restartpoint does not resurrect the state copied with the backup.
5158 : : * A crash at this point restarts from the same redo point, so the control file
5159 : : * does not run ahead of the replay position.
5160 : : *
5161 : : * lsn is the location of the checkpoint-family record the state was taken from
5162 : : * and becomes the new watermark if the state changed or the copied watermark
5163 : : * is newer. Even when the state matches, a newer watermark must be reset so
5164 : : * that transitions between the redo point and that watermark are replayed.
5165 : : * An older watermark can be kept if the state is unchanged, since replay
5166 : : * never revisits records below the redo point.
5167 : : */
5168 : : static void
5169 : 91 : AdoptReplayedDataChecksumState(uint32 new_version, XLogRecPtr lsn)
5170 : : {
5171 : 91 : bool changed = false;
5172 : :
5173 : 91 : SpinLockAcquire(&XLogCtl->info_lck);
5174 [ - + ]: 91 : if (XLogCtl->data_checksum_version != new_version)
5175 : : {
5176 : 0 : XLogCtl->data_checksum_version = new_version;
5177 : 0 : XLogCtl->data_checksum_lsn = lsn;
5178 : 0 : XLogCtl->data_checksum_is_local = false;
5179 : 0 : SetLocalDataChecksumState(new_version);
5180 : 0 : changed = true;
5181 : : }
5182 : 91 : SpinLockRelease(&XLogCtl->info_lck);
5183 : :
5184 [ + - ]: 91 : if (!changed)
5185 : 91 : return;
5186 : :
5187 : 0 : EmitAndWaitDataChecksumsBarrier(new_version);
5188 : :
5189 : 0 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5190 : 0 : ControlFile->data_checksum_version = new_version;
5191 : 0 : ControlFile->data_checksum_lsn = lsn;
5192 : 0 : ControlFile->data_checksum_is_local = false;
5193 : 0 : UpdateControlFile();
5194 : 0 : LWLockRelease(ControlFileLock);
5195 : : }
5196 : :
5197 : : /* guc hook */
5198 : : const char *
5199 : 2046 : show_data_checksums(void)
5200 : : {
5201 : 2046 : return get_checksum_state_string(LocalDataChecksumState);
5202 : : }
5203 : :
5204 : : /*
5205 : : * Return true if the cluster was initialized on a platform where the
5206 : : * default signedness of char is "signed". This function exists for code
5207 : : * that deals with pre-v18 data files that store data sorted by the 'char'
5208 : : * type on disk (e.g., GIN and GiST indexes). See the comments in
5209 : : * WriteControlFile() for details.
5210 : : */
5211 : : bool
5212 : 89903 : GetDefaultCharSignedness(void)
5213 : : {
5214 : 89903 : return ControlFile->default_char_signedness;
5215 : : }
5216 : :
5217 : : /*
5218 : : * Returns a fake LSN for unlogged relations.
5219 : : *
5220 : : * Each call generates an LSN that is greater than any previous value
5221 : : * returned. The current counter value is saved and restored across clean
5222 : : * shutdowns, but like unlogged relations, does not survive a crash. This can
5223 : : * be used in lieu of real LSN values returned by XLogInsert, if you need an
5224 : : * LSN-like increasing sequence of numbers without writing any WAL.
5225 : : */
5226 : : XLogRecPtr
5227 : 202668 : GetFakeLSNForUnloggedRel(void)
5228 : : {
5229 : 202668 : return pg_atomic_fetch_add_u64(&XLogCtl->unloggedLSN, 1);
5230 : : }
5231 : :
5232 : : /*
5233 : : * Auto-tune the number of XLOG buffers.
5234 : : *
5235 : : * The preferred setting for wal_buffers is about 3% of shared_buffers, with
5236 : : * a maximum of one XLOG segment (there is little reason to think that more
5237 : : * is helpful, at least so long as we force an fsync when switching log files)
5238 : : * and a minimum of 8 blocks (which was the default value prior to PostgreSQL
5239 : : * 9.1, when auto-tuning was added).
5240 : : *
5241 : : * This should not be called until NBuffers has received its final value.
5242 : : */
5243 : : static int
5244 : 1314 : XLOGChooseNumBuffers(void)
5245 : : {
5246 : : int xbuffers;
5247 : :
5248 : 1314 : xbuffers = NBuffers / 32;
5249 [ + + ]: 1314 : if (xbuffers > (wal_segment_size / XLOG_BLCKSZ))
5250 : 28 : xbuffers = (wal_segment_size / XLOG_BLCKSZ);
5251 [ + + ]: 1314 : if (xbuffers < 8)
5252 : 515 : xbuffers = 8;
5253 : 1314 : return xbuffers;
5254 : : }
5255 : :
5256 : : /*
5257 : : * GUC check_hook for wal_buffers
5258 : : */
5259 : : bool
5260 : 2677 : check_wal_buffers(int *newval, void **extra, GucSource source)
5261 : : {
5262 : : /*
5263 : : * -1 indicates a request for auto-tune.
5264 : : */
5265 [ + + ]: 2677 : if (*newval == -1)
5266 : : {
5267 : : /*
5268 : : * If we haven't yet changed the boot_val default of -1, just let it
5269 : : * be. We'll fix it when XLOGShmemRequest is called.
5270 : : */
5271 [ + - ]: 1362 : if (XLOGbuffers == -1)
5272 : 1362 : return true;
5273 : :
5274 : : /* Otherwise, substitute the auto-tune value */
5275 : 0 : *newval = XLOGChooseNumBuffers();
5276 : : }
5277 : :
5278 : : /*
5279 : : * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
5280 : : * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
5281 : : * the case, we just silently treat such values as a request for the
5282 : : * minimum. (We could throw an error instead, but that doesn't seem very
5283 : : * helpful.)
5284 : : */
5285 [ - + ]: 1315 : if (*newval < 4)
5286 : 0 : *newval = 4;
5287 : :
5288 : 1315 : return true;
5289 : : }
5290 : :
5291 : : /*
5292 : : * GUC check_hook for wal_consistency_checking
5293 : : */
5294 : : bool
5295 : 2338 : check_wal_consistency_checking(char **newval, void **extra, GucSource source)
5296 : : {
5297 : : char *rawstring;
5298 : : List *elemlist;
5299 : : ListCell *l;
5300 : : bool newwalconsistency[RM_MAX_ID + 1];
5301 : :
5302 : : /* Initialize the array */
5303 [ + - + - : 77154 : MemSet(newwalconsistency, 0, (RM_MAX_ID + 1) * sizeof(bool));
+ - + - +
+ ]
5304 : :
5305 : : /* Need a modifiable copy of string */
5306 : 2338 : rawstring = pstrdup(*newval);
5307 : :
5308 : : /* Parse string into list of identifiers */
5309 [ - + ]: 2338 : if (!SplitIdentifierString(rawstring, ',', &elemlist))
5310 : : {
5311 : : /* syntax error in list */
5312 : 0 : GUC_check_errdetail("List syntax is invalid.");
5313 : 0 : pfree(rawstring);
5314 : 0 : list_free(elemlist);
5315 : 0 : return false;
5316 : : }
5317 : :
5318 [ + + + + : 2829 : foreach(l, elemlist)
+ + ]
5319 : : {
5320 : 491 : char *tok = (char *) lfirst(l);
5321 : : int rmid;
5322 : :
5323 : : /* Check for 'all'. */
5324 [ + + ]: 491 : if (pg_strcasecmp(tok, "all") == 0)
5325 : : {
5326 [ + + ]: 125673 : for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5327 [ + + + + ]: 125184 : if (RmgrIdExists(rmid) && GetRmgr(rmid).rm_mask != NULL)
5328 : 4890 : newwalconsistency[rmid] = true;
5329 : : }
5330 : : else
5331 : : {
5332 : : /* Check if the token matches any known resource manager. */
5333 : 2 : bool found = false;
5334 : :
5335 [ + - ]: 36 : for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5336 : : {
5337 [ + - + + : 54 : if (RmgrIdExists(rmid) && GetRmgr(rmid).rm_mask != NULL &&
+ + ]
5338 : 18 : pg_strcasecmp(tok, GetRmgr(rmid).rm_name) == 0)
5339 : : {
5340 : 2 : newwalconsistency[rmid] = true;
5341 : 2 : found = true;
5342 : 2 : break;
5343 : : }
5344 : : }
5345 [ - + ]: 2 : if (!found)
5346 : : {
5347 : : /*
5348 : : * During startup, it might be a not-yet-loaded custom
5349 : : * resource manager. Defer checking until
5350 : : * InitializeWalConsistencyChecking().
5351 : : */
5352 [ # # ]: 0 : if (!process_shared_preload_libraries_done)
5353 : : {
5354 : 0 : check_wal_consistency_checking_deferred = true;
5355 : : }
5356 : : else
5357 : : {
5358 : 0 : GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
5359 : 0 : pfree(rawstring);
5360 : 0 : list_free(elemlist);
5361 : 0 : return false;
5362 : : }
5363 : : }
5364 : : }
5365 : : }
5366 : :
5367 : 2338 : pfree(rawstring);
5368 : 2338 : list_free(elemlist);
5369 : :
5370 : : /* assign new value */
5371 : 2338 : *extra = guc_malloc(LOG, (RM_MAX_ID + 1) * sizeof(bool));
5372 [ - + ]: 2338 : if (!*extra)
5373 : 0 : return false;
5374 : 2338 : memcpy(*extra, newwalconsistency, (RM_MAX_ID + 1) * sizeof(bool));
5375 : 2338 : return true;
5376 : : }
5377 : :
5378 : : /*
5379 : : * GUC assign_hook for wal_consistency_checking
5380 : : */
5381 : : void
5382 : 2337 : assign_wal_consistency_checking(const char *newval, void *extra)
5383 : : {
5384 : : /*
5385 : : * If some checks were deferred, it's possible that the checks will fail
5386 : : * later during InitializeWalConsistencyChecking(). But in that case, the
5387 : : * postmaster will exit anyway, so it's safe to proceed with the
5388 : : * assignment.
5389 : : *
5390 : : * Any built-in resource managers specified are assigned immediately,
5391 : : * which affects WAL created before shared_preload_libraries are
5392 : : * processed. Any custom resource managers specified won't be assigned
5393 : : * until after shared_preload_libraries are processed, but that's OK
5394 : : * because WAL for a custom resource manager can't be written before the
5395 : : * module is loaded anyway.
5396 : : */
5397 : 2337 : wal_consistency_checking = extra;
5398 : 2337 : }
5399 : :
5400 : : /*
5401 : : * InitializeWalConsistencyChecking: run after loading custom resource managers
5402 : : *
5403 : : * If any unknown resource managers were specified in the
5404 : : * wal_consistency_checking GUC, processing was deferred. Now that
5405 : : * shared_preload_libraries have been loaded, process wal_consistency_checking
5406 : : * again.
5407 : : */
5408 : : void
5409 : 1137 : InitializeWalConsistencyChecking(void)
5410 : : {
5411 : : Assert(process_shared_preload_libraries_done);
5412 : :
5413 [ - + ]: 1137 : if (check_wal_consistency_checking_deferred)
5414 : : {
5415 : : struct config_generic *guc;
5416 : :
5417 : 0 : guc = find_option("wal_consistency_checking", false, false, ERROR);
5418 : :
5419 : 0 : check_wal_consistency_checking_deferred = false;
5420 : :
5421 : 0 : set_config_option_ext("wal_consistency_checking",
5422 : : wal_consistency_checking_string,
5423 : : guc->scontext, guc->source, guc->srole,
5424 : : GUC_ACTION_SET, true, ERROR, false);
5425 : :
5426 : : /* checking should not be deferred again */
5427 : : Assert(!check_wal_consistency_checking_deferred);
5428 : : }
5429 : 1137 : }
5430 : :
5431 : : /*
5432 : : * GUC show_hook for archive_command
5433 : : */
5434 : : const char *
5435 : 2042 : show_archive_command(void)
5436 : : {
5437 [ + + ]: 2042 : if (XLogArchivingActive())
5438 : 145 : return XLogArchiveCommand;
5439 : : else
5440 : 1897 : return "(disabled)";
5441 : : }
5442 : :
5443 : : /*
5444 : : * GUC show_hook for in_hot_standby
5445 : : */
5446 : : const char *
5447 : 18556 : show_in_hot_standby(void)
5448 : : {
5449 : : /*
5450 : : * We display the actual state based on shared memory, so that this GUC
5451 : : * reports up-to-date state if examined intra-query. The underlying
5452 : : * variable (in_hot_standby_guc) changes only when we transmit a new value
5453 : : * to the client.
5454 : : */
5455 [ + + ]: 18556 : return RecoveryInProgress() ? "on" : "off";
5456 : : }
5457 : :
5458 : : /*
5459 : : * GUC show_hook for effective_wal_level
5460 : : */
5461 : : const char *
5462 : 2094 : show_effective_wal_level(void)
5463 : : {
5464 [ + + ]: 2094 : if (wal_level == WAL_LEVEL_MINIMAL)
5465 : 285 : return "minimal";
5466 : :
5467 : : /*
5468 : : * During recovery, effective_wal_level reflects the primary's
5469 : : * configuration rather than the local wal_level value.
5470 : : */
5471 [ + + ]: 1809 : if (RecoveryInProgress())
5472 [ + + ]: 43 : return IsXLogLogicalInfoEnabled() ? "logical" : "replica";
5473 : :
5474 [ + + + + ]: 1766 : return XLogLogicalInfoActive() ? "logical" : "replica";
5475 : : }
5476 : :
5477 : : /*
5478 : : * Read the control file, set respective GUCs.
5479 : : *
5480 : : * This is to be called during startup, including a crash recovery cycle,
5481 : : * unless in bootstrap mode, where no control file yet exists. As there's no
5482 : : * usable shared memory yet (its sizing can depend on the contents of the
5483 : : * control file!), first store the contents in local memory. XLOGShmemInit()
5484 : : * will then copy it to shared memory later.
5485 : : *
5486 : : * reset just controls whether previous contents are to be expected (in the
5487 : : * reset case, there's a dangling pointer into old shared memory), or not.
5488 : : */
5489 : : void
5490 : 1157 : LocalProcessControlFile(bool reset)
5491 : : {
5492 : : Assert(reset || ControlFile == NULL);
5493 : 1157 : LocalControlFile = palloc_object(ControlFileData);
5494 : 1157 : ControlFile = LocalControlFile;
5495 : 1157 : ReadControlFile();
5496 : 1157 : SetLocalDataChecksumState(ControlFile->data_checksum_version);
5497 : 1157 : }
5498 : :
5499 : : /*
5500 : : * Get the wal_level from the control file. For a standby, this value should be
5501 : : * considered as its active wal_level, because it may be different from what
5502 : : * was originally configured on standby.
5503 : : */
5504 : : WalLevel
5505 : 0 : GetActiveWalLevelOnStandby(void)
5506 : : {
5507 : 0 : return ControlFile->wal_level;
5508 : : }
5509 : :
5510 : : /*
5511 : : * Register shared memory for XLOG.
5512 : : */
5513 : : static void
5514 : 1321 : XLOGShmemRequest(void *arg)
5515 : : {
5516 : : Size size;
5517 : :
5518 : : /*
5519 : : * If the value of wal_buffers is -1, use the preferred auto-tune value.
5520 : : * This isn't an amazingly clean place to do this, but we must wait till
5521 : : * NBuffers has received its final value, and must do it before using the
5522 : : * value of XLOGbuffers to do anything important.
5523 : : *
5524 : : * We prefer to report this value's source as PGC_S_DYNAMIC_DEFAULT.
5525 : : * However, if the DBA explicitly set wal_buffers = -1 in the config file,
5526 : : * then PGC_S_DYNAMIC_DEFAULT will fail to override that and we must force
5527 : : * the matter with PGC_S_OVERRIDE.
5528 : : */
5529 [ + + ]: 1321 : if (XLOGbuffers == -1)
5530 : : {
5531 : : char buf[32];
5532 : :
5533 : 1314 : snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
5534 : 1314 : SetConfigOption("wal_buffers", buf, PGC_POSTMASTER,
5535 : : PGC_S_DYNAMIC_DEFAULT);
5536 [ - + ]: 1314 : if (XLOGbuffers == -1) /* failed to apply it? */
5537 : 0 : SetConfigOption("wal_buffers", buf, PGC_POSTMASTER,
5538 : : PGC_S_OVERRIDE);
5539 : : }
5540 : : Assert(XLOGbuffers > 0);
5541 : :
5542 : : /* XLogCtl */
5543 : 1321 : size = sizeof(XLogCtlData);
5544 : :
5545 : : /* WAL insertion locks, plus alignment */
5546 : 1321 : size = add_size(size, mul_size(sizeof(WALInsertLockPadded), NUM_XLOGINSERT_LOCKS + 1));
5547 : : /* xlblocks array */
5548 : 1321 : size = add_size(size, mul_size(sizeof(pg_atomic_uint64), XLOGbuffers));
5549 : : /* extra alignment padding for XLOG I/O buffers */
5550 : 1321 : size = add_size(size, Max(XLOG_BLCKSZ, PG_IO_ALIGN_SIZE));
5551 : : /* and the buffers themselves */
5552 : 1321 : size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
5553 : :
5554 : 1321 : ShmemRequestStruct(.name = "XLOG Ctl",
5555 : : .size = size,
5556 : : .ptr = (void **) &XLogCtl,
5557 : : );
5558 : 1321 : ShmemRequestStruct(.name = "Control File",
5559 : : .size = sizeof(ControlFileData),
5560 : : .ptr = (void **) &ControlFile,
5561 : : );
5562 : 1321 : }
5563 : :
5564 : : /*
5565 : : * XLOGShmemInit - initialize the XLogCtl shared memory area.
5566 : : */
5567 : : static void
5568 : 1317 : XLOGShmemInit(void *arg)
5569 : : {
5570 : : char *allocptr;
5571 : : int i;
5572 : :
5573 : 1317 : memset(XLogCtl, 0, sizeof(XLogCtlData));
5574 : :
5575 : : /*
5576 : : * Already have read control file locally, unless in bootstrap mode. Move
5577 : : * contents into shared memory.
5578 : : */
5579 [ + + ]: 1317 : if (LocalControlFile)
5580 : : {
5581 : 1140 : memcpy(ControlFile, LocalControlFile, sizeof(ControlFileData));
5582 : 1140 : pfree(LocalControlFile);
5583 : 1140 : LocalControlFile = NULL;
5584 : : }
5585 : :
5586 : : /*
5587 : : * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
5588 : : * multiple of the alignment for same, so no extra alignment padding is
5589 : : * needed here.
5590 : : */
5591 : 1317 : allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
5592 : 1317 : XLogCtl->xlblocks = (pg_atomic_uint64 *) allocptr;
5593 : 1317 : allocptr += sizeof(pg_atomic_uint64) * XLOGbuffers;
5594 : :
5595 [ + + ]: 374406 : for (i = 0; i < XLOGbuffers; i++)
5596 : : {
5597 : 373089 : pg_atomic_init_u64(&XLogCtl->xlblocks[i], InvalidXLogRecPtr);
5598 : : }
5599 : :
5600 : : /* WAL insertion locks. Ensure they're aligned to the full padded size */
5601 : 1317 : allocptr += sizeof(WALInsertLockPadded) -
5602 : 1317 : ((uintptr_t) allocptr) % sizeof(WALInsertLockPadded);
5603 : 1317 : WALInsertLocks = XLogCtl->Insert.WALInsertLocks =
5604 : : (WALInsertLockPadded *) allocptr;
5605 : 1317 : allocptr += sizeof(WALInsertLockPadded) * NUM_XLOGINSERT_LOCKS;
5606 : :
5607 [ + + ]: 11853 : for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
5608 : : {
5609 : 10536 : LWLockInitialize(&WALInsertLocks[i].l.lock, LWTRANCHE_WAL_INSERT);
5610 : 10536 : pg_atomic_init_u64(&WALInsertLocks[i].l.insertingAt, InvalidXLogRecPtr);
5611 : 10536 : WALInsertLocks[i].l.lastImportantAt = InvalidXLogRecPtr;
5612 : : }
5613 : :
5614 : : /*
5615 : : * Align the start of the page buffers to a full xlog block size boundary.
5616 : : * This simplifies some calculations in XLOG insertion. It is also
5617 : : * required for O_DIRECT.
5618 : : */
5619 : 1317 : allocptr = (char *) TYPEALIGN(XLOG_BLCKSZ, allocptr);
5620 : 1317 : XLogCtl->pages = allocptr;
5621 : 1317 : memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
5622 : :
5623 : : /*
5624 : : * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
5625 : : * in additional info.)
5626 : : */
5627 : 1317 : XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
5628 : 1317 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_CRASH;
5629 : 1317 : XLogCtl->InstallXLogFileSegmentActive = false;
5630 : 1317 : XLogCtl->WalWriterSleeping = false;
5631 : :
5632 : : /* Use the checksum info from control file */
5633 : 1317 : XLogCtl->data_checksum_version = ControlFile->data_checksum_version;
5634 : 1317 : XLogCtl->data_checksum_lsn = ControlFile->data_checksum_lsn;
5635 : 1317 : XLogCtl->data_checksum_is_local = ControlFile->data_checksum_is_local;
5636 : 1317 : SetLocalDataChecksumState(XLogCtl->data_checksum_version);
5637 : :
5638 : 1317 : SpinLockInit(&XLogCtl->Insert.insertpos_lck);
5639 : 1317 : SpinLockInit(&XLogCtl->info_lck);
5640 : 1317 : pg_atomic_init_u64(&XLogCtl->logInsertResult, InvalidXLogRecPtr);
5641 : 1317 : pg_atomic_init_u64(&XLogCtl->logWriteResult, InvalidXLogRecPtr);
5642 : 1317 : pg_atomic_init_u64(&XLogCtl->logFlushResult, InvalidXLogRecPtr);
5643 : 1317 : pg_atomic_init_u64(&XLogCtl->unloggedLSN, InvalidXLogRecPtr);
5644 : 1317 : pg_atomic_init_u64(&XLogCtl->lastChecksumChangeRecPtr, InvalidXLogRecPtr);
5645 : 1317 : }
5646 : :
5647 : : /*
5648 : : * XLOGShmemAttach - re-establish WALInsertLocks pointer after attaching.
5649 : : */
5650 : : static void
5651 : 0 : XLOGShmemAttach(void *arg)
5652 : : {
5653 : 0 : WALInsertLocks = XLogCtl->Insert.WALInsertLocks;
5654 : 0 : }
5655 : :
5656 : : /*
5657 : : * Initialize process-local state needed by wal_debug.
5658 : : *
5659 : : * This must be called before XLogInsertRecord().
5660 : : */
5661 : : #ifdef WAL_DEBUG
5662 : : void
5663 : : InitWalDebug(void)
5664 : : {
5665 : : /*
5666 : : * Create a memory context for WAL debugging that's exempt from the normal
5667 : : * "no pallocs in critical section" rule. Yes, that can lead to a PANIC if
5668 : : * an allocation fails, but wal_debug is not for production use anyway.
5669 : : */
5670 : : if (walDebugCxt == NULL)
5671 : : {
5672 : : walDebugCxt = AllocSetContextCreate(TopMemoryContext,
5673 : : "WAL Debug",
5674 : : ALLOCSET_DEFAULT_SIZES);
5675 : : MemoryContextAllowInCriticalSection(walDebugCxt, true);
5676 : : }
5677 : : }
5678 : : #endif
5679 : :
5680 : : /*
5681 : : * This func must be called ONCE on system install. It creates pg_control
5682 : : * and the initial XLOG segment.
5683 : : */
5684 : : void
5685 : 59 : BootStrapXLOG(uint32 data_checksum_version)
5686 : : {
5687 : : CheckPoint checkPoint;
5688 : : PGAlignedXLogBlock buffer;
5689 : : XLogPageHeader page;
5690 : : XLogLongPageHeader longpage;
5691 : : XLogRecord *record;
5692 : : char *recptr;
5693 : : uint64 sysidentifier;
5694 : : struct timeval tv;
5695 : : pg_crc32c crc;
5696 : :
5697 : : /* allow ordinary WAL segment creation, like StartupXLOG() would */
5698 : 59 : SetInstallXLogFileSegmentActive();
5699 : :
5700 : : /*
5701 : : * Select a hopefully-unique system identifier code for this installation.
5702 : : * We use the result of gettimeofday(), including the fractional seconds
5703 : : * field, as being about as unique as we can easily get. (Think not to
5704 : : * use random(), since it hasn't been seeded and there's no portable way
5705 : : * to seed it other than the system clock value...) The upper half of the
5706 : : * uint64 value is just the tv_sec part, while the lower half contains the
5707 : : * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5708 : : * PID for a little extra uniqueness. A person knowing this encoding can
5709 : : * determine the initialization time of the installation, which could
5710 : : * perhaps be useful sometimes.
5711 : : */
5712 : 59 : gettimeofday(&tv, NULL);
5713 : 59 : sysidentifier = ((uint64) tv.tv_sec) << 32;
5714 : 59 : sysidentifier |= ((uint64) tv.tv_usec) << 12;
5715 : 59 : sysidentifier |= getpid() & 0xFFF;
5716 : :
5717 : 59 : memset(&buffer, 0, sizeof buffer);
5718 : 59 : page = (XLogPageHeader) &buffer;
5719 : :
5720 : : /*
5721 : : * Set up information for the initial checkpoint record
5722 : : *
5723 : : * The initial checkpoint record is written to the beginning of the WAL
5724 : : * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5725 : : * used, so that we can use 0/0 to mean "before any valid WAL segment".
5726 : : */
5727 : 59 : checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5728 : 59 : checkPoint.ThisTimeLineID = BootstrapTimeLineID;
5729 : 59 : checkPoint.PrevTimeLineID = BootstrapTimeLineID;
5730 : 59 : checkPoint.fullPageWrites = fullPageWrites;
5731 : 59 : checkPoint.logicalDecodingEnabled = (wal_level == WAL_LEVEL_LOGICAL);
5732 : 59 : checkPoint.wal_level = wal_level;
5733 : : checkPoint.nextXid =
5734 : 59 : FullTransactionIdFromEpochAndXid(0, FirstNormalTransactionId);
5735 : 59 : checkPoint.nextOid = FirstGenbkiObjectId;
5736 : 59 : checkPoint.nextMulti = FirstMultiXactId;
5737 : 59 : checkPoint.nextMultiOffset = 1;
5738 : 59 : checkPoint.oldestXid = FirstNormalTransactionId;
5739 : 59 : checkPoint.oldestXidDB = Template1DbOid;
5740 : 59 : checkPoint.oldestMulti = FirstMultiXactId;
5741 : 59 : checkPoint.oldestMultiDB = Template1DbOid;
5742 : 59 : checkPoint.oldestCommitTsXid = InvalidTransactionId;
5743 : 59 : checkPoint.newestCommitTsXid = InvalidTransactionId;
5744 : 59 : checkPoint.time = (pg_time_t) time(NULL);
5745 : 59 : checkPoint.oldestActiveXid = InvalidTransactionId;
5746 : 59 : checkPoint.dataChecksumState = data_checksum_version;
5747 : :
5748 : 59 : TransamVariables->nextXid = checkPoint.nextXid;
5749 : 59 : TransamVariables->nextOid = checkPoint.nextOid;
5750 : 59 : TransamVariables->oidCount = 0;
5751 : 59 : MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5752 : 59 : AdvanceOldestClogXid(checkPoint.oldestXid);
5753 : 59 : SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5754 : 59 : SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
5755 : 59 : SetCommitTsLimit(InvalidTransactionId, InvalidTransactionId);
5756 : :
5757 : : /* Set up the XLOG page header */
5758 : 59 : page->xlp_magic = XLOG_PAGE_MAGIC;
5759 : 59 : page->xlp_info = XLP_LONG_HEADER;
5760 : 59 : page->xlp_tli = BootstrapTimeLineID;
5761 : 59 : page->xlp_pageaddr = wal_segment_size;
5762 : 59 : longpage = (XLogLongPageHeader) page;
5763 : 59 : longpage->xlp_sysid = sysidentifier;
5764 : 59 : longpage->xlp_seg_size = wal_segment_size;
5765 : 59 : longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5766 : :
5767 : : /* Insert the initial checkpoint record */
5768 : 59 : recptr = ((char *) page + SizeOfXLogLongPHD);
5769 : 59 : record = (XLogRecord *) recptr;
5770 : 59 : record->xl_prev = InvalidXLogRecPtr;
5771 : 59 : record->xl_xid = InvalidTransactionId;
5772 : 59 : record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5773 : 59 : record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
5774 : 59 : record->xl_rmid = RM_XLOG_ID;
5775 : 59 : recptr += SizeOfXLogRecord;
5776 : : /* fill the XLogRecordDataHeaderShort struct */
5777 : 59 : *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5778 : 59 : *(recptr++) = sizeof(checkPoint);
5779 : 59 : memcpy(recptr, &checkPoint, sizeof(checkPoint));
5780 : 59 : recptr += sizeof(checkPoint);
5781 : : Assert(recptr - (char *) record == record->xl_tot_len);
5782 : :
5783 : 59 : INIT_CRC32C(crc);
5784 : 59 : COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5785 : 59 : COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5786 : 59 : FIN_CRC32C(crc);
5787 : 59 : record->xl_crc = crc;
5788 : :
5789 : : /* Create first XLOG segment file */
5790 : 59 : openLogTLI = BootstrapTimeLineID;
5791 : 59 : openLogFile = XLogFileInit(1, BootstrapTimeLineID);
5792 : :
5793 : : /*
5794 : : * We needn't bother with Reserve/ReleaseExternalFD here, since we'll
5795 : : * close the file again in a moment.
5796 : : */
5797 : :
5798 : : /* Write the first page with the initial record */
5799 : 59 : errno = 0;
5800 : 59 : pgstat_report_wait_start(WAIT_EVENT_WAL_BOOTSTRAP_WRITE);
5801 [ - + ]: 59 : if (write(openLogFile, &buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5802 : : {
5803 : : /* if write didn't set errno, assume problem is no disk space */
5804 [ # # ]: 0 : if (errno == 0)
5805 : 0 : errno = ENOSPC;
5806 [ # # ]: 0 : ereport(PANIC,
5807 : : (errcode_for_file_access(),
5808 : : errmsg("could not write bootstrap write-ahead log file: %m")));
5809 : : }
5810 : 59 : pgstat_report_wait_end();
5811 : :
5812 : 59 : pgstat_report_wait_start(WAIT_EVENT_WAL_BOOTSTRAP_SYNC);
5813 [ - + ]: 59 : if (pg_fsync(openLogFile) != 0)
5814 [ # # ]: 0 : ereport(PANIC,
5815 : : (errcode_for_file_access(),
5816 : : errmsg("could not fsync bootstrap write-ahead log file: %m")));
5817 : 59 : pgstat_report_wait_end();
5818 : :
5819 [ - + ]: 59 : if (close(openLogFile) != 0)
5820 [ # # ]: 0 : ereport(PANIC,
5821 : : (errcode_for_file_access(),
5822 : : errmsg("could not close bootstrap write-ahead log file: %m")));
5823 : :
5824 : 59 : openLogFile = -1;
5825 : :
5826 : : /* Now create pg_control */
5827 : 59 : InitControlFile(sysidentifier, data_checksum_version);
5828 : 59 : ControlFile->time = checkPoint.time;
5829 : 59 : ControlFile->checkPoint = checkPoint.redo;
5830 : 59 : ControlFile->checkPointCopy = checkPoint;
5831 : :
5832 : : /* some additional ControlFile fields are set in WriteControlFile() */
5833 : 59 : WriteControlFile();
5834 : :
5835 : : /* Bootstrap the commit log, too */
5836 : 59 : BootStrapCLOG();
5837 : 59 : BootStrapCommitTs();
5838 : 59 : BootStrapSUBTRANS();
5839 : 59 : BootStrapMultiXact();
5840 : :
5841 : : /*
5842 : : * Force control file to be read - in contrast to normal processing we'd
5843 : : * otherwise never run the checks and GUC related initializations therein.
5844 : : */
5845 : 59 : ReadControlFile();
5846 : 59 : }
5847 : :
5848 : : static char *
5849 : 1018 : str_time(pg_time_t tnow, char *buf, size_t bufsize)
5850 : : {
5851 : 1018 : pg_strftime(buf, bufsize,
5852 : : "%Y-%m-%d %H:%M:%S %Z",
5853 : 1018 : pg_localtime(&tnow, log_timezone));
5854 : :
5855 : 1018 : return buf;
5856 : : }
5857 : :
5858 : : /*
5859 : : * Initialize the first WAL segment on new timeline.
5860 : : */
5861 : : static void
5862 : 65 : XLogInitNewTimeline(TimeLineID endTLI, XLogRecPtr endOfLog, TimeLineID newTLI)
5863 : : {
5864 : : char xlogfname[MAXFNAMELEN];
5865 : : XLogSegNo endLogSegNo;
5866 : : XLogSegNo startLogSegNo;
5867 : :
5868 : : /* we always switch to a new timeline after archive recovery */
5869 : : Assert(endTLI != newTLI);
5870 : :
5871 : : /*
5872 : : * Update min recovery point one last time.
5873 : : */
5874 : 65 : UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
5875 : :
5876 : : /*
5877 : : * Calculate the last segment on the old timeline, and the first segment
5878 : : * on the new timeline. If the switch happens in the middle of a segment,
5879 : : * they are the same, but if the switch happens exactly at a segment
5880 : : * boundary, startLogSegNo will be endLogSegNo + 1.
5881 : : */
5882 : 65 : XLByteToPrevSeg(endOfLog, endLogSegNo, wal_segment_size);
5883 : 65 : XLByteToSeg(endOfLog, startLogSegNo, wal_segment_size);
5884 : :
5885 : : /*
5886 : : * Initialize the starting WAL segment for the new timeline. If the switch
5887 : : * happens in the middle of a segment, copy data from the last WAL segment
5888 : : * of the old timeline up to the switch point, to the starting WAL segment
5889 : : * on the new timeline.
5890 : : */
5891 [ + + ]: 65 : if (endLogSegNo == startLogSegNo)
5892 : : {
5893 : : /*
5894 : : * Make a copy of the file on the new timeline.
5895 : : *
5896 : : * Writing WAL isn't allowed yet, so there are no locking
5897 : : * considerations. But we should be just as tense as XLogFileInit to
5898 : : * avoid emplacing a bogus file.
5899 : : */
5900 : 56 : XLogFileCopy(newTLI, endLogSegNo, endTLI, endLogSegNo,
5901 : 56 : XLogSegmentOffset(endOfLog, wal_segment_size));
5902 : : }
5903 : : else
5904 : : {
5905 : : /*
5906 : : * The switch happened at a segment boundary, so just create the next
5907 : : * segment on the new timeline.
5908 : : */
5909 : : int fd;
5910 : :
5911 : 9 : fd = XLogFileInit(startLogSegNo, newTLI);
5912 : :
5913 [ - + ]: 9 : if (close(fd) != 0)
5914 : : {
5915 : 0 : int save_errno = errno;
5916 : :
5917 : 0 : XLogFileName(xlogfname, newTLI, startLogSegNo, wal_segment_size);
5918 : 0 : errno = save_errno;
5919 [ # # ]: 0 : ereport(ERROR,
5920 : : (errcode_for_file_access(),
5921 : : errmsg("could not close file \"%s\": %m", xlogfname)));
5922 : : }
5923 : : }
5924 : :
5925 : : /*
5926 : : * Let's just make real sure there are not .ready or .done flags posted
5927 : : * for the new segment.
5928 : : */
5929 : 65 : XLogFileName(xlogfname, newTLI, startLogSegNo, wal_segment_size);
5930 : 65 : XLogArchiveCleanup(xlogfname);
5931 : 65 : }
5932 : :
5933 : : /*
5934 : : * Perform cleanup actions at the conclusion of archive recovery.
5935 : : */
5936 : : static void
5937 : 65 : CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI, XLogRecPtr EndOfLog,
5938 : : TimeLineID newTLI)
5939 : : {
5940 : : /*
5941 : : * Execute the recovery_end_command, if any.
5942 : : */
5943 [ + - + + ]: 65 : if (recoveryEndCommand && strcmp(recoveryEndCommand, "") != 0)
5944 : 2 : ExecuteRecoveryCommand(recoveryEndCommand,
5945 : : "recovery_end_command",
5946 : : true,
5947 : : WAIT_EVENT_RECOVERY_END_COMMAND);
5948 : :
5949 : : /*
5950 : : * We switched to a new timeline. Clean up segments on the old timeline.
5951 : : *
5952 : : * If there are any higher-numbered segments on the old timeline, remove
5953 : : * them. They might contain valid WAL, but they might also be
5954 : : * pre-allocated files containing garbage. In any case, they are not part
5955 : : * of the new timeline's history so we don't need them.
5956 : : */
5957 : 65 : RemoveNonParentXlogFiles(EndOfLog, newTLI);
5958 : :
5959 : : /*
5960 : : * If the switch happened in the middle of a segment, what to do with the
5961 : : * last, partial segment on the old timeline? If we don't archive it, and
5962 : : * the server that created the WAL never archives it either (e.g. because
5963 : : * it was hit by a meteor), it will never make it to the archive. That's
5964 : : * OK from our point of view, because the new segment that we created with
5965 : : * the new TLI contains all the WAL from the old timeline up to the switch
5966 : : * point. But if you later try to do PITR to the "missing" WAL on the old
5967 : : * timeline, recovery won't find it in the archive. It's physically
5968 : : * present in the new file with new TLI, but recovery won't look there
5969 : : * when it's recovering to the older timeline. On the other hand, if we
5970 : : * archive the partial segment, and the original server on that timeline
5971 : : * is still running and archives the completed version of the same segment
5972 : : * later, it will fail. (We used to do that in 9.4 and below, and it
5973 : : * caused such problems).
5974 : : *
5975 : : * As a compromise, we rename the last segment with the .partial suffix,
5976 : : * and archive it. Archive recovery will never try to read .partial
5977 : : * segments, so they will normally go unused. But in the odd PITR case,
5978 : : * the administrator can copy them manually to the pg_wal directory
5979 : : * (removing the suffix). They can be useful in debugging, too.
5980 : : *
5981 : : * If a .done or .ready file already exists for the old timeline, however,
5982 : : * we had already determined that the segment is complete, so we can let
5983 : : * it be archived normally. (In particular, if it was restored from the
5984 : : * archive to begin with, it's expected to have a .done file).
5985 : : */
5986 [ + + + + ]: 65 : if (XLogSegmentOffset(EndOfLog, wal_segment_size) != 0 &&
5987 : : XLogArchivingActive())
5988 : : {
5989 : : char origfname[MAXFNAMELEN];
5990 : : XLogSegNo endLogSegNo;
5991 : :
5992 : 12 : XLByteToPrevSeg(EndOfLog, endLogSegNo, wal_segment_size);
5993 : 12 : XLogFileName(origfname, EndOfLogTLI, endLogSegNo, wal_segment_size);
5994 : :
5995 [ + + ]: 12 : if (!XLogArchiveIsReadyOrDone(origfname))
5996 : : {
5997 : : char origpath[MAXPGPATH];
5998 : : char partialfname[MAXFNAMELEN];
5999 : : char partialpath[MAXPGPATH];
6000 : :
6001 : : /*
6002 : : * If we're summarizing WAL, we can't rename the partial file
6003 : : * until the summarizer finishes with it, else it will fail.
6004 : : */
6005 [ + + ]: 8 : if (summarize_wal)
6006 : 1 : WaitForWalSummarization(EndOfLog);
6007 : :
6008 : 8 : XLogFilePath(origpath, EndOfLogTLI, endLogSegNo, wal_segment_size);
6009 : 8 : snprintf(partialfname, MAXFNAMELEN, "%s.partial", origfname);
6010 : 8 : snprintf(partialpath, MAXPGPATH, "%s.partial", origpath);
6011 : :
6012 : : /*
6013 : : * Make sure there's no .done or .ready file for the .partial
6014 : : * file.
6015 : : */
6016 : 8 : XLogArchiveCleanup(partialfname);
6017 : :
6018 : 8 : durable_rename(origpath, partialpath, ERROR);
6019 : 8 : XLogArchiveNotify(partialfname);
6020 : : }
6021 : : }
6022 : 65 : }
6023 : :
6024 : : /*
6025 : : * Check to see if required parameters are set high enough on this server
6026 : : * for various aspects of recovery operation.
6027 : : *
6028 : : * Note that all the parameters which this function tests need to be
6029 : : * listed in Administrator's Overview section in high-availability.sgml.
6030 : : * If you change them, don't forget to update the list.
6031 : : */
6032 : : static void
6033 : 288 : CheckRequiredParameterValues(void)
6034 : : {
6035 : : /*
6036 : : * For archive recovery, the WAL must be generated with at least 'replica'
6037 : : * wal_level.
6038 : : */
6039 [ + + + + ]: 288 : if (ArchiveRecoveryRequested && ControlFile->wal_level == WAL_LEVEL_MINIMAL)
6040 : : {
6041 [ + - ]: 2 : ereport(FATAL,
6042 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6043 : : errmsg("WAL was generated with \"wal_level=minimal\", cannot continue recovering"),
6044 : : errdetail("This happens if you temporarily set \"wal_level=minimal\" on the server."),
6045 : : errhint("Use a backup taken after setting \"wal_level\" to higher than \"minimal\".")));
6046 : : }
6047 : :
6048 : : /*
6049 : : * For Hot Standby, the WAL must be generated with 'replica' mode, and we
6050 : : * must have at least as many backend slots as the primary.
6051 : : */
6052 [ + + + + ]: 286 : if (ArchiveRecoveryRequested && EnableHotStandby)
6053 : : {
6054 : : /* We ignore autovacuum_worker_slots when we make this test. */
6055 : 160 : RecoveryRequiresIntParameter("max_connections",
6056 : : MaxConnections,
6057 : 160 : ControlFile->MaxConnections);
6058 : 160 : RecoveryRequiresIntParameter("max_worker_processes",
6059 : : max_worker_processes,
6060 : 160 : ControlFile->max_worker_processes);
6061 : 160 : RecoveryRequiresIntParameter("max_wal_senders",
6062 : : max_wal_senders,
6063 : 160 : ControlFile->max_wal_senders);
6064 : 160 : RecoveryRequiresIntParameter("max_prepared_transactions",
6065 : : max_prepared_xacts,
6066 : 160 : ControlFile->max_prepared_xacts);
6067 : 160 : RecoveryRequiresIntParameter("max_locks_per_transaction",
6068 : : max_locks_per_xact,
6069 : 160 : ControlFile->max_locks_per_xact);
6070 : : }
6071 : 286 : }
6072 : :
6073 : : /*
6074 : : * This must be called ONCE during postmaster or standalone-backend startup
6075 : : */
6076 : : void
6077 : 1148 : StartupXLOG(void)
6078 : : {
6079 : : XLogCtlInsert *Insert;
6080 : : CheckPoint checkPoint;
6081 : : bool wasShutdown;
6082 : : bool didCrash;
6083 : : bool haveTblspcMap;
6084 : : bool haveBackupLabel;
6085 : : XLogRecPtr EndOfLog;
6086 : : TimeLineID EndOfLogTLI;
6087 : : TimeLineID newTLI;
6088 : : bool performedWalRecovery;
6089 : : EndOfWalRecoveryInfo *endOfRecoveryInfo;
6090 : : XLogRecPtr abortedRecPtr;
6091 : : XLogRecPtr missingContrecPtr;
6092 : : TransactionId oldestActiveXID;
6093 : 1148 : bool promoted = false;
6094 : : char timebuf[128];
6095 : :
6096 : : /*
6097 : : * We should have an aux process resource owner to use, and we should not
6098 : : * be in a transaction that's installed some other resowner.
6099 : : */
6100 : : Assert(AuxProcessResourceOwner != NULL);
6101 : : Assert(CurrentResourceOwner == NULL ||
6102 : : CurrentResourceOwner == AuxProcessResourceOwner);
6103 : 1148 : CurrentResourceOwner = AuxProcessResourceOwner;
6104 : :
6105 : : /*
6106 : : * Check that contents look valid.
6107 : : */
6108 [ - + ]: 1148 : if (!XRecOffIsValid(ControlFile->checkPoint))
6109 [ # # ]: 0 : ereport(FATAL,
6110 : : (errcode(ERRCODE_DATA_CORRUPTED),
6111 : : errmsg("control file contains invalid checkpoint location")));
6112 : :
6113 [ + + - - : 1148 : switch (ControlFile->state)
+ + - ]
6114 : : {
6115 : 901 : case DB_SHUTDOWNED:
6116 : :
6117 : : /*
6118 : : * This is the expected case, so don't be chatty in standalone
6119 : : * mode
6120 : : */
6121 [ + + + + ]: 901 : ereport(IsPostmasterEnvironment ? LOG : NOTICE,
6122 : : (errmsg("database system was shut down at %s",
6123 : : str_time(ControlFile->time,
6124 : : timebuf, sizeof(timebuf)))));
6125 : 901 : break;
6126 : :
6127 : 35 : case DB_SHUTDOWNED_IN_RECOVERY:
6128 [ + - ]: 35 : ereport(LOG,
6129 : : (errmsg("database system was shut down in recovery at %s",
6130 : : str_time(ControlFile->time,
6131 : : timebuf, sizeof(timebuf)))));
6132 : 35 : break;
6133 : :
6134 : 0 : case DB_SHUTDOWNING:
6135 [ # # ]: 0 : ereport(LOG,
6136 : : (errmsg("database system shutdown was interrupted; last known up at %s",
6137 : : str_time(ControlFile->time,
6138 : : timebuf, sizeof(timebuf)))));
6139 : 0 : break;
6140 : :
6141 : 0 : case DB_IN_CRASH_RECOVERY:
6142 [ # # ]: 0 : ereport(LOG,
6143 : : (errmsg("database system was interrupted while in recovery at %s",
6144 : : str_time(ControlFile->time,
6145 : : timebuf, sizeof(timebuf))),
6146 : : errhint("This probably means that some data is corrupted and"
6147 : : " you will have to use the last backup for recovery.")));
6148 : 0 : break;
6149 : :
6150 : 13 : case DB_IN_ARCHIVE_RECOVERY:
6151 [ + - ]: 13 : ereport(LOG,
6152 : : (errmsg("database system was interrupted while in recovery at log time %s",
6153 : : str_time(ControlFile->checkPointCopy.time,
6154 : : timebuf, sizeof(timebuf))),
6155 : : errhint("If this has occurred more than once some data might be corrupted"
6156 : : " and you might need to choose an earlier recovery target.")));
6157 : 13 : break;
6158 : :
6159 : 199 : case DB_IN_PRODUCTION:
6160 [ + - ]: 199 : ereport(LOG,
6161 : : (errmsg("database system was interrupted; last known up at %s",
6162 : : str_time(ControlFile->time,
6163 : : timebuf, sizeof(timebuf)))));
6164 : 199 : break;
6165 : :
6166 : 0 : default:
6167 [ # # ]: 0 : ereport(FATAL,
6168 : : (errcode(ERRCODE_DATA_CORRUPTED),
6169 : : errmsg("control file contains invalid database cluster state")));
6170 : : }
6171 : :
6172 : : /* This is just to allow attaching to startup process with a debugger */
6173 : : #ifdef XLOG_REPLAY_DELAY
6174 : : if (ControlFile->state != DB_SHUTDOWNED)
6175 : : pg_usleep(60000000L);
6176 : : #endif
6177 : :
6178 : : /*
6179 : : * Verify that pg_wal, pg_wal/archive_status, and pg_wal/summaries exist.
6180 : : * In cases where someone has performed a copy for PITR, these directories
6181 : : * may have been excluded and need to be re-created.
6182 : : */
6183 : 1148 : ValidateXLOGDirectoryStructure();
6184 : :
6185 : : /* Set up timeout handler needed to report startup progress. */
6186 [ + + ]: 1148 : if (!IsBootstrapProcessingMode())
6187 : 1089 : RegisterTimeout(STARTUP_PROGRESS_TIMEOUT,
6188 : : startup_progress_timeout_handler);
6189 : :
6190 : : /*----------
6191 : : * If we previously crashed, perform a couple of actions:
6192 : : *
6193 : : * - The pg_wal directory may still include some temporary WAL segments
6194 : : * used when creating a new segment, so perform some clean up to not
6195 : : * bloat this path. This is done first as there is no point to sync
6196 : : * this temporary data.
6197 : : *
6198 : : * - There might be data which we had written, intending to fsync it, but
6199 : : * which we had not actually fsync'd yet. Therefore, a power failure in
6200 : : * the near future might cause earlier unflushed writes to be lost, even
6201 : : * though more recent data written to disk from here on would be
6202 : : * persisted. To avoid that, fsync the entire data directory.
6203 : : */
6204 [ + + ]: 1148 : if (ControlFile->state != DB_SHUTDOWNED &&
6205 [ + + ]: 247 : ControlFile->state != DB_SHUTDOWNED_IN_RECOVERY)
6206 : : {
6207 : 212 : RemoveTempXlogFiles();
6208 : 212 : SyncDataDirectory();
6209 : 212 : didCrash = true;
6210 : : }
6211 : : else
6212 : 936 : didCrash = false;
6213 : :
6214 : : /*
6215 : : * Prepare for WAL recovery if needed.
6216 : : *
6217 : : * InitWalRecovery analyzes the control file and the backup label file, if
6218 : : * any. It updates the in-memory ControlFile buffer according to the
6219 : : * starting checkpoint, and sets InRecovery and ArchiveRecoveryRequested.
6220 : : * It also applies the tablespace map file, if any.
6221 : : */
6222 : 1148 : InitWalRecovery(ControlFile, &wasShutdown,
6223 : : &haveBackupLabel, &haveTblspcMap);
6224 : 1141 : checkPoint = ControlFile->checkPointCopy;
6225 : :
6226 : : /* initialize shared memory variables from the checkpoint record */
6227 : 1141 : TransamVariables->nextXid = checkPoint.nextXid;
6228 : 1141 : TransamVariables->nextOid = checkPoint.nextOid;
6229 : 1141 : TransamVariables->oidCount = 0;
6230 : 1141 : MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
6231 : 1141 : AdvanceOldestClogXid(checkPoint.oldestXid);
6232 : 1141 : SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
6233 : 1141 : SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
6234 : 1141 : SetCommitTsLimit(checkPoint.oldestCommitTsXid,
6235 : : checkPoint.newestCommitTsXid);
6236 : :
6237 : : /*
6238 : : * When recovery starts from a base backup, the control file was copied at
6239 : : * an arbitrary moment and its data checksum state may differ from the
6240 : : * state at the redo point, which is what the WAL from there on was
6241 : : * written under. Adopt the state of the starting checkpoint: a shutdown
6242 : : * checkpoint is not replayed, so take it from the record read above; the
6243 : : * redo point of an online checkpoint is its CHECKPOINT_REDO record, so
6244 : : * let the replay of that record adopt it. Check backupStartPoint in
6245 : : * addition to the label: on a crash restart during backup recovery the
6246 : : * label file is already renamed away, but the start point persists until
6247 : : * the backup end record.
6248 : : *
6249 : : * Not for a base backup taken from a standby, though. Its starting
6250 : : * checkpoint is the standby's last restartpoint, a record written by the
6251 : : * upstream primary, whose state is not the one the copied files were
6252 : : * written under. The copied control file is already correct: a standby
6253 : : * persists its state only at restartpoint horizons and never claims more
6254 : : * than what reached disk. Such backups are recognized by backupEndPoint
6255 : : * together with backupEndRequired; backupEndPoint is only set for "BACKUP
6256 : : * FROM: standby" labels and persists across a crash restart. pg_rewind
6257 : : * writes a standby label as well, but no backupEndPoint, and its recovery
6258 : : * keeps adopting: the control file it installs carries the target's own
6259 : : * checksum state, which can lag the redo point of the last common
6260 : : * checkpoint the same way a restartpoint horizon can.
6261 : : *
6262 : : * Never adopt over a state over the watermark or a node-local
6263 : : * pg_checksums change, it generats no WAL so nothing in the replayed WAL
6264 : : * could restore it once overwritten. Otherwise, even a watermark above
6265 : : * the redo point must not prevent adoption. A primary backup copies
6266 : : * pg_control after the relation files, which may still contain pages
6267 : : * written before that watermark.
6268 : : */
6269 [ + + - + ]: 1141 : if ((haveBackupLabel || XLogRecPtrIsValid(ControlFile->backupStartPoint)) &&
6270 [ + + ]: 99 : !(XLogRecPtrIsValid(ControlFile->backupEndPoint) &&
6271 [ + + ]: 10 : ControlFile->backupEndRequired) &&
6272 [ + + ]: 92 : !ControlFile->data_checksum_is_local &&
6273 [ + - ]: 91 : checkPoint.redo > ControlFile->data_checksum_lsn)
6274 : : {
6275 [ + + ]: 91 : if (wasShutdown)
6276 : 1 : AdoptReplayedDataChecksumState(checkPoint.dataChecksumState,
6277 : : checkPoint.redo);
6278 : : else
6279 : 90 : adoptChecksumStateFromNextCheckpoint = true;
6280 : : }
6281 : :
6282 : : /*
6283 : : * Clear out any old relcache cache files. This is *necessary* if we do
6284 : : * any WAL replay, since that would probably result in the cache files
6285 : : * being out of sync with database reality. In theory we could leave them
6286 : : * in place if the database had been cleanly shut down, but it seems
6287 : : * safest to just remove them always and let them be rebuilt during the
6288 : : * first backend startup. These files needs to be removed from all
6289 : : * directories including pg_tblspc, however the symlinks are created only
6290 : : * after reading tablespace_map file in case of archive recovery from
6291 : : * backup, so needs to clear old relcache files here after creating
6292 : : * symlinks.
6293 : : */
6294 : 1141 : RelationCacheInitFileRemove();
6295 : :
6296 : : /*
6297 : : * Initialize replication slots, before there's a chance to remove
6298 : : * required resources.
6299 : : */
6300 : 1141 : StartupReplicationSlots();
6301 : :
6302 : : /*
6303 : : * Startup the logical decoding status with the last status stored in the
6304 : : * checkpoint record.
6305 : : */
6306 : 1139 : StartupLogicalDecodingStatus(checkPoint.logicalDecodingEnabled);
6307 : :
6308 : : /*
6309 : : * Startup logical state, needs to be setup now so we have proper data
6310 : : * during crash recovery.
6311 : : */
6312 : 1139 : StartupReorderBuffer();
6313 : :
6314 : : /*
6315 : : * Startup CLOG. This must be done after TransamVariables->nextXid has
6316 : : * been initialized and before we accept connections or begin WAL replay.
6317 : : */
6318 : 1139 : StartupCLOG();
6319 : :
6320 : : /*
6321 : : * Startup MultiXact. We need to do this early to be able to replay
6322 : : * truncations.
6323 : : */
6324 : 1139 : StartupMultiXact();
6325 : :
6326 : : /*
6327 : : * Ditto for commit timestamps. Activate the facility if the setting is
6328 : : * enabled in the control file, as there should be no tracking of commit
6329 : : * timestamps done when the setting was disabled. This facility can be
6330 : : * started or stopped when replaying a XLOG_PARAMETER_CHANGE record.
6331 : : */
6332 [ + + ]: 1139 : if (ControlFile->track_commit_timestamp)
6333 : 14 : StartupCommitTs();
6334 : :
6335 : : /*
6336 : : * Recover knowledge about replay progress of known replication partners.
6337 : : */
6338 : 1139 : StartupReplicationOrigin();
6339 : :
6340 : : /*
6341 : : * Initialize unlogged LSN. On a clean shutdown, it's restored from the
6342 : : * control file. On recovery, all unlogged relations are blown away, so
6343 : : * the unlogged LSN counter can be reset too.
6344 : : */
6345 [ + + ]: 1139 : if (ControlFile->state == DB_SHUTDOWNED)
6346 : 891 : pg_atomic_write_membarrier_u64(&XLogCtl->unloggedLSN,
6347 : 891 : ControlFile->unloggedLSN);
6348 : : else
6349 : 248 : pg_atomic_write_membarrier_u64(&XLogCtl->unloggedLSN,
6350 : : FirstNormalUnloggedLSN);
6351 : :
6352 : : /*
6353 : : * Copy any missing timeline history files between 'now' and the recovery
6354 : : * target timeline from archive to pg_wal. While we don't need those files
6355 : : * ourselves - the history file of the recovery target timeline covers all
6356 : : * the previous timelines in the history too - a cascading standby server
6357 : : * might be interested in them. Or, if you archive the WAL from this
6358 : : * server to a different archive than the primary, it'd be good for all
6359 : : * the history files to get archived there after failover, so that you can
6360 : : * use one of the old timelines as a PITR target. Timeline history files
6361 : : * are small, so it's better to copy them unnecessarily than not copy them
6362 : : * and regret later.
6363 : : */
6364 : 1139 : restoreTimeLineHistoryFiles(checkPoint.ThisTimeLineID, recoveryTargetTLI);
6365 : :
6366 : : /*
6367 : : * Before running in recovery, scan pg_twophase and fill in its status to
6368 : : * be able to work on entries generated by redo. Doing a scan before
6369 : : * taking any recovery action has the merit to discard any 2PC files that
6370 : : * are newer than the first record to replay, saving from any conflicts at
6371 : : * replay. This avoids as well any subsequent scans when doing recovery
6372 : : * of the on-disk two-phase data.
6373 : : */
6374 : 1139 : restoreTwoPhaseData();
6375 : :
6376 : : /*
6377 : : * When starting with crash recovery, reset pgstat data - it might not be
6378 : : * valid. Otherwise restore pgstat data. It's safe to do this here,
6379 : : * because postmaster will not yet have started any other processes.
6380 : : *
6381 : : * NB: Restoring replication slot stats relies on slot state to have
6382 : : * already been restored from disk.
6383 : : *
6384 : : * TODO: With a bit of extra work we could just start with a pgstat file
6385 : : * associated with the checkpoint redo location we're starting from.
6386 : : */
6387 [ + + ]: 1139 : if (didCrash)
6388 : 205 : pgstat_discard_stats();
6389 : : else
6390 : 934 : pgstat_restore_stats();
6391 : :
6392 : 1139 : lastFullPageWrites = checkPoint.fullPageWrites;
6393 : :
6394 : 1139 : RedoRecPtr = XLogCtl->RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
6395 : 1139 : doPageWrites = lastFullPageWrites;
6396 : :
6397 : : /* REDO */
6398 [ + + ]: 1139 : if (InRecovery)
6399 : : {
6400 : : /* Initialize state for RecoveryInProgress() */
6401 : 248 : SpinLockAcquire(&XLogCtl->info_lck);
6402 [ + + ]: 248 : if (InArchiveRecovery)
6403 : 145 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_ARCHIVE;
6404 : : else
6405 : 103 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_CRASH;
6406 : 248 : SpinLockRelease(&XLogCtl->info_lck);
6407 : :
6408 : : /*
6409 : : * Update pg_control to show that we are recovering and to show the
6410 : : * selected checkpoint as the place we are starting from. We also mark
6411 : : * pg_control with any minimum recovery stop point obtained from a
6412 : : * backup history file.
6413 : : *
6414 : : * No need to hold ControlFileLock yet, we aren't up far enough.
6415 : : */
6416 : 248 : UpdateControlFile();
6417 : :
6418 : : /*
6419 : : * If there was a backup label file, it's done its job and the info
6420 : : * has now been propagated into pg_control. We must get rid of the
6421 : : * label file so that if we crash during recovery, we'll pick up at
6422 : : * the latest recovery restartpoint instead of going all the way back
6423 : : * to the backup start point. It seems prudent though to just rename
6424 : : * the file out of the way rather than delete it completely.
6425 : : */
6426 [ + + ]: 248 : if (haveBackupLabel)
6427 : : {
6428 : 99 : unlink(BACKUP_LABEL_OLD);
6429 : 99 : durable_rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, FATAL);
6430 : : }
6431 : :
6432 : : /*
6433 : : * If there was a tablespace_map file, it's done its job and the
6434 : : * symlinks have been created. We must get rid of the map file so
6435 : : * that if we crash during recovery, we don't create symlinks again.
6436 : : * It seems prudent though to just rename the file out of the way
6437 : : * rather than delete it completely.
6438 : : */
6439 [ + + ]: 248 : if (haveTblspcMap)
6440 : : {
6441 : 2 : unlink(TABLESPACE_MAP_OLD);
6442 : 2 : durable_rename(TABLESPACE_MAP, TABLESPACE_MAP_OLD, FATAL);
6443 : : }
6444 : :
6445 : : /*
6446 : : * Initialize our local copy of minRecoveryPoint. When doing crash
6447 : : * recovery we want to replay up to the end of WAL. Particularly, in
6448 : : * the case of a promoted standby minRecoveryPoint value in the
6449 : : * control file is only updated after the first checkpoint. However,
6450 : : * if the instance crashes before the first post-recovery checkpoint
6451 : : * is completed then recovery will use a stale location causing the
6452 : : * startup process to think that there are still invalid page
6453 : : * references when checking for data consistency.
6454 : : */
6455 [ + + ]: 248 : if (InArchiveRecovery)
6456 : : {
6457 : 145 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
6458 : : }
6459 : : else
6460 : : {
6461 : 103 : LocalMinRecoveryPoint = InvalidXLogRecPtr;
6462 : : }
6463 : :
6464 : : /* Check that the GUCs used to generate the WAL allow recovery */
6465 : 248 : CheckRequiredParameterValues();
6466 : :
6467 : : /*
6468 : : * We're in recovery, so unlogged relations may be trashed and must be
6469 : : * reset. This should be done BEFORE allowing Hot Standby
6470 : : * connections, so that read-only backends don't try to read whatever
6471 : : * garbage is left over from before.
6472 : : */
6473 : 248 : ResetUnloggedRelations(UNLOGGED_RELATION_CLEANUP);
6474 : :
6475 : : /*
6476 : : * Likewise, delete any saved transaction snapshot files that got left
6477 : : * behind by crashed backends.
6478 : : */
6479 : 248 : DeleteAllExportedSnapshotFiles();
6480 : :
6481 : : /*
6482 : : * Initialize for Hot Standby, if enabled. We won't let backends in
6483 : : * yet, not until we've reached the min recovery point specified in
6484 : : * control file and we've established a recovery snapshot from a
6485 : : * running-xacts WAL record.
6486 : : */
6487 [ + + + + ]: 248 : if (ArchiveRecoveryRequested && EnableHotStandby)
6488 : : {
6489 : : TransactionId *xids;
6490 : : int nxids;
6491 : :
6492 [ + + ]: 136 : ereport(DEBUG1,
6493 : : (errmsg_internal("initializing for hot standby")));
6494 : :
6495 : 136 : InitRecoveryTransactionEnvironment();
6496 : :
6497 [ + + ]: 136 : if (wasShutdown)
6498 : 29 : oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
6499 : : else
6500 : 107 : oldestActiveXID = checkPoint.oldestActiveXid;
6501 : : Assert(TransactionIdIsValid(oldestActiveXID));
6502 : :
6503 : : /* Tell procarray about the range of xids it has to deal with */
6504 : 136 : ProcArrayInitRecovery(XidFromFullTransactionId(TransamVariables->nextXid));
6505 : :
6506 : : /*
6507 : : * Startup subtrans only. CLOG, MultiXact and commit timestamp
6508 : : * have already been started up and other SLRUs are not maintained
6509 : : * during recovery and need not be started yet.
6510 : : */
6511 : 136 : StartupSUBTRANS(oldestActiveXID);
6512 : 136 : SetRecoverySubtransInitialized();
6513 : :
6514 : : /*
6515 : : * If we're beginning at a shutdown checkpoint, we know that
6516 : : * nothing was running on the primary at this point. So fake-up an
6517 : : * empty running-xacts record and use that here and now. Recover
6518 : : * additional standby state for prepared transactions.
6519 : : */
6520 [ + + ]: 136 : if (wasShutdown)
6521 : : {
6522 : : RunningTransactionsData running;
6523 : : TransactionId latestCompletedXid;
6524 : :
6525 : : /* Update pg_subtrans entries for any prepared transactions */
6526 : 29 : StandbyRecoverPreparedTransactions();
6527 : :
6528 : : /*
6529 : : * Construct a RunningTransactions snapshot representing a
6530 : : * shut down server, with only prepared transactions still
6531 : : * alive. We're never overflowed at this point because all
6532 : : * subxids are listed with their parent prepared transactions.
6533 : : */
6534 : 29 : running.xcnt = nxids;
6535 : 29 : running.subxcnt = 0;
6536 : 29 : running.subxid_status = SUBXIDS_IN_SUBTRANS;
6537 : 29 : running.nextXid = XidFromFullTransactionId(checkPoint.nextXid);
6538 : 29 : running.oldestRunningXid = oldestActiveXID;
6539 : 29 : latestCompletedXid = XidFromFullTransactionId(checkPoint.nextXid);
6540 [ - + ]: 29 : TransactionIdRetreat(latestCompletedXid);
6541 : : Assert(TransactionIdIsNormal(latestCompletedXid));
6542 : 29 : running.latestCompletedXid = latestCompletedXid;
6543 : 29 : running.xids = xids;
6544 : :
6545 : 29 : ProcArrayApplyRecoveryInfo(&running);
6546 : : }
6547 : : }
6548 : :
6549 : : /*
6550 : : * We're all set for replaying the WAL now. Do it.
6551 : : */
6552 : 248 : PerformWalRecovery();
6553 : 175 : performedWalRecovery = true;
6554 : : }
6555 : : else
6556 : 891 : performedWalRecovery = false;
6557 : :
6558 : : /*
6559 : : * Finish WAL recovery.
6560 : : */
6561 : 1066 : endOfRecoveryInfo = FinishWalRecovery();
6562 : 1066 : EndOfLog = endOfRecoveryInfo->endOfLog;
6563 : 1066 : EndOfLogTLI = endOfRecoveryInfo->endOfLogTLI;
6564 : 1066 : abortedRecPtr = endOfRecoveryInfo->abortedRecPtr;
6565 : 1066 : missingContrecPtr = endOfRecoveryInfo->missingContrecPtr;
6566 : :
6567 : : /*
6568 : : * Reset ps status display, so as no information related to recovery shows
6569 : : * up.
6570 : : */
6571 : 1066 : set_ps_display("");
6572 : :
6573 : : /*
6574 : : * When recovering from a backup (we are in recovery, and archive recovery
6575 : : * was requested), complain if we did not roll forward far enough to reach
6576 : : * the point where the database is consistent. For regular online
6577 : : * backup-from-primary, that means reaching the end-of-backup WAL record
6578 : : * (at which point we reset backupStartPoint to be Invalid), for
6579 : : * backup-from-replica (which can't inject records into the WAL stream),
6580 : : * that point is when we reach the minRecoveryPoint in pg_control (which
6581 : : * we purposefully copy last when backing up from a replica). For
6582 : : * pg_rewind (which creates a backup_label with a method of "pg_rewind")
6583 : : * or snapshot-style backups (which don't), backupEndRequired will be set
6584 : : * to false.
6585 : : *
6586 : : * Note: it is indeed okay to look at the local variable
6587 : : * LocalMinRecoveryPoint here, even though ControlFile->minRecoveryPoint
6588 : : * might be further ahead --- ControlFile->minRecoveryPoint cannot have
6589 : : * been advanced beyond the WAL we processed.
6590 : : */
6591 [ + + ]: 1066 : if (InRecovery &&
6592 [ + - ]: 175 : (EndOfLog < LocalMinRecoveryPoint ||
6593 [ - + ]: 175 : XLogRecPtrIsValid(ControlFile->backupStartPoint)))
6594 : : {
6595 : : /*
6596 : : * Ran off end of WAL before reaching end-of-backup WAL record, or
6597 : : * minRecoveryPoint. That's a bad sign, indicating that you tried to
6598 : : * recover from an online backup but never called pg_backup_stop(), or
6599 : : * you didn't archive all the WAL needed.
6600 : : */
6601 [ # # # # ]: 0 : if (ArchiveRecoveryRequested || ControlFile->backupEndRequired)
6602 : : {
6603 [ # # # # ]: 0 : if (XLogRecPtrIsValid(ControlFile->backupStartPoint) || ControlFile->backupEndRequired)
6604 [ # # ]: 0 : ereport(FATAL,
6605 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6606 : : errmsg("WAL ends before end of online backup"),
6607 : : errhint("All WAL generated while online backup was taken must be available at recovery.")));
6608 : : else
6609 [ # # ]: 0 : ereport(FATAL,
6610 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6611 : : errmsg("WAL ends before consistent recovery point")));
6612 : : }
6613 : : }
6614 : :
6615 : : /*
6616 : : * Reset unlogged relations to the contents of their INIT fork. This is
6617 : : * done AFTER recovery is complete so as to include any unlogged relations
6618 : : * created during recovery, but BEFORE recovery is marked as having
6619 : : * completed successfully. Otherwise we'd not retry if any of the post
6620 : : * end-of-recovery steps fail.
6621 : : */
6622 [ + + ]: 1066 : if (InRecovery)
6623 : 175 : ResetUnloggedRelations(UNLOGGED_RELATION_INIT);
6624 : :
6625 : : /*
6626 : : * Pre-scan prepared transactions to find out the range of XIDs present.
6627 : : * This information is not quite needed yet, but it is positioned here so
6628 : : * as potential problems are detected before any on-disk change is done.
6629 : : */
6630 : 1066 : oldestActiveXID = PrescanPreparedTransactions(NULL, NULL);
6631 : :
6632 : : /*
6633 : : * Allow ordinary WAL segment creation before possibly switching to a new
6634 : : * timeline, which creates a new segment, and after the last ReadRecord().
6635 : : */
6636 : 1066 : SetInstallXLogFileSegmentActive();
6637 : :
6638 : : /*
6639 : : * Consider whether we need to assign a new timeline ID.
6640 : : *
6641 : : * If we did archive recovery, we always assign a new ID. This handles a
6642 : : * couple of issues. If we stopped short of the end of WAL during
6643 : : * recovery, then we are clearly generating a new timeline and must assign
6644 : : * it a unique new ID. Even if we ran to the end, modifying the current
6645 : : * last segment is problematic because it may result in trying to
6646 : : * overwrite an already-archived copy of that segment, and we encourage
6647 : : * DBAs to make their archive_commands reject that. We can dodge the
6648 : : * problem by making the new active segment have a new timeline ID.
6649 : : *
6650 : : * In a normal crash recovery, we can just extend the timeline we were in.
6651 : : */
6652 : 1066 : newTLI = endOfRecoveryInfo->lastRecTLI;
6653 [ + + ]: 1066 : if (ArchiveRecoveryRequested)
6654 : : {
6655 : 65 : newTLI = findNewestTimeLine(recoveryTargetTLI) + 1;
6656 [ + - ]: 65 : ereport(LOG,
6657 : : (errmsg("selected new timeline ID: %u", newTLI)));
6658 : :
6659 : : /*
6660 : : * Make a writable copy of the last WAL segment. (Note that we also
6661 : : * have a copy of the last block of the old WAL in
6662 : : * endOfRecovery->lastPage; we will use that below.)
6663 : : */
6664 : 65 : XLogInitNewTimeline(EndOfLogTLI, EndOfLog, newTLI);
6665 : :
6666 : : /*
6667 : : * Remove the signal files out of the way, so that we don't
6668 : : * accidentally re-enter archive recovery mode in a subsequent crash.
6669 : : */
6670 [ + + ]: 65 : if (endOfRecoveryInfo->standby_signal_file_found)
6671 : 62 : durable_unlink(STANDBY_SIGNAL_FILE, FATAL);
6672 : :
6673 [ + + ]: 65 : if (endOfRecoveryInfo->recovery_signal_file_found)
6674 : 4 : durable_unlink(RECOVERY_SIGNAL_FILE, FATAL);
6675 : :
6676 : : /*
6677 : : * Write the timeline history file, and have it archived. After this
6678 : : * point (or rather, as soon as the file is archived), the timeline
6679 : : * will appear as "taken" in the WAL archive and to any standby
6680 : : * servers. If we crash before actually switching to the new
6681 : : * timeline, standby servers will nevertheless think that we switched
6682 : : * to the new timeline, and will try to connect to the new timeline.
6683 : : * To minimize the window for that, try to do as little as possible
6684 : : * between here and writing the end-of-recovery record.
6685 : : */
6686 : 65 : writeTimeLineHistory(newTLI, recoveryTargetTLI,
6687 : 65 : EndOfLog, endOfRecoveryInfo->recoveryStopReason);
6688 : :
6689 [ + - ]: 65 : ereport(LOG,
6690 : : (errmsg("archive recovery complete")));
6691 : : }
6692 : :
6693 : : /* Save the selected TimeLineID in shared memory, too */
6694 : 1066 : SpinLockAcquire(&XLogCtl->info_lck);
6695 : 1066 : XLogCtl->InsertTimeLineID = newTLI;
6696 : 1066 : XLogCtl->PrevTimeLineID = endOfRecoveryInfo->lastRecTLI;
6697 : 1066 : SpinLockRelease(&XLogCtl->info_lck);
6698 : :
6699 : : /*
6700 : : * Actually, if WAL ended in an incomplete record, skip the parts that
6701 : : * made it through and start writing after the portion that persisted.
6702 : : * (It's critical to first write an OVERWRITE_CONTRECORD message, which
6703 : : * we'll do as soon as we're open for writing new WAL.)
6704 : : */
6705 [ + + ]: 1066 : if (XLogRecPtrIsValid(missingContrecPtr))
6706 : : {
6707 : : /*
6708 : : * We should only have a missingContrecPtr if we're not switching to a
6709 : : * new timeline. When a timeline switch occurs, WAL is copied from the
6710 : : * old timeline to the new only up to the end of the last complete
6711 : : * record, so there can't be an incomplete WAL record that we need to
6712 : : * disregard.
6713 : : */
6714 : : Assert(newTLI == endOfRecoveryInfo->lastRecTLI);
6715 : : Assert(XLogRecPtrIsValid(abortedRecPtr));
6716 : 10 : EndOfLog = missingContrecPtr;
6717 : : }
6718 : :
6719 : : /*
6720 : : * Prepare to write WAL starting at EndOfLog location, and init xlog
6721 : : * buffer cache using the block containing the last record from the
6722 : : * previous incarnation.
6723 : : */
6724 : 1066 : Insert = &XLogCtl->Insert;
6725 : 1066 : Insert->PrevBytePos = XLogRecPtrToBytePos(endOfRecoveryInfo->lastRec);
6726 : 1066 : Insert->CurrBytePos = XLogRecPtrToBytePos(EndOfLog);
6727 : :
6728 : : /*
6729 : : * Tricky point here: lastPage contains the *last* block that the LastRec
6730 : : * record spans, not the one it starts in. The last block is indeed the
6731 : : * one we want to use.
6732 : : */
6733 [ + + ]: 1066 : if (EndOfLog % XLOG_BLCKSZ != 0)
6734 : : {
6735 : : char *page;
6736 : : int len;
6737 : : int firstIdx;
6738 : :
6739 : 1038 : firstIdx = XLogRecPtrToBufIdx(EndOfLog);
6740 : 1038 : len = EndOfLog - endOfRecoveryInfo->lastPageBeginPtr;
6741 : : Assert(len < XLOG_BLCKSZ);
6742 : :
6743 : : /* Copy the valid part of the last block, and zero the rest */
6744 : 1038 : page = &XLogCtl->pages[firstIdx * XLOG_BLCKSZ];
6745 : 1038 : memcpy(page, endOfRecoveryInfo->lastPage, len);
6746 : 1038 : memset(page + len, 0, XLOG_BLCKSZ - len);
6747 : :
6748 : 1038 : pg_atomic_write_u64(&XLogCtl->xlblocks[firstIdx], endOfRecoveryInfo->lastPageBeginPtr + XLOG_BLCKSZ);
6749 : 1038 : XLogCtl->InitializedUpTo = endOfRecoveryInfo->lastPageBeginPtr + XLOG_BLCKSZ;
6750 : : }
6751 : : else
6752 : : {
6753 : : /*
6754 : : * There is no partial block to copy. Just set InitializedUpTo, and
6755 : : * let the first attempt to insert a log record to initialize the next
6756 : : * buffer.
6757 : : */
6758 : 28 : XLogCtl->InitializedUpTo = EndOfLog;
6759 : : }
6760 : :
6761 : : /*
6762 : : * Update local and shared status. This is OK to do without any locks
6763 : : * because no other process can be reading or writing WAL yet.
6764 : : */
6765 : 1066 : LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
6766 : 1066 : pg_atomic_write_u64(&XLogCtl->logInsertResult, EndOfLog);
6767 : 1066 : pg_atomic_write_u64(&XLogCtl->logWriteResult, EndOfLog);
6768 : 1066 : pg_atomic_write_u64(&XLogCtl->logFlushResult, EndOfLog);
6769 : 1066 : XLogCtl->LogwrtRqst.Write = EndOfLog;
6770 : 1066 : XLogCtl->LogwrtRqst.Flush = EndOfLog;
6771 : :
6772 : : /*
6773 : : * Preallocate additional log files, if wanted.
6774 : : */
6775 : 1066 : PreallocXlogFiles(EndOfLog, newTLI);
6776 : :
6777 : : /*
6778 : : * Okay, we're officially UP.
6779 : : */
6780 : 1066 : InRecovery = false;
6781 : :
6782 : : /* start the archive_timeout timer and LSN running */
6783 : 1066 : XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
6784 : 1066 : XLogCtl->lastSegSwitchLSN = EndOfLog;
6785 : :
6786 : : /* also initialize latestCompletedXid, to nextXid - 1 */
6787 : 1066 : LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
6788 : 1066 : TransamVariables->latestCompletedXid = TransamVariables->nextXid;
6789 : 1066 : FullTransactionIdRetreat(&TransamVariables->latestCompletedXid);
6790 : 1066 : LWLockRelease(ProcArrayLock);
6791 : :
6792 : : /*
6793 : : * Start up subtrans, if not already done for hot standby. (commit
6794 : : * timestamps are started below, if necessary.)
6795 : : */
6796 [ + + ]: 1066 : if (standbyState == STANDBY_DISABLED)
6797 : 1001 : StartupSUBTRANS(oldestActiveXID);
6798 : :
6799 : : /*
6800 : : * Perform end of recovery actions for any SLRUs that need it.
6801 : : */
6802 : 1066 : TrimCLOG();
6803 : 1066 : TrimMultiXact();
6804 : :
6805 : : /*
6806 : : * Reload shared-memory state for prepared transactions. This needs to
6807 : : * happen before renaming the last partial segment of the old timeline as
6808 : : * it may be possible that we have to recover some transactions from it.
6809 : : */
6810 : 1066 : RecoverPreparedTransactions();
6811 : :
6812 : : /* Shut down xlogreader */
6813 : 1066 : ShutdownWalRecovery();
6814 : :
6815 : : /* Enable WAL writes for this backend only. */
6816 : 1066 : LocalSetXLogInsertAllowed();
6817 : :
6818 : : /* If necessary, write overwrite-contrecord before doing anything else */
6819 [ + + ]: 1066 : if (XLogRecPtrIsValid(abortedRecPtr))
6820 : : {
6821 : : Assert(XLogRecPtrIsValid(missingContrecPtr));
6822 : 10 : CreateOverwriteContrecordRecord(abortedRecPtr, missingContrecPtr, newTLI);
6823 : : }
6824 : :
6825 : : /*
6826 : : * Update full_page_writes in shared memory and write an XLOG_FPW_CHANGE
6827 : : * record before resource manager writes cleanup WAL records or checkpoint
6828 : : * record is written.
6829 : : */
6830 : 1066 : Insert->fullPageWrites = lastFullPageWrites;
6831 : 1066 : UpdateFullPageWrites();
6832 : :
6833 : : /*
6834 : : * Emit checkpoint or end-of-recovery record in XLOG, if required.
6835 : : */
6836 [ + + ]: 1066 : if (performedWalRecovery)
6837 : 175 : promoted = PerformRecoveryXLogAction();
6838 : :
6839 : : /*
6840 : : * If any of the critical GUCs have changed, log them before we allow
6841 : : * backends to write WAL.
6842 : : */
6843 : 1066 : XLogReportParameters();
6844 : :
6845 : : /* If this is archive recovery, perform post-recovery cleanup actions. */
6846 [ + + ]: 1066 : if (ArchiveRecoveryRequested)
6847 : 65 : CleanupAfterArchiveRecovery(EndOfLogTLI, EndOfLog, newTLI);
6848 : :
6849 : 1066 : INJECTION_POINT("promotion-after-wal-segment-cleanup", NULL);
6850 : :
6851 : : /*
6852 : : * Local WAL inserts enabled, so it's time to finish initialization of
6853 : : * commit timestamp.
6854 : : */
6855 : 1066 : CompleteCommitTsInitialization();
6856 : :
6857 : : /*
6858 : : * Update logical decoding status in shared memory and write an
6859 : : * XLOG_LOGICAL_DECODING_STATUS_CHANGE, if necessary.
6860 : : */
6861 : 1066 : UpdateLogicalDecodingStatusEndOfRecovery();
6862 : :
6863 : : /* Clean up EndOfWalRecoveryInfo data to appease Valgrind leak checking */
6864 [ + + ]: 1066 : if (endOfRecoveryInfo->lastPage)
6865 : 1048 : pfree(endOfRecoveryInfo->lastPage);
6866 : 1066 : pfree(endOfRecoveryInfo->recoveryStopReason);
6867 : 1066 : pfree(endOfRecoveryInfo);
6868 : :
6869 : : /*
6870 : : * If we reach this point with checksums in the state inprogress-on, it
6871 : : * means that data checksums were in the process of being enabled when the
6872 : : * cluster shut down. Since processing didn't finish, the operation will
6873 : : * have to be restarted from scratch since there is no capability to
6874 : : * continue where it was when the cluster shut down. Thus, revert the
6875 : : * state back to off, and inform the user with a warning message. Being
6876 : : * able to restart processing is a TODO, but it wouldn't be possible to
6877 : : * restart here since we cannot launch a dynamic background worker
6878 : : * directly from here (it has to be from a regular backend).
6879 : : */
6880 [ + + ]: 1066 : if (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_ON)
6881 : : {
6882 : 1 : XLogChecksums(PG_DATA_CHECKSUM_OFF);
6883 : 1 : SetLocalDataChecksumState(PG_DATA_CHECKSUM_OFF);
6884 : :
6885 : 1 : EmitAndWaitDataChecksumsBarrier(PG_DATA_CHECKSUM_OFF);
6886 [ + - ]: 1 : ereport(WARNING,
6887 : : errmsg("enabling data checksums was interrupted"),
6888 : : errhint("Data checksum processing must be manually restarted for checksums to be enabled."));
6889 : : }
6890 : :
6891 : : /*
6892 : : * If data checksums were being disabled when the cluster was shut down,
6893 : : * we know that we have a state where all backends have stopped validating
6894 : : * checksums and we can move to off instead of prompting the user to
6895 : : * perform any action.
6896 : : */
6897 [ - + ]: 1065 : else if (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_OFF)
6898 : : {
6899 : 0 : XLogChecksums(PG_DATA_CHECKSUM_OFF);
6900 : 0 : SetLocalDataChecksumState(PG_DATA_CHECKSUM_OFF);
6901 : :
6902 : 0 : EmitAndWaitDataChecksumsBarrier(PG_DATA_CHECKSUM_OFF);
6903 : : }
6904 : :
6905 : : /*
6906 : : * All done with end-of-recovery actions.
6907 : : *
6908 : : * Now allow backends to write WAL and update the control file status in
6909 : : * consequence. SharedRecoveryState, that controls if backends can write
6910 : : * WAL, is updated while holding ControlFileLock to prevent other backends
6911 : : * to look at an inconsistent state of the control file in shared memory.
6912 : : * There is still a small window during which backends can write WAL and
6913 : : * the control file is still referring to a system not in DB_IN_PRODUCTION
6914 : : * state while looking at the on-disk control file.
6915 : : *
6916 : : * Also, we use info_lck to update SharedRecoveryState to ensure that
6917 : : * there are no race conditions concerning visibility of other recent
6918 : : * updates to shared memory.
6919 : : */
6920 : 1066 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6921 : 1066 : ControlFile->state = DB_IN_PRODUCTION;
6922 : :
6923 : 1066 : SpinLockAcquire(&XLogCtl->info_lck);
6924 : 1066 : ControlFile->data_checksum_version = XLogCtl->data_checksum_version;
6925 : 1066 : ControlFile->data_checksum_lsn = XLogCtl->data_checksum_lsn;
6926 : 1066 : ControlFile->data_checksum_is_local = XLogCtl->data_checksum_is_local;
6927 : 1066 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_DONE;
6928 : 1066 : SpinLockRelease(&XLogCtl->info_lck);
6929 : :
6930 : 1066 : UpdateControlFile();
6931 : 1066 : LWLockRelease(ControlFileLock);
6932 : :
6933 : : /*
6934 : : * Wake up the checkpointer process as there might be a request to disable
6935 : : * logical decoding by concurrent slot drop.
6936 : : */
6937 : 1066 : WakeupCheckpointer();
6938 : :
6939 : : /*
6940 : : * Wake up all waiters. They need to report an error that recovery was
6941 : : * ended before reaching the target LSN.
6942 : : */
6943 : 1066 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_REPLAY, InvalidXLogRecPtr);
6944 : 1066 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_WRITE, InvalidXLogRecPtr);
6945 : 1066 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_FLUSH, InvalidXLogRecPtr);
6946 : :
6947 : : /*
6948 : : * Shutdown the recovery environment. This must occur after
6949 : : * RecoverPreparedTransactions() (see notes in lock_twophase_recover())
6950 : : * and after switching SharedRecoveryState to RECOVERY_STATE_DONE so as
6951 : : * any session building a snapshot will not rely on KnownAssignedXids as
6952 : : * RecoveryInProgress() would return false at this stage. This is
6953 : : * particularly critical for prepared 2PC transactions, that would still
6954 : : * need to be included in snapshots once recovery has ended.
6955 : : */
6956 [ + + ]: 1066 : if (standbyState != STANDBY_DISABLED)
6957 : 65 : ShutdownRecoveryTransactionEnvironment();
6958 : :
6959 : : /*
6960 : : * If there were cascading standby servers connected to us, nudge any wal
6961 : : * sender processes to notice that we've been promoted.
6962 : : */
6963 : 1066 : WalSndWakeup(true, true);
6964 : :
6965 : : /*
6966 : : * If this was a promotion, request an (online) checkpoint now. This isn't
6967 : : * required for consistency, but the last restartpoint might be far back,
6968 : : * and in case of a crash, recovering from it might take a longer than is
6969 : : * appropriate now that we're not in standby mode anymore.
6970 : : */
6971 [ + + ]: 1066 : if (promoted)
6972 : 57 : RequestCheckpoint(CHECKPOINT_FORCE);
6973 : 1066 : }
6974 : :
6975 : : /*
6976 : : * Callback from PerformWalRecovery(), called when we switch from crash
6977 : : * recovery to archive recovery mode. Updates the control file accordingly.
6978 : : */
6979 : : void
6980 : 1 : SwitchIntoArchiveRecovery(XLogRecPtr EndRecPtr, TimeLineID replayTLI)
6981 : : {
6982 : : /* initialize minRecoveryPoint to this record */
6983 : 1 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6984 : 1 : ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
6985 [ + - ]: 1 : if (ControlFile->minRecoveryPoint < EndRecPtr)
6986 : : {
6987 : 1 : ControlFile->minRecoveryPoint = EndRecPtr;
6988 : 1 : ControlFile->minRecoveryPointTLI = replayTLI;
6989 : : }
6990 : : /* update local copy */
6991 : 1 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
6992 : :
6993 : : /*
6994 : : * The startup process can update its local copy of minRecoveryPoint from
6995 : : * this point.
6996 : : */
6997 : 1 : updateMinRecoveryPoint = true;
6998 : :
6999 : 1 : UpdateControlFile();
7000 : :
7001 : : /*
7002 : : * We update SharedRecoveryState while holding the lock on ControlFileLock
7003 : : * so both states are consistent in shared memory.
7004 : : */
7005 : 1 : SpinLockAcquire(&XLogCtl->info_lck);
7006 : 1 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_ARCHIVE;
7007 : 1 : SpinLockRelease(&XLogCtl->info_lck);
7008 : :
7009 : 1 : LWLockRelease(ControlFileLock);
7010 : 1 : }
7011 : :
7012 : : /*
7013 : : * Callback from PerformWalRecovery(), called when we reach the end of backup.
7014 : : * Updates the control file accordingly.
7015 : : */
7016 : : void
7017 : 99 : ReachedEndOfBackup(XLogRecPtr EndRecPtr, TimeLineID tli)
7018 : : {
7019 : : /*
7020 : : * We have reached the end of base backup, as indicated by pg_control. The
7021 : : * data on disk is now consistent (unless minRecoveryPoint is further
7022 : : * ahead, which can happen if we crashed during previous recovery). Reset
7023 : : * backupStartPoint and backupEndPoint, and update minRecoveryPoint to
7024 : : * make sure we don't allow starting up at an earlier point even if
7025 : : * recovery is stopped and restarted soon after this.
7026 : : */
7027 : 99 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7028 : :
7029 [ + + ]: 99 : if (ControlFile->minRecoveryPoint < EndRecPtr)
7030 : : {
7031 : 89 : ControlFile->minRecoveryPoint = EndRecPtr;
7032 : 89 : ControlFile->minRecoveryPointTLI = tli;
7033 : : }
7034 : :
7035 : 99 : ControlFile->backupStartPoint = InvalidXLogRecPtr;
7036 : 99 : ControlFile->backupEndPoint = InvalidXLogRecPtr;
7037 : 99 : ControlFile->backupEndRequired = false;
7038 : 99 : UpdateControlFile();
7039 : :
7040 : 99 : LWLockRelease(ControlFileLock);
7041 : 99 : }
7042 : :
7043 : : /*
7044 : : * Perform whatever XLOG actions are necessary at end of REDO.
7045 : : *
7046 : : * The goal here is to make sure that we'll be able to recover properly if
7047 : : * we crash again. If we choose to write a checkpoint, we'll write a shutdown
7048 : : * checkpoint rather than an on-line one. This is not particularly critical,
7049 : : * but since we may be assigning a new TLI, using a shutdown checkpoint allows
7050 : : * us to have the rule that TLI only changes in shutdown checkpoints, which
7051 : : * allows some extra error checking in xlog_redo.
7052 : : */
7053 : : static bool
7054 : 175 : PerformRecoveryXLogAction(void)
7055 : : {
7056 : 175 : bool promoted = false;
7057 : : bool flushForChecksums;
7058 : : uint32 checksum_state;
7059 : :
7060 : : /*
7061 : : * The end-of-recovery record persists the data checksum state without
7062 : : * flushing the buffer pool, but the control file may only claim "on" once
7063 : : * every page on disk carries a checksum. If replay entered that state
7064 : : * without a restartpoint following it, the pages rewritten by the
7065 : : * transition are still only in the buffer pool, so take the full
7066 : : * checkpoint below instead of the lightweight record.
7067 : : */
7068 : 175 : SpinLockAcquire(&XLogCtl->info_lck);
7069 : 175 : checksum_state = XLogCtl->data_checksum_version;
7070 : 175 : SpinLockRelease(&XLogCtl->info_lck);
7071 : :
7072 [ + + ]: 347 : flushForChecksums = (checksum_state == PG_DATA_CHECKSUM_VERSION &&
7073 [ + + ]: 172 : ControlFile->data_checksum_version != checksum_state);
7074 : :
7075 : : /*
7076 : : * Perform a checkpoint to update all our recovery activity to disk.
7077 : : *
7078 : : * Note that we write a shutdown checkpoint rather than an on-line one.
7079 : : * This is not particularly critical, but since we may be assigning a new
7080 : : * TLI, using a shutdown checkpoint allows us to have the rule that TLI
7081 : : * only changes in shutdown checkpoints, which allows some extra error
7082 : : * checking in xlog_redo.
7083 : : *
7084 : : * In promotion, only create a lightweight end-of-recovery record instead
7085 : : * of a full checkpoint. A checkpoint is requested later, after we're
7086 : : * fully out of recovery mode and already accepting queries.
7087 : : */
7088 [ + + + - : 240 : if (ArchiveRecoveryRequested && IsUnderPostmaster &&
+ + ]
7089 [ + + ]: 123 : PromoteIsTriggered() && !flushForChecksums)
7090 : : {
7091 : 57 : promoted = true;
7092 : :
7093 : : /*
7094 : : * Insert a special WAL record to mark the end of recovery, since we
7095 : : * aren't doing a checkpoint. That means that the checkpointer process
7096 : : * may likely be in the middle of a time-smoothed restartpoint and
7097 : : * could continue to be for minutes after this. That sounds strange,
7098 : : * but the effect is roughly the same and it would be stranger to try
7099 : : * to come out of the restartpoint and then checkpoint. We request a
7100 : : * checkpoint later anyway, just for safety.
7101 : : */
7102 : 57 : CreateEndOfRecoveryRecord();
7103 : : }
7104 : : else
7105 : : {
7106 : 118 : RequestCheckpoint(CHECKPOINT_END_OF_RECOVERY |
7107 : : CHECKPOINT_FAST |
7108 : : CHECKPOINT_WAIT);
7109 : : }
7110 : :
7111 : 175 : return promoted;
7112 : : }
7113 : :
7114 : : /*
7115 : : * Is the system still in recovery?
7116 : : *
7117 : : * Unlike testing InRecovery, this works in any process that's connected to
7118 : : * shared memory.
7119 : : */
7120 : : bool
7121 : 81883792 : RecoveryInProgress(void)
7122 : : {
7123 : : /*
7124 : : * We check shared state each time only until we leave recovery mode. We
7125 : : * can't re-enter recovery, so there's no need to keep checking after the
7126 : : * shared variable has once been seen false.
7127 : : */
7128 [ + + ]: 81883792 : if (!LocalRecoveryInProgress)
7129 : 79655208 : return false;
7130 : : else
7131 : : {
7132 : : /*
7133 : : * use volatile pointer to make sure we make a fresh read of the
7134 : : * shared variable.
7135 : : */
7136 : 2228584 : volatile XLogCtlData *xlogctl = XLogCtl;
7137 : :
7138 : 2228584 : LocalRecoveryInProgress = (xlogctl->SharedRecoveryState != RECOVERY_STATE_DONE);
7139 : :
7140 : : /*
7141 : : * Note: We don't need a memory barrier when we're still in recovery.
7142 : : * We might exit recovery immediately after return, so the caller
7143 : : * can't rely on 'true' meaning that we're still in recovery anyway.
7144 : : */
7145 : :
7146 : 2228584 : return LocalRecoveryInProgress;
7147 : : }
7148 : : }
7149 : :
7150 : : /*
7151 : : * Returns current recovery state from shared memory.
7152 : : *
7153 : : * This returned state is kept consistent with the contents of the control
7154 : : * file. See details about the possible values of RecoveryState in xlog.h.
7155 : : */
7156 : : RecoveryState
7157 : 17111 : GetRecoveryState(void)
7158 : : {
7159 : : RecoveryState retval;
7160 : :
7161 : 17111 : SpinLockAcquire(&XLogCtl->info_lck);
7162 : 17111 : retval = XLogCtl->SharedRecoveryState;
7163 : 17111 : SpinLockRelease(&XLogCtl->info_lck);
7164 : :
7165 : 17111 : return retval;
7166 : : }
7167 : :
7168 : : /*
7169 : : * Is this process allowed to insert new WAL records?
7170 : : *
7171 : : * Ordinarily this is essentially equivalent to !RecoveryInProgress().
7172 : : * But we also have provisions for forcing the result "true" or "false"
7173 : : * within specific processes regardless of the global state.
7174 : : */
7175 : : bool
7176 : 68843268 : XLogInsertAllowed(void)
7177 : : {
7178 : : /*
7179 : : * If value is "unconditionally true" or "unconditionally false", just
7180 : : * return it. This provides the normal fast path once recovery is known
7181 : : * done.
7182 : : */
7183 [ + + ]: 68843268 : if (LocalXLogInsertAllowed >= 0)
7184 : 68072923 : return (bool) LocalXLogInsertAllowed;
7185 : :
7186 : : /*
7187 : : * Else, must check to see if we're still in recovery.
7188 : : */
7189 [ + + ]: 770345 : if (RecoveryInProgress())
7190 : 759263 : return false;
7191 : :
7192 : : /*
7193 : : * On exit from recovery, reset to "unconditionally true", since there is
7194 : : * no need to keep checking.
7195 : : */
7196 : 11082 : LocalXLogInsertAllowed = 1;
7197 : 11082 : return true;
7198 : : }
7199 : :
7200 : : /*
7201 : : * Make XLogInsertAllowed() return true in the current process only.
7202 : : *
7203 : : * Note: it is allowed to switch LocalXLogInsertAllowed back to -1 later,
7204 : : * and even call LocalSetXLogInsertAllowed() again after that.
7205 : : *
7206 : : * Returns the previous value of LocalXLogInsertAllowed.
7207 : : */
7208 : : static int
7209 : 1098 : LocalSetXLogInsertAllowed(void)
7210 : : {
7211 : 1098 : int oldXLogAllowed = LocalXLogInsertAllowed;
7212 : :
7213 : 1098 : LocalXLogInsertAllowed = 1;
7214 : :
7215 : 1098 : return oldXLogAllowed;
7216 : : }
7217 : :
7218 : : /*
7219 : : * Return the current Redo pointer from shared memory.
7220 : : *
7221 : : * As a side-effect, the local RedoRecPtr copy is updated.
7222 : : */
7223 : : XLogRecPtr
7224 : 362897 : GetRedoRecPtr(void)
7225 : : {
7226 : : XLogRecPtr ptr;
7227 : :
7228 : : /*
7229 : : * The possibly not up-to-date copy in XLogCtl is enough. Even if we
7230 : : * grabbed a WAL insertion lock to read the authoritative value in
7231 : : * Insert->RedoRecPtr, someone might update it just after we've released
7232 : : * the lock.
7233 : : */
7234 : 362897 : SpinLockAcquire(&XLogCtl->info_lck);
7235 : 362897 : ptr = XLogCtl->RedoRecPtr;
7236 : 362897 : SpinLockRelease(&XLogCtl->info_lck);
7237 : :
7238 [ + + ]: 362897 : if (RedoRecPtr < ptr)
7239 : 1825 : RedoRecPtr = ptr;
7240 : :
7241 : 362897 : return RedoRecPtr;
7242 : : }
7243 : :
7244 : : /*
7245 : : * Return information needed to decide whether a modified block needs a
7246 : : * full-page image to be included in the WAL record.
7247 : : *
7248 : : * The returned values are cached copies from backend-private memory, and
7249 : : * possibly out-of-date or, indeed, uninitialized, in which case they will
7250 : : * be InvalidXLogRecPtr and false, respectively. XLogInsertRecord will
7251 : : * re-check them against up-to-date values, while holding the WAL insert lock.
7252 : : */
7253 : : void
7254 : 25424674 : GetFullPageWriteInfo(XLogRecPtr *RedoRecPtr_p, bool *doPageWrites_p)
7255 : : {
7256 : 25424674 : *RedoRecPtr_p = RedoRecPtr;
7257 : 25424674 : *doPageWrites_p = doPageWrites;
7258 : 25424674 : }
7259 : :
7260 : : /*
7261 : : * GetInsertRecPtr -- Returns the current insert position.
7262 : : *
7263 : : * NOTE: The value *actually* returned is the position of the last full
7264 : : * xlog page. It lags behind the real insert position by at most 1 page.
7265 : : * For that, we don't need to scan through WAL insertion locks, and an
7266 : : * approximation is enough for the current usage of this function.
7267 : : */
7268 : : XLogRecPtr
7269 : 7481 : GetInsertRecPtr(void)
7270 : : {
7271 : : XLogRecPtr recptr;
7272 : :
7273 : 7481 : SpinLockAcquire(&XLogCtl->info_lck);
7274 : 7481 : recptr = XLogCtl->LogwrtRqst.Write;
7275 : 7481 : SpinLockRelease(&XLogCtl->info_lck);
7276 : :
7277 : 7481 : return recptr;
7278 : : }
7279 : :
7280 : : /*
7281 : : * GetFlushRecPtr -- Returns the current flush position, ie, the last WAL
7282 : : * position known to be fsync'd to disk. This should only be used on a
7283 : : * system that is known not to be in recovery.
7284 : : */
7285 : : XLogRecPtr
7286 : 244091 : GetFlushRecPtr(TimeLineID *insertTLI)
7287 : : {
7288 : : Assert(XLogCtl->SharedRecoveryState == RECOVERY_STATE_DONE);
7289 : :
7290 : 244091 : RefreshXLogWriteResult(LogwrtResult);
7291 : :
7292 : : /*
7293 : : * If we're writing and flushing WAL, the time line can't be changing, so
7294 : : * no lock is required.
7295 : : */
7296 [ + + ]: 244091 : if (insertTLI)
7297 : 48614 : *insertTLI = XLogCtl->InsertTimeLineID;
7298 : :
7299 : 244091 : return LogwrtResult.Flush;
7300 : : }
7301 : :
7302 : : /*
7303 : : * GetWALInsertionTimeLine -- Returns the current timeline of a system that
7304 : : * is not in recovery.
7305 : : */
7306 : : TimeLineID
7307 : 123888 : GetWALInsertionTimeLine(void)
7308 : : {
7309 : : Assert(XLogCtl->SharedRecoveryState == RECOVERY_STATE_DONE);
7310 : :
7311 : : /* Since the value can't be changing, no lock is required. */
7312 : 123888 : return XLogCtl->InsertTimeLineID;
7313 : : }
7314 : :
7315 : : /*
7316 : : * GetWALInsertionTimeLineIfSet -- If the system is not in recovery, returns
7317 : : * the WAL insertion timeline; else, returns 0. Wherever possible, use
7318 : : * GetWALInsertionTimeLine() instead, since it's cheaper. Note that this
7319 : : * function decides recovery has ended as soon as the insert TLI is set, which
7320 : : * happens before we set XLogCtl->SharedRecoveryState to RECOVERY_STATE_DONE.
7321 : : */
7322 : : TimeLineID
7323 : 1294 : GetWALInsertionTimeLineIfSet(void)
7324 : : {
7325 : : TimeLineID insertTLI;
7326 : :
7327 : 1294 : SpinLockAcquire(&XLogCtl->info_lck);
7328 : 1294 : insertTLI = XLogCtl->InsertTimeLineID;
7329 : 1294 : SpinLockRelease(&XLogCtl->info_lck);
7330 : :
7331 : 1294 : return insertTLI;
7332 : : }
7333 : :
7334 : : /*
7335 : : * GetLastImportantRecPtr -- Returns the LSN of the last important record
7336 : : * inserted. All records not explicitly marked as unimportant are considered
7337 : : * important.
7338 : : *
7339 : : * The LSN is determined by computing the maximum of
7340 : : * WALInsertLocks[i].lastImportantAt.
7341 : : */
7342 : : XLogRecPtr
7343 : 1868 : GetLastImportantRecPtr(void)
7344 : : {
7345 : 1868 : XLogRecPtr res = InvalidXLogRecPtr;
7346 : : int i;
7347 : :
7348 [ + + ]: 16812 : for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
7349 : : {
7350 : : XLogRecPtr last_important;
7351 : :
7352 : : /*
7353 : : * Need to take a lock to prevent torn reads of the LSN, which are
7354 : : * possible on some of the supported platforms. WAL insert locks only
7355 : : * support exclusive mode, so we have to use that.
7356 : : */
7357 : 14944 : LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
7358 : 14944 : last_important = WALInsertLocks[i].l.lastImportantAt;
7359 : 14944 : LWLockRelease(&WALInsertLocks[i].l.lock);
7360 : :
7361 [ + + ]: 14944 : if (res < last_important)
7362 : 3131 : res = last_important;
7363 : : }
7364 : :
7365 : 1868 : return res;
7366 : : }
7367 : :
7368 : : /*
7369 : : * Get the time and LSN of the last xlog segment switch
7370 : : */
7371 : : pg_time_t
7372 : 0 : GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
7373 : : {
7374 : : pg_time_t result;
7375 : :
7376 : : /* Need WALWriteLock, but shared lock is sufficient */
7377 : 0 : LWLockAcquire(WALWriteLock, LW_SHARED);
7378 : 0 : result = XLogCtl->lastSegSwitchTime;
7379 : 0 : *lastSwitchLSN = XLogCtl->lastSegSwitchLSN;
7380 : 0 : LWLockRelease(WALWriteLock);
7381 : :
7382 : 0 : return result;
7383 : : }
7384 : :
7385 : : /*
7386 : : * This must be called ONCE during postmaster or standalone-backend shutdown
7387 : : */
7388 : : void
7389 : 814 : ShutdownXLOG(int code, Datum arg)
7390 : : {
7391 : : /*
7392 : : * We should have an aux process resource owner to use, and we should not
7393 : : * be in a transaction that's installed some other resowner.
7394 : : */
7395 : : Assert(AuxProcessResourceOwner != NULL);
7396 : : Assert(CurrentResourceOwner == NULL ||
7397 : : CurrentResourceOwner == AuxProcessResourceOwner);
7398 : 814 : CurrentResourceOwner = AuxProcessResourceOwner;
7399 : :
7400 : : /* Don't be chatty in standalone mode */
7401 [ + + + + ]: 814 : ereport(IsPostmasterEnvironment ? LOG : NOTICE,
7402 : : (errmsg("shutting down")));
7403 : :
7404 : : /*
7405 : : * Signal walsenders to move to stopping state.
7406 : : */
7407 : 814 : WalSndInitStopping();
7408 : :
7409 : : /*
7410 : : * Wait for WAL senders to be in stopping state. This prevents commands
7411 : : * from writing new WAL.
7412 : : */
7413 : 814 : WalSndWaitStopping();
7414 : :
7415 [ + + ]: 814 : if (RecoveryInProgress())
7416 : 70 : CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FAST);
7417 : : else
7418 : : {
7419 : : /*
7420 : : * If archiving is enabled, rotate the last XLOG file so that all the
7421 : : * remaining records are archived (postmaster wakes up the archiver
7422 : : * process one more time at the end of shutdown). The checkpoint
7423 : : * record will go to the next XLOG file and won't be archived (yet).
7424 : : */
7425 [ + + ]: 744 : if (XLogArchivingActive())
7426 : 18 : RequestXLogSwitch(false);
7427 : :
7428 : 744 : CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FAST);
7429 : : }
7430 : 814 : }
7431 : :
7432 : : /*
7433 : : * Format checkpoint request flags as a space-separated string for
7434 : : * log messages.
7435 : : */
7436 : : static const char *
7437 : 3362 : CheckpointFlagsString(int flags)
7438 : : {
7439 : : static char buf[128];
7440 : :
7441 : 26896 : snprintf(buf, sizeof(buf), "%s%s%s%s%s%s%s%s",
7442 [ + + ]: 3362 : (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
7443 [ + + ]: 3362 : (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
7444 [ + + ]: 3362 : (flags & CHECKPOINT_FAST) ? " fast" : "",
7445 [ + + ]: 3362 : (flags & CHECKPOINT_FORCE) ? " force" : "",
7446 [ + + ]: 3362 : (flags & CHECKPOINT_WAIT) ? " wait" : "",
7447 [ + + ]: 3362 : (flags & CHECKPOINT_CAUSE_XLOG) ? " wal" : "",
7448 [ + + ]: 3362 : (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "",
7449 [ + + ]: 3362 : (flags & CHECKPOINT_FLUSH_UNLOGGED) ? " flush-unlogged" : "");
7450 : :
7451 : 3362 : return buf;
7452 : : }
7453 : :
7454 : : /*
7455 : : * Log start of a checkpoint.
7456 : : */
7457 : : static void
7458 : 1681 : LogCheckpointStart(int flags, bool restartpoint)
7459 : : {
7460 [ + + ]: 1681 : if (restartpoint)
7461 [ + - ]: 213 : ereport(LOG,
7462 : : /* translator: the placeholder shows checkpoint options */
7463 : : (errmsg("restartpoint starting:%s",
7464 : : CheckpointFlagsString(flags))));
7465 : : else
7466 [ + - ]: 1468 : ereport(LOG,
7467 : : /* translator: the placeholder shows checkpoint options */
7468 : : (errmsg("checkpoint starting:%s",
7469 : : CheckpointFlagsString(flags))));
7470 : 1681 : }
7471 : :
7472 : : /*
7473 : : * Log end of a checkpoint.
7474 : : */
7475 : : static void
7476 : 2027 : LogCheckpointEnd(bool restartpoint, int flags)
7477 : : {
7478 : : long write_msecs,
7479 : : sync_msecs,
7480 : : total_msecs,
7481 : : longest_msecs,
7482 : : average_msecs;
7483 : : uint64 average_sync_time;
7484 : :
7485 : 2027 : CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
7486 : :
7487 : 2027 : write_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_write_t,
7488 : : CheckpointStats.ckpt_sync_t);
7489 : :
7490 : 2027 : sync_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_sync_t,
7491 : : CheckpointStats.ckpt_sync_end_t);
7492 : :
7493 : : /* Accumulate checkpoint timing summary data, in milliseconds. */
7494 : 2027 : PendingCheckpointerStats.write_time += write_msecs;
7495 : 2027 : PendingCheckpointerStats.sync_time += sync_msecs;
7496 : :
7497 : : /*
7498 : : * All of the published timing statistics are accounted for. Only
7499 : : * continue if a log message is to be written.
7500 : : */
7501 [ + + ]: 2027 : if (!log_checkpoints)
7502 : 346 : return;
7503 : :
7504 : 1681 : total_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_start_t,
7505 : : CheckpointStats.ckpt_end_t);
7506 : :
7507 : : /*
7508 : : * Timing values returned from CheckpointStats are in microseconds.
7509 : : * Convert to milliseconds for consistent printing.
7510 : : */
7511 : 1681 : longest_msecs = (long) ((CheckpointStats.ckpt_longest_sync + 999) / 1000);
7512 : :
7513 : 1681 : average_sync_time = 0;
7514 [ - + ]: 1681 : if (CheckpointStats.ckpt_sync_rels > 0)
7515 : 0 : average_sync_time = CheckpointStats.ckpt_agg_sync_time /
7516 : 0 : CheckpointStats.ckpt_sync_rels;
7517 : 1681 : average_msecs = (long) ((average_sync_time + 999) / 1000);
7518 : :
7519 : : /*
7520 : : * ControlFileLock is not required to see ControlFile->checkPoint and
7521 : : * ->checkPointCopy here as we are the only updator of those variables at
7522 : : * this moment.
7523 : : */
7524 [ + + ]: 1681 : if (restartpoint)
7525 [ + - ]: 213 : ereport(LOG,
7526 : : (errmsg("restartpoint complete:%s: wrote %d buffers (%.1f%%), "
7527 : : "wrote %d SLRU buffers; %d WAL file(s) added, "
7528 : : "%d removed, %d recycled; write=%ld.%03d s, "
7529 : : "sync=%ld.%03d s, total=%ld.%03d s; sync files=%d, "
7530 : : "longest=%ld.%03d s, average=%ld.%03d s; distance=%d kB, "
7531 : : "estimate=%d kB; lsn=%X/%08X, redo lsn=%X/%08X",
7532 : : CheckpointFlagsString(flags),
7533 : : CheckpointStats.ckpt_bufs_written,
7534 : : (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
7535 : : CheckpointStats.ckpt_slru_written,
7536 : : CheckpointStats.ckpt_segs_added,
7537 : : CheckpointStats.ckpt_segs_removed,
7538 : : CheckpointStats.ckpt_segs_recycled,
7539 : : write_msecs / 1000, (int) (write_msecs % 1000),
7540 : : sync_msecs / 1000, (int) (sync_msecs % 1000),
7541 : : total_msecs / 1000, (int) (total_msecs % 1000),
7542 : : CheckpointStats.ckpt_sync_rels,
7543 : : longest_msecs / 1000, (int) (longest_msecs % 1000),
7544 : : average_msecs / 1000, (int) (average_msecs % 1000),
7545 : : (int) (PrevCheckPointDistance / 1024.0),
7546 : : (int) (CheckPointDistanceEstimate / 1024.0),
7547 : : LSN_FORMAT_ARGS(ControlFile->checkPoint),
7548 : : LSN_FORMAT_ARGS(ControlFile->checkPointCopy.redo))));
7549 : : else
7550 [ + - ]: 1468 : ereport(LOG,
7551 : : (errmsg("checkpoint complete:%s: wrote %d buffers (%.1f%%), "
7552 : : "wrote %d SLRU buffers; %d WAL file(s) added, "
7553 : : "%d removed, %d recycled; write=%ld.%03d s, "
7554 : : "sync=%ld.%03d s, total=%ld.%03d s; sync files=%d, "
7555 : : "longest=%ld.%03d s, average=%ld.%03d s; distance=%d kB, "
7556 : : "estimate=%d kB; lsn=%X/%08X, redo lsn=%X/%08X",
7557 : : CheckpointFlagsString(flags),
7558 : : CheckpointStats.ckpt_bufs_written,
7559 : : (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
7560 : : CheckpointStats.ckpt_slru_written,
7561 : : CheckpointStats.ckpt_segs_added,
7562 : : CheckpointStats.ckpt_segs_removed,
7563 : : CheckpointStats.ckpt_segs_recycled,
7564 : : write_msecs / 1000, (int) (write_msecs % 1000),
7565 : : sync_msecs / 1000, (int) (sync_msecs % 1000),
7566 : : total_msecs / 1000, (int) (total_msecs % 1000),
7567 : : CheckpointStats.ckpt_sync_rels,
7568 : : longest_msecs / 1000, (int) (longest_msecs % 1000),
7569 : : average_msecs / 1000, (int) (average_msecs % 1000),
7570 : : (int) (PrevCheckPointDistance / 1024.0),
7571 : : (int) (CheckPointDistanceEstimate / 1024.0),
7572 : : LSN_FORMAT_ARGS(ControlFile->checkPoint),
7573 : : LSN_FORMAT_ARGS(ControlFile->checkPointCopy.redo))));
7574 : : }
7575 : :
7576 : : /*
7577 : : * Update the estimate of distance between checkpoints.
7578 : : *
7579 : : * The estimate is used to calculate the number of WAL segments to keep
7580 : : * preallocated, see XLOGfileslop().
7581 : : */
7582 : : static void
7583 : 2027 : UpdateCheckPointDistanceEstimate(uint64 nbytes)
7584 : : {
7585 : : /*
7586 : : * To estimate the number of segments consumed between checkpoints, keep a
7587 : : * moving average of the amount of WAL generated in previous checkpoint
7588 : : * cycles. However, if the load is bursty, with quiet periods and busy
7589 : : * periods, we want to cater for the peak load. So instead of a plain
7590 : : * moving average, let the average decline slowly if the previous cycle
7591 : : * used less WAL than estimated, but bump it up immediately if it used
7592 : : * more.
7593 : : *
7594 : : * When checkpoints are triggered by max_wal_size, this should converge to
7595 : : * CheckpointSegments * wal_segment_size,
7596 : : *
7597 : : * Note: This doesn't pay any attention to what caused the checkpoint.
7598 : : * Checkpoints triggered manually with CHECKPOINT command, or by e.g.
7599 : : * starting a base backup, are counted the same as those created
7600 : : * automatically. The slow-decline will largely mask them out, if they are
7601 : : * not frequent. If they are frequent, it seems reasonable to count them
7602 : : * in as any others; if you issue a manual checkpoint every 5 minutes and
7603 : : * never let a timed checkpoint happen, it makes sense to base the
7604 : : * preallocation on that 5 minute interval rather than whatever
7605 : : * checkpoint_timeout is set to.
7606 : : */
7607 : 2027 : PrevCheckPointDistance = nbytes;
7608 [ + + ]: 2027 : if (CheckPointDistanceEstimate < nbytes)
7609 : 929 : CheckPointDistanceEstimate = nbytes;
7610 : : else
7611 : 1098 : CheckPointDistanceEstimate =
7612 : 1098 : (0.90 * CheckPointDistanceEstimate + 0.10 * (double) nbytes);
7613 : 2027 : }
7614 : :
7615 : : /*
7616 : : * Update the ps display for a process running a checkpoint. Note that
7617 : : * this routine should not do any allocations so as it can be called
7618 : : * from a critical section.
7619 : : */
7620 : : static void
7621 : 4054 : update_checkpoint_display(int flags, bool restartpoint, bool reset)
7622 : : {
7623 : : /*
7624 : : * The status is reported only for end-of-recovery and shutdown
7625 : : * checkpoints or shutdown restartpoints. Updating the ps display is
7626 : : * useful in those situations as it may not be possible to rely on
7627 : : * pg_stat_activity to see the status of the checkpointer or the startup
7628 : : * process.
7629 : : */
7630 [ + + ]: 4054 : if ((flags & (CHECKPOINT_END_OF_RECOVERY | CHECKPOINT_IS_SHUTDOWN)) == 0)
7631 : 2454 : return;
7632 : :
7633 [ + + ]: 1600 : if (reset)
7634 : 800 : set_ps_display("");
7635 : : else
7636 : : {
7637 : : char activitymsg[128];
7638 : :
7639 [ + + ]: 2400 : snprintf(activitymsg, sizeof(activitymsg), "performing %s%s%s",
7640 [ + + ]: 800 : (flags & CHECKPOINT_END_OF_RECOVERY) ? "end-of-recovery " : "",
7641 [ + + ]: 800 : (flags & CHECKPOINT_IS_SHUTDOWN) ? "shutdown " : "",
7642 : : restartpoint ? "restartpoint" : "checkpoint");
7643 : 800 : set_ps_display(activitymsg);
7644 : : }
7645 : : }
7646 : :
7647 : :
7648 : : /*
7649 : : * Perform a checkpoint --- either during shutdown, or on-the-fly
7650 : : *
7651 : : * flags is a bitwise OR of the following:
7652 : : * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
7653 : : * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
7654 : : * CHECKPOINT_FAST: finish the checkpoint ASAP, ignoring
7655 : : * checkpoint_completion_target parameter.
7656 : : * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
7657 : : * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
7658 : : * CHECKPOINT_END_OF_RECOVERY).
7659 : : * CHECKPOINT_FLUSH_UNLOGGED: also flush buffers of unlogged tables.
7660 : : *
7661 : : * Note: flags contains other bits, of interest here only for logging purposes.
7662 : : * In particular note that this routine is synchronous and does not pay
7663 : : * attention to CHECKPOINT_WAIT.
7664 : : *
7665 : : * If !shutdown then we are writing an online checkpoint. An XLOG_CHECKPOINT_REDO
7666 : : * record is inserted into WAL at the logical location of the checkpoint, before
7667 : : * flushing anything to disk, and when the checkpoint is eventually completed,
7668 : : * and it is from this point that WAL replay will begin in the case of a recovery
7669 : : * from this checkpoint. Once everything is written to disk, an
7670 : : * XLOG_CHECKPOINT_ONLINE record is written to complete the checkpoint, and
7671 : : * points back to the earlier XLOG_CHECKPOINT_REDO record. This mechanism allows
7672 : : * other write-ahead log records to be written while the checkpoint is in
7673 : : * progress, but we must be very careful about order of operations. This function
7674 : : * may take many minutes to execute on a busy system.
7675 : : *
7676 : : * On the other hand, when shutdown is true, concurrent insertion into the
7677 : : * write-ahead log is impossible, so there is no need for two separate records.
7678 : : * In this case, we only insert an XLOG_CHECKPOINT_SHUTDOWN record, and it's
7679 : : * both the record marking the completion of the checkpoint and the location
7680 : : * from which WAL replay would begin if needed.
7681 : : *
7682 : : * Returns true if a new checkpoint was performed, or false if it was skipped
7683 : : * because the system was idle.
7684 : : */
7685 : : bool
7686 : 1816 : CreateCheckPoint(int flags)
7687 : : {
7688 : : bool shutdown;
7689 : : CheckPoint checkPoint;
7690 : : XLogRecPtr recptr;
7691 : : XLogSegNo _logSegNo;
7692 : 1816 : XLogCtlInsert *Insert = &XLogCtl->Insert;
7693 : : uint32 freespace;
7694 : : XLogRecPtr PriorRedoPtr;
7695 : : XLogRecPtr last_important_lsn;
7696 : : XLogRecPtr checksumLsn;
7697 : : VirtualTransactionId *vxids;
7698 : : int nvxids;
7699 : 1816 : int oldXLogAllowed = 0;
7700 : :
7701 : : /*
7702 : : * An end-of-recovery checkpoint is really a shutdown checkpoint, just
7703 : : * issued at a different time.
7704 : : */
7705 [ + + ]: 1816 : if (flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY))
7706 : 776 : shutdown = true;
7707 : : else
7708 : 1040 : shutdown = false;
7709 : :
7710 : : /* sanity check */
7711 [ + + - + ]: 1816 : if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
7712 [ # # ]: 0 : elog(ERROR, "can't create a checkpoint during recovery");
7713 : :
7714 : : /*
7715 : : * Prepare to accumulate statistics.
7716 : : *
7717 : : * Note: because it is possible for log_checkpoints to change while a
7718 : : * checkpoint proceeds, we always accumulate stats, even if
7719 : : * log_checkpoints is currently off.
7720 : : */
7721 [ + - + - : 19976 : MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
+ - + - +
+ ]
7722 : 1816 : CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
7723 : :
7724 : : /*
7725 : : * Let smgr prepare for checkpoint; this has to happen outside the
7726 : : * critical section and before we determine the REDO pointer. Note that
7727 : : * smgr must not do anything that'd have to be undone if we decide no
7728 : : * checkpoint is needed.
7729 : : */
7730 : 1816 : SyncPreCheckpoint();
7731 : :
7732 : : /* Run these points outside the critical section. */
7733 : 1816 : INJECTION_POINT("create-checkpoint-initial", NULL);
7734 : 1816 : INJECTION_POINT_LOAD("create-checkpoint-run");
7735 : :
7736 : : /*
7737 : : * Use a critical section to force system panic if we have trouble.
7738 : : */
7739 : 1816 : START_CRIT_SECTION();
7740 : :
7741 [ + + ]: 1816 : if (shutdown)
7742 : : {
7743 : 776 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7744 : 776 : ControlFile->state = DB_SHUTDOWNING;
7745 : 776 : UpdateControlFile();
7746 : 776 : LWLockRelease(ControlFileLock);
7747 : : }
7748 : :
7749 : : /* Begin filling in the checkpoint WAL record */
7750 [ + - + - : 25424 : MemSet(&checkPoint, 0, sizeof(checkPoint));
+ - + - +
+ ]
7751 : 1816 : checkPoint.time = (pg_time_t) time(NULL);
7752 : :
7753 : : /*
7754 : : * For Hot Standby, derive the oldestActiveXid before we fix the redo
7755 : : * pointer. This allows us to begin accumulating changes to assemble our
7756 : : * starting snapshot of locks and transactions.
7757 : : */
7758 [ + + + + ]: 1816 : if (!shutdown && XLogStandbyInfoActive())
7759 : 978 : checkPoint.oldestActiveXid = GetOldestActiveTransactionId(false, true);
7760 : : else
7761 : 838 : checkPoint.oldestActiveXid = InvalidTransactionId;
7762 : :
7763 : : /*
7764 : : * Get location of last important record before acquiring insert locks (as
7765 : : * GetLastImportantRecPtr() also locks WAL locks).
7766 : : */
7767 : 1816 : last_important_lsn = GetLastImportantRecPtr();
7768 : :
7769 : : /*
7770 : : * If this isn't a shutdown or forced checkpoint, and if there has been no
7771 : : * WAL activity requiring a checkpoint, skip it. The idea here is to
7772 : : * avoid inserting duplicate checkpoints when the system is idle.
7773 : : */
7774 [ + + ]: 1816 : if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
7775 : : CHECKPOINT_FORCE)) == 0)
7776 : : {
7777 [ + + ]: 204 : if (last_important_lsn == ControlFile->checkPoint)
7778 : : {
7779 : 2 : END_CRIT_SECTION();
7780 [ - + ]: 2 : ereport(DEBUG1,
7781 : : (errmsg_internal("checkpoint skipped because system is idle")));
7782 : 2 : return false;
7783 : : }
7784 : : }
7785 : :
7786 : : /*
7787 : : * An end-of-recovery checkpoint is created before anyone is allowed to
7788 : : * write WAL. To allow us to write the checkpoint record, temporarily
7789 : : * enable XLogInsertAllowed.
7790 : : */
7791 [ + + ]: 1814 : if (flags & CHECKPOINT_END_OF_RECOVERY)
7792 : 32 : oldXLogAllowed = LocalSetXLogInsertAllowed();
7793 : :
7794 : 1814 : checkPoint.ThisTimeLineID = XLogCtl->InsertTimeLineID;
7795 [ + + ]: 1814 : if (flags & CHECKPOINT_END_OF_RECOVERY)
7796 : 32 : checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
7797 : : else
7798 : 1782 : checkPoint.PrevTimeLineID = checkPoint.ThisTimeLineID;
7799 : :
7800 : : /*
7801 : : * We must block concurrent insertions while examining insert state.
7802 : : */
7803 : 1814 : WALInsertLockAcquireExclusive();
7804 : :
7805 : 1814 : checkPoint.fullPageWrites = Insert->fullPageWrites;
7806 : 1814 : checkPoint.wal_level = wal_level;
7807 : :
7808 : : /*
7809 : : * Get the current data_checksum_version value from xlogctl. This is
7810 : : * final only for a shutdown checkpoint, where no concurrent transition is
7811 : : * possible; an online checkpoint resamples it together with the redo
7812 : : * record below.
7813 : : */
7814 : 1814 : SpinLockAcquire(&XLogCtl->info_lck);
7815 : 1814 : checkPoint.dataChecksumState = XLogCtl->data_checksum_version;
7816 : 1814 : checksumLsn = XLogCtl->data_checksum_lsn;
7817 : 1814 : SpinLockRelease(&XLogCtl->info_lck);
7818 : :
7819 [ + + ]: 1814 : if (shutdown)
7820 : : {
7821 : 776 : XLogRecPtr curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
7822 : :
7823 : : /*
7824 : : * Compute new REDO record ptr = location of next XLOG record.
7825 : : *
7826 : : * Since this is a shutdown checkpoint, there can't be any concurrent
7827 : : * WAL insertion.
7828 : : */
7829 [ + - ]: 776 : freespace = INSERT_FREESPACE(curInsert);
7830 [ - + ]: 776 : if (freespace == 0)
7831 : : {
7832 [ # # ]: 0 : if (XLogSegmentOffset(curInsert, wal_segment_size) == 0)
7833 : 0 : curInsert += SizeOfXLogLongPHD;
7834 : : else
7835 : 0 : curInsert += SizeOfXLogShortPHD;
7836 : : }
7837 : 776 : checkPoint.redo = curInsert;
7838 : :
7839 : : /*
7840 : : * Here we update the shared RedoRecPtr for future XLogInsert calls;
7841 : : * this must be done while holding all the insertion locks.
7842 : : *
7843 : : * Note: if we fail to complete the checkpoint, RedoRecPtr will be
7844 : : * left pointing past where it really needs to point. This is okay;
7845 : : * the only consequence is that XLogInsert might back up whole buffers
7846 : : * that it didn't really need to. We can't postpone advancing
7847 : : * RedoRecPtr because XLogInserts that happen while we are dumping
7848 : : * buffers must assume that their buffer changes are not included in
7849 : : * the checkpoint.
7850 : : */
7851 : 776 : RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
7852 : : }
7853 : :
7854 : : /*
7855 : : * Now we can release the WAL insertion locks, allowing other xacts to
7856 : : * proceed while we are flushing disk buffers.
7857 : : */
7858 : 1814 : WALInsertLockRelease();
7859 : :
7860 : : /*
7861 : : * If this is an online checkpoint, we have not yet determined the redo
7862 : : * point. We do so now by inserting the special XLOG_CHECKPOINT_REDO
7863 : : * record; the LSN at which it starts becomes the new redo pointer. We
7864 : : * don't do this for a shutdown checkpoint, because in that case no WAL
7865 : : * can be written between the redo point and the insertion of the
7866 : : * checkpoint record itself, so the checkpoint record itself serves to
7867 : : * mark the redo point.
7868 : : */
7869 [ + + ]: 1814 : if (!shutdown)
7870 : : {
7871 : : xl_checkpoint_redo redo_rec;
7872 : :
7873 : : /*
7874 : : * Sample the data checksum state and insert the redo record under
7875 : : * DataChecksumTransitionLock, so that a concurrent transition cannot
7876 : : * insert its XLOG2_CHECKSUMS record between the sampling and the
7877 : : * insertion below. Without this, the redo record could follow the
7878 : : * transition record in WAL while carrying the pre-transition state,
7879 : : * and recovery resuming here would never learn about the transition.
7880 : : * See XLogChecksums().
7881 : : */
7882 : 1038 : LWLockAcquire(DataChecksumTransitionLock, LW_EXCLUSIVE);
7883 : 1038 : WALInsertLockAcquire();
7884 : 1038 : redo_rec.wal_level = wal_level;
7885 : 1038 : SpinLockAcquire(&XLogCtl->info_lck);
7886 : 1038 : redo_rec.data_checksum_version = XLogCtl->data_checksum_version;
7887 : 1038 : checksumLsn = XLogCtl->data_checksum_lsn;
7888 : 1038 : SpinLockRelease(&XLogCtl->info_lck);
7889 : 1038 : WALInsertLockRelease();
7890 : :
7891 : : /* Include WAL level in record for WAL summarizer's benefit. */
7892 : 1038 : XLogBeginInsert();
7893 : 1038 : XLogRegisterData(&redo_rec, sizeof(xl_checkpoint_redo));
7894 : 1038 : (void) XLogInsert(RM_XLOG_ID, XLOG_CHECKPOINT_REDO);
7895 : 1038 : LWLockRelease(DataChecksumTransitionLock);
7896 : :
7897 : : /*
7898 : : * The checkpoint record must carry the same state as the redo record
7899 : : * just inserted: the sample taken before redo determination can be
7900 : : * stale by now, and the pair would otherwise disagree.
7901 : : */
7902 : 1038 : checkPoint.dataChecksumState = redo_rec.data_checksum_version;
7903 : :
7904 : : /*
7905 : : * XLogInsertRecord will have updated XLogCtl->Insert.RedoRecPtr in
7906 : : * shared memory and RedoRecPtr in backend-local memory, but we need
7907 : : * to copy that into the record that will be inserted when the
7908 : : * checkpoint is complete.
7909 : : */
7910 : 1038 : checkPoint.redo = RedoRecPtr;
7911 : : }
7912 : :
7913 : : /* Update the info_lck-protected copy of RedoRecPtr as well */
7914 : 1814 : SpinLockAcquire(&XLogCtl->info_lck);
7915 : 1814 : XLogCtl->RedoRecPtr = checkPoint.redo;
7916 : 1814 : SpinLockRelease(&XLogCtl->info_lck);
7917 : :
7918 : : /*
7919 : : * If enabled, log checkpoint start. We postpone this until now so as not
7920 : : * to log anything if we decided to skip the checkpoint.
7921 : : */
7922 [ + + ]: 1814 : if (log_checkpoints)
7923 : 1468 : LogCheckpointStart(flags, false);
7924 : :
7925 : 1814 : INJECTION_POINT_CACHED("create-checkpoint-run", NULL);
7926 : :
7927 : : /* Update the process title */
7928 : 1814 : update_checkpoint_display(flags, false, false);
7929 : :
7930 : : TRACE_POSTGRESQL_CHECKPOINT_START(flags);
7931 : :
7932 : : /*
7933 : : * Get the other info we need for the checkpoint record.
7934 : : *
7935 : : * We don't need to save oldestClogXid in the checkpoint, it only matters
7936 : : * for the short period in which clog is being truncated, and if we crash
7937 : : * during that we'll redo the clog truncation and fix up oldestClogXid
7938 : : * there.
7939 : : */
7940 : 1814 : LWLockAcquire(XidGenLock, LW_SHARED);
7941 : 1814 : checkPoint.nextXid = TransamVariables->nextXid;
7942 : 1814 : checkPoint.oldestXid = TransamVariables->oldestXid;
7943 : 1814 : checkPoint.oldestXidDB = TransamVariables->oldestXidDB;
7944 : 1814 : LWLockRelease(XidGenLock);
7945 : :
7946 : 1814 : LWLockAcquire(CommitTsLock, LW_SHARED);
7947 : 1814 : checkPoint.oldestCommitTsXid = TransamVariables->oldestCommitTsXid;
7948 : 1814 : checkPoint.newestCommitTsXid = TransamVariables->newestCommitTsXid;
7949 : 1814 : LWLockRelease(CommitTsLock);
7950 : :
7951 : 1814 : LWLockAcquire(OidGenLock, LW_SHARED);
7952 : 1814 : checkPoint.nextOid = TransamVariables->nextOid;
7953 [ + + ]: 1814 : if (!shutdown)
7954 : 1038 : checkPoint.nextOid += TransamVariables->oidCount;
7955 : 1814 : LWLockRelease(OidGenLock);
7956 : :
7957 : 1814 : checkPoint.logicalDecodingEnabled = IsLogicalDecodingEnabled();
7958 : :
7959 : 1814 : MultiXactGetCheckptMulti(shutdown,
7960 : : &checkPoint.nextMulti,
7961 : : &checkPoint.nextMultiOffset,
7962 : : &checkPoint.oldestMulti,
7963 : : &checkPoint.oldestMultiDB);
7964 : :
7965 : : /*
7966 : : * Having constructed the checkpoint record, ensure all shmem disk buffers
7967 : : * and commit-log buffers are flushed to disk.
7968 : : *
7969 : : * This I/O could fail for various reasons. If so, we will fail to
7970 : : * complete the checkpoint, but there is no reason to force a system
7971 : : * panic. Accordingly, exit critical section while doing it.
7972 : : */
7973 : 1814 : END_CRIT_SECTION();
7974 : :
7975 : : /*
7976 : : * In some cases there are groups of actions that must all occur on one
7977 : : * side or the other of a checkpoint record. Before flushing the
7978 : : * checkpoint record we must explicitly wait for any backend currently
7979 : : * performing those groups of actions.
7980 : : *
7981 : : * One example is end of transaction, so we must wait for any transactions
7982 : : * that are currently in commit critical sections. If an xact inserted
7983 : : * its commit record into XLOG just before the REDO point, then a crash
7984 : : * restart from the REDO point would not replay that record, which means
7985 : : * that our flushing had better include the xact's update of pg_xact. So
7986 : : * we wait till he's out of his commit critical section before proceeding.
7987 : : * See notes in RecordTransactionCommit().
7988 : : *
7989 : : * Because we've already released the insertion locks, this test is a bit
7990 : : * fuzzy: it is possible that we will wait for xacts we didn't really need
7991 : : * to wait for. But the delay should be short and it seems better to make
7992 : : * checkpoint take a bit longer than to hold off insertions longer than
7993 : : * necessary. (In fact, the whole reason we have this issue is that xact.c
7994 : : * does commit record XLOG insertion and clog update as two separate steps
7995 : : * protected by different locks, but again that seems best on grounds of
7996 : : * minimizing lock contention.)
7997 : : *
7998 : : * A transaction that has not yet set delayChkptFlags when we look cannot
7999 : : * be at risk, since it has not inserted its commit record yet; and one
8000 : : * that's already cleared it is not at risk either, since it's done fixing
8001 : : * clog and we will correctly flush the update below. So we cannot miss
8002 : : * any xacts we need to wait for.
8003 : : */
8004 : 1814 : vxids = GetVirtualXIDsDelayingChkpt(&nvxids, DELAY_CHKPT_START);
8005 [ + + ]: 1814 : if (nvxids > 0)
8006 : : {
8007 : : do
8008 : : {
8009 : : /*
8010 : : * Keep absorbing fsync requests while we wait. There could even
8011 : : * be a deadlock if we don't, if the process that prevents the
8012 : : * checkpoint is trying to add a request to the queue.
8013 : : */
8014 : 15 : AbsorbSyncRequests();
8015 : :
8016 : 15 : pgstat_report_wait_start(WAIT_EVENT_CHECKPOINT_DELAY_START);
8017 : 15 : pg_usleep(10000L); /* wait for 10 msec */
8018 : 15 : pgstat_report_wait_end();
8019 [ + + ]: 15 : } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids,
8020 : : DELAY_CHKPT_START));
8021 : : }
8022 : 1814 : pfree(vxids);
8023 : :
8024 : 1814 : CheckPointGuts(checkPoint.redo, flags);
8025 : :
8026 : 1814 : vxids = GetVirtualXIDsDelayingChkpt(&nvxids, DELAY_CHKPT_COMPLETE);
8027 [ - + ]: 1814 : if (nvxids > 0)
8028 : : {
8029 : : do
8030 : : {
8031 : 0 : AbsorbSyncRequests();
8032 : :
8033 : 0 : pgstat_report_wait_start(WAIT_EVENT_CHECKPOINT_DELAY_COMPLETE);
8034 : 0 : pg_usleep(10000L); /* wait for 10 msec */
8035 : 0 : pgstat_report_wait_end();
8036 [ # # ]: 0 : } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids,
8037 : : DELAY_CHKPT_COMPLETE));
8038 : : }
8039 : 1814 : pfree(vxids);
8040 : :
8041 : : /*
8042 : : * Take a snapshot of running transactions and write this to WAL. This
8043 : : * allows us to reconstruct the state of running transactions during
8044 : : * archive recovery, if required. Skip, if this info disabled.
8045 : : *
8046 : : * If we are shutting down, or Startup process is completing crash
8047 : : * recovery we don't need to write running xact data.
8048 : : */
8049 [ + + + + ]: 1814 : if (!shutdown && XLogStandbyInfoActive())
8050 : 976 : LogStandbySnapshot();
8051 : :
8052 : 1814 : START_CRIT_SECTION();
8053 : :
8054 : : /*
8055 : : * Now insert the checkpoint record into XLOG.
8056 : : */
8057 : 1814 : XLogBeginInsert();
8058 : 1814 : XLogRegisterData(&checkPoint, sizeof(checkPoint));
8059 [ + + ]: 1814 : recptr = XLogInsert(RM_XLOG_ID,
8060 : : shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
8061 : : XLOG_CHECKPOINT_ONLINE);
8062 : :
8063 : 1814 : XLogFlush(recptr);
8064 : :
8065 : : /*
8066 : : * We mustn't write any new WAL after a shutdown checkpoint, or it will be
8067 : : * overwritten at next startup. No-one should even try, this just allows
8068 : : * sanity-checking. In the case of an end-of-recovery checkpoint, we want
8069 : : * to just temporarily disable writing until the system has exited
8070 : : * recovery.
8071 : : */
8072 [ + + ]: 1814 : if (shutdown)
8073 : : {
8074 [ + + ]: 776 : if (flags & CHECKPOINT_END_OF_RECOVERY)
8075 : 32 : LocalXLogInsertAllowed = oldXLogAllowed;
8076 : : else
8077 : 744 : LocalXLogInsertAllowed = 0; /* never again write WAL */
8078 : : }
8079 : :
8080 : : /*
8081 : : * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
8082 : : * = end of actual checkpoint record.
8083 : : */
8084 [ + + - + ]: 1814 : if (shutdown && checkPoint.redo != ProcLastRecPtr)
8085 [ # # ]: 0 : ereport(PANIC,
8086 : : (errmsg("concurrent write-ahead log activity while database system is shutting down")));
8087 : :
8088 : : /*
8089 : : * Remember the prior checkpoint's redo ptr for
8090 : : * UpdateCheckPointDistanceEstimate()
8091 : : */
8092 : 1814 : PriorRedoPtr = ControlFile->checkPointCopy.redo;
8093 : :
8094 : : /*
8095 : : * Update the control file.
8096 : : */
8097 : 1814 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8098 [ + + ]: 1814 : if (shutdown)
8099 : 776 : ControlFile->state = DB_SHUTDOWNED;
8100 : 1814 : ControlFile->checkPoint = ProcLastRecPtr;
8101 : 1814 : ControlFile->checkPointCopy = checkPoint;
8102 : : /* crash recovery should always recover to the end of WAL */
8103 : 1814 : ControlFile->minRecoveryPoint = InvalidXLogRecPtr;
8104 : 1814 : ControlFile->minRecoveryPointTLI = 0;
8105 : :
8106 : : /*
8107 : : * Persist the data checksum state this node runs under into the control
8108 : : * file. Only the top-level field tracks this node, checkPointCopy is a
8109 : : * historical record used to resume replay.
8110 : : *
8111 : : * checkPoint.dataChecksumState was sampled while holding the
8112 : : * DataChecksumTransitionLock together with the redo record, so it is the
8113 : : * state in effect at the redo point. If it was "on", the XLOG2_CHECKSUMS
8114 : : * record announcing that precedes the redo point and every page the
8115 : : * transition rewrote was dirtied before it, so CheckPointGuts() has just
8116 : : * written all of them out. Recording the state here is what keeps a
8117 : : * finished transition from being resolved as interrupted when this
8118 : : * checkpoint is the one crash recovery resumes from: replay never sees
8119 : : * the record announcing it.
8120 : : *
8121 : : * Persist it only if the state did not change while the flush was in
8122 : : * progress. If it changed in between, the pages written out straddle two
8123 : : * states, and the newer one could claim checksums that pages already on
8124 : : * disk do not carry; leave the field to the next checkpoint then, the
8125 : : * transition itself has already persisted every state that is safe
8126 : : * without a flush.
8127 : : *
8128 : : * Compare the watermark rather than the state: record positions are
8129 : : * unique, so a full round trip back to the sampled state cannot alias,
8130 : : * while its flushed pages straddle the intermediate states all the same.
8131 : : */
8132 : 1814 : SpinLockAcquire(&XLogCtl->info_lck);
8133 [ + + ]: 1814 : if (checksumLsn == XLogCtl->data_checksum_lsn)
8134 : : {
8135 : 1810 : ControlFile->data_checksum_version = checkPoint.dataChecksumState;
8136 : 1810 : ControlFile->data_checksum_lsn = checksumLsn;
8137 : 1810 : ControlFile->data_checksum_is_local = XLogCtl->data_checksum_is_local;
8138 : : }
8139 : 1814 : SpinLockRelease(&XLogCtl->info_lck);
8140 : :
8141 : : /*
8142 : : * Persist unloggedLSN value. It's reset on crash recovery, so this goes
8143 : : * unused on non-shutdown checkpoints, but seems useful to store it always
8144 : : * for debugging purposes.
8145 : : */
8146 : 1814 : ControlFile->unloggedLSN = pg_atomic_read_membarrier_u64(&XLogCtl->unloggedLSN);
8147 : :
8148 : 1814 : UpdateControlFile();
8149 : 1814 : LWLockRelease(ControlFileLock);
8150 : :
8151 : : /*
8152 : : * We are now done with critical updates; no need for system panic if we
8153 : : * have trouble while fooling with old log segments.
8154 : : */
8155 : 1814 : END_CRIT_SECTION();
8156 : :
8157 : : /*
8158 : : * WAL summaries end when the next XLOG_CHECKPOINT_REDO or
8159 : : * XLOG_CHECKPOINT_SHUTDOWN record is reached. This is the first point
8160 : : * where (a) we're not inside of a critical section and (b) we can be
8161 : : * certain that the relevant record has been flushed to disk, which must
8162 : : * happen before it can be summarized.
8163 : : *
8164 : : * If this is a shutdown checkpoint, then this happens reasonably
8165 : : * promptly: we've only just inserted and flushed the
8166 : : * XLOG_CHECKPOINT_SHUTDOWN record. If this is not a shutdown checkpoint,
8167 : : * then this might not be very prompt at all: the XLOG_CHECKPOINT_REDO
8168 : : * record was written before we began flushing data to disk, and that
8169 : : * could be many minutes ago at this point. However, we don't XLogFlush()
8170 : : * after inserting that record, so we're not guaranteed that it's on disk
8171 : : * until after the above call that flushes the XLOG_CHECKPOINT_ONLINE
8172 : : * record.
8173 : : */
8174 : 1814 : WakeupWalSummarizer();
8175 : :
8176 : : /*
8177 : : * Let smgr do post-checkpoint cleanup (eg, deleting old files).
8178 : : */
8179 : 1814 : SyncPostCheckpoint();
8180 : :
8181 : : /*
8182 : : * Update the average distance between checkpoints if the prior checkpoint
8183 : : * exists.
8184 : : */
8185 [ + - ]: 1814 : if (XLogRecPtrIsValid(PriorRedoPtr))
8186 : 1814 : UpdateCheckPointDistanceEstimate(RedoRecPtr - PriorRedoPtr);
8187 : :
8188 : 1814 : INJECTION_POINT("checkpoint-before-old-wal-removal", NULL);
8189 : :
8190 : : /*
8191 : : * Delete old log files, those no longer needed for last checkpoint to
8192 : : * prevent the disk holding the xlog from growing full.
8193 : : */
8194 : 1814 : XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
8195 : 1814 : KeepLogSeg(recptr, &_logSegNo);
8196 [ + + ]: 1814 : if (InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_REMOVED | RS_INVAL_IDLE_TIMEOUT,
8197 : : _logSegNo, InvalidOid,
8198 : : InvalidTransactionId))
8199 : : {
8200 : : /*
8201 : : * Some slots have been invalidated; recalculate the old-segment
8202 : : * horizon, starting again from RedoRecPtr.
8203 : : */
8204 : 4 : XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
8205 : 4 : KeepLogSeg(recptr, &_logSegNo);
8206 : : }
8207 : 1814 : _logSegNo--;
8208 : 1814 : RemoveOldXlogFiles(_logSegNo, RedoRecPtr, recptr,
8209 : : checkPoint.ThisTimeLineID);
8210 : :
8211 : : /*
8212 : : * Make more log segments if needed. (Do this after recycling old log
8213 : : * segments, since that may supply some of the needed files.)
8214 : : */
8215 [ + + ]: 1814 : if (!shutdown)
8216 : 1038 : PreallocXlogFiles(recptr, checkPoint.ThisTimeLineID);
8217 : :
8218 : : /*
8219 : : * Truncate pg_subtrans if possible. We can throw away all data before
8220 : : * the oldest XMIN of any running transaction. No future transaction will
8221 : : * attempt to reference any pg_subtrans entry older than that (see Asserts
8222 : : * in subtrans.c). During recovery, though, we mustn't do this because
8223 : : * StartupSUBTRANS hasn't been called yet.
8224 : : */
8225 [ + + ]: 1814 : if (!RecoveryInProgress())
8226 : 1782 : TruncateSUBTRANS(GetOldestTransactionIdConsideredRunning());
8227 : :
8228 : : /* Real work is done; log and update stats. */
8229 : 1814 : LogCheckpointEnd(false, flags);
8230 : :
8231 : : /* Reset the process title */
8232 : 1814 : update_checkpoint_display(flags, false, true);
8233 : :
8234 : : TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
8235 : : NBuffers,
8236 : : CheckpointStats.ckpt_segs_added,
8237 : : CheckpointStats.ckpt_segs_removed,
8238 : : CheckpointStats.ckpt_segs_recycled);
8239 : :
8240 : 1814 : return true;
8241 : : }
8242 : :
8243 : : /*
8244 : : * Mark the end of recovery in WAL though without running a full checkpoint.
8245 : : * We can expect that a restartpoint is likely to be in progress as we
8246 : : * do this, though we are unwilling to wait for it to complete.
8247 : : *
8248 : : * CreateRestartPoint() allows for the case where recovery may end before
8249 : : * the restartpoint completes so there is no concern of concurrent behaviour.
8250 : : */
8251 : : static void
8252 : 57 : CreateEndOfRecoveryRecord(void)
8253 : : {
8254 : : xl_end_of_recovery xlrec;
8255 : : XLogRecPtr recptr;
8256 : :
8257 : : /* sanity check */
8258 [ - + ]: 57 : if (!RecoveryInProgress())
8259 [ # # ]: 0 : elog(ERROR, "can only be used to end recovery");
8260 : :
8261 : 57 : xlrec.end_time = GetCurrentTimestamp();
8262 : 57 : xlrec.wal_level = wal_level;
8263 : :
8264 : 57 : WALInsertLockAcquireExclusive();
8265 : 57 : xlrec.ThisTimeLineID = XLogCtl->InsertTimeLineID;
8266 : 57 : xlrec.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8267 : 57 : WALInsertLockRelease();
8268 : :
8269 : 57 : START_CRIT_SECTION();
8270 : :
8271 : 57 : XLogBeginInsert();
8272 : 57 : XLogRegisterData(&xlrec, sizeof(xl_end_of_recovery));
8273 : 57 : recptr = XLogInsert(RM_XLOG_ID, XLOG_END_OF_RECOVERY);
8274 : :
8275 : 57 : XLogFlush(recptr);
8276 : :
8277 : : /*
8278 : : * Update the control file so that crash recovery can follow the timeline
8279 : : * changes to this point.
8280 : : */
8281 : 57 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8282 : 57 : ControlFile->minRecoveryPoint = recptr;
8283 : 57 : ControlFile->minRecoveryPointTLI = xlrec.ThisTimeLineID;
8284 : :
8285 : : /* persist the data checksum state this node ended recovery with */
8286 : 57 : SpinLockAcquire(&XLogCtl->info_lck);
8287 : 57 : ControlFile->data_checksum_version = XLogCtl->data_checksum_version;
8288 : 57 : ControlFile->data_checksum_lsn = XLogCtl->data_checksum_lsn;
8289 : 57 : ControlFile->data_checksum_is_local = XLogCtl->data_checksum_is_local;
8290 : 57 : SpinLockRelease(&XLogCtl->info_lck);
8291 : :
8292 : 57 : UpdateControlFile();
8293 : 57 : LWLockRelease(ControlFileLock);
8294 : :
8295 : 57 : END_CRIT_SECTION();
8296 : 57 : }
8297 : :
8298 : : /*
8299 : : * Write an OVERWRITE_CONTRECORD message.
8300 : : *
8301 : : * When on WAL replay we expect a continuation record at the start of a page
8302 : : * that is not there, recovery ends and WAL writing resumes at that point.
8303 : : * But it's wrong to resume writing new WAL back at the start of the record
8304 : : * that was broken, because downstream consumers of that WAL (physical
8305 : : * replicas) are not prepared to "rewind". So the first action after
8306 : : * finishing replay of all valid WAL must be to write a record of this type
8307 : : * at the point where the contrecord was missing; to support xlogreader
8308 : : * detecting the special case, XLP_FIRST_IS_OVERWRITE_CONTRECORD is also added
8309 : : * to the page header where the record occurs. xlogreader has an ad-hoc
8310 : : * mechanism to report metadata about the broken record, which is what we
8311 : : * use here.
8312 : : *
8313 : : * At replay time, XLP_FIRST_IS_OVERWRITE_CONTRECORD instructs xlogreader to
8314 : : * skip the record it was reading, and pass back the LSN of the skipped
8315 : : * record, so that its caller can verify (on "replay" of that record) that the
8316 : : * XLOG_OVERWRITE_CONTRECORD matches what was effectively overwritten.
8317 : : *
8318 : : * 'aborted_lsn' is the beginning position of the record that was incomplete.
8319 : : * It is included in the WAL record. 'pagePtr' and 'newTLI' point to the
8320 : : * beginning of the XLOG page where the record is to be inserted. They must
8321 : : * match the current WAL insert position, they're passed here just so that we
8322 : : * can verify that.
8323 : : */
8324 : : static XLogRecPtr
8325 : 10 : CreateOverwriteContrecordRecord(XLogRecPtr aborted_lsn, XLogRecPtr pagePtr,
8326 : : TimeLineID newTLI)
8327 : : {
8328 : : xl_overwrite_contrecord xlrec;
8329 : : XLogRecPtr recptr;
8330 : : XLogPageHeader pagehdr;
8331 : : XLogRecPtr startPos;
8332 : :
8333 : : /* sanity checks */
8334 [ - + ]: 10 : if (!RecoveryInProgress())
8335 [ # # ]: 0 : elog(ERROR, "can only be used at end of recovery");
8336 [ - + ]: 10 : if (pagePtr % XLOG_BLCKSZ != 0)
8337 [ # # ]: 0 : elog(ERROR, "invalid position for missing continuation record %X/%08X",
8338 : : LSN_FORMAT_ARGS(pagePtr));
8339 : :
8340 : : /* The current WAL insert position should be right after the page header */
8341 : 10 : startPos = pagePtr;
8342 [ + + ]: 10 : if (XLogSegmentOffset(startPos, wal_segment_size) == 0)
8343 : 1 : startPos += SizeOfXLogLongPHD;
8344 : : else
8345 : 9 : startPos += SizeOfXLogShortPHD;
8346 : 10 : recptr = GetXLogInsertRecPtr();
8347 [ - + ]: 10 : if (recptr != startPos)
8348 [ # # ]: 0 : elog(ERROR, "invalid WAL insert position %X/%08X for OVERWRITE_CONTRECORD",
8349 : : LSN_FORMAT_ARGS(recptr));
8350 : :
8351 : 10 : START_CRIT_SECTION();
8352 : :
8353 : : /*
8354 : : * Initialize the XLOG page header (by GetXLogBuffer), and set the
8355 : : * XLP_FIRST_IS_OVERWRITE_CONTRECORD flag.
8356 : : *
8357 : : * No other backend is allowed to write WAL yet, so acquiring the WAL
8358 : : * insertion lock is just pro forma.
8359 : : */
8360 : 10 : WALInsertLockAcquire();
8361 : 10 : pagehdr = (XLogPageHeader) GetXLogBuffer(pagePtr, newTLI);
8362 : 10 : pagehdr->xlp_info |= XLP_FIRST_IS_OVERWRITE_CONTRECORD;
8363 : 10 : WALInsertLockRelease();
8364 : :
8365 : : /*
8366 : : * Insert the XLOG_OVERWRITE_CONTRECORD record as the first record on the
8367 : : * page. We know it becomes the first record, because no other backend is
8368 : : * allowed to write WAL yet.
8369 : : */
8370 : 10 : XLogBeginInsert();
8371 : 10 : xlrec.overwritten_lsn = aborted_lsn;
8372 : 10 : xlrec.overwrite_time = GetCurrentTimestamp();
8373 : 10 : XLogRegisterData(&xlrec, sizeof(xl_overwrite_contrecord));
8374 : 10 : recptr = XLogInsert(RM_XLOG_ID, XLOG_OVERWRITE_CONTRECORD);
8375 : :
8376 : : /* check that the record was inserted to the right place */
8377 [ - + ]: 10 : if (ProcLastRecPtr != startPos)
8378 [ # # ]: 0 : elog(ERROR, "OVERWRITE_CONTRECORD was inserted to unexpected position %X/%08X",
8379 : : LSN_FORMAT_ARGS(ProcLastRecPtr));
8380 : :
8381 : 10 : XLogFlush(recptr);
8382 : :
8383 : 10 : END_CRIT_SECTION();
8384 : :
8385 : 10 : return recptr;
8386 : : }
8387 : :
8388 : : /*
8389 : : * Flush all data in shared memory to disk, and fsync
8390 : : *
8391 : : * This is the common code shared between regular checkpoints and
8392 : : * recovery restartpoints.
8393 : : */
8394 : : static void
8395 : 2027 : CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
8396 : : {
8397 : 2027 : CheckPointRelationMap();
8398 : 2027 : CheckPointReplicationOrigin();
8399 : :
8400 : : /* Write out all dirty data in SLRUs and the main buffer pool */
8401 : : TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START(flags);
8402 : 2027 : CheckpointStats.ckpt_write_t = GetCurrentTimestamp();
8403 : 2027 : CheckPointCLOG();
8404 : 2027 : CheckPointCommitTs();
8405 : 2027 : CheckPointSUBTRANS();
8406 : 2027 : CheckPointMultiXact();
8407 : 2027 : CheckPointPredicate();
8408 : 2027 : CheckPointBuffers(flags);
8409 : :
8410 : : /* Perform all queued up fsyncs */
8411 : : TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START();
8412 : 2027 : CheckpointStats.ckpt_sync_t = GetCurrentTimestamp();
8413 : 2027 : ProcessSyncRequests();
8414 : 2027 : CheckpointStats.ckpt_sync_end_t = GetCurrentTimestamp();
8415 : : TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE();
8416 : :
8417 : : /*
8418 : : * Run replication slot checkpointing after buffer writes and
8419 : : * ProcessSyncRequests(), so WAL removal uses a fresher slot retention
8420 : : * horizon and avoids retaining WAL segments that slots no longer need.
8421 : : * Then clean up logical snapshots and rewrite mappings based on the
8422 : : * updated saved restart LSNs. Also delay 2PC checkpointing as long as
8423 : : * possible.
8424 : : */
8425 : 2027 : CheckPointReplicationSlots(flags & CHECKPOINT_IS_SHUTDOWN);
8426 : 2027 : CheckPointSnapBuild();
8427 : 2027 : CheckPointLogicalRewriteHeap();
8428 : 2027 : CheckPointTwoPhase(checkPointRedo);
8429 : 2027 : }
8430 : :
8431 : : /*
8432 : : * Save a checkpoint for recovery restart if appropriate
8433 : : *
8434 : : * This function is called each time a checkpoint record is read from XLOG.
8435 : : * It must determine whether the checkpoint represents a safe restartpoint or
8436 : : * not. If so, the checkpoint record is stashed in shared memory so that
8437 : : * CreateRestartPoint can consult it. (Note that the latter function is
8438 : : * executed by the checkpointer, while this one will be executed by the
8439 : : * startup process.)
8440 : : */
8441 : : static void
8442 : 778 : RecoveryRestartPoint(const CheckPoint *checkPoint, XLogReaderState *record)
8443 : : {
8444 : : /*
8445 : : * Also refrain from creating a restartpoint if we have seen any
8446 : : * references to non-existent pages. Restarting recovery from the
8447 : : * restartpoint would not see the references, so we would lose the
8448 : : * cross-check that the pages belonged to a relation that was dropped
8449 : : * later.
8450 : : */
8451 [ - + ]: 778 : if (XLogHaveInvalidPages())
8452 : : {
8453 [ # # ]: 0 : elog(DEBUG2,
8454 : : "could not record restart point at %X/%08X because there are unresolved references to invalid pages",
8455 : : LSN_FORMAT_ARGS(checkPoint->redo));
8456 : 0 : return;
8457 : : }
8458 : :
8459 : : /*
8460 : : * Copy the checkpoint record to shared memory, so that checkpointer can
8461 : : * work out the next time it wants to perform a restartpoint.
8462 : : */
8463 : 778 : SpinLockAcquire(&XLogCtl->info_lck);
8464 : 778 : XLogCtl->lastCheckPointRecPtr = record->ReadRecPtr;
8465 : 778 : XLogCtl->lastCheckPointEndPtr = record->EndRecPtr;
8466 : 778 : XLogCtl->lastCheckPoint = *checkPoint;
8467 : 778 : SpinLockRelease(&XLogCtl->info_lck);
8468 : : }
8469 : :
8470 : : /*
8471 : : * Establish a restartpoint if possible.
8472 : : *
8473 : : * This is similar to CreateCheckPoint, but is used during WAL recovery
8474 : : * to establish a point from which recovery can roll forward without
8475 : : * replaying the entire recovery log.
8476 : : *
8477 : : * Returns true if a new restartpoint was established. We can only establish
8478 : : * a restartpoint if we have replayed a safe checkpoint record since last
8479 : : * restartpoint.
8480 : : */
8481 : : bool
8482 : 627 : CreateRestartPoint(int flags)
8483 : : {
8484 : : XLogRecPtr lastCheckPointRecPtr;
8485 : : XLogRecPtr lastCheckPointEndPtr;
8486 : : CheckPoint lastCheckPoint;
8487 : : XLogRecPtr PriorRedoPtr;
8488 : : XLogRecPtr receivePtr;
8489 : : XLogRecPtr replayPtr;
8490 : : TimeLineID replayTLI;
8491 : : XLogRecPtr endptr;
8492 : : XLogSegNo _logSegNo;
8493 : : TimestampTz xtime;
8494 : : uint32 checksum_state;
8495 : : XLogRecPtr checksum_lsn;
8496 : : bool checksum_is_local;
8497 : :
8498 : : /* Concurrent checkpoint/restartpoint cannot happen */
8499 : : Assert(!IsUnderPostmaster || MyBackendType == B_CHECKPOINTER);
8500 : :
8501 : : /* Get a local copy of the last safe checkpoint record. */
8502 : 627 : SpinLockAcquire(&XLogCtl->info_lck);
8503 : 627 : lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
8504 : 627 : lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
8505 : 627 : lastCheckPoint = XLogCtl->lastCheckPoint;
8506 : 627 : SpinLockRelease(&XLogCtl->info_lck);
8507 : :
8508 : : /*
8509 : : * Check that we're still in recovery mode. It's ok if we exit recovery
8510 : : * mode after this check, the restart point is valid anyway.
8511 : : */
8512 [ - + ]: 627 : if (!RecoveryInProgress())
8513 : : {
8514 [ # # ]: 0 : ereport(DEBUG2,
8515 : : (errmsg_internal("skipping restartpoint, recovery has already ended")));
8516 : 0 : return false;
8517 : : }
8518 : :
8519 : : /*
8520 : : * If the last checkpoint record we've replayed is already our last
8521 : : * restartpoint, we can't perform a new restart point. We still update
8522 : : * minRecoveryPoint in that case, so that if this is a shutdown restart
8523 : : * point, we won't start up earlier than before. That's not strictly
8524 : : * necessary, but when hot standby is enabled, it would be rather weird if
8525 : : * the database opened up for read-only connections at a point-in-time
8526 : : * before the last shutdown. Such time travel is still possible in case of
8527 : : * immediate shutdown, though.
8528 : : *
8529 : : * We don't explicitly advance minRecoveryPoint when we do create a
8530 : : * restartpoint. It's assumed that flushing the buffers will do that as a
8531 : : * side-effect.
8532 : : */
8533 [ + + ]: 627 : if (!XLogRecPtrIsValid(lastCheckPointRecPtr) ||
8534 [ + + ]: 296 : lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
8535 : : {
8536 [ - + ]: 414 : ereport(DEBUG2,
8537 : : errmsg_internal("skipping restartpoint, already performed at %X/%08X",
8538 : : LSN_FORMAT_ARGS(lastCheckPoint.redo)));
8539 : :
8540 : 414 : UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
8541 [ + + ]: 414 : if (flags & CHECKPOINT_IS_SHUTDOWN)
8542 : : {
8543 : : bool catchUpChecksums;
8544 : :
8545 : : /*
8546 : : * There is no new restartpoint to persist the data checksum state
8547 : : * with, but a cleanly stopped node should not leave the control
8548 : : * file behind the state replay reached: pg_checksums and
8549 : : * pg_rewind read it, and an in-progress state there makes them
8550 : : * refuse to run. Catching it up needs the same guarantee a
8551 : : * restartpoint gives: that every page on disk carries a checksum,
8552 : : * so flush the buffer pool first. Only a transition to "on" that
8553 : : * no restartpoint followed can get here; the other states are
8554 : : * already persisted by XLOG2_CHECKSUMS replay. Replay has ended
8555 : : * by now, so the state cannot change under us.
8556 : : */
8557 : 46 : SpinLockAcquire(&XLogCtl->info_lck);
8558 : 46 : checksum_state = XLogCtl->data_checksum_version;
8559 : 46 : checksum_lsn = XLogCtl->data_checksum_lsn;
8560 : 46 : checksum_is_local = XLogCtl->data_checksum_is_local;
8561 : 46 : SpinLockRelease(&XLogCtl->info_lck);
8562 : :
8563 : 46 : LWLockAcquire(ControlFileLock, LW_SHARED);
8564 : 46 : catchUpChecksums =
8565 [ - + - - ]: 46 : (checksum_lsn != ControlFile->data_checksum_lsn &&
8566 : : XLogRecPtrIsValid(lastCheckPointRecPtr));
8567 : 46 : LWLockRelease(ControlFileLock);
8568 : :
8569 [ - + ]: 46 : if (catchUpChecksums)
8570 : : {
8571 [ # # # # : 0 : MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
# # # # #
# ]
8572 : 0 : CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
8573 : 0 : CheckPointGuts(lastCheckPoint.redo, flags);
8574 : : }
8575 : :
8576 : 46 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8577 : 46 : ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
8578 [ - + ]: 46 : if (catchUpChecksums)
8579 : : {
8580 : 0 : ControlFile->data_checksum_version = checksum_state;
8581 : 0 : ControlFile->data_checksum_lsn = checksum_lsn;
8582 : 0 : ControlFile->data_checksum_is_local = checksum_is_local;
8583 : : }
8584 : 46 : UpdateControlFile();
8585 : 46 : LWLockRelease(ControlFileLock);
8586 : : }
8587 : 414 : return false;
8588 : : }
8589 : :
8590 : : /*
8591 : : * Update the shared RedoRecPtr so that the startup process can calculate
8592 : : * the number of segments replayed since last restartpoint, and request a
8593 : : * restartpoint if it exceeds CheckPointSegments.
8594 : : *
8595 : : * Like in CreateCheckPoint(), hold off insertions to update it, although
8596 : : * during recovery this is just pro forma, because no WAL insertions are
8597 : : * happening.
8598 : : */
8599 : 213 : WALInsertLockAcquireExclusive();
8600 : 213 : RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
8601 : 213 : WALInsertLockRelease();
8602 : :
8603 : : /* Also update the info_lck-protected copy */
8604 : 213 : SpinLockAcquire(&XLogCtl->info_lck);
8605 : 213 : XLogCtl->RedoRecPtr = lastCheckPoint.redo;
8606 : 213 : SpinLockRelease(&XLogCtl->info_lck);
8607 : :
8608 : : /*
8609 : : * Prepare to accumulate statistics.
8610 : : *
8611 : : * Note: because it is possible for log_checkpoints to change while a
8612 : : * checkpoint proceeds, we always accumulate stats, even if
8613 : : * log_checkpoints is currently off.
8614 : : */
8615 [ + - + - : 2343 : MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
+ - + - +
+ ]
8616 : 213 : CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
8617 : :
8618 [ + - ]: 213 : if (log_checkpoints)
8619 : 213 : LogCheckpointStart(flags, true);
8620 : :
8621 : : /* Update the process title */
8622 : 213 : update_checkpoint_display(flags, true, false);
8623 : :
8624 : : /*
8625 : : * Note the data checksum state the flush below starts under. Replay runs
8626 : : * concurrently and can change the state while the flush is in progress,
8627 : : * in which case the flush covers pages written under both states; see
8628 : : * where the state is persisted further down.
8629 : : */
8630 : 213 : SpinLockAcquire(&XLogCtl->info_lck);
8631 : 213 : checksum_state = XLogCtl->data_checksum_version;
8632 : 213 : checksum_lsn = XLogCtl->data_checksum_lsn;
8633 : 213 : SpinLockRelease(&XLogCtl->info_lck);
8634 : :
8635 : 213 : CheckPointGuts(lastCheckPoint.redo, flags);
8636 : :
8637 : : /*
8638 : : * This location needs to be after CheckPointGuts() to ensure that some
8639 : : * work has already happened during this checkpoint.
8640 : : */
8641 : 213 : INJECTION_POINT("create-restart-point", NULL);
8642 : :
8643 : : /*
8644 : : * Remember the prior checkpoint's redo ptr for
8645 : : * UpdateCheckPointDistanceEstimate()
8646 : : */
8647 : 213 : PriorRedoPtr = ControlFile->checkPointCopy.redo;
8648 : :
8649 : : /*
8650 : : * Update pg_control, using current time. Check that it still shows an
8651 : : * older checkpoint, else do nothing; this is a quick hack to make sure
8652 : : * nothing really bad happens if somehow we get here after the
8653 : : * end-of-recovery checkpoint.
8654 : : */
8655 : 213 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8656 [ + - ]: 213 : if (ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
8657 : : {
8658 : : /*
8659 : : * Update the checkpoint information. We do this even if the cluster
8660 : : * does not show DB_IN_ARCHIVE_RECOVERY to match with the set of WAL
8661 : : * segments recycled below.
8662 : : */
8663 : 213 : ControlFile->checkPoint = lastCheckPointRecPtr;
8664 : 213 : ControlFile->checkPointCopy = lastCheckPoint;
8665 : :
8666 : : /*
8667 : : * Ensure minRecoveryPoint is past the checkpoint record and update it
8668 : : * if the control file still shows DB_IN_ARCHIVE_RECOVERY. Normally,
8669 : : * this will have happened already while writing out dirty buffers,
8670 : : * but not necessarily - e.g. because no buffers were dirtied. We do
8671 : : * this because a backup performed in recovery uses minRecoveryPoint
8672 : : * to determine which WAL files must be included in the backup, and
8673 : : * the file (or files) containing the checkpoint record must be
8674 : : * included, at a minimum. Note that for an ordinary restart of
8675 : : * recovery there's no value in having the minimum recovery point any
8676 : : * earlier than this anyway, because redo will begin just after the
8677 : : * checkpoint record.
8678 : : */
8679 [ + + ]: 213 : if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
8680 : : {
8681 [ + + ]: 212 : if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
8682 : : {
8683 : 18 : ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
8684 : 18 : ControlFile->minRecoveryPointTLI = lastCheckPoint.ThisTimeLineID;
8685 : :
8686 : : /* update local copy */
8687 : 18 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
8688 : : }
8689 [ + + ]: 212 : if (flags & CHECKPOINT_IS_SHUTDOWN)
8690 : 24 : ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
8691 : : }
8692 : :
8693 : : /*
8694 : : * Persist the data checksum state of this node. Not the state of the
8695 : : * replayed checkpoint: that one belongs to the node that wrote it and
8696 : : * may differ after an offline change on either side.
8697 : : * ControlFile->checkPointCopy above keeps the replayed value on
8698 : : * purpose, being a historical record used to resume replay rather
8699 : : * than a tracker of node state.
8700 : : *
8701 : : * Persist only if the flush above ran under one state throughout; see
8702 : : * CreateCheckPoint() for why, including why this compares the
8703 : : * watermark and not the state.
8704 : : */
8705 : 213 : SpinLockAcquire(&XLogCtl->info_lck);
8706 [ + + ]: 213 : if (checksum_lsn == XLogCtl->data_checksum_lsn)
8707 : : {
8708 : 212 : ControlFile->data_checksum_version = checksum_state;
8709 : 212 : ControlFile->data_checksum_lsn = checksum_lsn;
8710 : 212 : ControlFile->data_checksum_is_local = XLogCtl->data_checksum_is_local;
8711 : : }
8712 : 213 : SpinLockRelease(&XLogCtl->info_lck);
8713 : :
8714 : 213 : UpdateControlFile();
8715 : : }
8716 : 213 : LWLockRelease(ControlFileLock);
8717 : :
8718 : : /*
8719 : : * Update the average distance between checkpoints/restartpoints if the
8720 : : * prior checkpoint exists.
8721 : : */
8722 [ + - ]: 213 : if (XLogRecPtrIsValid(PriorRedoPtr))
8723 : 213 : UpdateCheckPointDistanceEstimate(RedoRecPtr - PriorRedoPtr);
8724 : :
8725 : : /*
8726 : : * Delete old log files, those no longer needed for last restartpoint to
8727 : : * prevent the disk holding the xlog from growing full.
8728 : : */
8729 : 213 : XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
8730 : :
8731 : : /*
8732 : : * Retreat _logSegNo using the current end of xlog replayed or received,
8733 : : * whichever is later.
8734 : : */
8735 : 213 : receivePtr = GetWalRcvFlushRecPtr(NULL, NULL);
8736 : 213 : replayPtr = GetXLogReplayRecPtr(&replayTLI);
8737 : 213 : endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
8738 : 213 : KeepLogSeg(endptr, &_logSegNo);
8739 : :
8740 : 213 : INJECTION_POINT("restartpoint-before-slot-invalidation", NULL);
8741 : :
8742 [ + + ]: 213 : if (InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_REMOVED | RS_INVAL_IDLE_TIMEOUT,
8743 : : _logSegNo, InvalidOid,
8744 : : InvalidTransactionId))
8745 : : {
8746 : : /*
8747 : : * Some slots have been invalidated; recalculate the old-segment
8748 : : * horizon, starting again from RedoRecPtr.
8749 : : */
8750 : 1 : XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
8751 : 1 : KeepLogSeg(endptr, &_logSegNo);
8752 : : }
8753 : 213 : _logSegNo--;
8754 : :
8755 : : /*
8756 : : * Try to recycle segments on a useful timeline. If we've been promoted
8757 : : * since the beginning of this restartpoint, use the new timeline chosen
8758 : : * at end of recovery. If we're still in recovery, use the timeline we're
8759 : : * currently replaying.
8760 : : *
8761 : : * There is no guarantee that the WAL segments will be useful on the
8762 : : * current timeline; if recovery proceeds to a new timeline right after
8763 : : * this, the pre-allocated WAL segments on this timeline will not be used,
8764 : : * and will go wasted until recycled on the next restartpoint. We'll live
8765 : : * with that.
8766 : : */
8767 [ + + ]: 213 : if (!RecoveryInProgress())
8768 : 1 : replayTLI = XLogCtl->InsertTimeLineID;
8769 : :
8770 : 213 : RemoveOldXlogFiles(_logSegNo, RedoRecPtr, endptr, replayTLI);
8771 : :
8772 : : /*
8773 : : * Make more log segments if needed. (Do this after recycling old log
8774 : : * segments, since that may supply some of the needed files.)
8775 : : */
8776 : 213 : PreallocXlogFiles(endptr, replayTLI);
8777 : :
8778 : : /*
8779 : : * Truncate pg_subtrans if possible. We can throw away all data before
8780 : : * the oldest XMIN of any running transaction. No future transaction will
8781 : : * attempt to reference any pg_subtrans entry older than that (see Asserts
8782 : : * in subtrans.c). During recovery, don't truncate pg_subtrans until hot
8783 : : * standby initialization has started it.
8784 : : */
8785 [ + - ]: 213 : if (RecoverySubtransInitialized())
8786 : 213 : TruncateSUBTRANS(GetOldestTransactionIdConsideredRunning());
8787 : :
8788 : : /* Real work is done; log and update stats. */
8789 : 213 : LogCheckpointEnd(true, flags);
8790 : :
8791 : : /* Reset the process title */
8792 : 213 : update_checkpoint_display(flags, true, true);
8793 : :
8794 : 213 : xtime = GetLatestXTime();
8795 [ + - + - : 213 : ereport((log_checkpoints ? LOG : DEBUG2),
+ + ]
8796 : : errmsg("recovery restart point at %X/%08X",
8797 : : LSN_FORMAT_ARGS(lastCheckPoint.redo)),
8798 : : xtime ? errdetail("Last completed transaction was at log time %s.",
8799 : : timestamptz_to_str(xtime)) : 0);
8800 : :
8801 : : /*
8802 : : * Finally, execute archive_cleanup_command, if any.
8803 : : */
8804 [ + - - + ]: 213 : if (archiveCleanupCommand && strcmp(archiveCleanupCommand, "") != 0)
8805 : 0 : ExecuteRecoveryCommand(archiveCleanupCommand,
8806 : : "archive_cleanup_command",
8807 : : false,
8808 : : WAIT_EVENT_ARCHIVE_CLEANUP_COMMAND);
8809 : :
8810 : 213 : return true;
8811 : : }
8812 : :
8813 : : /*
8814 : : * Report availability of WAL for the given target LSN
8815 : : * (typically a slot's restart_lsn)
8816 : : *
8817 : : * Returns one of the following enum values:
8818 : : *
8819 : : * * WALAVAIL_RESERVED means targetLSN is available and it is in the range of
8820 : : * max_wal_size.
8821 : : *
8822 : : * * WALAVAIL_EXTENDED means it is still available by preserving extra
8823 : : * segments beyond max_wal_size. If max_slot_wal_keep_size is smaller
8824 : : * than max_wal_size, this state is not returned.
8825 : : *
8826 : : * * WALAVAIL_UNRESERVED means it is being lost and the next checkpoint will
8827 : : * remove reserved segments. The walsender using this slot may return to the
8828 : : * above.
8829 : : *
8830 : : * * WALAVAIL_REMOVED means it has been removed. A replication stream on
8831 : : * a slot with this LSN cannot continue. (Any associated walsender
8832 : : * processes should have been terminated already.)
8833 : : *
8834 : : * * WALAVAIL_INVALID_LSN means the slot hasn't been set to reserve WAL.
8835 : : */
8836 : : WALAvailability
8837 : 648 : GetWALAvailability(XLogRecPtr targetLSN)
8838 : : {
8839 : : XLogRecPtr currpos; /* current write LSN */
8840 : : XLogSegNo currSeg; /* segid of currpos */
8841 : : XLogSegNo targetSeg; /* segid of targetLSN */
8842 : : XLogSegNo oldestSeg; /* actual oldest segid */
8843 : : XLogSegNo oldestSegMaxWalSize; /* oldest segid kept by max_wal_size */
8844 : : XLogSegNo oldestSlotSeg; /* oldest segid kept by slot */
8845 : : uint64 keepSegs;
8846 : :
8847 : : /*
8848 : : * slot does not reserve WAL. Either deactivated, or has never been active
8849 : : */
8850 [ + + ]: 648 : if (!XLogRecPtrIsValid(targetLSN))
8851 : 34 : return WALAVAIL_INVALID_LSN;
8852 : :
8853 : : /*
8854 : : * Calculate the oldest segment currently reserved by all slots,
8855 : : * considering wal_keep_size and max_slot_wal_keep_size. Initialize
8856 : : * oldestSlotSeg to the current segment.
8857 : : */
8858 : 614 : currpos = GetXLogWriteRecPtr();
8859 : 614 : XLByteToSeg(currpos, oldestSlotSeg, wal_segment_size);
8860 : 614 : KeepLogSeg(currpos, &oldestSlotSeg);
8861 : :
8862 : : /*
8863 : : * Find the oldest extant segment file. We get 1 until checkpoint removes
8864 : : * the first WAL segment file since startup, which causes the status being
8865 : : * wrong under certain abnormal conditions but that doesn't actually harm.
8866 : : */
8867 : 614 : oldestSeg = XLogGetLastRemovedSegno() + 1;
8868 : :
8869 : : /* calculate oldest segment by max_wal_size */
8870 : 614 : XLByteToSeg(currpos, currSeg, wal_segment_size);
8871 : 614 : keepSegs = ConvertToXSegs(max_wal_size_mb, wal_segment_size) + 1;
8872 : :
8873 [ + + ]: 614 : if (currSeg > keepSegs)
8874 : 13 : oldestSegMaxWalSize = currSeg - keepSegs;
8875 : : else
8876 : 601 : oldestSegMaxWalSize = 1;
8877 : :
8878 : : /* the segment we care about */
8879 : 614 : XLByteToSeg(targetLSN, targetSeg, wal_segment_size);
8880 : :
8881 : : /*
8882 : : * No point in returning reserved or extended status values if the
8883 : : * targetSeg is known to be lost.
8884 : : */
8885 [ + + ]: 614 : if (targetSeg >= oldestSlotSeg)
8886 : : {
8887 : : /* show "reserved" when targetSeg is within max_wal_size */
8888 [ + + ]: 613 : if (targetSeg >= oldestSegMaxWalSize)
8889 : 611 : return WALAVAIL_RESERVED;
8890 : :
8891 : : /* being retained by slots exceeding max_wal_size */
8892 : 2 : return WALAVAIL_EXTENDED;
8893 : : }
8894 : :
8895 : : /* WAL segments are no longer retained but haven't been removed yet */
8896 [ + - ]: 1 : if (targetSeg >= oldestSeg)
8897 : 1 : return WALAVAIL_UNRESERVED;
8898 : :
8899 : : /* Definitely lost */
8900 : 0 : return WALAVAIL_REMOVED;
8901 : : }
8902 : :
8903 : :
8904 : : /*
8905 : : * Retreat *logSegNo to the last segment that we need to retain because of
8906 : : * either wal_keep_size or replication slots.
8907 : : *
8908 : : * This is calculated by subtracting wal_keep_size from the given xlog
8909 : : * location, recptr and by making sure that that result is below the
8910 : : * requirement of replication slots. For the latter criterion we do consider
8911 : : * the effects of max_slot_wal_keep_size: reserve at most that much space back
8912 : : * from recptr.
8913 : : *
8914 : : * Note about replication slots: if this function calculates a value
8915 : : * that's further ahead than what slots need reserved, then affected
8916 : : * slots need to be invalidated and this function invoked again.
8917 : : * XXX it might be a good idea to rewrite this function so that
8918 : : * invalidation is optionally done here, instead.
8919 : : */
8920 : : static void
8921 : 2646 : KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
8922 : : {
8923 : : XLogSegNo currSegNo;
8924 : : XLogSegNo segno;
8925 : : XLogRecPtr keep;
8926 : :
8927 : 2646 : XLByteToSeg(recptr, currSegNo, wal_segment_size);
8928 : 2646 : segno = currSegNo;
8929 : :
8930 : : /* Calculate how many segments are kept by slots. */
8931 : 2646 : keep = XLogGetReplicationSlotMinimumLSN();
8932 [ + + + + ]: 2646 : if (XLogRecPtrIsValid(keep) && keep < recptr)
8933 : : {
8934 : 761 : XLByteToSeg(keep, segno, wal_segment_size);
8935 : :
8936 : : /*
8937 : : * Account for max_slot_wal_keep_size to avoid keeping more than
8938 : : * configured. However, don't do that during a binary upgrade: if
8939 : : * slots were to be invalidated because of this, it would not be
8940 : : * possible to preserve logical ones during the upgrade.
8941 : : */
8942 [ + + + - ]: 761 : if (max_slot_wal_keep_size_mb >= 0 && !IsBinaryUpgrade)
8943 : : {
8944 : : uint64 slot_keep_segs;
8945 : :
8946 : 24 : slot_keep_segs =
8947 : 24 : ConvertToXSegs(max_slot_wal_keep_size_mb, wal_segment_size);
8948 : :
8949 [ + + ]: 24 : if (currSegNo - segno > slot_keep_segs)
8950 : 7 : segno = currSegNo - slot_keep_segs;
8951 : : }
8952 : : }
8953 : :
8954 : : /*
8955 : : * If WAL summarization is in use, don't remove WAL that has yet to be
8956 : : * summarized.
8957 : : */
8958 : 2646 : keep = GetOldestUnsummarizedLSN(NULL, NULL);
8959 [ + + ]: 2646 : if (XLogRecPtrIsValid(keep))
8960 : : {
8961 : : XLogSegNo unsummarized_segno;
8962 : :
8963 : 12 : XLByteToSeg(keep, unsummarized_segno, wal_segment_size);
8964 [ + + ]: 12 : if (unsummarized_segno < segno)
8965 : 10 : segno = unsummarized_segno;
8966 : : }
8967 : :
8968 : : /* but, keep at least wal_keep_size if that's set */
8969 [ + + ]: 2646 : if (wal_keep_size_mb > 0)
8970 : : {
8971 : : uint64 keep_segs;
8972 : :
8973 : 97 : keep_segs = ConvertToXSegs(wal_keep_size_mb, wal_segment_size);
8974 [ + - ]: 97 : if (currSegNo - segno < keep_segs)
8975 : : {
8976 : : /* avoid underflow, don't go below 1 */
8977 [ + + ]: 97 : if (currSegNo <= keep_segs)
8978 : 93 : segno = 1;
8979 : : else
8980 : 4 : segno = currSegNo - keep_segs;
8981 : : }
8982 : : }
8983 : :
8984 : : /* don't delete WAL segments newer than the calculated segment */
8985 [ + + ]: 2646 : if (segno < *logSegNo)
8986 : 284 : *logSegNo = segno;
8987 : 2646 : }
8988 : :
8989 : : /*
8990 : : * Write a NEXTOID log record
8991 : : */
8992 : : void
8993 : 730 : XLogPutNextOid(Oid8 nextOid)
8994 : : {
8995 : 730 : XLogBeginInsert();
8996 : 730 : XLogRegisterData(&nextOid, sizeof(Oid8));
8997 : 730 : (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID);
8998 : :
8999 : : /*
9000 : : * We need not flush the NEXTOID record immediately, because any of the
9001 : : * just-allocated OIDs could only reach disk as part of a tuple insert or
9002 : : * update that would have its own XLOG record that must follow the NEXTOID
9003 : : * record. Therefore, the standard buffer LSN interlock applied to those
9004 : : * records will ensure no such OID reaches disk before the NEXTOID record
9005 : : * does.
9006 : : *
9007 : : * Note, however, that the above statement only covers state "within" the
9008 : : * database. When we use a generated OID as a file or directory name, we
9009 : : * are in a sense violating the basic WAL rule, because that filesystem
9010 : : * change may reach disk before the NEXTOID WAL record does. The impact
9011 : : * of this is that if a database crash occurs immediately afterward, we
9012 : : * might after restart re-generate the same OID and find that it conflicts
9013 : : * with the leftover file or directory. But since for safety's sake we
9014 : : * always loop until finding a nonconflicting filename, this poses no real
9015 : : * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
9016 : : */
9017 : 730 : }
9018 : :
9019 : : /*
9020 : : * Write an XLOG SWITCH record.
9021 : : *
9022 : : * Here we just blindly issue an XLogInsert request for the record.
9023 : : * All the magic happens inside XLogInsert.
9024 : : *
9025 : : * The return value is either the end+1 address of the switch record,
9026 : : * or the end+1 address of the prior segment if we did not need to
9027 : : * write a switch record because we are already at segment start.
9028 : : */
9029 : : XLogRecPtr
9030 : 862 : RequestXLogSwitch(bool mark_unimportant)
9031 : : {
9032 : : XLogRecPtr RecPtr;
9033 : :
9034 : : /* XLOG SWITCH has no data */
9035 : 862 : XLogBeginInsert();
9036 : :
9037 [ - + ]: 862 : if (mark_unimportant)
9038 : 0 : XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
9039 : 862 : RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH);
9040 : :
9041 : 862 : return RecPtr;
9042 : : }
9043 : :
9044 : : /*
9045 : : * Write a RESTORE POINT record
9046 : : */
9047 : : XLogRecPtr
9048 : 3 : XLogRestorePoint(const char *rpName)
9049 : : {
9050 : : XLogRecPtr RecPtr;
9051 : : xl_restore_point xlrec;
9052 : :
9053 : 3 : xlrec.rp_time = GetCurrentTimestamp();
9054 : 3 : strlcpy(xlrec.rp_name, rpName, MAXFNAMELEN);
9055 : :
9056 : 3 : XLogBeginInsert();
9057 : 3 : XLogRegisterData(&xlrec, sizeof(xl_restore_point));
9058 : :
9059 : 3 : RecPtr = XLogInsert(RM_XLOG_ID, XLOG_RESTORE_POINT);
9060 : :
9061 [ + - ]: 3 : ereport(LOG,
9062 : : errmsg("restore point \"%s\" created at %X/%08X",
9063 : : rpName, LSN_FORMAT_ARGS(RecPtr)));
9064 : :
9065 : 3 : return RecPtr;
9066 : : }
9067 : :
9068 : : /*
9069 : : * Write an empty XLOG record to assign a distinct LSN.
9070 : : *
9071 : : * This is used by some index AMs when building indexes on permanent relations
9072 : : * with wal_level=minimal. In that scenario, WAL-logging will start after
9073 : : * commit, but the index AM needs distinct LSNs to detect concurrent page
9074 : : * modifications. When the current WAL insert position hasn't advanced since
9075 : : * the last call, we emit a dummy record to ensure we get a new, distinct LSN.
9076 : : */
9077 : : XLogRecPtr
9078 : 3428 : XLogAssignLSN(void)
9079 : : {
9080 : 3428 : int dummy = 0;
9081 : :
9082 : : /*
9083 : : * Records other than XLOG_SWITCH must have content. We use an integer 0
9084 : : * to satisfy this restriction.
9085 : : */
9086 : 3428 : XLogBeginInsert();
9087 : 3428 : XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
9088 : 3428 : XLogRegisterData(&dummy, sizeof(dummy));
9089 : 3428 : return XLogInsert(RM_XLOG_ID, XLOG_ASSIGN_LSN);
9090 : : }
9091 : :
9092 : : /*
9093 : : * Check if any of the GUC parameters that are critical for hot standby
9094 : : * have changed, and update the value in pg_control file if necessary.
9095 : : */
9096 : : static void
9097 : 1066 : XLogReportParameters(void)
9098 : : {
9099 [ + + ]: 1066 : if (wal_level != ControlFile->wal_level ||
9100 [ + + ]: 792 : wal_log_hints != ControlFile->wal_log_hints ||
9101 [ + + ]: 690 : MaxConnections != ControlFile->MaxConnections ||
9102 [ + + ]: 689 : max_worker_processes != ControlFile->max_worker_processes ||
9103 [ + + ]: 686 : max_wal_senders != ControlFile->max_wal_senders ||
9104 [ + + ]: 658 : max_prepared_xacts != ControlFile->max_prepared_xacts ||
9105 [ + - ]: 549 : max_locks_per_xact != ControlFile->max_locks_per_xact ||
9106 [ + + ]: 549 : track_commit_timestamp != ControlFile->track_commit_timestamp)
9107 : : {
9108 : : /*
9109 : : * The change in number of backend slots doesn't need to be WAL-logged
9110 : : * if archiving is not enabled, as you can't start archive recovery
9111 : : * with wal_level=minimal anyway. We don't really care about the
9112 : : * values in pg_control either if wal_level=minimal, but seems better
9113 : : * to keep them up-to-date to avoid confusion.
9114 : : */
9115 [ + + + + ]: 529 : if (wal_level != ControlFile->wal_level || XLogIsNeeded())
9116 : : {
9117 : : xl_parameter_change xlrec;
9118 : : XLogRecPtr recptr;
9119 : :
9120 : 501 : xlrec.MaxConnections = MaxConnections;
9121 : 501 : xlrec.max_worker_processes = max_worker_processes;
9122 : 501 : xlrec.max_wal_senders = max_wal_senders;
9123 : 501 : xlrec.max_prepared_xacts = max_prepared_xacts;
9124 : 501 : xlrec.max_locks_per_xact = max_locks_per_xact;
9125 : 501 : xlrec.wal_level = wal_level;
9126 : 501 : xlrec.wal_log_hints = wal_log_hints;
9127 : 501 : xlrec.track_commit_timestamp = track_commit_timestamp;
9128 : :
9129 : 501 : XLogBeginInsert();
9130 : 501 : XLogRegisterData(&xlrec, sizeof(xlrec));
9131 : :
9132 : 501 : recptr = XLogInsert(RM_XLOG_ID, XLOG_PARAMETER_CHANGE);
9133 : 501 : XLogFlush(recptr);
9134 : : }
9135 : :
9136 : 529 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9137 : :
9138 : 529 : ControlFile->MaxConnections = MaxConnections;
9139 : 529 : ControlFile->max_worker_processes = max_worker_processes;
9140 : 529 : ControlFile->max_wal_senders = max_wal_senders;
9141 : 529 : ControlFile->max_prepared_xacts = max_prepared_xacts;
9142 : 529 : ControlFile->max_locks_per_xact = max_locks_per_xact;
9143 : 529 : ControlFile->wal_level = wal_level;
9144 : 529 : ControlFile->wal_log_hints = wal_log_hints;
9145 : 529 : ControlFile->track_commit_timestamp = track_commit_timestamp;
9146 : 529 : UpdateControlFile();
9147 : :
9148 : 529 : LWLockRelease(ControlFileLock);
9149 : : }
9150 : 1066 : }
9151 : :
9152 : : /*
9153 : : * XLogChecksums
9154 : : * Log and publish the new state of checksums
9155 : : *
9156 : : * Inserting the record and publishing the new state must be atomic with
9157 : : * respect to a checkpoint sampling the state for its XLOG_CHECKPOINT_REDO
9158 : : * record: without that, a checkpoint could read the old state after the
9159 : : * record is already in WAL and insert a redo record that both follows the
9160 : : * transition in WAL order and carries the pre-transition state. Recovery
9161 : : * resuming from such a redo point would never replay the transition record
9162 : : * and resolve the finished transition as interrupted.
9163 : : * DataChecksumTransitionLock serializes the two; see CreateCheckPoint().
9164 : : *
9165 : : * Returns the end LSN of the inserted record, which the caller persists
9166 : : * together with the new state as the data checksum watermark.
9167 : : */
9168 : : static XLogRecPtr
9169 : 53 : XLogChecksums(uint32 new_type)
9170 : : {
9171 : : xl_checksum_state xlrec;
9172 : : XLogRecPtr recptr;
9173 : :
9174 : 53 : xlrec.new_checksum_state = new_type;
9175 : :
9176 : 53 : LWLockAcquire(DataChecksumTransitionLock, LW_EXCLUSIVE);
9177 : :
9178 : 53 : XLogBeginInsert();
9179 : 53 : XLogRegisterData((char *) &xlrec, sizeof(xl_checksum_state));
9180 : :
9181 : 53 : recptr = XLogInsert(RM_XLOG2_ID, XLOG2_CHECKSUMS);
9182 : 53 : pg_atomic_write_u64(&XLogCtl->lastChecksumChangeRecPtr, recptr);
9183 : :
9184 : : /* only loaded by SetDataChecksumsOn(), a no-op for the other callers */
9185 : 53 : INJECTION_POINT_CACHED("datachecksums-on-before-publish", NULL);
9186 : :
9187 : 53 : SpinLockAcquire(&XLogCtl->info_lck);
9188 : 53 : XLogCtl->data_checksum_version = new_type;
9189 : 53 : XLogCtl->data_checksum_lsn = recptr;
9190 : 53 : XLogCtl->data_checksum_is_local = false;
9191 : 53 : SpinLockRelease(&XLogCtl->info_lck);
9192 : :
9193 : 53 : LWLockRelease(DataChecksumTransitionLock);
9194 : :
9195 : 53 : XLogFlush(recptr);
9196 : :
9197 : 53 : return recptr;
9198 : : }
9199 : :
9200 : : /*
9201 : : * Update full_page_writes in shared memory, and write an
9202 : : * XLOG_FPW_CHANGE record if necessary.
9203 : : *
9204 : : * Note: this function assumes there is no other process running
9205 : : * concurrently that could update it.
9206 : : */
9207 : : void
9208 : 1838 : UpdateFullPageWrites(void)
9209 : : {
9210 : 1838 : XLogCtlInsert *Insert = &XLogCtl->Insert;
9211 : : bool recoveryInProgress;
9212 : :
9213 : : /*
9214 : : * Do nothing if full_page_writes has not been changed.
9215 : : *
9216 : : * It's safe to check the shared full_page_writes without the lock,
9217 : : * because we assume that there is no concurrently running process which
9218 : : * can update it.
9219 : : */
9220 [ + + ]: 1838 : if (fullPageWrites == Insert->fullPageWrites)
9221 : 1335 : return;
9222 : :
9223 : : /*
9224 : : * Perform this outside critical section so that the WAL insert
9225 : : * initialization done by RecoveryInProgress() doesn't trigger an
9226 : : * assertion failure.
9227 : : */
9228 : 503 : recoveryInProgress = RecoveryInProgress();
9229 : :
9230 : 503 : START_CRIT_SECTION();
9231 : :
9232 : : /*
9233 : : * It's always safe to take full page images, even when not strictly
9234 : : * required, but not the other way round. So if we're setting
9235 : : * full_page_writes to true, first set it true and then write the WAL
9236 : : * record. If we're setting it to false, first write the WAL record and
9237 : : * then set the global flag.
9238 : : */
9239 [ + + ]: 503 : if (fullPageWrites)
9240 : : {
9241 : 489 : WALInsertLockAcquireExclusive();
9242 : 489 : Insert->fullPageWrites = true;
9243 : 489 : WALInsertLockRelease();
9244 : : }
9245 : :
9246 : : /*
9247 : : * Write an XLOG_FPW_CHANGE record. This allows us to keep track of
9248 : : * full_page_writes during archive recovery, if required.
9249 : : */
9250 [ + + + + ]: 503 : if (XLogStandbyInfoActive() && !recoveryInProgress)
9251 : : {
9252 : 1 : XLogBeginInsert();
9253 : 1 : XLogRegisterData(&fullPageWrites, sizeof(bool));
9254 : :
9255 : 1 : XLogInsert(RM_XLOG_ID, XLOG_FPW_CHANGE);
9256 : : }
9257 : :
9258 [ + + ]: 503 : if (!fullPageWrites)
9259 : : {
9260 : 14 : WALInsertLockAcquireExclusive();
9261 : 14 : Insert->fullPageWrites = false;
9262 : 14 : WALInsertLockRelease();
9263 : : }
9264 : 503 : END_CRIT_SECTION();
9265 : : }
9266 : :
9267 : : /*
9268 : : * XLOG resource manager's routines
9269 : : *
9270 : : * Definitions of info values are in include/catalog/pg_control.h, though
9271 : : * not all record types are related to control file updates.
9272 : : *
9273 : : * NOTE: Some XLOG record types that are directly related to WAL recovery
9274 : : * are handled in xlogrecovery_redo().
9275 : : */
9276 : : void
9277 : 118002 : xlog_redo(XLogReaderState *record)
9278 : : {
9279 : 118002 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9280 : 118002 : XLogRecPtr lsn = record->EndRecPtr;
9281 : :
9282 : : /*
9283 : : * In XLOG rmgr, backup blocks are only used by XLOG_FPI and
9284 : : * XLOG_FPI_FOR_HINT records.
9285 : : */
9286 : : Assert(info == XLOG_FPI || info == XLOG_FPI_FOR_HINT ||
9287 : : !XLogRecHasAnyBlockRefs(record));
9288 : :
9289 [ + + ]: 118002 : if (info == XLOG_NEXTOID)
9290 : : {
9291 : : Oid8 nextOid;
9292 : :
9293 : : /*
9294 : : * We used to try to take the maximum of TransamVariables->nextOid and
9295 : : * the recorded nextOid, but that failed back when the counter was 4
9296 : : * bytes wide and could wrap around. Since no OID allocation should
9297 : : * be happening during replay anyway, better to just believe the
9298 : : * record exactly. We still take OidGenLock while setting the
9299 : : * variable, just in case.
9300 : : */
9301 : 106 : memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid8));
9302 : 106 : LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9303 : 106 : TransamVariables->nextOid = nextOid;
9304 : 106 : TransamVariables->oidCount = 0;
9305 : 106 : LWLockRelease(OidGenLock);
9306 : : }
9307 [ + + ]: 117896 : else if (info == XLOG_CHECKPOINT_SHUTDOWN)
9308 : : {
9309 : : CheckPoint checkPoint;
9310 : : TimeLineID replayTLI;
9311 : :
9312 : 50 : memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9313 : : /* In a SHUTDOWN checkpoint, believe the counters exactly */
9314 : 50 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
9315 : 50 : TransamVariables->nextXid = checkPoint.nextXid;
9316 : 50 : LWLockRelease(XidGenLock);
9317 : 50 : LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9318 : 50 : TransamVariables->nextOid = checkPoint.nextOid;
9319 : 50 : TransamVariables->oidCount = 0;
9320 : 50 : LWLockRelease(OidGenLock);
9321 : 50 : MultiXactSetNextMXact(checkPoint.nextMulti,
9322 : : checkPoint.nextMultiOffset);
9323 : :
9324 : 50 : MultiXactAdvanceOldest(checkPoint.oldestMulti,
9325 : : checkPoint.oldestMultiDB);
9326 : :
9327 : : /*
9328 : : * No need to set oldestClogXid here as well; it'll be set when we
9329 : : * redo an xl_clog_truncate if it changed since initialization.
9330 : : */
9331 : 50 : SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
9332 : :
9333 : : /*
9334 : : * If we see a shutdown checkpoint while waiting for an end-of-backup
9335 : : * record, the backup was canceled and the end-of-backup record will
9336 : : * never arrive.
9337 : : */
9338 [ + + ]: 50 : if (ArchiveRecoveryRequested &&
9339 [ + + ]: 49 : XLogRecPtrIsValid(ControlFile->backupStartPoint) &&
9340 [ - + ]: 1 : !XLogRecPtrIsValid(ControlFile->backupEndPoint))
9341 [ # # ]: 0 : ereport(PANIC,
9342 : : (errmsg("online backup was canceled, recovery cannot continue")));
9343 : :
9344 : : /*
9345 : : * If we see a shutdown checkpoint, we know that nothing was running
9346 : : * on the primary at this point. So fake-up an empty running-xacts
9347 : : * record and use that here and now. Recover additional standby state
9348 : : * for prepared transactions.
9349 : : */
9350 [ + + ]: 50 : if (standbyState >= STANDBY_INITIALIZED)
9351 : : {
9352 : : TransactionId *xids;
9353 : : int nxids;
9354 : : TransactionId oldestActiveXID;
9355 : : TransactionId latestCompletedXid;
9356 : : RunningTransactionsData running;
9357 : :
9358 : 47 : oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
9359 : :
9360 : : /* Update pg_subtrans entries for any prepared transactions */
9361 : 47 : StandbyRecoverPreparedTransactions();
9362 : :
9363 : : /*
9364 : : * Construct a RunningTransactions snapshot representing a shut
9365 : : * down server, with only prepared transactions still alive. We're
9366 : : * never overflowed at this point because all subxids are listed
9367 : : * with their parent prepared transactions.
9368 : : */
9369 : 47 : running.xcnt = nxids;
9370 : 47 : running.subxcnt = 0;
9371 : 47 : running.subxid_status = SUBXIDS_IN_SUBTRANS;
9372 : 47 : running.nextXid = XidFromFullTransactionId(checkPoint.nextXid);
9373 : 47 : running.oldestRunningXid = oldestActiveXID;
9374 : 47 : latestCompletedXid = XidFromFullTransactionId(checkPoint.nextXid);
9375 [ - + ]: 47 : TransactionIdRetreat(latestCompletedXid);
9376 : : Assert(TransactionIdIsNormal(latestCompletedXid));
9377 : 47 : running.latestCompletedXid = latestCompletedXid;
9378 : 47 : running.xids = xids;
9379 : :
9380 : 47 : ProcArrayApplyRecoveryInfo(&running);
9381 : : }
9382 : :
9383 : : /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
9384 : 50 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9385 : 50 : ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
9386 : :
9387 : 50 : UpdateControlFile();
9388 : 50 : LWLockRelease(ControlFileLock);
9389 : :
9390 [ - + ]: 50 : if (adoptChecksumStateFromNextCheckpoint)
9391 : : {
9392 : 0 : adoptChecksumStateFromNextCheckpoint = false;
9393 : 0 : AdoptReplayedDataChecksumState(checkPoint.dataChecksumState,
9394 : : record->ReadRecPtr);
9395 : : }
9396 : : else
9397 : 50 : CheckReplayedDataChecksumState(checkPoint.dataChecksumState);
9398 : :
9399 : : /*
9400 : : * We should've already switched to the new TLI before replaying this
9401 : : * record.
9402 : : */
9403 : 50 : (void) GetCurrentReplayRecPtr(&replayTLI);
9404 [ - + ]: 50 : if (checkPoint.ThisTimeLineID != replayTLI)
9405 [ # # ]: 0 : ereport(PANIC,
9406 : : (errmsg("unexpected timeline ID %u (should be %u) in shutdown checkpoint record",
9407 : : checkPoint.ThisTimeLineID, replayTLI)));
9408 : :
9409 : 50 : RecoveryRestartPoint(&checkPoint, record);
9410 : :
9411 : : /*
9412 : : * After replaying a checkpoint record, free all smgr objects.
9413 : : * Otherwise we would never do so for dropped relations, as the
9414 : : * startup does not process shared invalidation messages or call
9415 : : * AtEOXact_SMgr().
9416 : : */
9417 : 50 : smgrdestroyall();
9418 : : }
9419 [ + + ]: 117846 : else if (info == XLOG_CHECKPOINT_ONLINE)
9420 : : {
9421 : : CheckPoint checkPoint;
9422 : : TimeLineID replayTLI;
9423 : :
9424 : 728 : memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9425 : : /* In an ONLINE checkpoint, treat the XID counter as a minimum */
9426 : 728 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
9427 [ - + ]: 728 : if (FullTransactionIdPrecedes(TransamVariables->nextXid,
9428 : : checkPoint.nextXid))
9429 : 0 : TransamVariables->nextXid = checkPoint.nextXid;
9430 : 728 : LWLockRelease(XidGenLock);
9431 : :
9432 : : /*
9433 : : * We ignore the nextOid counter in an ONLINE checkpoint, preferring
9434 : : * to track OID assignment through XLOG_NEXTOID records. The nextOid
9435 : : * counter is from the start of the checkpoint and might well be stale
9436 : : * compared to later XLOG_NEXTOID records. We could try to take the
9437 : : * maximum of the nextOid counter and our latest value, but there is
9438 : : * no point in doing so: an online checkpoint records nextOid plus
9439 : : * oidCount, which is never ahead of the last XLOG_NEXTOID record that
9440 : : * replay has applied.
9441 : : */
9442 : :
9443 : : /* Handle multixact */
9444 : 728 : MultiXactAdvanceNextMXact(checkPoint.nextMulti,
9445 : : checkPoint.nextMultiOffset);
9446 : :
9447 : : /*
9448 : : * NB: This may perform multixact truncation when replaying WAL
9449 : : * generated by an older primary.
9450 : : */
9451 : 728 : MultiXactAdvanceOldest(checkPoint.oldestMulti,
9452 : : checkPoint.oldestMultiDB);
9453 [ - + ]: 728 : if (TransactionIdPrecedes(TransamVariables->oldestXid,
9454 : : checkPoint.oldestXid))
9455 : 0 : SetTransactionIdLimit(checkPoint.oldestXid,
9456 : : checkPoint.oldestXidDB);
9457 : : /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
9458 : 728 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9459 : 728 : ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
9460 : 728 : LWLockRelease(ControlFileLock);
9461 : :
9462 : : /* TLI should not change in an on-line checkpoint */
9463 : 728 : (void) GetCurrentReplayRecPtr(&replayTLI);
9464 [ - + ]: 728 : if (checkPoint.ThisTimeLineID != replayTLI)
9465 [ # # ]: 0 : ereport(PANIC,
9466 : : (errmsg("unexpected timeline ID %u (should be %u) in online checkpoint record",
9467 : : checkPoint.ThisTimeLineID, replayTLI)));
9468 : :
9469 : 728 : RecoveryRestartPoint(&checkPoint, record);
9470 : :
9471 : : /*
9472 : : * After replaying a checkpoint record, free all smgr objects.
9473 : : * Otherwise we would never do so for dropped relations, as the
9474 : : * startup does not process shared invalidation messages or call
9475 : : * AtEOXact_SMgr().
9476 : : */
9477 : 728 : smgrdestroyall();
9478 : : }
9479 [ + + ]: 117118 : else if (info == XLOG_OVERWRITE_CONTRECORD)
9480 : : {
9481 : : /* nothing to do here, handled in xlogrecovery_redo() */
9482 : : }
9483 [ + + ]: 117117 : else if (info == XLOG_END_OF_RECOVERY)
9484 : : {
9485 : : xl_end_of_recovery xlrec;
9486 : : TimeLineID replayTLI;
9487 : :
9488 : 15 : memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_end_of_recovery));
9489 : :
9490 : : /*
9491 : : * For Hot Standby, we could treat this like a Shutdown Checkpoint,
9492 : : * but this case is rarer and harder to test, so the benefit doesn't
9493 : : * outweigh the potential extra cost of maintenance.
9494 : : */
9495 : :
9496 : : /*
9497 : : * We should've already switched to the new TLI before replaying this
9498 : : * record.
9499 : : */
9500 : 15 : (void) GetCurrentReplayRecPtr(&replayTLI);
9501 [ - + ]: 15 : if (xlrec.ThisTimeLineID != replayTLI)
9502 [ # # ]: 0 : ereport(PANIC,
9503 : : (errmsg("unexpected timeline ID %u (should be %u) in end-of-recovery record",
9504 : : xlrec.ThisTimeLineID, replayTLI)));
9505 : : }
9506 [ + - ]: 117102 : else if (info == XLOG_NOOP)
9507 : : {
9508 : : /* nothing to do here */
9509 : : }
9510 [ + + ]: 117102 : else if (info == XLOG_SWITCH)
9511 : : {
9512 : : /* nothing to do here */
9513 : : }
9514 [ + + ]: 116623 : else if (info == XLOG_RESTORE_POINT)
9515 : : {
9516 : : /* nothing to do here, handled in xlogrecovery.c */
9517 : : }
9518 [ + + ]: 116618 : else if (info == XLOG_ASSIGN_LSN)
9519 : : {
9520 : : /* nothing to do here, see XLogGetFakeLSN() */
9521 : : }
9522 [ + + + + ]: 54291 : else if (info == XLOG_FPI || info == XLOG_FPI_FOR_HINT)
9523 : : {
9524 : : /*
9525 : : * XLOG_FPI records contain nothing else but one or more block
9526 : : * references. Every block reference must include a full-page image
9527 : : * even if full_page_writes was disabled when the record was generated
9528 : : * - otherwise there would be no point in this record.
9529 : : *
9530 : : * XLOG_FPI_FOR_HINT records are generated when a page needs to be
9531 : : * WAL-logged because of a hint bit update. They are only generated
9532 : : * when checksums and/or wal_log_hints are enabled. They may include
9533 : : * no full-page images if full_page_writes was disabled when they were
9534 : : * generated. In this case there is nothing to do here.
9535 : : *
9536 : : * No recovery conflicts are generated by these generic records - if a
9537 : : * resource manager needs to generate conflicts, it has to define a
9538 : : * separate WAL record type and redo routine.
9539 : : */
9540 [ + + ]: 111603 : for (uint8 block_id = 0; block_id <= XLogRecMaxBlockId(record); block_id++)
9541 : : {
9542 : : Buffer buffer;
9543 : :
9544 [ + + ]: 58230 : if (!XLogRecHasBlockImage(record, block_id))
9545 : : {
9546 [ - + ]: 70 : if (info == XLOG_FPI)
9547 [ # # ]: 0 : elog(ERROR, "XLOG_FPI record did not contain a full-page image");
9548 : 70 : continue;
9549 : : }
9550 : :
9551 [ - + ]: 58160 : if (XLogReadBufferForRedo(record, block_id, &buffer) != BLK_RESTORED)
9552 [ # # ]: 0 : elog(ERROR, "unexpected XLogReadBufferForRedo result when restoring backup block");
9553 : 58160 : UnlockReleaseBuffer(buffer);
9554 : : }
9555 : : }
9556 [ + + ]: 918 : else if (info == XLOG_BACKUP_END)
9557 : : {
9558 : : /* nothing to do here, handled in xlogrecovery_redo() */
9559 : : }
9560 [ + + ]: 805 : else if (info == XLOG_PARAMETER_CHANGE)
9561 : : {
9562 : : xl_parameter_change xlrec;
9563 : :
9564 : : /* Update our copy of the parameters in pg_control */
9565 : 40 : memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_parameter_change));
9566 : :
9567 : 40 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9568 : 40 : ControlFile->MaxConnections = xlrec.MaxConnections;
9569 : 40 : ControlFile->max_worker_processes = xlrec.max_worker_processes;
9570 : 40 : ControlFile->max_wal_senders = xlrec.max_wal_senders;
9571 : 40 : ControlFile->max_prepared_xacts = xlrec.max_prepared_xacts;
9572 : 40 : ControlFile->max_locks_per_xact = xlrec.max_locks_per_xact;
9573 : 40 : ControlFile->wal_level = xlrec.wal_level;
9574 : 40 : ControlFile->wal_log_hints = xlrec.wal_log_hints;
9575 : :
9576 : : /*
9577 : : * Update minRecoveryPoint to ensure that if recovery is aborted, we
9578 : : * recover back up to this point before allowing hot standby again.
9579 : : * This is important if the max_* settings are decreased, to ensure
9580 : : * you don't run queries against the WAL preceding the change. The
9581 : : * local copies cannot be updated as long as crash recovery is
9582 : : * happening and we expect all the WAL to be replayed.
9583 : : */
9584 [ + + ]: 40 : if (InArchiveRecovery)
9585 : : {
9586 : 25 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
9587 : : }
9588 [ + + + + ]: 40 : if (XLogRecPtrIsValid(LocalMinRecoveryPoint) && LocalMinRecoveryPoint < lsn)
9589 : : {
9590 : : TimeLineID replayTLI;
9591 : :
9592 : 14 : (void) GetCurrentReplayRecPtr(&replayTLI);
9593 : 14 : ControlFile->minRecoveryPoint = lsn;
9594 : 14 : ControlFile->minRecoveryPointTLI = replayTLI;
9595 : : }
9596 : :
9597 : 40 : CommitTsParameterChange(xlrec.track_commit_timestamp,
9598 : 40 : ControlFile->track_commit_timestamp);
9599 : 40 : ControlFile->track_commit_timestamp = xlrec.track_commit_timestamp;
9600 : :
9601 : 40 : UpdateControlFile();
9602 : 40 : LWLockRelease(ControlFileLock);
9603 : :
9604 : : /* Check to see if any parameter change gives a problem on recovery */
9605 : 40 : CheckRequiredParameterValues();
9606 : : }
9607 [ + + ]: 765 : else if (info == XLOG_FPW_CHANGE)
9608 : : {
9609 : : bool fpw;
9610 : :
9611 : 1 : memcpy(&fpw, XLogRecGetData(record), sizeof(bool));
9612 : :
9613 : : /*
9614 : : * Update the LSN of the last replayed XLOG_FPW_CHANGE record so that
9615 : : * do_pg_backup_start() and do_pg_backup_stop() can check whether
9616 : : * full_page_writes has been disabled during online backup.
9617 : : */
9618 [ - + ]: 1 : if (!fpw)
9619 : : {
9620 : 0 : SpinLockAcquire(&XLogCtl->info_lck);
9621 [ # # ]: 0 : if (XLogCtl->lastFpwDisableRecPtr < record->ReadRecPtr)
9622 : 0 : XLogCtl->lastFpwDisableRecPtr = record->ReadRecPtr;
9623 : 0 : SpinLockRelease(&XLogCtl->info_lck);
9624 : : }
9625 : :
9626 : : /* Keep track of full_page_writes */
9627 : 1 : lastFullPageWrites = fpw;
9628 : : }
9629 [ + + ]: 764 : else if (info == XLOG_CHECKPOINT_REDO)
9630 : : {
9631 : : xl_checkpoint_redo redo_rec;
9632 : :
9633 : 730 : memcpy(&redo_rec, XLogRecGetData(record), sizeof(xl_checkpoint_redo));
9634 : :
9635 [ + + ]: 730 : if (adoptChecksumStateFromNextCheckpoint)
9636 : : {
9637 : 90 : adoptChecksumStateFromNextCheckpoint = false;
9638 : 90 : AdoptReplayedDataChecksumState(redo_rec.data_checksum_version,
9639 : : record->ReadRecPtr);
9640 : : }
9641 : : else
9642 : 640 : CheckReplayedDataChecksumState(redo_rec.data_checksum_version);
9643 : : }
9644 [ + - ]: 34 : else if (info == XLOG_LOGICAL_DECODING_STATUS_CHANGE)
9645 : : {
9646 : : bool status;
9647 : :
9648 : 34 : memcpy(&status, XLogRecGetData(record), sizeof(bool));
9649 : :
9650 : : /*
9651 : : * We need to toggle the logical decoding status and update the
9652 : : * XLogLogicalInfo cache of processes synchronously because
9653 : : * XLogLogicalInfoActive() is used even during read-only queries
9654 : : * (e.g., via RelationIsAccessibleInLogicalDecoding()). In the
9655 : : * 'disable' case, it is safe to invalidate existing slots after
9656 : : * disabling logical decoding because logical decoding cannot process
9657 : : * subsequent WAL records, which may not contain logical information.
9658 : : */
9659 [ + + ]: 34 : if (status)
9660 : 17 : EnableLogicalDecoding(lsn);
9661 : : else
9662 : 17 : DisableLogicalDecoding();
9663 : :
9664 [ + + ]: 34 : elog(DEBUG1, "update logical decoding status to %d during recovery",
9665 : : status);
9666 : :
9667 [ + - + + ]: 34 : if (InRecovery && InHotStandby)
9668 : : {
9669 [ + + ]: 32 : if (!status)
9670 : : {
9671 : : /*
9672 : : * Invalidate logical slots if we are in hot standby and the
9673 : : * primary disabled logical decoding.
9674 : : */
9675 : 17 : InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_LEVEL,
9676 : : 0, InvalidOid,
9677 : : InvalidTransactionId);
9678 : : }
9679 [ - + ]: 15 : else if (sync_replication_slots)
9680 : : {
9681 : : /*
9682 : : * Signal the postmaster to launch the slotsync worker.
9683 : : *
9684 : : * XXX: For simplicity, we keep the slotsync worker running
9685 : : * even after logical decoding is disabled. A future
9686 : : * improvement can consider starting and stopping the worker
9687 : : * based on logical decoding status change.
9688 : : */
9689 : 0 : kill(PostmasterPid, SIGUSR1);
9690 : : }
9691 : : }
9692 : : }
9693 : 118000 : }
9694 : :
9695 : : void
9696 : 9 : xlog2_redo(XLogReaderState *record)
9697 : : {
9698 : 9 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9699 : :
9700 [ + - ]: 9 : if (info == XLOG2_CHECKSUMS)
9701 : : {
9702 : : xl_checksum_state state;
9703 : 9 : XLogRecPtr lsn = record->EndRecPtr;
9704 : : XLogRecPtr watermark;
9705 : :
9706 : 9 : memcpy(&state, XLogRecGetData(record), sizeof(xl_checksum_state));
9707 : :
9708 : 9 : SpinLockAcquire(&XLogCtl->info_lck);
9709 : 9 : watermark = XLogCtl->data_checksum_lsn;
9710 : 9 : SpinLockRelease(&XLogCtl->info_lck);
9711 : :
9712 : : /*
9713 : : * Skip records this node has already applied. The control file
9714 : : * carries the watermark, so this holds across restarts: recovery
9715 : : * resuming below a record whose effect the control file already
9716 : : * contains must not re-apply it, or it would revert a state change
9717 : : * made with pg_checksums in between, which moves the state without
9718 : : * writing any record of its own.
9719 : : */
9720 [ - + ]: 9 : if (lsn <= watermark)
9721 : 0 : return;
9722 : :
9723 : : /* advertise the location before the new state becomes visible */
9724 : 9 : pg_atomic_write_u64(&XLogCtl->lastChecksumChangeRecPtr, lsn);
9725 : :
9726 : 9 : SpinLockAcquire(&XLogCtl->info_lck);
9727 : 9 : XLogCtl->data_checksum_version = state.new_checksum_state;
9728 : 9 : XLogCtl->data_checksum_lsn = lsn;
9729 : 9 : XLogCtl->data_checksum_is_local = false;
9730 : 9 : SetLocalDataChecksumState(state.new_checksum_state);
9731 : 9 : SpinLockRelease(&XLogCtl->info_lck);
9732 : :
9733 : 9 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9734 : :
9735 : : /*
9736 : : * Persist the new state, except when it is "on". Only "on" verifies
9737 : : * checksums during reads, and between the last restartpoint and this
9738 : : * record there may be pages on disk flushed under the old state; a
9739 : : * crash-restart initializes verification from the control file and
9740 : : * replay reads those pages back, so the control file may only say
9741 : : * "on" once everything written under the transition has been flushed,
9742 : : * as restartpoints and the end of recovery do. The opposite direction
9743 : : * cannot wait for the restartpoint: once this record is replayed,
9744 : : * evicted pages are written without checksums, and a control file
9745 : : * still saying "on" would fail verification on exactly those pages
9746 : : * after a crash.
9747 : : */
9748 [ + + ]: 9 : if (state.new_checksum_state != PG_DATA_CHECKSUM_VERSION)
9749 : : {
9750 : 6 : ControlFile->data_checksum_version = state.new_checksum_state;
9751 : 6 : ControlFile->data_checksum_lsn = lsn;
9752 : 6 : ControlFile->data_checksum_is_local = false;
9753 : : }
9754 : :
9755 : : /*
9756 : : * Update minRecoveryPoint to ensure that if recovery is aborted, we
9757 : : * recover back up to this point before allowing hot standby again.
9758 : : * The change location is only tracked in shared memory and is lost
9759 : : * over a restart; a standby becoming consistent below this record
9760 : : * would let base backups resume checksum verification with the
9761 : : * location unknown. The local copies cannot be updated as long as
9762 : : * crash recovery is happening and we expect all the WAL to be
9763 : : * replayed.
9764 : : */
9765 [ + - ]: 9 : if (InArchiveRecovery)
9766 : : {
9767 : 9 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
9768 : : }
9769 [ + - + + ]: 9 : if (XLogRecPtrIsValid(LocalMinRecoveryPoint) && LocalMinRecoveryPoint < lsn)
9770 : : {
9771 : : TimeLineID replayTLI;
9772 : :
9773 : 7 : (void) GetCurrentReplayRecPtr(&replayTLI);
9774 : 7 : ControlFile->minRecoveryPoint = lsn;
9775 : 7 : ControlFile->minRecoveryPointTLI = replayTLI;
9776 : : }
9777 : :
9778 : 9 : UpdateControlFile();
9779 : 9 : LWLockRelease(ControlFileLock);
9780 : :
9781 : : /*
9782 : : * Block on a procsignalbarrier to await all processes having seen the
9783 : : * change to checksum status. Once the barrier has been passed we can
9784 : : * initiate the corresponding processing.
9785 : : */
9786 : 9 : EmitAndWaitDataChecksumsBarrier(state.new_checksum_state);
9787 : : }
9788 : : }
9789 : :
9790 : : /*
9791 : : * Return the extra open flags used for opening a file, depending on the
9792 : : * value of the GUCs wal_sync_method, fsync and debug_io_direct.
9793 : : */
9794 : : static int
9795 : 17958 : get_sync_bit(int method)
9796 : : {
9797 : 17958 : int o_direct_flag = 0;
9798 : :
9799 : : /*
9800 : : * Use O_DIRECT if requested, except in walreceiver process. The WAL
9801 : : * written by walreceiver is normally read by the startup process soon
9802 : : * after it's written. Also, walreceiver performs unaligned writes, which
9803 : : * don't work with O_DIRECT, so it is required for correctness too.
9804 : : */
9805 [ + + + - ]: 17958 : if ((io_direct_flags & IO_DIRECT_WAL) && !AmWalReceiverProcess())
9806 : 9 : o_direct_flag = PG_O_DIRECT;
9807 : :
9808 : : /* If fsync is disabled, never open in sync mode */
9809 [ + + ]: 17958 : if (!enableFsync)
9810 : 17957 : return o_direct_flag;
9811 : :
9812 [ + - - - ]: 1 : switch (method)
9813 : : {
9814 : : /*
9815 : : * enum values for all sync options are defined even if they are
9816 : : * not supported on the current platform. But if not, they are
9817 : : * not included in the enum option array, and therefore will never
9818 : : * be seen here.
9819 : : */
9820 : 1 : case WAL_SYNC_METHOD_FSYNC:
9821 : : case WAL_SYNC_METHOD_FSYNC_WRITETHROUGH:
9822 : : case WAL_SYNC_METHOD_FDATASYNC:
9823 : 1 : return o_direct_flag;
9824 : : #ifdef O_SYNC
9825 : 0 : case WAL_SYNC_METHOD_OPEN:
9826 : 0 : return O_SYNC | o_direct_flag;
9827 : : #endif
9828 : : #ifdef O_DSYNC
9829 : 0 : case WAL_SYNC_METHOD_OPEN_DSYNC:
9830 : 0 : return O_DSYNC | o_direct_flag;
9831 : : #endif
9832 : 0 : default:
9833 : : /* can't happen (unless we are out of sync with option array) */
9834 [ # # ]: 0 : elog(ERROR, "unrecognized \"wal_sync_method\": %d", method);
9835 : : return 0; /* silence warning */
9836 : : }
9837 : : }
9838 : :
9839 : : /*
9840 : : * GUC support
9841 : : */
9842 : : void
9843 : 1362 : assign_wal_sync_method(int new_wal_sync_method, void *extra)
9844 : : {
9845 [ - + ]: 1362 : if (wal_sync_method != new_wal_sync_method)
9846 : : {
9847 : : /*
9848 : : * To ensure that no blocks escape unsynced, force an fsync on the
9849 : : * currently open log segment (if any). Also, if the open flag is
9850 : : * changing, close the log file so it will be reopened (with new flag
9851 : : * bit) at next use.
9852 : : */
9853 [ # # ]: 0 : if (openLogFile >= 0)
9854 : : {
9855 : 0 : pgstat_report_wait_start(WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN);
9856 [ # # ]: 0 : if (pg_fsync(openLogFile) != 0)
9857 : : {
9858 : : char xlogfname[MAXFNAMELEN];
9859 : : int save_errno;
9860 : :
9861 : 0 : save_errno = errno;
9862 : 0 : XLogFileName(xlogfname, openLogTLI, openLogSegNo,
9863 : : wal_segment_size);
9864 : 0 : errno = save_errno;
9865 [ # # ]: 0 : ereport(PANIC,
9866 : : (errcode_for_file_access(),
9867 : : errmsg("could not fsync file \"%s\": %m", xlogfname)));
9868 : : }
9869 : :
9870 : 0 : pgstat_report_wait_end();
9871 [ # # ]: 0 : if (get_sync_bit(wal_sync_method) != get_sync_bit(new_wal_sync_method))
9872 : 0 : XLogFileClose();
9873 : : }
9874 : : }
9875 : 1362 : }
9876 : :
9877 : :
9878 : : /*
9879 : : * Issue appropriate kind of fsync (if any) for an XLOG output file.
9880 : : *
9881 : : * 'fd' is a file descriptor for the XLOG file to be fsync'd.
9882 : : * 'segno' is for error reporting purposes.
9883 : : */
9884 : : void
9885 : 208961 : issue_xlog_fsync(int fd, XLogSegNo segno, TimeLineID tli)
9886 : : {
9887 : 208961 : char *msg = NULL;
9888 : : instr_time start;
9889 : :
9890 : : Assert(tli != 0);
9891 : :
9892 : : /*
9893 : : * Quick exit if fsync is disabled or write() has already synced the WAL
9894 : : * file.
9895 : : */
9896 [ + + ]: 208961 : if (!enableFsync ||
9897 [ + - ]: 1 : wal_sync_method == WAL_SYNC_METHOD_OPEN ||
9898 [ - + ]: 1 : wal_sync_method == WAL_SYNC_METHOD_OPEN_DSYNC)
9899 : 208960 : return;
9900 : :
9901 : : /*
9902 : : * Measure I/O timing to sync the WAL file for pg_stat_io.
9903 : : */
9904 : 1 : start = pgstat_prepare_io_time(track_wal_io_timing);
9905 : :
9906 : 1 : pgstat_report_wait_start(WAIT_EVENT_WAL_SYNC);
9907 [ - + - - ]: 1 : switch (wal_sync_method)
9908 : : {
9909 : 0 : case WAL_SYNC_METHOD_FSYNC:
9910 [ # # ]: 0 : if (pg_fsync_no_writethrough(fd) != 0)
9911 : 0 : msg = _("could not fsync file \"%s\": %m");
9912 : 0 : break;
9913 : : #ifdef HAVE_FSYNC_WRITETHROUGH
9914 : : case WAL_SYNC_METHOD_FSYNC_WRITETHROUGH:
9915 : : if (pg_fsync_writethrough(fd) != 0)
9916 : : msg = _("could not fsync write-through file \"%s\": %m");
9917 : : break;
9918 : : #endif
9919 : 1 : case WAL_SYNC_METHOD_FDATASYNC:
9920 [ - + ]: 1 : if (pg_fdatasync(fd) != 0)
9921 : 0 : msg = _("could not fdatasync file \"%s\": %m");
9922 : 1 : break;
9923 : 0 : case WAL_SYNC_METHOD_OPEN:
9924 : : case WAL_SYNC_METHOD_OPEN_DSYNC:
9925 : : /* not reachable */
9926 : : Assert(false);
9927 : 0 : break;
9928 : 0 : default:
9929 [ # # ]: 0 : ereport(PANIC,
9930 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9931 : : errmsg_internal("unrecognized \"wal_sync_method\": %d", wal_sync_method));
9932 : : break;
9933 : : }
9934 : :
9935 : : /* PANIC if failed to fsync */
9936 [ - + ]: 1 : if (msg)
9937 : : {
9938 : : char xlogfname[MAXFNAMELEN];
9939 : 0 : int save_errno = errno;
9940 : :
9941 : 0 : XLogFileName(xlogfname, tli, segno, wal_segment_size);
9942 : 0 : errno = save_errno;
9943 [ # # ]: 0 : ereport(PANIC,
9944 : : (errcode_for_file_access(),
9945 : : errmsg(msg, xlogfname)));
9946 : : }
9947 : :
9948 : 1 : pgstat_report_wait_end();
9949 : :
9950 : 1 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL, IOOP_FSYNC,
9951 : : start, 1, 0);
9952 : : }
9953 : :
9954 : : /*
9955 : : * do_pg_backup_start is the workhorse of the user-visible pg_backup_start()
9956 : : * function. It creates the necessary starting checkpoint and constructs the
9957 : : * backup state and tablespace map.
9958 : : *
9959 : : * Input parameters are "state" (the backup state), "fast" (if true, we do
9960 : : * the checkpoint in fast mode), and "tablespaces" (if non-NULL, indicates a
9961 : : * list of tablespaceinfo structs describing the cluster's tablespaces.).
9962 : : *
9963 : : * The tablespace map contents are appended to passed-in parameter
9964 : : * tablespace_map and the caller is responsible for including it in the backup
9965 : : * archive as 'tablespace_map'. The tablespace_map file is required mainly for
9966 : : * tar format in windows as native windows utilities are not able to create
9967 : : * symlinks while extracting files from tar. However for consistency and
9968 : : * platform-independence, we do it the same way everywhere.
9969 : : *
9970 : : * It fills in "state" with the information required for the backup, such
9971 : : * as the minimum WAL location that must be present to restore from this
9972 : : * backup (starttli) and the corresponding timeline ID (starttli).
9973 : : *
9974 : : * Every successfully started backup must be stopped by calling
9975 : : * do_pg_backup_stop() or do_pg_abort_backup(). There can be many
9976 : : * backups active at the same time.
9977 : : *
9978 : : * It is the responsibility of the caller of this function to verify the
9979 : : * permissions of the calling user!
9980 : : */
9981 : : void
9982 : 200 : do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces,
9983 : : BackupState *state, StringInfo tblspcmapfile)
9984 : : {
9985 : : bool backup_started_in_recovery;
9986 : :
9987 : : Assert(state != NULL);
9988 : 200 : backup_started_in_recovery = RecoveryInProgress();
9989 : :
9990 : : /*
9991 : : * During recovery, we don't need to check WAL level. Because, if WAL
9992 : : * level is not sufficient, it's impossible to get here during recovery.
9993 : : */
9994 [ + + - + ]: 200 : if (!backup_started_in_recovery && !XLogIsNeeded())
9995 [ # # ]: 0 : ereport(ERROR,
9996 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9997 : : errmsg("WAL level not sufficient for making an online backup"),
9998 : : errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start.")));
9999 : :
10000 [ + + ]: 200 : if (strlen(backupidstr) > MAXPGPATH)
10001 [ + - ]: 1 : ereport(ERROR,
10002 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10003 : : errmsg("backup label too long (max %d bytes)",
10004 : : MAXPGPATH)));
10005 : :
10006 [ + + ]: 199 : if (strpbrk(backupidstr, "\n\r"))
10007 [ + - ]: 2 : ereport(ERROR,
10008 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10009 : : errmsg("backup label contains a newline or carriage return character")));
10010 : :
10011 : 197 : strlcpy(state->name, backupidstr, sizeof(state->name));
10012 : :
10013 : : /*
10014 : : * Mark backup active in shared memory. We must do full-page WAL writes
10015 : : * during an on-line backup even if not doing so at other times, because
10016 : : * it's quite possible for the backup dump to obtain a "torn" (partially
10017 : : * written) copy of a database page if it reads the page concurrently with
10018 : : * our write to the same page. This can be fixed as long as the first
10019 : : * write to the page in the WAL sequence is a full-page write. Hence, we
10020 : : * increment runningBackups then force a CHECKPOINT, to ensure there are
10021 : : * no dirty pages in shared memory that might get dumped while the backup
10022 : : * is in progress without having a corresponding WAL record. (Once the
10023 : : * backup is complete, we need not force full-page writes anymore, since
10024 : : * we expect that any pages not modified during the backup interval must
10025 : : * have been correctly captured by the backup.)
10026 : : *
10027 : : * Note that forcing full-page writes has no effect during an online
10028 : : * backup from the standby.
10029 : : *
10030 : : * We must hold all the insertion locks to change the value of
10031 : : * runningBackups, to ensure adequate interlocking against
10032 : : * XLogInsertRecord().
10033 : : */
10034 : 197 : WALInsertLockAcquireExclusive();
10035 : 197 : XLogCtl->Insert.runningBackups++;
10036 : 197 : WALInsertLockRelease();
10037 : :
10038 : : /*
10039 : : * Ensure we decrement runningBackups if we fail below. NB -- for this to
10040 : : * work correctly, it is critical that sessionBackupState is only updated
10041 : : * after this block is over.
10042 : : */
10043 [ + - ]: 197 : PG_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(true));
10044 : : {
10045 : 197 : bool gotUniqueStartpoint = false;
10046 : : DIR *tblspcdir;
10047 : : struct dirent *de;
10048 : : tablespaceinfo *ti;
10049 : : int datadirpathlen;
10050 : :
10051 : : /*
10052 : : * Force an XLOG file switch before the checkpoint, to ensure that the
10053 : : * WAL segment the checkpoint is written to doesn't contain pages with
10054 : : * old timeline IDs. That would otherwise happen if you called
10055 : : * pg_backup_start() right after restoring from a PITR archive: the
10056 : : * first WAL segment containing the startup checkpoint has pages in
10057 : : * the beginning with the old timeline ID. That can cause trouble at
10058 : : * recovery: we won't have a history file covering the old timeline if
10059 : : * pg_wal directory was not included in the base backup and the WAL
10060 : : * archive was cleared too before starting the backup.
10061 : : *
10062 : : * During recovery, we skip forcing XLOG file switch, which means that
10063 : : * the backup taken during recovery is not available for the special
10064 : : * recovery case described above.
10065 : : */
10066 [ + + ]: 197 : if (!backup_started_in_recovery)
10067 : 186 : RequestXLogSwitch(false);
10068 : :
10069 : : do
10070 : : {
10071 : : bool checkpointfpw;
10072 : :
10073 : : /*
10074 : : * Force a CHECKPOINT. Aside from being necessary to prevent torn
10075 : : * page problems, this guarantees that two successive backup runs
10076 : : * will have different checkpoint positions and hence different
10077 : : * history file names, even if nothing happened in between.
10078 : : *
10079 : : * During recovery, establish a restartpoint if possible. We use
10080 : : * the last restartpoint as the backup starting checkpoint. This
10081 : : * means that two successive backup runs can have same checkpoint
10082 : : * positions.
10083 : : *
10084 : : * Since the fact that we are executing do_pg_backup_start()
10085 : : * during recovery means that checkpointer is running, we can use
10086 : : * RequestCheckpoint() to establish a restartpoint.
10087 : : *
10088 : : * We use CHECKPOINT_FAST only if requested by user (via passing
10089 : : * fast = true). Otherwise this can take awhile.
10090 : : */
10091 [ + + ]: 197 : RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT |
10092 : : (fast ? CHECKPOINT_FAST : 0));
10093 : :
10094 : : /*
10095 : : * Now we need to fetch the checkpoint record location, and also
10096 : : * its REDO pointer. The oldest point in WAL that would be needed
10097 : : * to restore starting from the checkpoint is precisely the REDO
10098 : : * pointer.
10099 : : */
10100 : 197 : LWLockAcquire(ControlFileLock, LW_SHARED);
10101 : 197 : state->checkpointloc = ControlFile->checkPoint;
10102 : 197 : state->startpoint = ControlFile->checkPointCopy.redo;
10103 : 197 : state->starttli = ControlFile->checkPointCopy.ThisTimeLineID;
10104 : 197 : checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
10105 : 197 : LWLockRelease(ControlFileLock);
10106 : :
10107 [ + + ]: 197 : if (backup_started_in_recovery)
10108 : : {
10109 : : XLogRecPtr recptr;
10110 : :
10111 : : /*
10112 : : * Check to see if all WAL replayed during online backup
10113 : : * (i.e., since last restartpoint used as backup starting
10114 : : * checkpoint) contain full-page writes.
10115 : : */
10116 : 11 : SpinLockAcquire(&XLogCtl->info_lck);
10117 : 11 : recptr = XLogCtl->lastFpwDisableRecPtr;
10118 : 11 : SpinLockRelease(&XLogCtl->info_lck);
10119 : :
10120 [ + - - + ]: 11 : if (!checkpointfpw || state->startpoint <= recptr)
10121 [ # # ]: 0 : ereport(ERROR,
10122 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10123 : : errmsg("WAL generated with \"full_page_writes=off\" was replayed "
10124 : : "since last restartpoint"),
10125 : : errhint("This means that the backup being taken on the standby "
10126 : : "is corrupt and should not be used. "
10127 : : "Enable \"full_page_writes\" and run CHECKPOINT on the primary, "
10128 : : "and then try an online backup again.")));
10129 : :
10130 : : /*
10131 : : * During recovery, since we don't use the end-of-backup WAL
10132 : : * record and don't write the backup history file, the
10133 : : * starting WAL location doesn't need to be unique. This means
10134 : : * that two base backups started at the same time might use
10135 : : * the same checkpoint as starting locations.
10136 : : */
10137 : 11 : gotUniqueStartpoint = true;
10138 : : }
10139 : :
10140 : : /*
10141 : : * If two base backups are started at the same time (in WAL sender
10142 : : * processes), we need to make sure that they use different
10143 : : * checkpoints as starting locations, because we use the starting
10144 : : * WAL location as a unique identifier for the base backup in the
10145 : : * end-of-backup WAL record and when we write the backup history
10146 : : * file. Perhaps it would be better generate a separate unique ID
10147 : : * for each backup instead of forcing another checkpoint, but
10148 : : * taking a checkpoint right after another is not that expensive
10149 : : * either because only few buffers have been dirtied yet.
10150 : : */
10151 : 197 : WALInsertLockAcquireExclusive();
10152 [ + - ]: 197 : if (XLogCtl->Insert.lastBackupStart < state->startpoint)
10153 : : {
10154 : 197 : XLogCtl->Insert.lastBackupStart = state->startpoint;
10155 : 197 : gotUniqueStartpoint = true;
10156 : : }
10157 : 197 : WALInsertLockRelease();
10158 [ - + ]: 197 : } while (!gotUniqueStartpoint);
10159 : :
10160 : : /*
10161 : : * Construct tablespace_map file.
10162 : : */
10163 : 197 : datadirpathlen = strlen(DataDir);
10164 : :
10165 : : /* Collect information about all tablespaces */
10166 : 197 : tblspcdir = AllocateDir(PG_TBLSPC_DIR);
10167 [ + + ]: 629 : while ((de = ReadDir(tblspcdir, PG_TBLSPC_DIR)) != NULL)
10168 : : {
10169 : : char fullpath[MAXPGPATH + sizeof(PG_TBLSPC_DIR)];
10170 : : char linkpath[MAXPGPATH];
10171 : 432 : char *relpath = NULL;
10172 : : char *s;
10173 : : PGFileType de_type;
10174 : : char *badp;
10175 : : Oid tsoid;
10176 : :
10177 : : /*
10178 : : * Try to parse the directory name as an unsigned integer.
10179 : : *
10180 : : * Tablespace directories should be positive integers that can be
10181 : : * represented in 32 bits, with no leading zeroes or trailing
10182 : : * garbage. If we come across a name that doesn't meet those
10183 : : * criteria, skip it.
10184 : : */
10185 [ + + - + ]: 432 : if (de->d_name[0] < '1' || de->d_name[1] > '9')
10186 : 394 : continue;
10187 : 38 : errno = 0;
10188 : 38 : tsoid = strtoul(de->d_name, &badp, 10);
10189 [ + - + - : 38 : if (*badp != '\0' || errno == EINVAL || errno == ERANGE)
- + ]
10190 : 0 : continue;
10191 : :
10192 : 38 : snprintf(fullpath, sizeof(fullpath), "%s/%s", PG_TBLSPC_DIR, de->d_name);
10193 : :
10194 : 38 : de_type = get_dirent_type(fullpath, de, false, ERROR);
10195 : :
10196 [ + + ]: 38 : if (de_type == PGFILETYPE_LNK)
10197 : : {
10198 : : StringInfoData escapedpath;
10199 : : ssize_t rllen;
10200 : :
10201 : 23 : rllen = readlink(fullpath, linkpath, sizeof(linkpath));
10202 [ - + ]: 23 : if (rllen < 0)
10203 : : {
10204 [ # # ]: 0 : ereport(WARNING,
10205 : : (errmsg("could not read symbolic link \"%s\": %m",
10206 : : fullpath)));
10207 : 0 : continue;
10208 : : }
10209 [ - + ]: 23 : else if (rllen >= sizeof(linkpath))
10210 : : {
10211 [ # # ]: 0 : ereport(WARNING,
10212 : : (errmsg("symbolic link \"%s\" target is too long",
10213 : : fullpath)));
10214 : 0 : continue;
10215 : : }
10216 : 23 : linkpath[rllen] = '\0';
10217 : :
10218 : : /*
10219 : : * Relpath holds the relative path of the tablespace directory
10220 : : * when it's located within PGDATA, or NULL if it's located
10221 : : * elsewhere.
10222 : : */
10223 [ + + ]: 23 : if (rllen > datadirpathlen &&
10224 [ - + ]: 1 : strncmp(linkpath, DataDir, datadirpathlen) == 0 &&
10225 [ # # ]: 0 : IS_DIR_SEP(linkpath[datadirpathlen]))
10226 : 0 : relpath = pstrdup(linkpath + datadirpathlen + 1);
10227 : :
10228 : : /*
10229 : : * Add a backslash-escaped version of the link path to the
10230 : : * tablespace map file.
10231 : : */
10232 : 23 : initStringInfo(&escapedpath);
10233 [ + + ]: 562 : for (s = linkpath; *s; s++)
10234 : : {
10235 [ + - + - : 539 : if (*s == '\n' || *s == '\r' || *s == '\\')
- + ]
10236 : 0 : appendStringInfoChar(&escapedpath, '\\');
10237 : 539 : appendStringInfoChar(&escapedpath, *s);
10238 : : }
10239 : 23 : appendStringInfo(tblspcmapfile, "%s %s\n",
10240 : 23 : de->d_name, escapedpath.data);
10241 : 23 : pfree(escapedpath.data);
10242 : : }
10243 [ + - ]: 15 : else if (de_type == PGFILETYPE_DIR)
10244 : : {
10245 : : /*
10246 : : * It's possible to use allow_in_place_tablespaces to create
10247 : : * directories directly under pg_tblspc, for testing purposes
10248 : : * only.
10249 : : *
10250 : : * In this case, we store a relative path rather than an
10251 : : * absolute path into the tablespaceinfo.
10252 : : */
10253 : 15 : snprintf(linkpath, sizeof(linkpath), "%s/%s",
10254 : 15 : PG_TBLSPC_DIR, de->d_name);
10255 : 15 : relpath = pstrdup(linkpath);
10256 : : }
10257 : : else
10258 : : {
10259 : : /* Skip any other file type that appears here. */
10260 : 0 : continue;
10261 : : }
10262 : :
10263 : 38 : ti = palloc_object(tablespaceinfo);
10264 : 38 : ti->oid = tsoid;
10265 : 38 : ti->path = pstrdup(linkpath);
10266 : 38 : ti->rpath = relpath;
10267 : 38 : ti->size = -1;
10268 : :
10269 [ + - ]: 38 : if (tablespaces)
10270 : 38 : *tablespaces = lappend(*tablespaces, ti);
10271 : : }
10272 : 197 : FreeDir(tblspcdir);
10273 : :
10274 : 197 : state->starttime = (pg_time_t) time(NULL);
10275 : : }
10276 [ - + ]: 197 : PG_END_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(true));
10277 : :
10278 : 197 : state->started_in_recovery = backup_started_in_recovery;
10279 : :
10280 : : /*
10281 : : * Mark that the start phase has correctly finished for the backup.
10282 : : */
10283 : 197 : sessionBackupState = SESSION_BACKUP_RUNNING;
10284 : 197 : }
10285 : :
10286 : : /*
10287 : : * Utility routine to fetch the session-level status of a backup running.
10288 : : */
10289 : : SessionBackupState
10290 : 221 : get_backup_status(void)
10291 : : {
10292 : 221 : return sessionBackupState;
10293 : : }
10294 : :
10295 : : /*
10296 : : * do_pg_backup_stop
10297 : : *
10298 : : * Utility function called at the end of an online backup. It creates history
10299 : : * file (if required), resets sessionBackupState and so on. It can optionally
10300 : : * wait for WAL segments to be archived.
10301 : : *
10302 : : * "state" is filled with the information necessary to restore from this
10303 : : * backup with its stop LSN (stoppoint), its timeline ID (stoptli), etc.
10304 : : *
10305 : : * It is the responsibility of the caller of this function to verify the
10306 : : * permissions of the calling user!
10307 : : */
10308 : : void
10309 : 191 : do_pg_backup_stop(BackupState *state, bool waitforarchive)
10310 : : {
10311 : 191 : bool backup_stopped_in_recovery = false;
10312 : : char histfilepath[MAXPGPATH];
10313 : : char lastxlogfilename[MAXFNAMELEN];
10314 : : char histfilename[MAXFNAMELEN];
10315 : : XLogSegNo _logSegNo;
10316 : : FILE *fp;
10317 : : int seconds_before_warning;
10318 : 191 : int waits = 0;
10319 : 191 : bool reported_waiting = false;
10320 : :
10321 : : Assert(state != NULL);
10322 : :
10323 : 191 : backup_stopped_in_recovery = RecoveryInProgress();
10324 : :
10325 : : /*
10326 : : * During recovery, we don't need to check WAL level. Because, if WAL
10327 : : * level is not sufficient, it's impossible to get here during recovery.
10328 : : */
10329 [ + + - + ]: 191 : if (!backup_stopped_in_recovery && !XLogIsNeeded())
10330 [ # # ]: 0 : ereport(ERROR,
10331 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10332 : : errmsg("WAL level not sufficient for making an online backup"),
10333 : : errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start.")));
10334 : :
10335 : : /*
10336 : : * OK to update backup counter and session-level lock.
10337 : : *
10338 : : * Note that CHECK_FOR_INTERRUPTS() must not occur while updating them,
10339 : : * otherwise they can be updated inconsistently, which might cause
10340 : : * do_pg_abort_backup() to fail.
10341 : : */
10342 : 191 : WALInsertLockAcquireExclusive();
10343 : :
10344 : : /*
10345 : : * It is expected that each do_pg_backup_start() call is matched by
10346 : : * exactly one do_pg_backup_stop() call.
10347 : : */
10348 : : Assert(XLogCtl->Insert.runningBackups > 0);
10349 : 191 : XLogCtl->Insert.runningBackups--;
10350 : :
10351 : : /*
10352 : : * Clean up session-level lock.
10353 : : *
10354 : : * You might think that WALInsertLockRelease() can be called before
10355 : : * cleaning up session-level lock because session-level lock doesn't need
10356 : : * to be protected with WAL insertion lock. But since
10357 : : * CHECK_FOR_INTERRUPTS() can occur in it, session-level lock must be
10358 : : * cleaned up before it.
10359 : : */
10360 : 191 : sessionBackupState = SESSION_BACKUP_NONE;
10361 : :
10362 : 191 : WALInsertLockRelease();
10363 : :
10364 : : /*
10365 : : * If we are taking an online backup from the standby, we confirm that the
10366 : : * standby has not been promoted during the backup.
10367 : : */
10368 [ + + - + ]: 191 : if (state->started_in_recovery && !backup_stopped_in_recovery)
10369 [ # # ]: 0 : ereport(ERROR,
10370 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10371 : : errmsg("the standby was promoted during online backup"),
10372 : : errhint("This means that the backup being taken is corrupt "
10373 : : "and should not be used. "
10374 : : "Try taking another online backup.")));
10375 : :
10376 : : /*
10377 : : * During recovery, we don't write an end-of-backup record. We assume that
10378 : : * pg_control was backed up last and its minimum recovery point can be
10379 : : * available as the backup end location. Since we don't have an
10380 : : * end-of-backup record, we use the pg_control value to check whether
10381 : : * we've reached the end of backup when starting recovery from this
10382 : : * backup. We have no way of checking if pg_control wasn't backed up last
10383 : : * however.
10384 : : *
10385 : : * We don't force a switch to new WAL file but it is still possible to
10386 : : * wait for all the required files to be archived if waitforarchive is
10387 : : * true. This is okay if we use the backup to start a standby and fetch
10388 : : * the missing WAL using streaming replication. But in the case of an
10389 : : * archive recovery, a user should set waitforarchive to true and wait for
10390 : : * them to be archived to ensure that all the required files are
10391 : : * available.
10392 : : *
10393 : : * We return the current minimum recovery point as the backup end
10394 : : * location. Note that it can be greater than the exact backup end
10395 : : * location if the minimum recovery point is updated after the backup of
10396 : : * pg_control. This is harmless for current uses.
10397 : : *
10398 : : * XXX currently a backup history file is for informational and debug
10399 : : * purposes only. It's not essential for an online backup. Furthermore,
10400 : : * even if it's created, it will not be archived during recovery because
10401 : : * an archiver is not invoked. So it doesn't seem worthwhile to write a
10402 : : * backup history file during recovery.
10403 : : */
10404 [ + + ]: 191 : if (backup_stopped_in_recovery)
10405 : : {
10406 : : XLogRecPtr recptr;
10407 : :
10408 : : /*
10409 : : * Check to see if all WAL replayed during online backup contain
10410 : : * full-page writes.
10411 : : */
10412 : 11 : SpinLockAcquire(&XLogCtl->info_lck);
10413 : 11 : recptr = XLogCtl->lastFpwDisableRecPtr;
10414 : 11 : SpinLockRelease(&XLogCtl->info_lck);
10415 : :
10416 [ - + ]: 11 : if (state->startpoint <= recptr)
10417 [ # # ]: 0 : ereport(ERROR,
10418 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10419 : : errmsg("WAL generated with \"full_page_writes=off\" was replayed "
10420 : : "during online backup"),
10421 : : errhint("This means that the backup being taken on the standby "
10422 : : "is corrupt and should not be used. "
10423 : : "Enable \"full_page_writes\" and run CHECKPOINT on the primary, "
10424 : : "and then try an online backup again.")));
10425 : :
10426 : :
10427 : 11 : LWLockAcquire(ControlFileLock, LW_SHARED);
10428 : 11 : state->stoppoint = ControlFile->minRecoveryPoint;
10429 : 11 : state->stoptli = ControlFile->minRecoveryPointTLI;
10430 : 11 : LWLockRelease(ControlFileLock);
10431 : : }
10432 : : else
10433 : : {
10434 : : char *history_file;
10435 : :
10436 : : /*
10437 : : * Write the backup-end xlog record
10438 : : */
10439 : 180 : XLogBeginInsert();
10440 : 180 : XLogRegisterData(&state->startpoint,
10441 : : sizeof(state->startpoint));
10442 : 180 : state->stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END);
10443 : :
10444 : : /*
10445 : : * Given that we're not in recovery, InsertTimeLineID is set and can't
10446 : : * change, so we can read it without a lock.
10447 : : */
10448 : 180 : state->stoptli = XLogCtl->InsertTimeLineID;
10449 : :
10450 : : /*
10451 : : * Force a switch to a new xlog segment file, so that the backup is
10452 : : * valid as soon as archiver moves out the current segment file.
10453 : : */
10454 : 180 : RequestXLogSwitch(false);
10455 : :
10456 : 180 : state->stoptime = (pg_time_t) time(NULL);
10457 : :
10458 : : /*
10459 : : * Write the backup history file
10460 : : */
10461 : 180 : XLByteToSeg(state->startpoint, _logSegNo, wal_segment_size);
10462 : 180 : BackupHistoryFilePath(histfilepath, state->stoptli, _logSegNo,
10463 : : state->startpoint, wal_segment_size);
10464 : 180 : fp = AllocateFile(histfilepath, "w");
10465 [ - + ]: 180 : if (!fp)
10466 [ # # ]: 0 : ereport(ERROR,
10467 : : (errcode_for_file_access(),
10468 : : errmsg("could not create file \"%s\": %m",
10469 : : histfilepath)));
10470 : :
10471 : : /* Build and save the contents of the backup history file */
10472 : 180 : history_file = build_backup_content(state, true);
10473 : 180 : fprintf(fp, "%s", history_file);
10474 : 180 : pfree(history_file);
10475 : :
10476 [ + - + - : 180 : if (fflush(fp) || ferror(fp) || FreeFile(fp))
- + ]
10477 [ # # ]: 0 : ereport(ERROR,
10478 : : (errcode_for_file_access(),
10479 : : errmsg("could not write file \"%s\": %m",
10480 : : histfilepath)));
10481 : :
10482 : : /*
10483 : : * Clean out any no-longer-needed history files. As a side effect,
10484 : : * this will post a .ready file for the newly created history file,
10485 : : * notifying the archiver that history file may be archived
10486 : : * immediately.
10487 : : */
10488 : 180 : CleanupBackupHistory();
10489 : : }
10490 : :
10491 : : /*
10492 : : * If archiving is enabled, wait for all the required WAL files to be
10493 : : * archived before returning. If archiving isn't enabled, the required WAL
10494 : : * needs to be transported via streaming replication (hopefully with
10495 : : * wal_keep_size set high enough), or some more exotic mechanism like
10496 : : * polling and copying files from pg_wal with script. We have no knowledge
10497 : : * of those mechanisms, so it's up to the user to ensure that he gets all
10498 : : * the required WAL.
10499 : : *
10500 : : * We wait until both the last WAL file filled during backup and the
10501 : : * history file have been archived, and assume that the alphabetic sorting
10502 : : * property of the WAL files ensures any earlier WAL files are safely
10503 : : * archived as well.
10504 : : *
10505 : : * We wait forever, since archive_command is supposed to work and we
10506 : : * assume the admin wanted his backup to work completely. If you don't
10507 : : * wish to wait, then either waitforarchive should be passed in as false,
10508 : : * or you can set statement_timeout. Also, some notices are issued to
10509 : : * clue in anyone who might be doing this interactively.
10510 : : */
10511 : :
10512 [ + + ]: 191 : if (waitforarchive &&
10513 [ + + + + : 12 : ((!backup_stopped_in_recovery && XLogArchivingActive()) ||
+ + ]
10514 [ - + ]: 1 : (backup_stopped_in_recovery && XLogArchivingAlways())))
10515 : : {
10516 : 5 : XLByteToPrevSeg(state->stoppoint, _logSegNo, wal_segment_size);
10517 : 5 : XLogFileName(lastxlogfilename, state->stoptli, _logSegNo,
10518 : : wal_segment_size);
10519 : :
10520 : 5 : XLByteToSeg(state->startpoint, _logSegNo, wal_segment_size);
10521 : 5 : BackupHistoryFileName(histfilename, state->stoptli, _logSegNo,
10522 : : state->startpoint, wal_segment_size);
10523 : :
10524 : 5 : seconds_before_warning = 60;
10525 : 5 : waits = 0;
10526 : :
10527 [ + + - + ]: 15 : while (XLogArchiveIsBusy(lastxlogfilename) ||
10528 : 5 : XLogArchiveIsBusy(histfilename))
10529 : : {
10530 [ - + ]: 5 : CHECK_FOR_INTERRUPTS();
10531 : :
10532 [ + - - + ]: 5 : if (!reported_waiting && waits > 5)
10533 : : {
10534 [ # # ]: 0 : ereport(NOTICE,
10535 : : (errmsg("base backup done, waiting for required WAL segments to be archived")));
10536 : 0 : reported_waiting = true;
10537 : : }
10538 : :
10539 : 5 : (void) WaitLatch(MyLatch,
10540 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
10541 : : 1000L,
10542 : : WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE);
10543 : 5 : ResetLatch(MyLatch);
10544 : :
10545 [ - + ]: 5 : if (++waits >= seconds_before_warning)
10546 : : {
10547 : 0 : seconds_before_warning *= 2; /* This wraps in >10 years... */
10548 [ # # ]: 0 : ereport(WARNING,
10549 : : (errmsg("still waiting for all required WAL segments to be archived (%d seconds elapsed)",
10550 : : waits),
10551 : : errhint("Check that your \"archive_command\" is executing properly. "
10552 : : "You can safely cancel this backup, "
10553 : : "but the database backup will not be usable without all the WAL segments.")));
10554 : : }
10555 : : }
10556 : :
10557 [ + + ]: 5 : ereport(NOTICE,
10558 : : (errmsg("all required WAL segments have been archived")));
10559 : : }
10560 [ + + ]: 186 : else if (waitforarchive)
10561 [ + - ]: 7 : ereport(NOTICE,
10562 : : (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
10563 : 191 : }
10564 : :
10565 : :
10566 : : /*
10567 : : * do_pg_abort_backup: abort a running backup
10568 : : *
10569 : : * This does just the most basic steps of do_pg_backup_stop(), by taking the
10570 : : * system out of backup mode, thus making it a lot more safe to call from
10571 : : * an error handler.
10572 : : *
10573 : : * 'arg' indicates that it's being called during backup setup; so
10574 : : * sessionBackupState has not been modified yet, but runningBackups has
10575 : : * already been incremented. When it's false, then it's invoked as a
10576 : : * before_shmem_exit handler, and therefore we must not change state
10577 : : * unless sessionBackupState indicates that a backup is actually running.
10578 : : *
10579 : : * NB: This gets used as a PG_ENSURE_ERROR_CLEANUP callback and
10580 : : * before_shmem_exit handler, hence the odd-looking signature.
10581 : : */
10582 : : void
10583 : 11 : do_pg_abort_backup(int code, Datum arg)
10584 : : {
10585 : 11 : bool during_backup_start = DatumGetBool(arg);
10586 : :
10587 : : /* If called during backup start, there shouldn't be one already running */
10588 : : Assert(!during_backup_start || sessionBackupState == SESSION_BACKUP_NONE);
10589 : :
10590 [ + - + + ]: 11 : if (during_backup_start || sessionBackupState != SESSION_BACKUP_NONE)
10591 : : {
10592 : 6 : WALInsertLockAcquireExclusive();
10593 : : Assert(XLogCtl->Insert.runningBackups > 0);
10594 : 6 : XLogCtl->Insert.runningBackups--;
10595 : :
10596 : 6 : sessionBackupState = SESSION_BACKUP_NONE;
10597 : 6 : WALInsertLockRelease();
10598 : :
10599 [ + - ]: 6 : if (!during_backup_start)
10600 [ + - ]: 6 : ereport(WARNING,
10601 : : errmsg("aborting backup due to backend exiting before pg_backup_stop was called"));
10602 : : }
10603 : 11 : }
10604 : :
10605 : : /*
10606 : : * Register a handler that will warn about unterminated backups at end of
10607 : : * session, unless this has already been done.
10608 : : */
10609 : : void
10610 : 7 : register_persistent_abort_backup_handler(void)
10611 : : {
10612 : : static bool already_done = false;
10613 : :
10614 [ + + ]: 7 : if (already_done)
10615 : 1 : return;
10616 : 6 : before_shmem_exit(do_pg_abort_backup, BoolGetDatum(false));
10617 : 6 : already_done = true;
10618 : : }
10619 : :
10620 : : /*
10621 : : * Get latest WAL insert pointer
10622 : : */
10623 : : XLogRecPtr
10624 : 2253 : GetXLogInsertRecPtr(void)
10625 : : {
10626 : 2253 : XLogCtlInsert *Insert = &XLogCtl->Insert;
10627 : : uint64 current_bytepos;
10628 : :
10629 : 2253 : SpinLockAcquire(&Insert->insertpos_lck);
10630 : 2253 : current_bytepos = Insert->CurrBytePos;
10631 : 2253 : SpinLockRelease(&Insert->insertpos_lck);
10632 : :
10633 : 2253 : return XLogBytePosToRecPtr(current_bytepos);
10634 : : }
10635 : :
10636 : : /*
10637 : : * Get latest WAL record end pointer
10638 : : */
10639 : : XLogRecPtr
10640 : 10599 : GetXLogInsertEndRecPtr(void)
10641 : : {
10642 : 10599 : XLogCtlInsert *Insert = &XLogCtl->Insert;
10643 : : uint64 current_bytepos;
10644 : :
10645 : 10599 : SpinLockAcquire(&Insert->insertpos_lck);
10646 : 10599 : current_bytepos = Insert->CurrBytePos;
10647 : 10599 : SpinLockRelease(&Insert->insertpos_lck);
10648 : :
10649 : 10599 : return XLogBytePosToEndRecPtr(current_bytepos);
10650 : : }
10651 : :
10652 : : /*
10653 : : * Get latest WAL write pointer
10654 : : */
10655 : : XLogRecPtr
10656 : 1814 : GetXLogWriteRecPtr(void)
10657 : : {
10658 : 1814 : RefreshXLogWriteResult(LogwrtResult);
10659 : :
10660 : 1814 : return LogwrtResult.Write;
10661 : : }
10662 : :
10663 : : /*
10664 : : * Returns the redo pointer of the last checkpoint or restartpoint. This is
10665 : : * the oldest point in WAL that we still need, if we have to restart recovery.
10666 : : */
10667 : : void
10668 : 406 : GetOldestRestartPoint(XLogRecPtr *oldrecptr, TimeLineID *oldtli)
10669 : : {
10670 : 406 : LWLockAcquire(ControlFileLock, LW_SHARED);
10671 : 406 : *oldrecptr = ControlFile->checkPointCopy.redo;
10672 : 406 : *oldtli = ControlFile->checkPointCopy.ThisTimeLineID;
10673 : 406 : LWLockRelease(ControlFileLock);
10674 : 406 : }
10675 : :
10676 : : /* Thin wrapper around ShutdownWalRcv(). */
10677 : : void
10678 : 1132 : XLogShutdownWalRcv(void)
10679 : : {
10680 : : Assert(AmStartupProcess() || !IsUnderPostmaster);
10681 : :
10682 : 1132 : ShutdownWalRcv();
10683 : 1132 : ResetInstallXLogFileSegmentActive();
10684 : 1132 : }
10685 : :
10686 : : /* Enable WAL file recycling and preallocation. */
10687 : : void
10688 : 1353 : SetInstallXLogFileSegmentActive(void)
10689 : : {
10690 : 1353 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
10691 : 1353 : XLogCtl->InstallXLogFileSegmentActive = true;
10692 : 1353 : LWLockRelease(ControlFileLock);
10693 : 1353 : }
10694 : :
10695 : : /* Disable WAL file recycling and preallocation. */
10696 : : void
10697 : 1309 : ResetInstallXLogFileSegmentActive(void)
10698 : : {
10699 : 1309 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
10700 : 1309 : XLogCtl->InstallXLogFileSegmentActive = false;
10701 : 1309 : LWLockRelease(ControlFileLock);
10702 : 1309 : }
10703 : :
10704 : : bool
10705 : 0 : IsInstallXLogFileSegmentActive(void)
10706 : : {
10707 : : bool result;
10708 : :
10709 : 0 : LWLockAcquire(ControlFileLock, LW_SHARED);
10710 : 0 : result = XLogCtl->InstallXLogFileSegmentActive;
10711 : 0 : LWLockRelease(ControlFileLock);
10712 : :
10713 : 0 : return result;
10714 : : }
10715 : :
10716 : : /*
10717 : : * Update the WalWriterSleeping flag.
10718 : : */
10719 : : void
10720 : 650 : SetWalWriterSleeping(bool sleeping)
10721 : : {
10722 : 650 : SpinLockAcquire(&XLogCtl->info_lck);
10723 : 650 : XLogCtl->WalWriterSleeping = sleeping;
10724 : 650 : SpinLockRelease(&XLogCtl->info_lck);
10725 : 650 : }
|