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 : 25190162 : PrimaryFlushWakeupProcessRequests(void)
675 : : {
676 [ + + ]: 25190162 : if (unlikely(primaryFlushWakeupPending))
677 : : {
678 : : /* Clear the process-local request before satisfying it. */
679 : 788 : primaryFlushWakeupPending = false;
680 : :
681 : : /* XLogWrite() published this frontier before setting the request. */
682 : 788 : WaitLSNWakeup(WAIT_LSN_TYPE_PRIMARY_FLUSH, LogwrtResult.Flush);
683 : : }
684 : 25190162 : }
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 : 25199328 : XLogInsertRecord(XLogRecData *rdata,
839 : : XLogRecPtr fpw_lsn,
840 : : uint8 flags,
841 : : int num_fpi,
842 : : uint64 fpi_bytes,
843 : : bool topxid_included)
844 : : {
845 : 25199328 : XLogCtlInsert *Insert = &XLogCtl->Insert;
846 : : pg_crc32c rdata_crc;
847 : : bool inserted;
848 : 25199328 : XLogRecord *rechdr = (XLogRecord *) rdata->data;
849 : 25199328 : uint8 info = rechdr->xl_info & ~XLR_INFO_MASK;
850 : 25199328 : WalInsertClass class = WALINSERT_NORMAL;
851 : : XLogRecPtr StartPos;
852 : : XLogRecPtr EndPos;
853 : 25199328 : bool prevDoPageWrites = doPageWrites;
854 : : TimeLineID insertTLI;
855 : :
856 : : /* Does this record type require special handling? */
857 [ + + ]: 25199328 : if (unlikely(rechdr->xl_rmid == RM_XLOG_ID))
858 : : {
859 [ + + ]: 339312 : if (info == XLOG_SWITCH)
860 : 853 : class = WALINSERT_SPECIAL_SWITCH;
861 [ + + ]: 338459 : else if (info == XLOG_CHECKPOINT_REDO)
862 : 1035 : 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 [ - + ]: 25199328 : 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 : 25199328 : 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 : 25199328 : START_CRIT_SECTION();
911 : :
912 [ + + ]: 25199328 : if (likely(class == WALINSERT_NORMAL))
913 : : {
914 : 25197440 : 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 [ + + ]: 25197440 : if (RedoRecPtr != Insert->RedoRecPtr)
933 : : {
934 : : Assert(RedoRecPtr < Insert->RedoRecPtr);
935 : 8400 : RedoRecPtr = Insert->RedoRecPtr;
936 : : }
937 [ + + + + ]: 25197440 : doPageWrites = (Insert->fullPageWrites || Insert->runningBackups > 0);
938 : :
939 [ + + ]: 25197440 : if (doPageWrites &&
940 [ + + + + ]: 22890059 : (!prevDoPageWrites ||
941 [ + + ]: 21448494 : (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 : 9166 : WALInsertLockRelease();
948 : 9166 : END_CRIT_SECTION();
949 : 9166 : return InvalidXLogRecPtr;
950 : : }
951 : :
952 : : /*
953 : : * Reserve space for the record in the WAL. This also sets the xl_prev
954 : : * pointer.
955 : : */
956 : 25188274 : ReserveXLogInsertLocation(rechdr->xl_tot_len, &StartPos, &EndPos,
957 : : &rechdr->xl_prev);
958 : :
959 : : /* Normal records are always inserted. */
960 : 25188274 : inserted = true;
961 : : }
962 [ + + ]: 1888 : 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 : 853 : WALInsertLockAcquireExclusive();
977 : 853 : 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 : 1035 : WALInsertLockAcquireExclusive();
992 : 1035 : ReserveXLogInsertLocation(rechdr->xl_tot_len, &StartPos, &EndPos,
993 : : &rechdr->xl_prev);
994 : 1035 : RedoRecPtr = Insert->RedoRecPtr = StartPos;
995 : 1035 : inserted = true;
996 : : }
997 : :
998 [ + + ]: 25190162 : if (inserted)
999 : : {
1000 : : /*
1001 : : * Now that xl_prev has been filled in, calculate CRC of the record
1002 : : * header.
1003 : : */
1004 : 25190100 : rdata_crc = rechdr->xl_crc;
1005 : 25190100 : COMP_CRC32C(rdata_crc, rechdr, offsetof(XLogRecord, xl_crc));
1006 : 25190100 : FIN_CRC32C(rdata_crc);
1007 : 25190100 : 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 : 25190100 : 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 [ + + ]: 25190100 : if ((flags & XLOG_MARK_UNIMPORTANT) == 0)
1023 : : {
1024 [ + + ]: 25037393 : int lockno = holdingAllLocks ? 0 : MyLockNo;
1025 : :
1026 : 25037393 : 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 : 25190162 : WALInsertLockRelease();
1042 : :
1043 : 25190162 : END_CRIT_SECTION();
1044 : :
1045 : 25190162 : 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 [ + + ]: 25190162 : if (topxid_included)
1052 : 224 : MarkSubxactTopXidLogged();
1053 : :
1054 : : /*
1055 : : * Update shared LogwrtRqst.Write, if we crossed page boundary.
1056 : : */
1057 [ + + ]: 25190162 : if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
1058 : : {
1059 : 1893259 : SpinLockAcquire(&XLogCtl->info_lck);
1060 : : /* advance global request to include new block(s) */
1061 [ + + ]: 1893259 : if (XLogCtl->LogwrtRqst.Write < EndPos)
1062 : 1835085 : XLogCtl->LogwrtRqst.Write = EndPos;
1063 : 1893259 : SpinLockRelease(&XLogCtl->info_lck);
1064 : 1893259 : 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 [ + + ]: 25190162 : if (class == WALINSERT_SPECIAL_SWITCH)
1073 : : {
1074 : : TRACE_POSTGRESQL_WAL_SWITCH();
1075 : 853 : 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 [ + + ]: 853 : if (inserted)
1083 : : {
1084 : 791 : EndPos = StartPos + SizeOfXLogRecord;
1085 [ - + ]: 791 : 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 : 25190162 : 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 : 25190162 : ProcLastRecPtr = StartPos;
1170 : 25190162 : XactLastRecEnd = EndPos;
1171 : :
1172 : : /* Report WAL traffic to the instrumentation. */
1173 [ + + ]: 25190162 : if (inserted)
1174 : : {
1175 : 25190100 : pgWalUsage.wal_bytes += rechdr->xl_tot_len;
1176 : 25190100 : pgWalUsage.wal_records++;
1177 : 25190100 : pgWalUsage.wal_fpi += num_fpi;
1178 : 25190100 : pgWalUsage.wal_fpi_bytes += fpi_bytes;
1179 : :
1180 : : /* Required for the flush of pending stats WAL data */
1181 : 25190100 : pgstat_report_fixed = true;
1182 : : }
1183 : :
1184 : 25190162 : 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 : 25189309 : ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos, XLogRecPtr *EndPos,
1207 : : XLogRecPtr *PrevPtr)
1208 : : {
1209 : 25189309 : XLogCtlInsert *Insert = &XLogCtl->Insert;
1210 : : uint64 startbytepos;
1211 : : uint64 endbytepos;
1212 : : uint64 prevbytepos;
1213 : :
1214 : 25189309 : 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 : 25189309 : SpinLockAcquire(&Insert->insertpos_lck);
1230 : :
1231 : 25189309 : startbytepos = Insert->CurrBytePos;
1232 : 25189309 : endbytepos = startbytepos + size;
1233 : 25189309 : prevbytepos = Insert->PrevBytePos;
1234 : 25189309 : Insert->CurrBytePos = endbytepos;
1235 : 25189309 : Insert->PrevBytePos = startbytepos;
1236 : :
1237 : 25189309 : SpinLockRelease(&Insert->insertpos_lck);
1238 : :
1239 : 25189309 : *StartPos = XLogBytePosToRecPtr(startbytepos);
1240 : 25189309 : *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1241 : 25189309 : *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 : 25189309 : }
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 : 853 : ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
1263 : : {
1264 : 853 : XLogCtlInsert *Insert = &XLogCtl->Insert;
1265 : : uint64 startbytepos;
1266 : : uint64 endbytepos;
1267 : : uint64 prevbytepos;
1268 : 853 : 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 : 853 : SpinLockAcquire(&Insert->insertpos_lck);
1279 : :
1280 : 853 : startbytepos = Insert->CurrBytePos;
1281 : :
1282 : 853 : ptr = XLogBytePosToEndRecPtr(startbytepos);
1283 [ + + ]: 853 : if (XLogSegmentOffset(ptr, wal_segment_size) == 0)
1284 : : {
1285 : 62 : SpinLockRelease(&Insert->insertpos_lck);
1286 : 62 : *EndPos = *StartPos = ptr;
1287 : 62 : return false;
1288 : : }
1289 : :
1290 : 791 : endbytepos = startbytepos + size;
1291 : 791 : prevbytepos = Insert->PrevBytePos;
1292 : :
1293 : 791 : *StartPos = XLogBytePosToRecPtr(startbytepos);
1294 : 791 : *EndPos = XLogBytePosToEndRecPtr(endbytepos);
1295 : :
1296 : 791 : segleft = wal_segment_size - XLogSegmentOffset(*EndPos, wal_segment_size);
1297 [ + - ]: 791 : if (segleft != wal_segment_size)
1298 : : {
1299 : : /* consume the rest of the segment */
1300 : 791 : *EndPos += segleft;
1301 : 791 : endbytepos = XLogRecPtrToBytePos(*EndPos);
1302 : : }
1303 : 791 : Insert->CurrBytePos = endbytepos;
1304 : 791 : Insert->PrevBytePos = startbytepos;
1305 : :
1306 : 791 : SpinLockRelease(&Insert->insertpos_lck);
1307 : :
1308 : 791 : *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 : 791 : 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 : 25190100 : 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 : 25190100 : CurrPos = StartPos;
1337 : 25190100 : currpos = GetXLogBuffer(CurrPos, tli);
1338 [ + - ]: 25190100 : 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 : 25190100 : written = 0;
1348 [ + + ]: 114972202 : while (rdata != NULL)
1349 : : {
1350 : 89782102 : const char *rdata_data = rdata->data;
1351 : 89782102 : int rdata_len = rdata->len;
1352 : :
1353 [ + + ]: 91790164 : 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 : 2008062 : memcpy(currpos, rdata_data, freespace);
1360 : 2008062 : rdata_data += freespace;
1361 : 2008062 : rdata_len -= freespace;
1362 : 2008062 : written += freespace;
1363 : 2008062 : 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 : 2008062 : currpos = GetXLogBuffer(CurrPos, tli);
1375 : 2008062 : pagehdr = (XLogPageHeader) currpos;
1376 : 2008062 : pagehdr->xlp_rem_len = write_len - written;
1377 : 2008062 : pagehdr->xlp_info |= XLP_FIRST_IS_CONTRECORD;
1378 : :
1379 : : /* skip over the page header */
1380 [ + + ]: 2008062 : if (XLogSegmentOffset(CurrPos, wal_segment_size) == 0)
1381 : : {
1382 : 1288 : CurrPos += SizeOfXLogLongPHD;
1383 : 1288 : currpos += SizeOfXLogLongPHD;
1384 : : }
1385 : : else
1386 : : {
1387 : 2006774 : CurrPos += SizeOfXLogShortPHD;
1388 : 2006774 : currpos += SizeOfXLogShortPHD;
1389 : : }
1390 [ + - ]: 2008062 : freespace = INSERT_FREESPACE(CurrPos);
1391 : : }
1392 : :
1393 : : Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || rdata_len == 0);
1394 : 89782102 : memcpy(currpos, rdata_data, rdata_len);
1395 : 89782102 : currpos += rdata_len;
1396 : 89782102 : CurrPos += rdata_len;
1397 : 89782102 : freespace -= rdata_len;
1398 : 89782102 : written += rdata_len;
1399 : :
1400 : 89782102 : 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 [ + + + - ]: 25190100 : 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 : 791 : 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 [ + + ]: 815853 : 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 : 815062 : currpos = GetXLogBuffer(CurrPos, tli);
1448 [ + - + - : 3260248 : MemSet(currpos, 0, SizeOfXLogShortPHD);
+ - + - +
+ ]
1449 : :
1450 : 815062 : CurrPos += XLOG_BLCKSZ;
1451 : : }
1452 : : }
1453 : : else
1454 : : {
1455 : : /* Align the end position, so that the next record starts aligned */
1456 : 25189309 : CurrPos = MAXALIGN64(CurrPos);
1457 : : }
1458 : :
1459 [ - + ]: 25190100 : 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 : 25190100 : }
1464 : :
1465 : : /*
1466 : : * Acquire a WAL insertion lock, for inserting to WAL.
1467 : : */
1468 : : static void
1469 : 25198487 : 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 [ + + ]: 25198487 : if (lockToTry == -1)
1487 : 9692 : lockToTry = MyProcNumber % NUM_XLOGINSERT_LOCKS;
1488 : 25198487 : 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 : 25198487 : immed = LWLockAcquire(&WALInsertLocks[MyLockNo].l.lock, LW_EXCLUSIVE);
1495 [ + + ]: 25198487 : 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 : 17481 : lockToTry = (lockToTry + 1) % NUM_XLOGINSERT_LOCKS;
1506 : : }
1507 : 25198487 : }
1508 : :
1509 : : /*
1510 : : * Acquire all WAL insertion locks, to prevent other backends from inserting
1511 : : * to WAL.
1512 : : */
1513 : : static void
1514 : 5026 : 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 [ + + ]: 40208 : for (i = 0; i < NUM_XLOGINSERT_LOCKS - 1; i++)
1524 : : {
1525 : 35182 : LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
1526 : 35182 : LWLockUpdateVar(&WALInsertLocks[i].l.lock,
1527 : 35182 : &WALInsertLocks[i].l.insertingAt,
1528 : : PG_UINT64_MAX);
1529 : : }
1530 : : /* Variable value reset to 0 at release */
1531 : 5026 : LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
1532 : :
1533 : 5026 : holdingAllLocks = true;
1534 : 5026 : }
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 : 25203513 : WALInsertLockRelease(void)
1544 : : {
1545 [ + + ]: 25203513 : if (holdingAllLocks)
1546 : : {
1547 : : int i;
1548 : :
1549 [ + + ]: 45234 : for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1550 : 40208 : LWLockReleaseClearVar(&WALInsertLocks[i].l.lock,
1551 : 40208 : &WALInsertLocks[i].l.insertingAt,
1552 : : 0);
1553 : :
1554 : 5026 : holdingAllLocks = false;
1555 : : }
1556 : : else
1557 : : {
1558 : 25198487 : LWLockReleaseClearVar(&WALInsertLocks[MyLockNo].l.lock,
1559 : 25198487 : &WALInsertLocks[MyLockNo].l.insertingAt,
1560 : : 0);
1561 : : }
1562 : 25203513 : }
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 : 2742604 : WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt)
1570 : : {
1571 [ + + ]: 2742604 : if (holdingAllLocks)
1572 : : {
1573 : : /*
1574 : : * We use the last lock to mark our actual position, see comments in
1575 : : * WALInsertLockAcquireExclusive.
1576 : : */
1577 : 814785 : LWLockUpdateVar(&WALInsertLocks[NUM_XLOGINSERT_LOCKS - 1].l.lock,
1578 : 814785 : &WALInsertLocks[NUM_XLOGINSERT_LOCKS - 1].l.insertingAt,
1579 : : insertingAt);
1580 : : }
1581 : : else
1582 : 1927819 : LWLockUpdateVar(&WALInsertLocks[MyLockNo].l.lock,
1583 : 1927819 : &WALInsertLocks[MyLockNo].l.insertingAt,
1584 : : insertingAt);
1585 : 2742604 : }
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 : 2541857 : WaitXLogInsertionsToFinish(XLogRecPtr upto)
1603 : : {
1604 : : uint64 bytepos;
1605 : : XLogRecPtr inserted;
1606 : : XLogRecPtr reservedUpto;
1607 : : XLogRecPtr finishedUpto;
1608 : 2541857 : XLogCtlInsert *Insert = &XLogCtl->Insert;
1609 : : int i;
1610 : :
1611 [ - + ]: 2541857 : 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 : 2541857 : inserted = pg_atomic_read_membarrier_u64(&XLogCtl->logInsertResult);
1619 [ + + ]: 2541857 : if (upto <= inserted)
1620 : 2033429 : return inserted;
1621 : :
1622 : : /* Read the current insert position */
1623 : 508428 : SpinLockAcquire(&Insert->insertpos_lck);
1624 : 508428 : bytepos = Insert->CurrBytePos;
1625 : 508428 : SpinLockRelease(&Insert->insertpos_lck);
1626 : 508428 : 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 [ - + ]: 508428 : 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 : 508428 : finishedUpto = reservedUpto;
1654 [ + + ]: 4575852 : for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
1655 : : {
1656 : 4067424 : 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 [ + + ]: 4160899 : if (LWLockWaitForVar(&WALInsertLocks[i].l.lock,
1684 : 4160899 : &WALInsertLocks[i].l.insertingAt,
1685 : : insertingat, &insertingat))
1686 : : {
1687 : : /* the lock was free, so no insertion in progress */
1688 : 2906494 : insertingat = InvalidXLogRecPtr;
1689 : 2906494 : break;
1690 : : }
1691 : :
1692 : : /*
1693 : : * This insertion is still in progress. Have to wait, unless the
1694 : : * inserter has proceeded past 'upto'.
1695 : : */
1696 [ + + ]: 1254405 : } while (insertingat < upto);
1697 : :
1698 [ + + + + ]: 4067424 : if (XLogRecPtrIsValid(insertingat) && insertingat < finishedUpto)
1699 : 402555 : 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 : 508428 : finishedUpto = pg_atomic_monotonic_advance_u64(&XLogCtl->logInsertResult,
1708 : : finishedUpto);
1709 : :
1710 : 508428 : 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 : 28013236 : 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 [ + + ]: 28013236 : 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 : 24773770 : 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 : 3239466 : 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 : 3239466 : expectedEndPtr = ptr;
1770 : 3239466 : expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
1771 : :
1772 : 3239466 : endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1773 [ + + ]: 3239466 : 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 [ + + ]: 2742604 : if (ptr % XLOG_BLCKSZ == SizeOfXLogShortPHD &&
1792 [ + - ]: 12492 : XLogSegmentOffset(ptr, wal_segment_size) > XLOG_BLCKSZ)
1793 : 12492 : initializedUpto = ptr - SizeOfXLogShortPHD;
1794 [ + + ]: 2730112 : else if (ptr % XLOG_BLCKSZ == SizeOfXLogLongPHD &&
1795 [ + + ]: 1092 : XLogSegmentOffset(ptr, wal_segment_size) < XLOG_BLCKSZ)
1796 : 657 : initializedUpto = ptr - SizeOfXLogLongPHD;
1797 : : else
1798 : 2729455 : initializedUpto = ptr;
1799 : :
1800 : 2742604 : WALInsertLockUpdateInsertingAt(initializedUpto);
1801 : :
1802 : 2742604 : AdvanceXLInsertBuffer(ptr, tli, false);
1803 : 2742604 : endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1804 : :
1805 [ - + ]: 2742604 : 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 : 496862 : 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 : 3239466 : cachedPage = ptr / XLOG_BLCKSZ;
1823 : 3239466 : 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 : 3239466 : 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 : 107004 : WALReadFromBuffers(char *dstbuf, XLogRecPtr startptr, Size count,
1847 : : TimeLineID tli)
1848 : : {
1849 : 107004 : char *pdst = dstbuf;
1850 : 107004 : XLogRecPtr recptr = startptr;
1851 : : XLogRecPtr inserted;
1852 : 107004 : Size nbytes = count;
1853 : :
1854 [ + + + + ]: 107004 : if (RecoveryInProgress() || tli != GetWALInsertionTimeLine())
1855 : 1371 : 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 : 105633 : inserted = pg_atomic_read_u64(&XLogCtl->logInsertResult);
1864 [ - + ]: 105633 : 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 [ + + ]: 137501 : while (nbytes > 0)
1885 : : {
1886 : 128305 : uint32 offset = recptr % XLOG_BLCKSZ;
1887 : 128305 : 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 : 128305 : 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 : 128305 : endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1905 [ + + ]: 128305 : if (expectedEndPtr != endptr)
1906 : 96435 : 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 : 31870 : page = XLogCtl->pages + idx * (Size) XLOG_BLCKSZ;
1914 : 31870 : psrc = page + offset;
1915 : 31870 : 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 : 31870 : pg_read_barrier();
1922 : :
1923 : : /* data copy */
1924 : 31870 : memcpy(pdst, psrc, npagebytes);
1925 : :
1926 : : /*
1927 : : * Ensure that the data copy and the second verification step are not
1928 : : * reordered.
1929 : : */
1930 : 31870 : 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 : 31870 : endptr = pg_atomic_read_u64(&XLogCtl->xlblocks[idx]);
1937 [ + + ]: 31870 : if (expectedEndPtr != endptr)
1938 : 2 : break;
1939 : :
1940 : 31868 : pdst += npagebytes;
1941 : 31868 : recptr += npagebytes;
1942 : 31868 : nbytes -= npagebytes;
1943 : : }
1944 : :
1945 : : Assert(pdst - dstbuf <= count);
1946 : :
1947 : 105633 : 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 : 50383219 : XLogBytePosToRecPtr(uint64 bytepos)
1957 : : {
1958 : : uint64 fullsegs;
1959 : : uint64 fullpages;
1960 : : uint64 bytesleft;
1961 : : uint32 seg_offset;
1962 : : XLogRecPtr result;
1963 : :
1964 : 50383219 : fullsegs = bytepos / UsableBytesInSegment;
1965 : 50383219 : bytesleft = bytepos % UsableBytesInSegment;
1966 : :
1967 [ + + ]: 50383219 : if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
1968 : : {
1969 : : /* fits on first page of segment */
1970 : 71501 : seg_offset = bytesleft + SizeOfXLogLongPHD;
1971 : : }
1972 : : else
1973 : : {
1974 : : /* account for the first page on segment with long header */
1975 : 50311718 : seg_offset = XLOG_BLCKSZ;
1976 : 50311718 : bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
1977 : :
1978 : 50311718 : fullpages = bytesleft / UsableBytesInPage;
1979 : 50311718 : bytesleft = bytesleft % UsableBytesInPage;
1980 : :
1981 : 50311718 : seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
1982 : : }
1983 : :
1984 : 50383219 : XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
1985 : :
1986 : 50383219 : 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 : 25711598 : XLogBytePosToEndRecPtr(uint64 bytepos)
1997 : : {
1998 : : uint64 fullsegs;
1999 : : uint64 fullpages;
2000 : : uint64 bytesleft;
2001 : : uint32 seg_offset;
2002 : : XLogRecPtr result;
2003 : :
2004 : 25711598 : fullsegs = bytepos / UsableBytesInSegment;
2005 : 25711598 : bytesleft = bytepos % UsableBytesInSegment;
2006 : :
2007 [ + + ]: 25711598 : if (bytesleft < XLOG_BLCKSZ - SizeOfXLogLongPHD)
2008 : : {
2009 : : /* fits on first page of segment */
2010 [ + + ]: 116860 : if (bytesleft == 0)
2011 : 79605 : seg_offset = 0;
2012 : : else
2013 : 37255 : seg_offset = bytesleft + SizeOfXLogLongPHD;
2014 : : }
2015 : : else
2016 : : {
2017 : : /* account for the first page on segment with long header */
2018 : 25594738 : seg_offset = XLOG_BLCKSZ;
2019 : 25594738 : bytesleft -= XLOG_BLCKSZ - SizeOfXLogLongPHD;
2020 : :
2021 : 25594738 : fullpages = bytesleft / UsableBytesInPage;
2022 : 25594738 : bytesleft = bytesleft % UsableBytesInPage;
2023 : :
2024 [ + + ]: 25594738 : if (bytesleft == 0)
2025 : 24910 : seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
2026 : : else
2027 : 25569828 : seg_offset += fullpages * XLOG_BLCKSZ + bytesleft + SizeOfXLogShortPHD;
2028 : : }
2029 : :
2030 : 25711598 : XLogSegNoOffsetToRecPtr(fullsegs, seg_offset, wal_segment_size, result);
2031 : :
2032 : 25711598 : return result;
2033 : : }
2034 : :
2035 : : /*
2036 : : * Convert an XLogRecPtr to a "usable byte position".
2037 : : */
2038 : : static uint64
2039 : 2905 : XLogRecPtrToBytePos(XLogRecPtr ptr)
2040 : : {
2041 : : uint64 fullsegs;
2042 : : uint32 fullpages;
2043 : : uint32 offset;
2044 : : uint64 result;
2045 : :
2046 : 2905 : XLByteToSeg(ptr, fullsegs, wal_segment_size);
2047 : :
2048 : 2905 : fullpages = (XLogSegmentOffset(ptr, wal_segment_size)) / XLOG_BLCKSZ;
2049 : 2905 : offset = ptr % XLOG_BLCKSZ;
2050 : :
2051 [ + + ]: 2905 : if (fullpages == 0)
2052 : : {
2053 : 1105 : result = fullsegs * UsableBytesInSegment;
2054 [ + + ]: 1105 : if (offset > 0)
2055 : : {
2056 : : Assert(offset >= SizeOfXLogLongPHD);
2057 : 295 : result += offset - SizeOfXLogLongPHD;
2058 : : }
2059 : : }
2060 : : else
2061 : : {
2062 : 1800 : result = fullsegs * UsableBytesInSegment +
2063 : 1800 : (XLOG_BLCKSZ - SizeOfXLogLongPHD) + /* account for first page */
2064 : 1800 : (fullpages - 1) * UsableBytesInPage; /* full pages */
2065 [ + + ]: 1800 : if (offset > 0)
2066 : : {
2067 : : Assert(offset >= SizeOfXLogShortPHD);
2068 : 1789 : result += offset - SizeOfXLogShortPHD;
2069 : : }
2070 : : }
2071 : :
2072 : 2905 : 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 : 2747723 : AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli, bool opportunistic)
2084 : : {
2085 : : int nextidx;
2086 : : XLogRecPtr OldPageRqstPtr;
2087 : : XLogwrtRqst WriteRqst;
2088 : 2747723 : XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
2089 : : XLogRecPtr NewPageBeginPtr;
2090 : : XLogPageHeader NewPage;
2091 : 2747723 : int npages pg_attribute_unused() = 0;
2092 : :
2093 : 2747723 : LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2094 : :
2095 : : /*
2096 : : * Now that we have the lock, check if someone initialized the page
2097 : : * already.
2098 : : */
2099 [ + + + + ]: 8004230 : while (upto >= XLogCtl->InitializedUpTo || opportunistic)
2100 : : {
2101 : 5261626 : 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 : 5261626 : OldPageRqstPtr = pg_atomic_read_u64(&XLogCtl->xlblocks[nextidx]);
2109 [ + + ]: 5261626 : 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 [ + + ]: 2393426 : if (opportunistic)
2116 : 5119 : break;
2117 : :
2118 : : /* Advance shared memory write request position */
2119 : 2388307 : SpinLockAcquire(&XLogCtl->info_lck);
2120 [ + + ]: 2388307 : if (XLogCtl->LogwrtRqst.Write < OldPageRqstPtr)
2121 : 765111 : XLogCtl->LogwrtRqst.Write = OldPageRqstPtr;
2122 : 2388307 : 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 : 2388307 : RefreshXLogWriteResult(LogwrtResult);
2129 [ + + ]: 2388307 : 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 : 2371388 : LWLockRelease(WALBufMappingLock);
2138 : :
2139 : 2371388 : WaitXLogInsertionsToFinish(OldPageRqstPtr);
2140 : :
2141 : 2371388 : LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2142 : :
2143 : 2371388 : RefreshXLogWriteResult(LogwrtResult);
2144 [ + + ]: 2371388 : if (LogwrtResult.Write >= OldPageRqstPtr)
2145 : : {
2146 : : /* OK, someone wrote it already */
2147 : 136897 : LWLockRelease(WALWriteLock);
2148 : : }
2149 : : else
2150 : : {
2151 : : /* Have to write it ourselves */
2152 : : TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2153 : 2234491 : WriteRqst.Write = OldPageRqstPtr;
2154 : 2234491 : WriteRqst.Flush = InvalidXLogRecPtr;
2155 : 2234491 : XLogWrite(WriteRqst, tli, false);
2156 : 2234491 : LWLockRelease(WALWriteLock);
2157 : 2234491 : 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 : 2234491 : pgstat_report_fixed = true;
2165 : : }
2166 : : /* Re-acquire WALBufMappingLock and retry */
2167 : 2371388 : LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2168 : 2371388 : 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 : 2885119 : NewPageBeginPtr = XLogCtl->InitializedUpTo;
2177 : 2885119 : NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2178 : :
2179 : : Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
2180 : :
2181 : 2885119 : 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 : 2885119 : pg_atomic_write_u64(&XLogCtl->xlblocks[nextidx], InvalidXLogRecPtr);
2189 : 2885119 : 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 [ + - + - : 2885119 : MemSet(NewPage, 0, XLOG_BLCKSZ);
+ - - + -
- ]
2196 : :
2197 : : /*
2198 : : * Fill the new page's header
2199 : : */
2200 : 2885119 : NewPage->xlp_magic = XLOG_PAGE_MAGIC;
2201 : :
2202 : : /* NewPage->xlp_info = 0; */ /* done by memset */
2203 : 2885119 : NewPage->xlp_tli = tli;
2204 : 2885119 : 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 [ + + ]: 2885119 : if ((XLogSegmentOffset(NewPage->xlp_pageaddr, wal_segment_size)) == 0)
2212 : : {
2213 : 1957 : XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
2214 : :
2215 : 1957 : NewLongPage->xlp_sysid = ControlFile->system_identifier;
2216 : 1957 : NewLongPage->xlp_seg_size = wal_segment_size;
2217 : 1957 : NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
2218 : 1957 : 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 : 2885119 : pg_write_barrier();
2227 : :
2228 : 2885119 : pg_atomic_write_u64(&XLogCtl->xlblocks[nextidx], NewPageEndPtr);
2229 : 2885119 : XLogCtl->InitializedUpTo = NewPageEndPtr;
2230 : :
2231 : 2885119 : npages++;
2232 : : }
2233 : 2747723 : 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 : 2747723 : }
2243 : :
2244 : : /*
2245 : : * Calculate CheckPointSegments based on max_wal_size_mb and
2246 : : * checkpoint_completion_target.
2247 : : */
2248 : : static void
2249 : 9968 : 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 : 9968 : target = (double) ConvertToXSegs(max_wal_size_mb, wal_segment_size) /
2268 : 9968 : (1.0 + CheckPointCompletionTarget);
2269 : :
2270 : : /* round down */
2271 : 9968 : CheckPointSegments = (int) target;
2272 : :
2273 [ + + ]: 9968 : if (CheckPointSegments < 1)
2274 : 8 : CheckPointSegments = 1;
2275 : 9968 : }
2276 : :
2277 : : void
2278 : 7411 : assign_max_wal_size(int newval, void *extra)
2279 : : {
2280 : 7411 : max_wal_size_mb = newval;
2281 : 7411 : CalculateCheckpointSegments();
2282 : 7411 : }
2283 : :
2284 : : void
2285 : 1352 : assign_checkpoint_completion_target(double newval, void *extra)
2286 : : {
2287 : 1352 : CheckPointCompletionTarget = newval;
2288 : 1352 : CalculateCheckpointSegments();
2289 : 1352 : }
2290 : :
2291 : : bool
2292 : 2617 : check_wal_segment_size(int *newval, void **extra, GucSource source)
2293 : : {
2294 [ + - + - : 2617 : 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 : 2617 : 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 : 2016 : 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 : 2016 : minSegNo = lastredoptr / wal_segment_size +
2321 : 2016 : ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
2322 : 2016 : maxSegNo = lastredoptr / wal_segment_size +
2323 : 2016 : 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 : 2016 : distance = (1.0 + CheckPointCompletionTarget) * CheckPointDistanceEstimate;
2334 : : /* add 10% for good measure. */
2335 : 2016 : distance *= 1.10;
2336 : :
2337 : 2016 : recycleSegNo = (XLogSegNo) ceil(((double) lastredoptr + distance) /
2338 : : wal_segment_size);
2339 : :
2340 [ + + ]: 2016 : if (recycleSegNo < minSegNo)
2341 : 1429 : recycleSegNo = minSegNo;
2342 [ + + ]: 2016 : if (recycleSegNo > maxSegNo)
2343 : 416 : recycleSegNo = maxSegNo;
2344 : :
2345 : 2016 : 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 : 5146 : XLogCheckpointNeeded(XLogSegNo new_segno)
2359 : : {
2360 : : XLogSegNo old_segno;
2361 : :
2362 : 5146 : XLByteToSeg(RedoRecPtr, old_segno, wal_segment_size);
2363 : :
2364 [ + + ]: 5146 : if (new_segno >= old_segno + (uint64) (CheckPointSegments - 1))
2365 : 3161 : return true;
2366 : 1985 : 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 : 2400040 : 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 : 2400040 : RefreshXLogWriteResult(LogwrtResult);
2400 : 2400040 : 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 : 2400040 : npages = 0;
2412 : 2400040 : startidx = 0;
2413 : 2400040 : 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 : 2400040 : curridx = XLogRecPtrToBufIdx(LogwrtResult.Write);
2421 : :
2422 [ + + ]: 5233997 : 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 : 2995345 : XLogRecPtr EndPtr = pg_atomic_read_u64(&XLogCtl->xlblocks[curridx]);
2430 : :
2431 [ - + ]: 2995345 : 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 : 2995345 : LogwrtResult.Write = EndPtr;
2438 : 2995345 : ispartialpage = WriteRqst.Write < LogwrtResult.Write;
2439 : :
2440 [ + + ]: 2995345 : 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 [ + + ]: 15085 : if (openLogFile >= 0)
2449 : 6455 : XLogFileClose();
2450 : 15085 : XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2451 : : wal_segment_size);
2452 : 15085 : openLogTLI = tli;
2453 : :
2454 : : /* create/use new log file */
2455 : 15085 : openLogFile = XLogFileInit(openLogSegNo, tli);
2456 : 15085 : ReserveExternalFD();
2457 : : }
2458 : :
2459 : : /* Make sure we have the current logfile open */
2460 [ - + ]: 2995345 : 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 [ + + ]: 2995345 : if (npages == 0)
2471 : : {
2472 : : /* first of group */
2473 : 2417327 : startidx = curridx;
2474 : 2417327 : startoffset = XLogSegmentOffset(LogwrtResult.Write - XLOG_BLCKSZ,
2475 : : wal_segment_size);
2476 : : }
2477 : 2995345 : 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 : 2995345 : last_iteration = WriteRqst.Write <= LogwrtResult.Write;
2486 : :
2487 [ + + ]: 5833435 : finishing_seg = !ispartialpage &&
2488 [ + + ]: 2838090 : (startoffset + npages * XLOG_BLCKSZ) >= wal_segment_size;
2489 : :
2490 [ + + ]: 2995345 : if (last_iteration ||
2491 [ + + - + ]: 596820 : 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 : 2417327 : from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
2502 : 2417327 : nbytes = npages * (Size) XLOG_BLCKSZ;
2503 : 2417327 : nleft = nbytes;
2504 : : do
2505 : : {
2506 : 2417327 : errno = 0;
2507 : :
2508 : : /*
2509 : : * Measure I/O timing to write WAL data, for pg_stat_io.
2510 : : */
2511 : 2417327 : start = pgstat_prepare_io_time(track_wal_io_timing);
2512 : :
2513 : 2417327 : pgstat_report_wait_start(WAIT_EVENT_WAL_WRITE);
2514 : 2417327 : written = pg_pwrite(openLogFile, from, nleft, startoffset);
2515 : 2417327 : pgstat_report_wait_end();
2516 : :
2517 [ - + ]: 2417327 : 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 : 2417327 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL,
2536 : : IOOP_WRITE, start, 1, written);
2537 : 2417327 : nleft -= written;
2538 : 2417327 : from += written;
2539 : 2417327 : startoffset += written;
2540 [ - + ]: 2417327 : } while (nleft > 0);
2541 : :
2542 : 2417327 : 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 [ + + ]: 2417327 : if (finishing_seg)
2558 : : {
2559 : 2100 : issue_xlog_fsync(openLogFile, openLogSegNo, tli);
2560 : :
2561 : : /* signal that we need to wakeup walsenders later */
2562 : 2100 : WalSndWakeupRequest();
2563 : :
2564 : 2100 : LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
2565 : :
2566 [ + + ]: 2100 : if (XLogArchivingActive())
2567 : 422 : XLogArchiveNotifySeg(openLogSegNo, tli);
2568 : :
2569 : 2100 : XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
2570 : 2100 : 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 [ + + + + ]: 2100 : if (IsUnderPostmaster && XLogCheckpointNeeded(openLogSegNo))
2580 : : {
2581 : 275 : (void) GetRedoRecPtr();
2582 [ + + ]: 275 : if (XLogCheckpointNeeded(openLogSegNo))
2583 : 213 : RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
2584 : : }
2585 : : }
2586 : : }
2587 : :
2588 [ + + ]: 2995345 : if (ispartialpage)
2589 : : {
2590 : : /* Only asked to write a partial page */
2591 : 157255 : LogwrtResult.Write = WriteRqst.Write;
2592 : 157255 : break;
2593 : : }
2594 [ + + ]: 2838090 : curridx = NextBufIdx(curridx);
2595 : :
2596 : : /* If flexible, break out of loop as soon as we wrote something */
2597 [ + + + + ]: 2838090 : if (flexible && npages == 0)
2598 : 4133 : break;
2599 : : }
2600 : :
2601 : : Assert(npages == 0);
2602 : :
2603 : : /*
2604 : : * If asked to flush, do so
2605 : : */
2606 [ + + ]: 2400040 : if (LogwrtResult.Flush < WriteRqst.Flush &&
2607 [ + + ]: 164656 : 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 [ + - ]: 164572 : if (wal_sync_method != WAL_SYNC_METHOD_OPEN &&
2615 [ + - ]: 164572 : wal_sync_method != WAL_SYNC_METHOD_OPEN_DSYNC)
2616 : : {
2617 [ + + ]: 164572 : if (openLogFile >= 0 &&
2618 [ + + ]: 164551 : !XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
2619 : : wal_segment_size))
2620 : 94 : XLogFileClose();
2621 [ + + ]: 164572 : if (openLogFile < 0)
2622 : : {
2623 : 115 : XLByteToPrevSeg(LogwrtResult.Write, openLogSegNo,
2624 : : wal_segment_size);
2625 : 115 : openLogTLI = tli;
2626 : 115 : openLogFile = XLogFileOpen(openLogSegNo, tli);
2627 : 115 : ReserveExternalFD();
2628 : : }
2629 : :
2630 : 164572 : issue_xlog_fsync(openLogFile, openLogSegNo, tli);
2631 : : }
2632 : :
2633 : : /* signal that we need to wakeup walsenders later */
2634 : 164572 : WalSndWakeupRequest();
2635 : :
2636 : 164572 : 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 : 2400040 : SpinLockAcquire(&XLogCtl->info_lck);
2647 [ + + ]: 2400040 : if (XLogCtl->LogwrtRqst.Write < LogwrtResult.Write)
2648 : 144576 : XLogCtl->LogwrtRqst.Write = LogwrtResult.Write;
2649 [ + + ]: 2400040 : if (XLogCtl->LogwrtRqst.Flush < LogwrtResult.Flush)
2650 : 166241 : XLogCtl->LogwrtRqst.Flush = LogwrtResult.Flush;
2651 : 2400040 : 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 : 2400040 : pg_atomic_write_u64(&XLogCtl->logWriteResult, LogwrtResult.Write);
2659 : 2400040 : pg_write_barrier();
2660 : 2400040 : pg_atomic_write_u64(&XLogCtl->logFlushResult, LogwrtResult.Flush);
2661 : :
2662 : : /* Defer notification until the caller has released its WAL locks. */
2663 [ + + ]: 2400040 : if (LogwrtResult.Flush > oldFlush)
2664 : 166241 : 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 : 2400040 : }
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 : 63253 : XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
2694 : : {
2695 : 63253 : XLogRecPtr WriteRqstPtr = asyncXactLSN;
2696 : : bool sleeping;
2697 : 63253 : bool wakeup = false;
2698 : : XLogRecPtr prevAsyncXactLSN;
2699 : :
2700 : 63253 : SpinLockAcquire(&XLogCtl->info_lck);
2701 : 63253 : sleeping = XLogCtl->WalWriterSleeping;
2702 : 63253 : prevAsyncXactLSN = XLogCtl->asyncXactLSN;
2703 [ + + ]: 63253 : if (XLogCtl->asyncXactLSN < asyncXactLSN)
2704 : 62715 : XLogCtl->asyncXactLSN = asyncXactLSN;
2705 : 63253 : 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 [ + + ]: 63253 : if (asyncXactLSN <= prevAsyncXactLSN)
2712 : 538 : 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 [ + + ]: 62715 : if (sleeping)
2721 : 48 : wakeup = true;
2722 : : else
2723 : : {
2724 : : int flushblocks;
2725 : :
2726 : 62667 : RefreshXLogWriteResult(LogwrtResult);
2727 : :
2728 : 62667 : flushblocks =
2729 : 62667 : WriteRqstPtr / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
2730 : :
2731 [ + - + + ]: 62667 : if (WalWriterFlushAfter == 0 || flushblocks >= WalWriterFlushAfter)
2732 : 5599 : wakeup = true;
2733 : : }
2734 : :
2735 [ + + ]: 62715 : if (wakeup)
2736 : : {
2737 : 5647 : ProcNumber walwriterProc = pg_atomic_read_u32(&ProcGlobal->walwriterProc);
2738 : :
2739 [ + + ]: 5647 : if (walwriterProc != INVALID_PROC_NUMBER)
2740 : 1650 : 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 : 42193 : XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
2750 : : {
2751 : 42193 : SpinLockAcquire(&XLogCtl->info_lck);
2752 : 42193 : XLogCtl->replicationSlotMinLSN = lsn;
2753 : 42193 : SpinLockRelease(&XLogCtl->info_lck);
2754 : 42193 : }
2755 : :
2756 : :
2757 : : /*
2758 : : * Return the oldest LSN we must retain to satisfy the needs of some
2759 : : * replication slot.
2760 : : */
2761 : : XLogRecPtr
2762 : 2634 : XLogGetReplicationSlotMinimumLSN(void)
2763 : : {
2764 : : XLogRecPtr retval;
2765 : :
2766 : 2634 : SpinLockAcquire(&XLogCtl->info_lck);
2767 : 2634 : retval = XLogCtl->replicationSlotMinLSN;
2768 : 2634 : SpinLockRelease(&XLogCtl->info_lck);
2769 : :
2770 : 2634 : 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 : 121550 : UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
2784 : : {
2785 : : /* Quick check using our local copy of the variable */
2786 [ + + + + : 121550 : if (!updateMinRecoveryPoint || (!force && lsn <= LocalMinRecoveryPoint))
+ + ]
2787 : 114270 : 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 [ + + + + ]: 7280 : if (!XLogRecPtrIsValid(LocalMinRecoveryPoint) && InRecovery)
2801 : : {
2802 : 32 : updateMinRecoveryPoint = false;
2803 : 32 : return;
2804 : : }
2805 : :
2806 : 7248 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2807 : :
2808 : : /* update local copy */
2809 : 7248 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
2810 : :
2811 [ + + ]: 7248 : if (!XLogRecPtrIsValid(LocalMinRecoveryPoint))
2812 : 1 : updateMinRecoveryPoint = false;
2813 [ + + + + ]: 7247 : 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 : 5861 : newMinRecoveryPoint = GetCurrentReplayRecPtr(&newMinRecoveryPointTLI);
2832 [ + + - + ]: 5861 : 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 [ + + ]: 5861 : if (ControlFile->minRecoveryPoint < newMinRecoveryPoint)
2839 : : {
2840 : 5499 : ControlFile->minRecoveryPoint = newMinRecoveryPoint;
2841 : 5499 : ControlFile->minRecoveryPointTLI = newMinRecoveryPointTLI;
2842 : 5499 : UpdateControlFile();
2843 : 5499 : LocalMinRecoveryPoint = newMinRecoveryPoint;
2844 : :
2845 [ + + ]: 5499 : 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 : 7248 : 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 : 861409 : XLogFlush(XLogRecPtr record)
2862 : : {
2863 : : XLogRecPtr WriteRqstPtr;
2864 : : XLogwrtRqst WriteRqst;
2865 : 861409 : 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 [ + + ]: 861409 : if (!XLogInsertAllowed())
2875 : : {
2876 : 121065 : UpdateMinRecoveryPoint(record, false);
2877 : 687293 : return;
2878 : : }
2879 : :
2880 : : /* Quick exit if already known flushed */
2881 [ + + ]: 740344 : if (record <= LogwrtResult.Flush)
2882 : 566228 : 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 : 174116 : 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 : 174116 : 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 : 2958 : {
2911 : : XLogRecPtr insertpos;
2912 : :
2913 : : /* done already? */
2914 : 177074 : RefreshXLogWriteResult(LogwrtResult);
2915 [ + + ]: 177074 : if (record <= LogwrtResult.Flush)
2916 : 11724 : 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 : 165350 : SpinLockAcquire(&XLogCtl->info_lck);
2923 [ + + ]: 165350 : if (WriteRqstPtr < XLogCtl->LogwrtRqst.Write)
2924 : 10266 : WriteRqstPtr = XLogCtl->LogwrtRqst.Write;
2925 : 165350 : SpinLockRelease(&XLogCtl->info_lck);
2926 : 165350 : 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 [ + + ]: 165350 : 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 : 2958 : continue;
2943 : : }
2944 : :
2945 : : /* Got the lock; recheck whether request is satisfied */
2946 : 162392 : RefreshXLogWriteResult(LogwrtResult);
2947 [ + + ]: 162392 : if (record <= LogwrtResult.Flush)
2948 : : {
2949 : 1893 : LWLockRelease(WALWriteLock);
2950 : 1893 : 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 [ - + - - : 160499 : 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 : 160499 : WriteRqst.Write = insertpos;
2984 : 160499 : WriteRqst.Flush = insertpos;
2985 : :
2986 : 160499 : XLogWrite(WriteRqst, insertTLI, false);
2987 : :
2988 : 160499 : LWLockRelease(WALWriteLock);
2989 : : /* done */
2990 : 160499 : break;
2991 : : }
2992 : :
2993 : 174116 : END_CRIT_SECTION();
2994 : :
2995 : : /* wake up walsenders now that we've released heavily contended locks */
2996 : 174116 : WalSndWakeupProcessRequests(true, !RecoveryInProgress());
2997 : :
2998 : : /*
2999 : : * Wake up processes waiting for primary flush LSN to reach current flush
3000 : : * position.
3001 : : */
3002 : 174116 : primaryFlushWakeupPending = false;
3003 : 174116 : 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 [ - + ]: 174116 : 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 : 16364 : XLogBackgroundFlush(void)
3066 : : {
3067 : : XLogwrtRqst WriteRqst;
3068 : 16364 : 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 [ - + ]: 16364 : 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 : 16364 : insertTLI = XLogCtl->InsertTimeLineID;
3083 : :
3084 : : /* read updated LogwrtRqst */
3085 : 16364 : SpinLockAcquire(&XLogCtl->info_lck);
3086 : 16364 : WriteRqst = XLogCtl->LogwrtRqst;
3087 : 16364 : SpinLockRelease(&XLogCtl->info_lck);
3088 : :
3089 : : /* back off to last completed page boundary */
3090 : 16364 : WriteRqst.Write -= WriteRqst.Write % XLOG_BLCKSZ;
3091 : :
3092 : : /* if we have already flushed that far, consider async commit records */
3093 : 16364 : RefreshXLogWriteResult(LogwrtResult);
3094 [ + + ]: 16364 : if (WriteRqst.Write <= LogwrtResult.Flush)
3095 : : {
3096 : 12116 : SpinLockAcquire(&XLogCtl->info_lck);
3097 : 12116 : WriteRqst.Write = XLogCtl->asyncXactLSN;
3098 : 12116 : SpinLockRelease(&XLogCtl->info_lck);
3099 : 12116 : 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 [ + + ]: 16364 : if (WriteRqst.Write <= LogwrtResult.Flush)
3108 : : {
3109 [ + + ]: 11245 : if (openLogFile >= 0)
3110 : : {
3111 [ + + ]: 7150 : if (!XLByteInPrevSeg(LogwrtResult.Write, openLogSegNo,
3112 : : wal_segment_size))
3113 : : {
3114 : 204 : XLogFileClose();
3115 : : }
3116 : : }
3117 : 11245 : 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 : 5119 : now = GetCurrentTimestamp();
3129 : 5119 : flushblocks =
3130 : 5119 : WriteRqst.Write / XLOG_BLCKSZ - LogwrtResult.Flush / XLOG_BLCKSZ;
3131 : :
3132 [ + - + + ]: 5119 : if (WalWriterFlushAfter == 0 || lastflush == 0)
3133 : : {
3134 : : /* first call, or block based limits disabled */
3135 : 318 : WriteRqst.Flush = WriteRqst.Write;
3136 : 318 : lastflush = now;
3137 : : }
3138 [ + + ]: 4801 : 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 : 4374 : WriteRqst.Flush = WriteRqst.Write;
3146 : 4374 : lastflush = now;
3147 : : }
3148 [ + + ]: 427 : else if (flushblocks >= WalWriterFlushAfter)
3149 : : {
3150 : : /* exceeded wal_writer_flush_after blocks, flush */
3151 : 327 : WriteRqst.Flush = WriteRqst.Write;
3152 : 327 : lastflush = now;
3153 : : }
3154 : : else
3155 : : {
3156 : : /* no flushing, this time round */
3157 : 100 : 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 : 5119 : START_CRIT_SECTION();
3170 : :
3171 : : /* now wait for any in-progress insertions to finish and get write lock */
3172 : 5119 : WaitXLogInsertionsToFinish(WriteRqst.Write);
3173 : 5119 : LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
3174 : 5119 : RefreshXLogWriteResult(LogwrtResult);
3175 [ + + ]: 5119 : if (WriteRqst.Write > LogwrtResult.Write ||
3176 [ + + ]: 124 : WriteRqst.Flush > LogwrtResult.Flush)
3177 : : {
3178 : 5050 : XLogWrite(WriteRqst, insertTLI, flexible);
3179 : : }
3180 : 5119 : LWLockRelease(WALWriteLock);
3181 : :
3182 : 5119 : END_CRIT_SECTION();
3183 : :
3184 : : /* wake up walsenders now that we've released heavily contended locks */
3185 : 5119 : WalSndWakeupProcessRequests(true, !RecoveryInProgress());
3186 : :
3187 : : /*
3188 : : * Wake up processes waiting for primary flush LSN to reach current flush
3189 : : * position.
3190 : : */
3191 : 5119 : primaryFlushWakeupPending = false;
3192 : 5119 : 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 : 5119 : 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 : 5119 : 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 : 16744284 : 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 [ + + ]: 16744284 : if (!XLogInsertAllowed())
3233 : : {
3234 : : /* Quick exit if already known to be updated or cannot be updated */
3235 [ + - + + ]: 626981 : if (!updateMinRecoveryPoint || record <= LocalMinRecoveryPoint)
3236 : 602729 : 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 [ + + - + ]: 24252 : 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 [ + + ]: 24252 : if (!LWLockConditionalAcquire(ControlFileLock, LW_SHARED))
3257 : 1 : return true;
3258 : 24251 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
3259 : 24251 : 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 [ - + ]: 24251 : if (!XLogRecPtrIsValid(LocalMinRecoveryPoint))
3267 : 0 : updateMinRecoveryPoint = false;
3268 : :
3269 : : /* check again */
3270 [ + + - + ]: 24251 : if (record <= LocalMinRecoveryPoint || !updateMinRecoveryPoint)
3271 : 114 : return false;
3272 : : else
3273 : 24137 : return true;
3274 : : }
3275 : :
3276 : : /* Quick exit if already known flushed */
3277 [ + + ]: 16117303 : if (record <= LogwrtResult.Flush)
3278 : 15902381 : return false;
3279 : :
3280 : : /* read LogwrtResult and update local state */
3281 : 214922 : RefreshXLogWriteResult(LogwrtResult);
3282 : :
3283 : : /* check again */
3284 [ + + ]: 214922 : if (record <= LogwrtResult.Flush)
3285 : 2783 : return false;
3286 : :
3287 : 212139 : 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 : 16263 : 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 : 16263 : int open_flags = O_RDWR | O_CREAT | O_EXCL | PG_BINARY;
3313 : : instr_time io_start;
3314 : :
3315 : : Assert(logtli != 0);
3316 : :
3317 : 16263 : XLogFilePath(path, logtli, logsegno, wal_segment_size);
3318 : :
3319 : : /*
3320 : : * Try to use existent file (checkpoint maker may have created it already)
3321 : : */
3322 : 16263 : *added = false;
3323 : 16263 : fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3324 : 16263 : get_sync_bit(wal_sync_method));
3325 [ + + ]: 16263 : if (fd < 0)
3326 : : {
3327 [ - + ]: 1553 : 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 : 14710 : 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 [ + + ]: 1553 : elog(DEBUG2, "creating and filling new WAL file");
3342 : :
3343 : 1553 : snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3344 : :
3345 : 1553 : unlink(tmppath);
3346 : :
3347 [ - + ]: 1553 : 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 : 1553 : fd = BasicOpenFile(tmppath, open_flags);
3352 [ - + ]: 1553 : 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 : 1553 : io_start = pgstat_prepare_io_time(track_wal_io_timing);
3359 : :
3360 : 1553 : pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_WRITE);
3361 : 1553 : save_errno = 0;
3362 [ + - ]: 1553 : 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 : 1553 : rc = pg_pwrite_zeros(fd, wal_segment_size, 0);
3376 : :
3377 [ - + ]: 1553 : 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 : 1553 : pgstat_report_wait_end();
3394 : :
3395 [ - + ]: 1553 : 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 : 1553 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_INIT, IOOP_WRITE,
3416 : : io_start, 1,
3417 [ + - ]: 1553 : wal_init_zero ? wal_segment_size : 1);
3418 : :
3419 : : /* Measure I/O timing when flushing segment */
3420 : 1553 : io_start = pgstat_prepare_io_time(track_wal_io_timing);
3421 : :
3422 : 1553 : pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_SYNC);
3423 [ - + ]: 1553 : 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 : 1553 : pgstat_report_wait_end();
3433 : :
3434 : 1553 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_INIT,
3435 : : IOOP_FSYNC, io_start, 1, 0);
3436 : :
3437 [ - + ]: 1553 : 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 : 1553 : 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 : 1553 : max_segno = logsegno + CheckPointSegments;
3459 [ + - ]: 1553 : if (InstallXLogFileSegment(&installed_segno, tmppath, true, max_segno,
3460 : : logtli))
3461 : : {
3462 : 1553 : *added = true;
3463 [ + + ]: 1553 : 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 : 1553 : 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 : 16056 : XLogFileInit(XLogSegNo logsegno, TimeLineID logtli)
3493 : : {
3494 : : bool ignore_added;
3495 : : char path[MAXPGPATH];
3496 : : int fd;
3497 : :
3498 : : Assert(logtli != 0);
3499 : :
3500 : 16056 : fd = XLogFileInitInternal(logsegno, logtli, &ignore_added, path);
3501 [ + + ]: 16056 : if (fd >= 0)
3502 : 14557 : return fd;
3503 : :
3504 : : /* Now open original target segment (might not be file I just made) */
3505 : 1499 : fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3506 : 1499 : get_sync_bit(wal_sync_method));
3507 [ - + ]: 1499 : if (fd < 0)
3508 [ # # ]: 0 : ereport(ERROR,
3509 : : (errcode_for_file_access(),
3510 : : errmsg("could not open file \"%s\": %m", path)));
3511 : 1499 : 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 : 55 : 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 : 55 : XLogFilePath(path, srcTLI, srcsegno, wal_segment_size);
3545 : 55 : srcfd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3546 [ - + ]: 55 : 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 : 55 : snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3555 : :
3556 : 55 : unlink(tmppath);
3557 : :
3558 : : /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3559 : 55 : fd = OpenTransientFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
3560 [ - + ]: 55 : 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 [ + + ]: 112695 : for (nbytes = 0; nbytes < wal_segment_size; nbytes += sizeof(buffer))
3569 : : {
3570 : : ssize_t nread;
3571 : :
3572 : 112640 : nread = upto - nbytes;
3573 : :
3574 : : /*
3575 : : * The part that is not read from the source file is filled with
3576 : : * zeros.
3577 : : */
3578 [ + + ]: 112640 : if (nread < sizeof(buffer))
3579 : 55 : memset(buffer.data, 0, sizeof(buffer));
3580 : :
3581 [ + + ]: 112640 : if (nread > 0)
3582 : : {
3583 : : ssize_t r;
3584 : :
3585 [ + + ]: 4887 : if (nread > sizeof(buffer))
3586 : 4832 : nread = sizeof(buffer);
3587 : 4887 : pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_READ);
3588 : 4887 : r = read(srcfd, buffer.data, nread);
3589 [ - + ]: 4887 : 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 : 4887 : pgstat_report_wait_end();
3603 : : }
3604 : 112640 : errno = 0;
3605 : 112640 : pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_WRITE);
3606 [ - + ]: 112640 : 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 : 112640 : pgstat_report_wait_end();
3622 : : }
3623 : :
3624 : 55 : pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_SYNC);
3625 [ - + ]: 55 : 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 : 55 : pgstat_report_wait_end();
3630 : :
3631 [ - + ]: 55 : if (CloseTransientFile(fd) != 0)
3632 [ # # ]: 0 : ereport(ERROR,
3633 : : (errcode_for_file_access(),
3634 : : errmsg("could not close file \"%s\": %m", tmppath)));
3635 : :
3636 [ - + ]: 55 : 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 [ - + ]: 55 : if (!InstallXLogFileSegment(&destsegno, tmppath, false, 0, destTLI))
3645 [ # # ]: 0 : elog(ERROR, "InstallXLogFileSegment should not have failed");
3646 : 55 : }
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 : 3423 : 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 : 3423 : XLogFilePath(path, tli, *segno, wal_segment_size);
3684 : :
3685 : 3423 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3686 [ - + ]: 3423 : if (!XLogCtl->InstallXLogFileSegmentActive)
3687 : : {
3688 : 0 : LWLockRelease(ControlFileLock);
3689 : 0 : return false;
3690 : : }
3691 : :
3692 [ + + ]: 3423 : if (!find_free)
3693 : : {
3694 : : /* Force installation: get rid of any pre-existing segment file */
3695 : 55 : durable_unlink(path, DEBUG1);
3696 : : }
3697 : : else
3698 : : {
3699 : : /* Find a free slot to put it in */
3700 [ + + ]: 4685 : while (stat(path, &stat_buf) == 0)
3701 : : {
3702 [ + + ]: 1570 : if ((*segno) >= max_segno)
3703 : : {
3704 : : /* Failed to find a free slot within specified range */
3705 : 253 : LWLockRelease(ControlFileLock);
3706 : 253 : return false;
3707 : : }
3708 : 1317 : (*segno)++;
3709 : 1317 : XLogFilePath(path, tli, *segno, wal_segment_size);
3710 : : }
3711 : : }
3712 : :
3713 : : Assert(access(path, F_OK) != 0 && errno == ENOENT);
3714 [ - + ]: 3170 : 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 : 3170 : LWLockRelease(ControlFileLock);
3722 : :
3723 : 3170 : return true;
3724 : : }
3725 : :
3726 : : /*
3727 : : * Open a pre-existing logfile segment for writing.
3728 : : */
3729 : : int
3730 : 115 : XLogFileOpen(XLogSegNo segno, TimeLineID tli)
3731 : : {
3732 : : char path[MAXPGPATH];
3733 : : int fd;
3734 : :
3735 : 115 : XLogFilePath(path, tli, segno, wal_segment_size);
3736 : :
3737 : 115 : fd = BasicOpenFile(path, O_RDWR | PG_BINARY | O_CLOEXEC |
3738 : 115 : get_sync_bit(wal_sync_method));
3739 [ - + ]: 115 : if (fd < 0)
3740 [ # # ]: 0 : ereport(PANIC,
3741 : : (errcode_for_file_access(),
3742 : : errmsg("could not open file \"%s\": %m", path)));
3743 : :
3744 : 115 : return fd;
3745 : : }
3746 : :
3747 : : /*
3748 : : * Close the current logfile segment for writing.
3749 : : */
3750 : : static void
3751 : 6753 : 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 [ + + + - ]: 6753 : if (!XLogIsNeeded() && (io_direct_flags & IO_DIRECT_WAL) == 0)
3763 : 156 : (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3764 : : #endif
3765 : :
3766 [ - + ]: 6753 : 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 : 6753 : openLogFile = -1;
3779 : 6753 : ReleaseExternalFD();
3780 : 6753 : }
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 : 2304 : PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli)
3803 : : {
3804 : : XLogSegNo _logSegNo;
3805 : : int lf;
3806 : : bool added;
3807 : : char path[MAXPGPATH];
3808 : : uint64 offset;
3809 : :
3810 [ + + ]: 2304 : if (!XLogCtl->InstallXLogFileSegmentActive)
3811 : 10 : return; /* unlocked check says no */
3812 : :
3813 : 2294 : XLByteToPrevSeg(endptr, _logSegNo, wal_segment_size);
3814 : 2294 : offset = XLogSegmentOffset(endptr - 1, wal_segment_size);
3815 [ + + ]: 2294 : if (offset >= (uint32) (0.75 * wal_segment_size))
3816 : : {
3817 : 207 : _logSegNo++;
3818 : 207 : lf = XLogFileInitInternal(_logSegNo, tli, &added, path);
3819 [ + + ]: 207 : if (lf >= 0)
3820 : 153 : close(lf);
3821 [ + + ]: 207 : if (added)
3822 : 54 : 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 : 130665 : CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
3840 : : {
3841 : 130665 : int save_errno = errno;
3842 : : XLogSegNo lastRemovedSegNo;
3843 : :
3844 : 130665 : SpinLockAcquire(&XLogCtl->info_lck);
3845 : 130665 : lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3846 : 130665 : SpinLockRelease(&XLogCtl->info_lck);
3847 : :
3848 [ - + ]: 130665 : 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 : 130665 : errno = save_errno;
3860 : 130665 : }
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 : 1317 : XLogGetLastRemovedSegno(void)
3871 : : {
3872 : : XLogSegNo lastRemovedSegNo;
3873 : :
3874 : 1317 : SpinLockAcquire(&XLogCtl->info_lck);
3875 : 1317 : lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3876 : 1317 : SpinLockRelease(&XLogCtl->info_lck);
3877 : :
3878 : 1317 : 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 : 2726 : UpdateLastRemovedPtr(char *filename)
3925 : : {
3926 : : uint32 tli;
3927 : : XLogSegNo segno;
3928 : :
3929 : 2726 : XLogFromFileName(filename, &tli, &segno, wal_segment_size);
3930 : :
3931 : 2726 : SpinLockAcquire(&XLogCtl->info_lck);
3932 [ + + ]: 2726 : if (segno > XLogCtl->lastRemovedSegNo)
3933 : 1231 : XLogCtl->lastRemovedSegNo = segno;
3934 : 2726 : SpinLockRelease(&XLogCtl->info_lck);
3935 : 2726 : }
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 : 209 : RemoveTempXlogFiles(void)
3945 : : {
3946 : : DIR *xldir;
3947 : : struct dirent *xlde;
3948 : :
3949 [ + + ]: 209 : elog(DEBUG2, "removing all temporary WAL segments");
3950 : :
3951 : 209 : xldir = AllocateDir(XLOGDIR);
3952 [ + + ]: 1408 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3953 : : {
3954 : : char path[MAXPGPATH];
3955 : :
3956 [ + - ]: 1199 : if (strncmp(xlde->d_name, "xlogtemp.", 9) != 0)
3957 : 1199 : 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 : 209 : FreeDir(xldir);
3964 : 209 : }
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 : 2016 : 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 : 2016 : XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
3988 : 2016 : 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 : 2016 : XLogFileName(lastoff, 0, segno, wal_segment_size);
3996 : :
3997 [ + + ]: 2016 : elog(DEBUG2, "attempting to remove WAL segments older than log file %s",
3998 : : lastoff);
3999 : :
4000 : 2016 : xldir = AllocateDir(XLOGDIR);
4001 : :
4002 [ + + ]: 49701 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4003 : : {
4004 : : /* Ignore files that are not XLOG segments */
4005 [ + + ]: 47685 : if (!IsXLogFileName(xlde->d_name) &&
4006 [ + + ]: 8537 : !IsPartialXLogFileName(xlde->d_name))
4007 : 8533 : 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 [ + + ]: 39152 : if (strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
4021 : : {
4022 [ + + ]: 32538 : if (XLogArchiveCheckDone(xlde->d_name))
4023 : : {
4024 : : /* Update the last removed location in shared memory first */
4025 : 2726 : UpdateLastRemovedPtr(xlde->d_name);
4026 : :
4027 : 2726 : RemoveXlogFile(xlde, recycleSegNo, &endlogSegNo, insertTLI);
4028 : : }
4029 : : }
4030 : : }
4031 : :
4032 : 2016 : FreeDir(xldir);
4033 : 2016 : }
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 : 79 : 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 : 79 : XLByteToPrevSeg(switchpoint, switchLogSegNo, wal_segment_size);
4066 : 79 : XLByteToSeg(switchpoint, endLogSegNo, wal_segment_size);
4067 : 79 : recycleSegNo = endLogSegNo + 10;
4068 : :
4069 : : /*
4070 : : * Construct a filename of the last segment to be kept.
4071 : : */
4072 : 79 : XLogFileName(switchseg, newTLI, switchLogSegNo, wal_segment_size);
4073 : :
4074 [ + + ]: 79 : elog(DEBUG2, "attempting to remove WAL segments newer than log file %s",
4075 : : switchseg);
4076 : :
4077 : 79 : xldir = AllocateDir(XLOGDIR);
4078 : :
4079 [ + + ]: 748 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4080 : : {
4081 : : /* Ignore files that are not XLOG segments */
4082 [ + + ]: 669 : if (!IsXLogFileName(xlde->d_name))
4083 : 414 : 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 [ + + ]: 255 : if (strncmp(xlde->d_name, switchseg, 8) < 0 &&
4091 [ + + ]: 165 : 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 : 79 : FreeDir(xldir);
4105 : 79 : }
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 : 2745 : 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 : 2745 : const char *segname = segment_de->d_name;
4130 : :
4131 : 2745 : 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 [ + - ]: 2745 : if (wal_recycle &&
4139 [ + + ]: 2745 : *endlogSegNo <= recycleSegNo &&
4140 [ + + + - ]: 3957 : 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 [ + + ]: 1562 : ereport(DEBUG2,
4146 : : (errmsg_internal("recycled write-ahead log file \"%s\"",
4147 : : segname)));
4148 : 1562 : CheckpointStats.ckpt_segs_recycled++;
4149 : : /* Needn't recheck that slot on future iterations */
4150 : 1562 : (*endlogSegNo)++;
4151 : : }
4152 : : else
4153 : : {
4154 : : /* No need for any more future segments, or recycling failed ... */
4155 : : int rc;
4156 : :
4157 [ + + ]: 1183 : 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 : 1183 : rc = durable_unlink(path, LOG);
4185 : : #endif
4186 [ - + ]: 1183 : if (rc != 0)
4187 : : {
4188 : : /* Message already logged by durable_unlink() */
4189 : 0 : return;
4190 : : }
4191 : 1183 : CheckpointStats.ckpt_segs_removed++;
4192 : : }
4193 : :
4194 : 2745 : 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 : 1137 : 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 [ + - ]: 1137 : if (stat(XLOGDIR, &stat_buf) != 0 ||
4218 [ - + ]: 1137 : !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 : 1137 : snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
4226 [ + + ]: 1137 : if (stat(path, &stat_buf) == 0)
4227 : : {
4228 : : /* Check for weird cases where it exists but isn't a directory */
4229 [ - + ]: 1135 : 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 : 1137 : snprintf(path, MAXPGPATH, XLOGDIR "/summaries");
4248 [ + + ]: 1137 : if (stat(path, &stat_buf) == 0)
4249 : : {
4250 : : /* Check for weird cases where it exists but isn't a directory */
4251 [ - + ]: 1135 : 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 : 1137 : }
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 : 176 : CleanupBackupHistory(void)
4274 : : {
4275 : : DIR *xldir;
4276 : : struct dirent *xlde;
4277 : : char path[MAXPGPATH + sizeof(XLOGDIR)];
4278 : :
4279 : 176 : xldir = AllocateDir(XLOGDIR);
4280 : :
4281 [ + + ]: 1798 : while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4282 : : {
4283 [ + + ]: 1446 : if (IsBackupHistoryFileName(xlde->d_name))
4284 : : {
4285 [ + + ]: 186 : if (XLogArchiveCheckDone(xlde->d_name))
4286 : : {
4287 [ + + ]: 148 : elog(DEBUG2, "removing WAL backup history file \"%s\"",
4288 : : xlde->d_name);
4289 : 148 : snprintf(path, sizeof(path), XLOGDIR "/%s", xlde->d_name);
4290 : 148 : unlink(path);
4291 : 148 : XLogArchiveCleanup(xlde->d_name);
4292 : : }
4293 : : }
4294 : : }
4295 : :
4296 : 176 : FreeDir(xldir);
4297 : 176 : }
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 : 1205 : 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 : 1205 : fd = BasicOpenFile(XLOG_CONTROL_FILE,
4481 : : O_RDWR | PG_BINARY);
4482 [ - + ]: 1205 : 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 : 1205 : pgstat_report_wait_start(WAIT_EVENT_CONTROL_FILE_READ);
4489 : 1205 : r = read(fd, ControlFile, sizeof(ControlFileData));
4490 [ - + ]: 1205 : 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 : 1205 : pgstat_report_wait_end();
4504 : :
4505 : 1205 : 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 [ - + - - : 1205 : 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 [ - + ]: 1205 : 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 : 1205 : INIT_CRC32C(crc);
4535 : 1205 : COMP_CRC32C(crc,
4536 : : ControlFile,
4537 : : offsetof(ControlFileData, crc));
4538 : 1205 : FIN_CRC32C(crc);
4539 : :
4540 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 : 1205 : wal_segment_size = ControlFile->xlog_seg_size;
4660 : :
4661 [ + - + - : 1205 : 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 : 1205 : snprintf(wal_segsz_str, sizeof(wal_segsz_str), "%d", wal_segment_size);
4670 : 1205 : 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 [ - + ]: 1205 : 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 [ - + ]: 1205 : 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 : 1205 : UsableBytesInSegment =
4687 : 1205 : (wal_segment_size / XLOG_BLCKSZ * UsableBytesInPage) -
4688 : : (SizeOfXLogLongPHD - SizeOfXLogShortPHD);
4689 : :
4690 : 1205 : CalculateCheckpointSegments();
4691 : 1205 : }
4692 : :
4693 : : /*
4694 : : * Utility wrapper to update the control file. Note that the control
4695 : : * file gets flushed.
4696 : : */
4697 : : static void
4698 : 10459 : UpdateControlFile(void)
4699 : : {
4700 : 10459 : update_controlfile(DataDir, ControlFile, true);
4701 : 10459 : }
4702 : :
4703 : : /*
4704 : : * Returns the unique system identifier from control file.
4705 : : */
4706 : : uint64
4707 : 1695 : GetSystemIdentifier(void)
4708 : : {
4709 : : Assert(ControlFile != NULL);
4710 : 1695 : 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 : 854178 : DataChecksumsNeedWrite(void)
4739 : : {
4740 : 966304 : return (LocalDataChecksumState == PG_DATA_CHECKSUM_VERSION ||
4741 [ + + + + ]: 913265 : LocalDataChecksumState == PG_DATA_CHECKSUM_INPROGRESS_ON ||
4742 [ + + ]: 59087 : 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 : 2737006 : DataChecksumsNeedVerify(void)
4798 : : {
4799 : 2737006 : 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 : 1383647 : GetLastChecksumChangeRecPtr(void)
4815 : : {
4816 : 1383647 : 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 : 25549 : InitLocalDataChecksumState(void)
5055 : : {
5056 : : Assert(InterruptHoldoffCount > 0);
5057 : 25549 : SpinLockAcquire(&XLogCtl->info_lck);
5058 : 25549 : SetLocalDataChecksumState(XLogCtl->data_checksum_version);
5059 : 25549 : SpinLockRelease(&XLogCtl->info_lck);
5060 : 25549 : }
5061 : :
5062 : : void
5063 : 28473 : SetLocalDataChecksumState(uint32 data_checksum_version)
5064 : : {
5065 : 28473 : LocalDataChecksumState = data_checksum_version;
5066 : :
5067 : 28473 : data_checksums = data_checksum_version;
5068 : 28473 : }
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 : 685 : 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 [ + + ]: 685 : if (!ArchiveRecoveryRequested)
5099 : 27 : 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 [ + + ]: 658 : if (!reachedConsistency)
5110 : 34 : return;
5111 : :
5112 : 624 : SpinLockAcquire(&XLogCtl->info_lck);
5113 : 624 : local_state = XLogCtl->data_checksum_version;
5114 : 624 : SpinLockRelease(&XLogCtl->info_lck);
5115 : :
5116 [ + + ]: 624 : 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 [ - + ]: 622 : 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 : 622 : last_warned_version = NO_WARNING_ISSUED;
5129 : 622 : 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 : 89 : AdoptReplayedDataChecksumState(uint32 new_version, XLogRecPtr lsn)
5170 : : {
5171 : 89 : bool changed = false;
5172 : :
5173 : 89 : SpinLockAcquire(&XLogCtl->info_lck);
5174 [ - + ]: 89 : 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 : 89 : SpinLockRelease(&XLogCtl->info_lck);
5183 : :
5184 [ + - ]: 89 : if (!changed)
5185 : 89 : 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 : 2040 : show_data_checksums(void)
5200 : : {
5201 : 2040 : 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 : 1304 : XLOGChooseNumBuffers(void)
5245 : : {
5246 : : int xbuffers;
5247 : :
5248 : 1304 : xbuffers = NBuffers / 32;
5249 [ + + ]: 1304 : if (xbuffers > (wal_segment_size / XLOG_BLCKSZ))
5250 : 28 : xbuffers = (wal_segment_size / XLOG_BLCKSZ);
5251 [ + + ]: 1304 : if (xbuffers < 8)
5252 : 511 : xbuffers = 8;
5253 : 1304 : return xbuffers;
5254 : : }
5255 : :
5256 : : /*
5257 : : * GUC check_hook for wal_buffers
5258 : : */
5259 : : bool
5260 : 2657 : check_wal_buffers(int *newval, void **extra, GucSource source)
5261 : : {
5262 : : /*
5263 : : * -1 indicates a request for auto-tune.
5264 : : */
5265 [ + + ]: 2657 : 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 [ + - ]: 1352 : if (XLOGbuffers == -1)
5272 : 1352 : 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 [ - + ]: 1305 : if (*newval < 4)
5286 : 0 : *newval = 4;
5287 : :
5288 : 1305 : return true;
5289 : : }
5290 : :
5291 : : /*
5292 : : * GUC check_hook for wal_consistency_checking
5293 : : */
5294 : : bool
5295 : 2336 : 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 [ + - + - : 77088 : MemSet(newwalconsistency, 0, (RM_MAX_ID + 1) * sizeof(bool));
+ - + - +
+ ]
5304 : :
5305 : : /* Need a modifiable copy of string */
5306 : 2336 : rawstring = pstrdup(*newval);
5307 : :
5308 : : /* Parse string into list of identifiers */
5309 [ - + ]: 2336 : 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 [ + + + + : 2831 : foreach(l, elemlist)
+ + ]
5319 : : {
5320 : 495 : char *tok = (char *) lfirst(l);
5321 : : int rmid;
5322 : :
5323 : : /* Check for 'all'. */
5324 [ + + ]: 495 : if (pg_strcasecmp(tok, "all") == 0)
5325 : : {
5326 [ + + ]: 126701 : for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5327 [ + + + + ]: 126208 : if (RmgrIdExists(rmid) && GetRmgr(rmid).rm_mask != NULL)
5328 : 4930 : 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 : 2336 : pfree(rawstring);
5368 : 2336 : list_free(elemlist);
5369 : :
5370 : : /* assign new value */
5371 : 2336 : *extra = guc_malloc(LOG, (RM_MAX_ID + 1) * sizeof(bool));
5372 [ - + ]: 2336 : if (!*extra)
5373 : 0 : return false;
5374 : 2336 : memcpy(*extra, newwalconsistency, (RM_MAX_ID + 1) * sizeof(bool));
5375 : 2336 : return true;
5376 : : }
5377 : :
5378 : : /*
5379 : : * GUC assign_hook for wal_consistency_checking
5380 : : */
5381 : : void
5382 : 2335 : 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 : 2335 : wal_consistency_checking = extra;
5398 : 2335 : }
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 : 1128 : InitializeWalConsistencyChecking(void)
5410 : : {
5411 : : Assert(process_shared_preload_libraries_done);
5412 : :
5413 [ - + ]: 1128 : 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 : 1128 : }
5430 : :
5431 : : /*
5432 : : * GUC show_hook for archive_command
5433 : : */
5434 : : const char *
5435 : 2036 : show_archive_command(void)
5436 : : {
5437 [ + + ]: 2036 : if (XLogArchivingActive())
5438 : 145 : return XLogArchiveCommand;
5439 : : else
5440 : 1891 : return "(disabled)";
5441 : : }
5442 : :
5443 : : /*
5444 : : * GUC show_hook for in_hot_standby
5445 : : */
5446 : : const char *
5447 : 18320 : 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 [ + + ]: 18320 : return RecoveryInProgress() ? "on" : "off";
5456 : : }
5457 : :
5458 : : /*
5459 : : * GUC show_hook for effective_wal_level
5460 : : */
5461 : : const char *
5462 : 2082 : show_effective_wal_level(void)
5463 : : {
5464 [ + + ]: 2082 : if (wal_level == WAL_LEVEL_MINIMAL)
5465 : 283 : 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 [ + + ]: 1799 : if (RecoveryInProgress())
5472 [ + + ]: 41 : return IsXLogLogicalInfoEnabled() ? "logical" : "replica";
5473 : :
5474 [ + + + + ]: 1758 : 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 : 1146 : LocalProcessControlFile(bool reset)
5491 : : {
5492 : : Assert(reset || ControlFile == NULL);
5493 : 1146 : LocalControlFile = palloc_object(ControlFileData);
5494 : 1146 : ControlFile = LocalControlFile;
5495 : 1146 : ReadControlFile();
5496 : 1146 : SetLocalDataChecksumState(ControlFile->data_checksum_version);
5497 : 1146 : }
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 : 1310 : 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 [ + + ]: 1310 : if (XLOGbuffers == -1)
5530 : : {
5531 : : char buf[32];
5532 : :
5533 : 1304 : snprintf(buf, sizeof(buf), "%d", XLOGChooseNumBuffers());
5534 : 1304 : SetConfigOption("wal_buffers", buf, PGC_POSTMASTER,
5535 : : PGC_S_DYNAMIC_DEFAULT);
5536 [ - + ]: 1304 : 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 : 1310 : size = sizeof(XLogCtlData);
5544 : :
5545 : : /* WAL insertion locks, plus alignment */
5546 : 1310 : size = add_size(size, mul_size(sizeof(WALInsertLockPadded), NUM_XLOGINSERT_LOCKS + 1));
5547 : : /* xlblocks array */
5548 : 1310 : size = add_size(size, mul_size(sizeof(pg_atomic_uint64), XLOGbuffers));
5549 : : /* extra alignment padding for XLOG I/O buffers */
5550 : 1310 : size = add_size(size, Max(XLOG_BLCKSZ, PG_IO_ALIGN_SIZE));
5551 : : /* and the buffers themselves */
5552 : 1310 : size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
5553 : :
5554 : 1310 : ShmemRequestStruct(.name = "XLOG Ctl",
5555 : : .size = size,
5556 : : .ptr = (void **) &XLogCtl,
5557 : : );
5558 : 1310 : ShmemRequestStruct(.name = "Control File",
5559 : : .size = sizeof(ControlFileData),
5560 : : .ptr = (void **) &ControlFile,
5561 : : );
5562 : 1310 : }
5563 : :
5564 : : /*
5565 : : * XLOGShmemInit - initialize the XLogCtl shared memory area.
5566 : : */
5567 : : static void
5568 : 1307 : XLOGShmemInit(void *arg)
5569 : : {
5570 : : char *allocptr;
5571 : : int i;
5572 : :
5573 : : #ifdef WAL_DEBUG
5574 : :
5575 : : /*
5576 : : * Create a memory context for WAL debugging that's exempt from the normal
5577 : : * "no pallocs in critical section" rule. Yes, that can lead to a PANIC if
5578 : : * an allocation fails, but wal_debug is not for production use anyway.
5579 : : */
5580 : : if (walDebugCxt == NULL)
5581 : : {
5582 : : walDebugCxt = AllocSetContextCreate(TopMemoryContext,
5583 : : "WAL Debug",
5584 : : ALLOCSET_DEFAULT_SIZES);
5585 : : MemoryContextAllowInCriticalSection(walDebugCxt, true);
5586 : : }
5587 : : #endif
5588 : :
5589 : 1307 : memset(XLogCtl, 0, sizeof(XLogCtlData));
5590 : :
5591 : : /*
5592 : : * Already have read control file locally, unless in bootstrap mode. Move
5593 : : * contents into shared memory.
5594 : : */
5595 [ + + ]: 1307 : if (LocalControlFile)
5596 : : {
5597 : 1130 : memcpy(ControlFile, LocalControlFile, sizeof(ControlFileData));
5598 : 1130 : pfree(LocalControlFile);
5599 : 1130 : LocalControlFile = NULL;
5600 : : }
5601 : :
5602 : : /*
5603 : : * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
5604 : : * multiple of the alignment for same, so no extra alignment padding is
5605 : : * needed here.
5606 : : */
5607 : 1307 : allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
5608 : 1307 : XLogCtl->xlblocks = (pg_atomic_uint64 *) allocptr;
5609 : 1307 : allocptr += sizeof(pg_atomic_uint64) * XLOGbuffers;
5610 : :
5611 [ + + ]: 371796 : for (i = 0; i < XLOGbuffers; i++)
5612 : : {
5613 : 370489 : pg_atomic_init_u64(&XLogCtl->xlblocks[i], InvalidXLogRecPtr);
5614 : : }
5615 : :
5616 : : /* WAL insertion locks. Ensure they're aligned to the full padded size */
5617 : 1307 : allocptr += sizeof(WALInsertLockPadded) -
5618 : 1307 : ((uintptr_t) allocptr) % sizeof(WALInsertLockPadded);
5619 : 1307 : WALInsertLocks = XLogCtl->Insert.WALInsertLocks =
5620 : : (WALInsertLockPadded *) allocptr;
5621 : 1307 : allocptr += sizeof(WALInsertLockPadded) * NUM_XLOGINSERT_LOCKS;
5622 : :
5623 [ + + ]: 11763 : for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
5624 : : {
5625 : 10456 : LWLockInitialize(&WALInsertLocks[i].l.lock, LWTRANCHE_WAL_INSERT);
5626 : 10456 : pg_atomic_init_u64(&WALInsertLocks[i].l.insertingAt, InvalidXLogRecPtr);
5627 : 10456 : WALInsertLocks[i].l.lastImportantAt = InvalidXLogRecPtr;
5628 : : }
5629 : :
5630 : : /*
5631 : : * Align the start of the page buffers to a full xlog block size boundary.
5632 : : * This simplifies some calculations in XLOG insertion. It is also
5633 : : * required for O_DIRECT.
5634 : : */
5635 : 1307 : allocptr = (char *) TYPEALIGN(XLOG_BLCKSZ, allocptr);
5636 : 1307 : XLogCtl->pages = allocptr;
5637 : 1307 : memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
5638 : :
5639 : : /*
5640 : : * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
5641 : : * in additional info.)
5642 : : */
5643 : 1307 : XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
5644 : 1307 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_CRASH;
5645 : 1307 : XLogCtl->InstallXLogFileSegmentActive = false;
5646 : 1307 : XLogCtl->WalWriterSleeping = false;
5647 : :
5648 : : /* Use the checksum info from control file */
5649 : 1307 : XLogCtl->data_checksum_version = ControlFile->data_checksum_version;
5650 : 1307 : XLogCtl->data_checksum_lsn = ControlFile->data_checksum_lsn;
5651 : 1307 : XLogCtl->data_checksum_is_local = ControlFile->data_checksum_is_local;
5652 : 1307 : SetLocalDataChecksumState(XLogCtl->data_checksum_version);
5653 : :
5654 : 1307 : SpinLockInit(&XLogCtl->Insert.insertpos_lck);
5655 : 1307 : SpinLockInit(&XLogCtl->info_lck);
5656 : 1307 : pg_atomic_init_u64(&XLogCtl->logInsertResult, InvalidXLogRecPtr);
5657 : 1307 : pg_atomic_init_u64(&XLogCtl->logWriteResult, InvalidXLogRecPtr);
5658 : 1307 : pg_atomic_init_u64(&XLogCtl->logFlushResult, InvalidXLogRecPtr);
5659 : 1307 : pg_atomic_init_u64(&XLogCtl->unloggedLSN, InvalidXLogRecPtr);
5660 : 1307 : pg_atomic_init_u64(&XLogCtl->lastChecksumChangeRecPtr, InvalidXLogRecPtr);
5661 : 1307 : }
5662 : :
5663 : : /*
5664 : : * XLOGShmemAttach - re-establish WALInsertLocks pointer after attaching.
5665 : : */
5666 : : static void
5667 : 0 : XLOGShmemAttach(void *arg)
5668 : : {
5669 : 0 : WALInsertLocks = XLogCtl->Insert.WALInsertLocks;
5670 : 0 : }
5671 : :
5672 : : /*
5673 : : * This func must be called ONCE on system install. It creates pg_control
5674 : : * and the initial XLOG segment.
5675 : : */
5676 : : void
5677 : 59 : BootStrapXLOG(uint32 data_checksum_version)
5678 : : {
5679 : : CheckPoint checkPoint;
5680 : : PGAlignedXLogBlock buffer;
5681 : : XLogPageHeader page;
5682 : : XLogLongPageHeader longpage;
5683 : : XLogRecord *record;
5684 : : char *recptr;
5685 : : uint64 sysidentifier;
5686 : : struct timeval tv;
5687 : : pg_crc32c crc;
5688 : :
5689 : : /* allow ordinary WAL segment creation, like StartupXLOG() would */
5690 : 59 : SetInstallXLogFileSegmentActive();
5691 : :
5692 : : /*
5693 : : * Select a hopefully-unique system identifier code for this installation.
5694 : : * We use the result of gettimeofday(), including the fractional seconds
5695 : : * field, as being about as unique as we can easily get. (Think not to
5696 : : * use random(), since it hasn't been seeded and there's no portable way
5697 : : * to seed it other than the system clock value...) The upper half of the
5698 : : * uint64 value is just the tv_sec part, while the lower half contains the
5699 : : * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5700 : : * PID for a little extra uniqueness. A person knowing this encoding can
5701 : : * determine the initialization time of the installation, which could
5702 : : * perhaps be useful sometimes.
5703 : : */
5704 : 59 : gettimeofday(&tv, NULL);
5705 : 59 : sysidentifier = ((uint64) tv.tv_sec) << 32;
5706 : 59 : sysidentifier |= ((uint64) tv.tv_usec) << 12;
5707 : 59 : sysidentifier |= getpid() & 0xFFF;
5708 : :
5709 : 59 : memset(&buffer, 0, sizeof buffer);
5710 : 59 : page = (XLogPageHeader) &buffer;
5711 : :
5712 : : /*
5713 : : * Set up information for the initial checkpoint record
5714 : : *
5715 : : * The initial checkpoint record is written to the beginning of the WAL
5716 : : * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5717 : : * used, so that we can use 0/0 to mean "before any valid WAL segment".
5718 : : */
5719 : 59 : checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5720 : 59 : checkPoint.ThisTimeLineID = BootstrapTimeLineID;
5721 : 59 : checkPoint.PrevTimeLineID = BootstrapTimeLineID;
5722 : 59 : checkPoint.fullPageWrites = fullPageWrites;
5723 : 59 : checkPoint.logicalDecodingEnabled = (wal_level == WAL_LEVEL_LOGICAL);
5724 : 59 : checkPoint.wal_level = wal_level;
5725 : : checkPoint.nextXid =
5726 : 59 : FullTransactionIdFromEpochAndXid(0, FirstNormalTransactionId);
5727 : 59 : checkPoint.nextOid = FirstGenbkiObjectId;
5728 : 59 : checkPoint.nextMulti = FirstMultiXactId;
5729 : 59 : checkPoint.nextMultiOffset = 1;
5730 : 59 : checkPoint.oldestXid = FirstNormalTransactionId;
5731 : 59 : checkPoint.oldestXidDB = Template1DbOid;
5732 : 59 : checkPoint.oldestMulti = FirstMultiXactId;
5733 : 59 : checkPoint.oldestMultiDB = Template1DbOid;
5734 : 59 : checkPoint.oldestCommitTsXid = InvalidTransactionId;
5735 : 59 : checkPoint.newestCommitTsXid = InvalidTransactionId;
5736 : 59 : checkPoint.time = (pg_time_t) time(NULL);
5737 : 59 : checkPoint.oldestActiveXid = InvalidTransactionId;
5738 : 59 : checkPoint.dataChecksumState = data_checksum_version;
5739 : :
5740 : 59 : TransamVariables->nextXid = checkPoint.nextXid;
5741 : 59 : TransamVariables->nextOid = checkPoint.nextOid;
5742 : 59 : TransamVariables->oidCount = 0;
5743 : 59 : MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5744 : 59 : AdvanceOldestClogXid(checkPoint.oldestXid);
5745 : 59 : SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5746 : 59 : SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
5747 : 59 : SetCommitTsLimit(InvalidTransactionId, InvalidTransactionId);
5748 : :
5749 : : /* Set up the XLOG page header */
5750 : 59 : page->xlp_magic = XLOG_PAGE_MAGIC;
5751 : 59 : page->xlp_info = XLP_LONG_HEADER;
5752 : 59 : page->xlp_tli = BootstrapTimeLineID;
5753 : 59 : page->xlp_pageaddr = wal_segment_size;
5754 : 59 : longpage = (XLogLongPageHeader) page;
5755 : 59 : longpage->xlp_sysid = sysidentifier;
5756 : 59 : longpage->xlp_seg_size = wal_segment_size;
5757 : 59 : longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5758 : :
5759 : : /* Insert the initial checkpoint record */
5760 : 59 : recptr = ((char *) page + SizeOfXLogLongPHD);
5761 : 59 : record = (XLogRecord *) recptr;
5762 : 59 : record->xl_prev = InvalidXLogRecPtr;
5763 : 59 : record->xl_xid = InvalidTransactionId;
5764 : 59 : record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5765 : 59 : record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
5766 : 59 : record->xl_rmid = RM_XLOG_ID;
5767 : 59 : recptr += SizeOfXLogRecord;
5768 : : /* fill the XLogRecordDataHeaderShort struct */
5769 : 59 : *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5770 : 59 : *(recptr++) = sizeof(checkPoint);
5771 : 59 : memcpy(recptr, &checkPoint, sizeof(checkPoint));
5772 : 59 : recptr += sizeof(checkPoint);
5773 : : Assert(recptr - (char *) record == record->xl_tot_len);
5774 : :
5775 : 59 : INIT_CRC32C(crc);
5776 : 59 : COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5777 : 59 : COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5778 : 59 : FIN_CRC32C(crc);
5779 : 59 : record->xl_crc = crc;
5780 : :
5781 : : /* Create first XLOG segment file */
5782 : 59 : openLogTLI = BootstrapTimeLineID;
5783 : 59 : openLogFile = XLogFileInit(1, BootstrapTimeLineID);
5784 : :
5785 : : /*
5786 : : * We needn't bother with Reserve/ReleaseExternalFD here, since we'll
5787 : : * close the file again in a moment.
5788 : : */
5789 : :
5790 : : /* Write the first page with the initial record */
5791 : 59 : errno = 0;
5792 : 59 : pgstat_report_wait_start(WAIT_EVENT_WAL_BOOTSTRAP_WRITE);
5793 [ - + ]: 59 : if (write(openLogFile, &buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5794 : : {
5795 : : /* if write didn't set errno, assume problem is no disk space */
5796 [ # # ]: 0 : if (errno == 0)
5797 : 0 : errno = ENOSPC;
5798 [ # # ]: 0 : ereport(PANIC,
5799 : : (errcode_for_file_access(),
5800 : : errmsg("could not write bootstrap write-ahead log file: %m")));
5801 : : }
5802 : 59 : pgstat_report_wait_end();
5803 : :
5804 : 59 : pgstat_report_wait_start(WAIT_EVENT_WAL_BOOTSTRAP_SYNC);
5805 [ - + ]: 59 : if (pg_fsync(openLogFile) != 0)
5806 [ # # ]: 0 : ereport(PANIC,
5807 : : (errcode_for_file_access(),
5808 : : errmsg("could not fsync bootstrap write-ahead log file: %m")));
5809 : 59 : pgstat_report_wait_end();
5810 : :
5811 [ - + ]: 59 : if (close(openLogFile) != 0)
5812 [ # # ]: 0 : ereport(PANIC,
5813 : : (errcode_for_file_access(),
5814 : : errmsg("could not close bootstrap write-ahead log file: %m")));
5815 : :
5816 : 59 : openLogFile = -1;
5817 : :
5818 : : /* Now create pg_control */
5819 : 59 : InitControlFile(sysidentifier, data_checksum_version);
5820 : 59 : ControlFile->time = checkPoint.time;
5821 : 59 : ControlFile->checkPoint = checkPoint.redo;
5822 : 59 : ControlFile->checkPointCopy = checkPoint;
5823 : :
5824 : : /* some additional ControlFile fields are set in WriteControlFile() */
5825 : 59 : WriteControlFile();
5826 : :
5827 : : /* Bootstrap the commit log, too */
5828 : 59 : BootStrapCLOG();
5829 : 59 : BootStrapCommitTs();
5830 : 59 : BootStrapSUBTRANS();
5831 : 59 : BootStrapMultiXact();
5832 : :
5833 : : /*
5834 : : * Force control file to be read - in contrast to normal processing we'd
5835 : : * otherwise never run the checks and GUC related initializations therein.
5836 : : */
5837 : 59 : ReadControlFile();
5838 : 59 : }
5839 : :
5840 : : static char *
5841 : 1008 : str_time(pg_time_t tnow, char *buf, size_t bufsize)
5842 : : {
5843 : 1008 : pg_strftime(buf, bufsize,
5844 : : "%Y-%m-%d %H:%M:%S %Z",
5845 : 1008 : pg_localtime(&tnow, log_timezone));
5846 : :
5847 : 1008 : return buf;
5848 : : }
5849 : :
5850 : : /*
5851 : : * Initialize the first WAL segment on new timeline.
5852 : : */
5853 : : static void
5854 : 64 : XLogInitNewTimeline(TimeLineID endTLI, XLogRecPtr endOfLog, TimeLineID newTLI)
5855 : : {
5856 : : char xlogfname[MAXFNAMELEN];
5857 : : XLogSegNo endLogSegNo;
5858 : : XLogSegNo startLogSegNo;
5859 : :
5860 : : /* we always switch to a new timeline after archive recovery */
5861 : : Assert(endTLI != newTLI);
5862 : :
5863 : : /*
5864 : : * Update min recovery point one last time.
5865 : : */
5866 : 64 : UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
5867 : :
5868 : : /*
5869 : : * Calculate the last segment on the old timeline, and the first segment
5870 : : * on the new timeline. If the switch happens in the middle of a segment,
5871 : : * they are the same, but if the switch happens exactly at a segment
5872 : : * boundary, startLogSegNo will be endLogSegNo + 1.
5873 : : */
5874 : 64 : XLByteToPrevSeg(endOfLog, endLogSegNo, wal_segment_size);
5875 : 64 : XLByteToSeg(endOfLog, startLogSegNo, wal_segment_size);
5876 : :
5877 : : /*
5878 : : * Initialize the starting WAL segment for the new timeline. If the switch
5879 : : * happens in the middle of a segment, copy data from the last WAL segment
5880 : : * of the old timeline up to the switch point, to the starting WAL segment
5881 : : * on the new timeline.
5882 : : */
5883 [ + + ]: 64 : if (endLogSegNo == startLogSegNo)
5884 : : {
5885 : : /*
5886 : : * Make a copy of the file on the new timeline.
5887 : : *
5888 : : * Writing WAL isn't allowed yet, so there are no locking
5889 : : * considerations. But we should be just as tense as XLogFileInit to
5890 : : * avoid emplacing a bogus file.
5891 : : */
5892 : 55 : XLogFileCopy(newTLI, endLogSegNo, endTLI, endLogSegNo,
5893 : 55 : XLogSegmentOffset(endOfLog, wal_segment_size));
5894 : : }
5895 : : else
5896 : : {
5897 : : /*
5898 : : * The switch happened at a segment boundary, so just create the next
5899 : : * segment on the new timeline.
5900 : : */
5901 : : int fd;
5902 : :
5903 : 9 : fd = XLogFileInit(startLogSegNo, newTLI);
5904 : :
5905 [ - + ]: 9 : if (close(fd) != 0)
5906 : : {
5907 : 0 : int save_errno = errno;
5908 : :
5909 : 0 : XLogFileName(xlogfname, newTLI, startLogSegNo, wal_segment_size);
5910 : 0 : errno = save_errno;
5911 [ # # ]: 0 : ereport(ERROR,
5912 : : (errcode_for_file_access(),
5913 : : errmsg("could not close file \"%s\": %m", xlogfname)));
5914 : : }
5915 : : }
5916 : :
5917 : : /*
5918 : : * Let's just make real sure there are not .ready or .done flags posted
5919 : : * for the new segment.
5920 : : */
5921 : 64 : XLogFileName(xlogfname, newTLI, startLogSegNo, wal_segment_size);
5922 : 64 : XLogArchiveCleanup(xlogfname);
5923 : 64 : }
5924 : :
5925 : : /*
5926 : : * Perform cleanup actions at the conclusion of archive recovery.
5927 : : */
5928 : : static void
5929 : 64 : CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI, XLogRecPtr EndOfLog,
5930 : : TimeLineID newTLI)
5931 : : {
5932 : : /*
5933 : : * Execute the recovery_end_command, if any.
5934 : : */
5935 [ + - + + ]: 64 : if (recoveryEndCommand && strcmp(recoveryEndCommand, "") != 0)
5936 : 2 : ExecuteRecoveryCommand(recoveryEndCommand,
5937 : : "recovery_end_command",
5938 : : true,
5939 : : WAIT_EVENT_RECOVERY_END_COMMAND);
5940 : :
5941 : : /*
5942 : : * We switched to a new timeline. Clean up segments on the old timeline.
5943 : : *
5944 : : * If there are any higher-numbered segments on the old timeline, remove
5945 : : * them. They might contain valid WAL, but they might also be
5946 : : * pre-allocated files containing garbage. In any case, they are not part
5947 : : * of the new timeline's history so we don't need them.
5948 : : */
5949 : 64 : RemoveNonParentXlogFiles(EndOfLog, newTLI);
5950 : :
5951 : : /*
5952 : : * If the switch happened in the middle of a segment, what to do with the
5953 : : * last, partial segment on the old timeline? If we don't archive it, and
5954 : : * the server that created the WAL never archives it either (e.g. because
5955 : : * it was hit by a meteor), it will never make it to the archive. That's
5956 : : * OK from our point of view, because the new segment that we created with
5957 : : * the new TLI contains all the WAL from the old timeline up to the switch
5958 : : * point. But if you later try to do PITR to the "missing" WAL on the old
5959 : : * timeline, recovery won't find it in the archive. It's physically
5960 : : * present in the new file with new TLI, but recovery won't look there
5961 : : * when it's recovering to the older timeline. On the other hand, if we
5962 : : * archive the partial segment, and the original server on that timeline
5963 : : * is still running and archives the completed version of the same segment
5964 : : * later, it will fail. (We used to do that in 9.4 and below, and it
5965 : : * caused such problems).
5966 : : *
5967 : : * As a compromise, we rename the last segment with the .partial suffix,
5968 : : * and archive it. Archive recovery will never try to read .partial
5969 : : * segments, so they will normally go unused. But in the odd PITR case,
5970 : : * the administrator can copy them manually to the pg_wal directory
5971 : : * (removing the suffix). They can be useful in debugging, too.
5972 : : *
5973 : : * If a .done or .ready file already exists for the old timeline, however,
5974 : : * we had already determined that the segment is complete, so we can let
5975 : : * it be archived normally. (In particular, if it was restored from the
5976 : : * archive to begin with, it's expected to have a .done file).
5977 : : */
5978 [ + + + + ]: 64 : if (XLogSegmentOffset(EndOfLog, wal_segment_size) != 0 &&
5979 : : XLogArchivingActive())
5980 : : {
5981 : : char origfname[MAXFNAMELEN];
5982 : : XLogSegNo endLogSegNo;
5983 : :
5984 : 12 : XLByteToPrevSeg(EndOfLog, endLogSegNo, wal_segment_size);
5985 : 12 : XLogFileName(origfname, EndOfLogTLI, endLogSegNo, wal_segment_size);
5986 : :
5987 [ + + ]: 12 : if (!XLogArchiveIsReadyOrDone(origfname))
5988 : : {
5989 : : char origpath[MAXPGPATH];
5990 : : char partialfname[MAXFNAMELEN];
5991 : : char partialpath[MAXPGPATH];
5992 : :
5993 : : /*
5994 : : * If we're summarizing WAL, we can't rename the partial file
5995 : : * until the summarizer finishes with it, else it will fail.
5996 : : */
5997 [ + + ]: 8 : if (summarize_wal)
5998 : 1 : WaitForWalSummarization(EndOfLog);
5999 : :
6000 : 8 : XLogFilePath(origpath, EndOfLogTLI, endLogSegNo, wal_segment_size);
6001 : 8 : snprintf(partialfname, MAXFNAMELEN, "%s.partial", origfname);
6002 : 8 : snprintf(partialpath, MAXPGPATH, "%s.partial", origpath);
6003 : :
6004 : : /*
6005 : : * Make sure there's no .done or .ready file for the .partial
6006 : : * file.
6007 : : */
6008 : 8 : XLogArchiveCleanup(partialfname);
6009 : :
6010 : 8 : durable_rename(origpath, partialpath, ERROR);
6011 : 8 : XLogArchiveNotify(partialfname);
6012 : : }
6013 : : }
6014 : 64 : }
6015 : :
6016 : : /*
6017 : : * Check to see if required parameters are set high enough on this server
6018 : : * for various aspects of recovery operation.
6019 : : *
6020 : : * Note that all the parameters which this function tests need to be
6021 : : * listed in Administrator's Overview section in high-availability.sgml.
6022 : : * If you change them, don't forget to update the list.
6023 : : */
6024 : : static void
6025 : 286 : CheckRequiredParameterValues(void)
6026 : : {
6027 : : /*
6028 : : * For archive recovery, the WAL must be generated with at least 'replica'
6029 : : * wal_level.
6030 : : */
6031 [ + + + + ]: 286 : if (ArchiveRecoveryRequested && ControlFile->wal_level == WAL_LEVEL_MINIMAL)
6032 : : {
6033 [ + - ]: 2 : ereport(FATAL,
6034 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6035 : : errmsg("WAL was generated with \"wal_level=minimal\", cannot continue recovering"),
6036 : : errdetail("This happens if you temporarily set \"wal_level=minimal\" on the server."),
6037 : : errhint("Use a backup taken after setting \"wal_level\" to higher than \"minimal\".")));
6038 : : }
6039 : :
6040 : : /*
6041 : : * For Hot Standby, the WAL must be generated with 'replica' mode, and we
6042 : : * must have at least as many backend slots as the primary.
6043 : : */
6044 [ + + + + ]: 284 : if (ArchiveRecoveryRequested && EnableHotStandby)
6045 : : {
6046 : : /* We ignore autovacuum_worker_slots when we make this test. */
6047 : 158 : RecoveryRequiresIntParameter("max_connections",
6048 : : MaxConnections,
6049 : 158 : ControlFile->MaxConnections);
6050 : 158 : RecoveryRequiresIntParameter("max_worker_processes",
6051 : : max_worker_processes,
6052 : 158 : ControlFile->max_worker_processes);
6053 : 158 : RecoveryRequiresIntParameter("max_wal_senders",
6054 : : max_wal_senders,
6055 : 158 : ControlFile->max_wal_senders);
6056 : 158 : RecoveryRequiresIntParameter("max_prepared_transactions",
6057 : : max_prepared_xacts,
6058 : 158 : ControlFile->max_prepared_xacts);
6059 : 158 : RecoveryRequiresIntParameter("max_locks_per_transaction",
6060 : : max_locks_per_xact,
6061 : 158 : ControlFile->max_locks_per_xact);
6062 : : }
6063 : 284 : }
6064 : :
6065 : : /*
6066 : : * This must be called ONCE during postmaster or standalone-backend startup
6067 : : */
6068 : : void
6069 : 1137 : StartupXLOG(void)
6070 : : {
6071 : : XLogCtlInsert *Insert;
6072 : : CheckPoint checkPoint;
6073 : : bool wasShutdown;
6074 : : bool didCrash;
6075 : : bool haveTblspcMap;
6076 : : bool haveBackupLabel;
6077 : : XLogRecPtr EndOfLog;
6078 : : TimeLineID EndOfLogTLI;
6079 : : TimeLineID newTLI;
6080 : : bool performedWalRecovery;
6081 : : EndOfWalRecoveryInfo *endOfRecoveryInfo;
6082 : : XLogRecPtr abortedRecPtr;
6083 : : XLogRecPtr missingContrecPtr;
6084 : : TransactionId oldestActiveXID;
6085 : 1137 : bool promoted = false;
6086 : : char timebuf[128];
6087 : :
6088 : : /*
6089 : : * We should have an aux process resource owner to use, and we should not
6090 : : * be in a transaction that's installed some other resowner.
6091 : : */
6092 : : Assert(AuxProcessResourceOwner != NULL);
6093 : : Assert(CurrentResourceOwner == NULL ||
6094 : : CurrentResourceOwner == AuxProcessResourceOwner);
6095 : 1137 : CurrentResourceOwner = AuxProcessResourceOwner;
6096 : :
6097 : : /*
6098 : : * Check that contents look valid.
6099 : : */
6100 [ - + ]: 1137 : if (!XRecOffIsValid(ControlFile->checkPoint))
6101 [ # # ]: 0 : ereport(FATAL,
6102 : : (errcode(ERRCODE_DATA_CORRUPTED),
6103 : : errmsg("control file contains invalid checkpoint location")));
6104 : :
6105 [ + + - - : 1137 : switch (ControlFile->state)
+ + - ]
6106 : : {
6107 : 893 : case DB_SHUTDOWNED:
6108 : :
6109 : : /*
6110 : : * This is the expected case, so don't be chatty in standalone
6111 : : * mode
6112 : : */
6113 [ + + + + ]: 893 : ereport(IsPostmasterEnvironment ? LOG : NOTICE,
6114 : : (errmsg("database system was shut down at %s",
6115 : : str_time(ControlFile->time,
6116 : : timebuf, sizeof(timebuf)))));
6117 : 893 : break;
6118 : :
6119 : 35 : case DB_SHUTDOWNED_IN_RECOVERY:
6120 [ + - ]: 35 : ereport(LOG,
6121 : : (errmsg("database system was shut down in recovery at %s",
6122 : : str_time(ControlFile->time,
6123 : : timebuf, sizeof(timebuf)))));
6124 : 35 : break;
6125 : :
6126 : 0 : case DB_SHUTDOWNING:
6127 [ # # ]: 0 : ereport(LOG,
6128 : : (errmsg("database system shutdown was interrupted; last known up at %s",
6129 : : str_time(ControlFile->time,
6130 : : timebuf, sizeof(timebuf)))));
6131 : 0 : break;
6132 : :
6133 : 0 : case DB_IN_CRASH_RECOVERY:
6134 [ # # ]: 0 : ereport(LOG,
6135 : : (errmsg("database system was interrupted while in recovery at %s",
6136 : : str_time(ControlFile->time,
6137 : : timebuf, sizeof(timebuf))),
6138 : : errhint("This probably means that some data is corrupted and"
6139 : : " you will have to use the last backup for recovery.")));
6140 : 0 : break;
6141 : :
6142 : 13 : case DB_IN_ARCHIVE_RECOVERY:
6143 [ + - ]: 13 : ereport(LOG,
6144 : : (errmsg("database system was interrupted while in recovery at log time %s",
6145 : : str_time(ControlFile->checkPointCopy.time,
6146 : : timebuf, sizeof(timebuf))),
6147 : : errhint("If this has occurred more than once some data might be corrupted"
6148 : : " and you might need to choose an earlier recovery target.")));
6149 : 13 : break;
6150 : :
6151 : 196 : case DB_IN_PRODUCTION:
6152 [ + - ]: 196 : ereport(LOG,
6153 : : (errmsg("database system was interrupted; last known up at %s",
6154 : : str_time(ControlFile->time,
6155 : : timebuf, sizeof(timebuf)))));
6156 : 196 : break;
6157 : :
6158 : 0 : default:
6159 [ # # ]: 0 : ereport(FATAL,
6160 : : (errcode(ERRCODE_DATA_CORRUPTED),
6161 : : errmsg("control file contains invalid database cluster state")));
6162 : : }
6163 : :
6164 : : /* This is just to allow attaching to startup process with a debugger */
6165 : : #ifdef XLOG_REPLAY_DELAY
6166 : : if (ControlFile->state != DB_SHUTDOWNED)
6167 : : pg_usleep(60000000L);
6168 : : #endif
6169 : :
6170 : : /*
6171 : : * Verify that pg_wal, pg_wal/archive_status, and pg_wal/summaries exist.
6172 : : * In cases where someone has performed a copy for PITR, these directories
6173 : : * may have been excluded and need to be re-created.
6174 : : */
6175 : 1137 : ValidateXLOGDirectoryStructure();
6176 : :
6177 : : /* Set up timeout handler needed to report startup progress. */
6178 [ + + ]: 1137 : if (!IsBootstrapProcessingMode())
6179 : 1078 : RegisterTimeout(STARTUP_PROGRESS_TIMEOUT,
6180 : : startup_progress_timeout_handler);
6181 : :
6182 : : /*----------
6183 : : * If we previously crashed, perform a couple of actions:
6184 : : *
6185 : : * - The pg_wal directory may still include some temporary WAL segments
6186 : : * used when creating a new segment, so perform some clean up to not
6187 : : * bloat this path. This is done first as there is no point to sync
6188 : : * this temporary data.
6189 : : *
6190 : : * - There might be data which we had written, intending to fsync it, but
6191 : : * which we had not actually fsync'd yet. Therefore, a power failure in
6192 : : * the near future might cause earlier unflushed writes to be lost, even
6193 : : * though more recent data written to disk from here on would be
6194 : : * persisted. To avoid that, fsync the entire data directory.
6195 : : */
6196 [ + + ]: 1137 : if (ControlFile->state != DB_SHUTDOWNED &&
6197 [ + + ]: 244 : ControlFile->state != DB_SHUTDOWNED_IN_RECOVERY)
6198 : : {
6199 : 209 : RemoveTempXlogFiles();
6200 : 209 : SyncDataDirectory();
6201 : 209 : didCrash = true;
6202 : : }
6203 : : else
6204 : 928 : didCrash = false;
6205 : :
6206 : : /*
6207 : : * Prepare for WAL recovery if needed.
6208 : : *
6209 : : * InitWalRecovery analyzes the control file and the backup label file, if
6210 : : * any. It updates the in-memory ControlFile buffer according to the
6211 : : * starting checkpoint, and sets InRecovery and ArchiveRecoveryRequested.
6212 : : * It also applies the tablespace map file, if any.
6213 : : */
6214 : 1137 : InitWalRecovery(ControlFile, &wasShutdown,
6215 : : &haveBackupLabel, &haveTblspcMap);
6216 : 1131 : checkPoint = ControlFile->checkPointCopy;
6217 : :
6218 : : /* initialize shared memory variables from the checkpoint record */
6219 : 1131 : TransamVariables->nextXid = checkPoint.nextXid;
6220 : 1131 : TransamVariables->nextOid = checkPoint.nextOid;
6221 : 1131 : TransamVariables->oidCount = 0;
6222 : 1131 : MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
6223 : 1131 : AdvanceOldestClogXid(checkPoint.oldestXid);
6224 : 1131 : SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
6225 : 1131 : SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB);
6226 : 1131 : SetCommitTsLimit(checkPoint.oldestCommitTsXid,
6227 : : checkPoint.newestCommitTsXid);
6228 : :
6229 : : /*
6230 : : * When recovery starts from a base backup, the control file was copied at
6231 : : * an arbitrary moment and its data checksum state may differ from the
6232 : : * state at the redo point, which is what the WAL from there on was
6233 : : * written under. Adopt the state of the starting checkpoint: a shutdown
6234 : : * checkpoint is not replayed, so take it from the record read above; the
6235 : : * redo point of an online checkpoint is its CHECKPOINT_REDO record, so
6236 : : * let the replay of that record adopt it. Check backupStartPoint in
6237 : : * addition to the label: on a crash restart during backup recovery the
6238 : : * label file is already renamed away, but the start point persists until
6239 : : * the backup end record.
6240 : : *
6241 : : * Not for a base backup taken from a standby, though. Its starting
6242 : : * checkpoint is the standby's last restartpoint, a record written by the
6243 : : * upstream primary, whose state is not the one the copied files were
6244 : : * written under. The copied control file is already correct: a standby
6245 : : * persists its state only at restartpoint horizons and never claims more
6246 : : * than what reached disk. Such backups are recognized by backupEndPoint
6247 : : * together with backupEndRequired; backupEndPoint is only set for "BACKUP
6248 : : * FROM: standby" labels and persists across a crash restart. pg_rewind
6249 : : * writes a standby label as well, but no backupEndPoint, and its recovery
6250 : : * keeps adopting: the control file it installs carries the target's own
6251 : : * checksum state, which can lag the redo point of the last common
6252 : : * checkpoint the same way a restartpoint horizon can.
6253 : : *
6254 : : * Never adopt over a state over the watermark or a node-local
6255 : : * pg_checksums change, it generats no WAL so nothing in the replayed WAL
6256 : : * could restore it once overwritten. Otherwise, even a watermark above
6257 : : * the redo point must not prevent adoption. A primary backup copies
6258 : : * pg_control after the relation files, which may still contain pages
6259 : : * written before that watermark.
6260 : : */
6261 [ + + - + ]: 1131 : if ((haveBackupLabel || XLogRecPtrIsValid(ControlFile->backupStartPoint)) &&
6262 [ + + ]: 97 : !(XLogRecPtrIsValid(ControlFile->backupEndPoint) &&
6263 [ + + ]: 10 : ControlFile->backupEndRequired) &&
6264 [ + + ]: 90 : !ControlFile->data_checksum_is_local &&
6265 [ + - ]: 89 : checkPoint.redo > ControlFile->data_checksum_lsn)
6266 : : {
6267 [ + + ]: 89 : if (wasShutdown)
6268 : 1 : AdoptReplayedDataChecksumState(checkPoint.dataChecksumState,
6269 : : checkPoint.redo);
6270 : : else
6271 : 88 : adoptChecksumStateFromNextCheckpoint = true;
6272 : : }
6273 : :
6274 : : /*
6275 : : * Clear out any old relcache cache files. This is *necessary* if we do
6276 : : * any WAL replay, since that would probably result in the cache files
6277 : : * being out of sync with database reality. In theory we could leave them
6278 : : * in place if the database had been cleanly shut down, but it seems
6279 : : * safest to just remove them always and let them be rebuilt during the
6280 : : * first backend startup. These files needs to be removed from all
6281 : : * directories including pg_tblspc, however the symlinks are created only
6282 : : * after reading tablespace_map file in case of archive recovery from
6283 : : * backup, so needs to clear old relcache files here after creating
6284 : : * symlinks.
6285 : : */
6286 : 1131 : RelationCacheInitFileRemove();
6287 : :
6288 : : /*
6289 : : * Initialize replication slots, before there's a chance to remove
6290 : : * required resources.
6291 : : */
6292 : 1131 : StartupReplicationSlots();
6293 : :
6294 : : /*
6295 : : * Startup the logical decoding status with the last status stored in the
6296 : : * checkpoint record.
6297 : : */
6298 : 1129 : StartupLogicalDecodingStatus(checkPoint.logicalDecodingEnabled);
6299 : :
6300 : : /*
6301 : : * Startup logical state, needs to be setup now so we have proper data
6302 : : * during crash recovery.
6303 : : */
6304 : 1129 : StartupReorderBuffer();
6305 : :
6306 : : /*
6307 : : * Startup CLOG. This must be done after TransamVariables->nextXid has
6308 : : * been initialized and before we accept connections or begin WAL replay.
6309 : : */
6310 : 1129 : StartupCLOG();
6311 : :
6312 : : /*
6313 : : * Startup MultiXact. We need to do this early to be able to replay
6314 : : * truncations.
6315 : : */
6316 : 1129 : StartupMultiXact();
6317 : :
6318 : : /*
6319 : : * Ditto for commit timestamps. Activate the facility if the setting is
6320 : : * enabled in the control file, as there should be no tracking of commit
6321 : : * timestamps done when the setting was disabled. This facility can be
6322 : : * started or stopped when replaying a XLOG_PARAMETER_CHANGE record.
6323 : : */
6324 [ + + ]: 1129 : if (ControlFile->track_commit_timestamp)
6325 : 14 : StartupCommitTs();
6326 : :
6327 : : /*
6328 : : * Recover knowledge about replay progress of known replication partners.
6329 : : */
6330 : 1129 : StartupReplicationOrigin();
6331 : :
6332 : : /*
6333 : : * Initialize unlogged LSN. On a clean shutdown, it's restored from the
6334 : : * control file. On recovery, all unlogged relations are blown away, so
6335 : : * the unlogged LSN counter can be reset too.
6336 : : */
6337 [ + + ]: 1129 : if (ControlFile->state == DB_SHUTDOWNED)
6338 : 883 : pg_atomic_write_membarrier_u64(&XLogCtl->unloggedLSN,
6339 : 883 : ControlFile->unloggedLSN);
6340 : : else
6341 : 246 : pg_atomic_write_membarrier_u64(&XLogCtl->unloggedLSN,
6342 : : FirstNormalUnloggedLSN);
6343 : :
6344 : : /*
6345 : : * Copy any missing timeline history files between 'now' and the recovery
6346 : : * target timeline from archive to pg_wal. While we don't need those files
6347 : : * ourselves - the history file of the recovery target timeline covers all
6348 : : * the previous timelines in the history too - a cascading standby server
6349 : : * might be interested in them. Or, if you archive the WAL from this
6350 : : * server to a different archive than the primary, it'd be good for all
6351 : : * the history files to get archived there after failover, so that you can
6352 : : * use one of the old timelines as a PITR target. Timeline history files
6353 : : * are small, so it's better to copy them unnecessarily than not copy them
6354 : : * and regret later.
6355 : : */
6356 : 1129 : restoreTimeLineHistoryFiles(checkPoint.ThisTimeLineID, recoveryTargetTLI);
6357 : :
6358 : : /*
6359 : : * Before running in recovery, scan pg_twophase and fill in its status to
6360 : : * be able to work on entries generated by redo. Doing a scan before
6361 : : * taking any recovery action has the merit to discard any 2PC files that
6362 : : * are newer than the first record to replay, saving from any conflicts at
6363 : : * replay. This avoids as well any subsequent scans when doing recovery
6364 : : * of the on-disk two-phase data.
6365 : : */
6366 : 1129 : restoreTwoPhaseData();
6367 : :
6368 : : /*
6369 : : * When starting with crash recovery, reset pgstat data - it might not be
6370 : : * valid. Otherwise restore pgstat data. It's safe to do this here,
6371 : : * because postmaster will not yet have started any other processes.
6372 : : *
6373 : : * NB: Restoring replication slot stats relies on slot state to have
6374 : : * already been restored from disk.
6375 : : *
6376 : : * TODO: With a bit of extra work we could just start with a pgstat file
6377 : : * associated with the checkpoint redo location we're starting from.
6378 : : */
6379 [ + + ]: 1129 : if (didCrash)
6380 : 203 : pgstat_discard_stats();
6381 : : else
6382 : 926 : pgstat_restore_stats();
6383 : :
6384 : 1129 : lastFullPageWrites = checkPoint.fullPageWrites;
6385 : :
6386 : 1129 : RedoRecPtr = XLogCtl->RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
6387 : 1129 : doPageWrites = lastFullPageWrites;
6388 : :
6389 : : /* REDO */
6390 [ + + ]: 1129 : if (InRecovery)
6391 : : {
6392 : : /* Initialize state for RecoveryInProgress() */
6393 : 246 : SpinLockAcquire(&XLogCtl->info_lck);
6394 [ + + ]: 246 : if (InArchiveRecovery)
6395 : 143 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_ARCHIVE;
6396 : : else
6397 : 103 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_CRASH;
6398 : 246 : SpinLockRelease(&XLogCtl->info_lck);
6399 : :
6400 : : /*
6401 : : * Update pg_control to show that we are recovering and to show the
6402 : : * selected checkpoint as the place we are starting from. We also mark
6403 : : * pg_control with any minimum recovery stop point obtained from a
6404 : : * backup history file.
6405 : : *
6406 : : * No need to hold ControlFileLock yet, we aren't up far enough.
6407 : : */
6408 : 246 : UpdateControlFile();
6409 : :
6410 : : /*
6411 : : * If there was a backup label file, it's done its job and the info
6412 : : * has now been propagated into pg_control. We must get rid of the
6413 : : * label file so that if we crash during recovery, we'll pick up at
6414 : : * the latest recovery restartpoint instead of going all the way back
6415 : : * to the backup start point. It seems prudent though to just rename
6416 : : * the file out of the way rather than delete it completely.
6417 : : */
6418 [ + + ]: 246 : if (haveBackupLabel)
6419 : : {
6420 : 97 : unlink(BACKUP_LABEL_OLD);
6421 : 97 : durable_rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, FATAL);
6422 : : }
6423 : :
6424 : : /*
6425 : : * If there was a tablespace_map file, it's done its job and the
6426 : : * symlinks have been created. We must get rid of the map file so
6427 : : * that if we crash during recovery, we don't create symlinks again.
6428 : : * It seems prudent though to just rename the file out of the way
6429 : : * rather than delete it completely.
6430 : : */
6431 [ + + ]: 246 : if (haveTblspcMap)
6432 : : {
6433 : 2 : unlink(TABLESPACE_MAP_OLD);
6434 : 2 : durable_rename(TABLESPACE_MAP, TABLESPACE_MAP_OLD, FATAL);
6435 : : }
6436 : :
6437 : : /*
6438 : : * Initialize our local copy of minRecoveryPoint. When doing crash
6439 : : * recovery we want to replay up to the end of WAL. Particularly, in
6440 : : * the case of a promoted standby minRecoveryPoint value in the
6441 : : * control file is only updated after the first checkpoint. However,
6442 : : * if the instance crashes before the first post-recovery checkpoint
6443 : : * is completed then recovery will use a stale location causing the
6444 : : * startup process to think that there are still invalid page
6445 : : * references when checking for data consistency.
6446 : : */
6447 [ + + ]: 246 : if (InArchiveRecovery)
6448 : : {
6449 : 143 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
6450 : : }
6451 : : else
6452 : : {
6453 : 103 : LocalMinRecoveryPoint = InvalidXLogRecPtr;
6454 : : }
6455 : :
6456 : : /* Check that the GUCs used to generate the WAL allow recovery */
6457 : 246 : CheckRequiredParameterValues();
6458 : :
6459 : : /*
6460 : : * We're in recovery, so unlogged relations may be trashed and must be
6461 : : * reset. This should be done BEFORE allowing Hot Standby
6462 : : * connections, so that read-only backends don't try to read whatever
6463 : : * garbage is left over from before.
6464 : : */
6465 : 246 : ResetUnloggedRelations(UNLOGGED_RELATION_CLEANUP);
6466 : :
6467 : : /*
6468 : : * Likewise, delete any saved transaction snapshot files that got left
6469 : : * behind by crashed backends.
6470 : : */
6471 : 246 : DeleteAllExportedSnapshotFiles();
6472 : :
6473 : : /*
6474 : : * Initialize for Hot Standby, if enabled. We won't let backends in
6475 : : * yet, not until we've reached the min recovery point specified in
6476 : : * control file and we've established a recovery snapshot from a
6477 : : * running-xacts WAL record.
6478 : : */
6479 [ + + + + ]: 246 : if (ArchiveRecoveryRequested && EnableHotStandby)
6480 : : {
6481 : : TransactionId *xids;
6482 : : int nxids;
6483 : :
6484 [ + + ]: 134 : ereport(DEBUG1,
6485 : : (errmsg_internal("initializing for hot standby")));
6486 : :
6487 : 134 : InitRecoveryTransactionEnvironment();
6488 : :
6489 [ + + ]: 134 : if (wasShutdown)
6490 : 29 : oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
6491 : : else
6492 : 105 : oldestActiveXID = checkPoint.oldestActiveXid;
6493 : : Assert(TransactionIdIsValid(oldestActiveXID));
6494 : :
6495 : : /* Tell procarray about the range of xids it has to deal with */
6496 : 134 : ProcArrayInitRecovery(XidFromFullTransactionId(TransamVariables->nextXid));
6497 : :
6498 : : /*
6499 : : * Startup subtrans only. CLOG, MultiXact and commit timestamp
6500 : : * have already been started up and other SLRUs are not maintained
6501 : : * during recovery and need not be started yet.
6502 : : */
6503 : 134 : StartupSUBTRANS(oldestActiveXID);
6504 : 134 : SetRecoverySubtransInitialized();
6505 : :
6506 : : /*
6507 : : * If we're beginning at a shutdown checkpoint, we know that
6508 : : * nothing was running on the primary at this point. So fake-up an
6509 : : * empty running-xacts record and use that here and now. Recover
6510 : : * additional standby state for prepared transactions.
6511 : : */
6512 [ + + ]: 134 : if (wasShutdown)
6513 : : {
6514 : : RunningTransactionsData running;
6515 : : TransactionId latestCompletedXid;
6516 : :
6517 : : /* Update pg_subtrans entries for any prepared transactions */
6518 : 29 : StandbyRecoverPreparedTransactions();
6519 : :
6520 : : /*
6521 : : * Construct a RunningTransactions snapshot representing a
6522 : : * shut down server, with only prepared transactions still
6523 : : * alive. We're never overflowed at this point because all
6524 : : * subxids are listed with their parent prepared transactions.
6525 : : */
6526 : 29 : running.xcnt = nxids;
6527 : 29 : running.subxcnt = 0;
6528 : 29 : running.subxid_status = SUBXIDS_IN_SUBTRANS;
6529 : 29 : running.nextXid = XidFromFullTransactionId(checkPoint.nextXid);
6530 : 29 : running.oldestRunningXid = oldestActiveXID;
6531 : 29 : latestCompletedXid = XidFromFullTransactionId(checkPoint.nextXid);
6532 [ - + ]: 29 : TransactionIdRetreat(latestCompletedXid);
6533 : : Assert(TransactionIdIsNormal(latestCompletedXid));
6534 : 29 : running.latestCompletedXid = latestCompletedXid;
6535 : 29 : running.xids = xids;
6536 : :
6537 : 29 : ProcArrayApplyRecoveryInfo(&running);
6538 : : }
6539 : : }
6540 : :
6541 : : /*
6542 : : * We're all set for replaying the WAL now. Do it.
6543 : : */
6544 : 246 : PerformWalRecovery();
6545 : 174 : performedWalRecovery = true;
6546 : : }
6547 : : else
6548 : 883 : performedWalRecovery = false;
6549 : :
6550 : : /*
6551 : : * Finish WAL recovery.
6552 : : */
6553 : 1057 : endOfRecoveryInfo = FinishWalRecovery();
6554 : 1057 : EndOfLog = endOfRecoveryInfo->endOfLog;
6555 : 1057 : EndOfLogTLI = endOfRecoveryInfo->endOfLogTLI;
6556 : 1057 : abortedRecPtr = endOfRecoveryInfo->abortedRecPtr;
6557 : 1057 : missingContrecPtr = endOfRecoveryInfo->missingContrecPtr;
6558 : :
6559 : : /*
6560 : : * Reset ps status display, so as no information related to recovery shows
6561 : : * up.
6562 : : */
6563 : 1057 : set_ps_display("");
6564 : :
6565 : : /*
6566 : : * When recovering from a backup (we are in recovery, and archive recovery
6567 : : * was requested), complain if we did not roll forward far enough to reach
6568 : : * the point where the database is consistent. For regular online
6569 : : * backup-from-primary, that means reaching the end-of-backup WAL record
6570 : : * (at which point we reset backupStartPoint to be Invalid), for
6571 : : * backup-from-replica (which can't inject records into the WAL stream),
6572 : : * that point is when we reach the minRecoveryPoint in pg_control (which
6573 : : * we purposefully copy last when backing up from a replica). For
6574 : : * pg_rewind (which creates a backup_label with a method of "pg_rewind")
6575 : : * or snapshot-style backups (which don't), backupEndRequired will be set
6576 : : * to false.
6577 : : *
6578 : : * Note: it is indeed okay to look at the local variable
6579 : : * LocalMinRecoveryPoint here, even though ControlFile->minRecoveryPoint
6580 : : * might be further ahead --- ControlFile->minRecoveryPoint cannot have
6581 : : * been advanced beyond the WAL we processed.
6582 : : */
6583 [ + + ]: 1057 : if (InRecovery &&
6584 [ + - ]: 174 : (EndOfLog < LocalMinRecoveryPoint ||
6585 [ - + ]: 174 : XLogRecPtrIsValid(ControlFile->backupStartPoint)))
6586 : : {
6587 : : /*
6588 : : * Ran off end of WAL before reaching end-of-backup WAL record, or
6589 : : * minRecoveryPoint. That's a bad sign, indicating that you tried to
6590 : : * recover from an online backup but never called pg_backup_stop(), or
6591 : : * you didn't archive all the WAL needed.
6592 : : */
6593 [ # # # # ]: 0 : if (ArchiveRecoveryRequested || ControlFile->backupEndRequired)
6594 : : {
6595 [ # # # # ]: 0 : if (XLogRecPtrIsValid(ControlFile->backupStartPoint) || ControlFile->backupEndRequired)
6596 [ # # ]: 0 : ereport(FATAL,
6597 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6598 : : errmsg("WAL ends before end of online backup"),
6599 : : errhint("All WAL generated while online backup was taken must be available at recovery.")));
6600 : : else
6601 [ # # ]: 0 : ereport(FATAL,
6602 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6603 : : errmsg("WAL ends before consistent recovery point")));
6604 : : }
6605 : : }
6606 : :
6607 : : /*
6608 : : * Reset unlogged relations to the contents of their INIT fork. This is
6609 : : * done AFTER recovery is complete so as to include any unlogged relations
6610 : : * created during recovery, but BEFORE recovery is marked as having
6611 : : * completed successfully. Otherwise we'd not retry if any of the post
6612 : : * end-of-recovery steps fail.
6613 : : */
6614 [ + + ]: 1057 : if (InRecovery)
6615 : 174 : ResetUnloggedRelations(UNLOGGED_RELATION_INIT);
6616 : :
6617 : : /*
6618 : : * Pre-scan prepared transactions to find out the range of XIDs present.
6619 : : * This information is not quite needed yet, but it is positioned here so
6620 : : * as potential problems are detected before any on-disk change is done.
6621 : : */
6622 : 1057 : oldestActiveXID = PrescanPreparedTransactions(NULL, NULL);
6623 : :
6624 : : /*
6625 : : * Allow ordinary WAL segment creation before possibly switching to a new
6626 : : * timeline, which creates a new segment, and after the last ReadRecord().
6627 : : */
6628 : 1057 : SetInstallXLogFileSegmentActive();
6629 : :
6630 : : /*
6631 : : * Consider whether we need to assign a new timeline ID.
6632 : : *
6633 : : * If we did archive recovery, we always assign a new ID. This handles a
6634 : : * couple of issues. If we stopped short of the end of WAL during
6635 : : * recovery, then we are clearly generating a new timeline and must assign
6636 : : * it a unique new ID. Even if we ran to the end, modifying the current
6637 : : * last segment is problematic because it may result in trying to
6638 : : * overwrite an already-archived copy of that segment, and we encourage
6639 : : * DBAs to make their archive_commands reject that. We can dodge the
6640 : : * problem by making the new active segment have a new timeline ID.
6641 : : *
6642 : : * In a normal crash recovery, we can just extend the timeline we were in.
6643 : : */
6644 : 1057 : newTLI = endOfRecoveryInfo->lastRecTLI;
6645 [ + + ]: 1057 : if (ArchiveRecoveryRequested)
6646 : : {
6647 : 64 : newTLI = findNewestTimeLine(recoveryTargetTLI) + 1;
6648 [ + - ]: 64 : ereport(LOG,
6649 : : (errmsg("selected new timeline ID: %u", newTLI)));
6650 : :
6651 : : /*
6652 : : * Make a writable copy of the last WAL segment. (Note that we also
6653 : : * have a copy of the last block of the old WAL in
6654 : : * endOfRecovery->lastPage; we will use that below.)
6655 : : */
6656 : 64 : XLogInitNewTimeline(EndOfLogTLI, EndOfLog, newTLI);
6657 : :
6658 : : /*
6659 : : * Remove the signal files out of the way, so that we don't
6660 : : * accidentally re-enter archive recovery mode in a subsequent crash.
6661 : : */
6662 [ + + ]: 64 : if (endOfRecoveryInfo->standby_signal_file_found)
6663 : 61 : durable_unlink(STANDBY_SIGNAL_FILE, FATAL);
6664 : :
6665 [ + + ]: 64 : if (endOfRecoveryInfo->recovery_signal_file_found)
6666 : 4 : durable_unlink(RECOVERY_SIGNAL_FILE, FATAL);
6667 : :
6668 : : /*
6669 : : * Write the timeline history file, and have it archived. After this
6670 : : * point (or rather, as soon as the file is archived), the timeline
6671 : : * will appear as "taken" in the WAL archive and to any standby
6672 : : * servers. If we crash before actually switching to the new
6673 : : * timeline, standby servers will nevertheless think that we switched
6674 : : * to the new timeline, and will try to connect to the new timeline.
6675 : : * To minimize the window for that, try to do as little as possible
6676 : : * between here and writing the end-of-recovery record.
6677 : : */
6678 : 64 : writeTimeLineHistory(newTLI, recoveryTargetTLI,
6679 : 64 : EndOfLog, endOfRecoveryInfo->recoveryStopReason);
6680 : :
6681 [ + - ]: 64 : ereport(LOG,
6682 : : (errmsg("archive recovery complete")));
6683 : : }
6684 : :
6685 : : /* Save the selected TimeLineID in shared memory, too */
6686 : 1057 : SpinLockAcquire(&XLogCtl->info_lck);
6687 : 1057 : XLogCtl->InsertTimeLineID = newTLI;
6688 : 1057 : XLogCtl->PrevTimeLineID = endOfRecoveryInfo->lastRecTLI;
6689 : 1057 : SpinLockRelease(&XLogCtl->info_lck);
6690 : :
6691 : : /*
6692 : : * Actually, if WAL ended in an incomplete record, skip the parts that
6693 : : * made it through and start writing after the portion that persisted.
6694 : : * (It's critical to first write an OVERWRITE_CONTRECORD message, which
6695 : : * we'll do as soon as we're open for writing new WAL.)
6696 : : */
6697 [ + + ]: 1057 : if (XLogRecPtrIsValid(missingContrecPtr))
6698 : : {
6699 : : /*
6700 : : * We should only have a missingContrecPtr if we're not switching to a
6701 : : * new timeline. When a timeline switch occurs, WAL is copied from the
6702 : : * old timeline to the new only up to the end of the last complete
6703 : : * record, so there can't be an incomplete WAL record that we need to
6704 : : * disregard.
6705 : : */
6706 : : Assert(newTLI == endOfRecoveryInfo->lastRecTLI);
6707 : : Assert(XLogRecPtrIsValid(abortedRecPtr));
6708 : 12 : EndOfLog = missingContrecPtr;
6709 : : }
6710 : :
6711 : : /*
6712 : : * Prepare to write WAL starting at EndOfLog location, and init xlog
6713 : : * buffer cache using the block containing the last record from the
6714 : : * previous incarnation.
6715 : : */
6716 : 1057 : Insert = &XLogCtl->Insert;
6717 : 1057 : Insert->PrevBytePos = XLogRecPtrToBytePos(endOfRecoveryInfo->lastRec);
6718 : 1057 : Insert->CurrBytePos = XLogRecPtrToBytePos(EndOfLog);
6719 : :
6720 : : /*
6721 : : * Tricky point here: lastPage contains the *last* block that the LastRec
6722 : : * record spans, not the one it starts in. The last block is indeed the
6723 : : * one we want to use.
6724 : : */
6725 [ + + ]: 1057 : if (EndOfLog % XLOG_BLCKSZ != 0)
6726 : : {
6727 : : char *page;
6728 : : int len;
6729 : : int firstIdx;
6730 : :
6731 : 1027 : firstIdx = XLogRecPtrToBufIdx(EndOfLog);
6732 : 1027 : len = EndOfLog - endOfRecoveryInfo->lastPageBeginPtr;
6733 : : Assert(len < XLOG_BLCKSZ);
6734 : :
6735 : : /* Copy the valid part of the last block, and zero the rest */
6736 : 1027 : page = &XLogCtl->pages[firstIdx * XLOG_BLCKSZ];
6737 : 1027 : memcpy(page, endOfRecoveryInfo->lastPage, len);
6738 : 1027 : memset(page + len, 0, XLOG_BLCKSZ - len);
6739 : :
6740 : 1027 : pg_atomic_write_u64(&XLogCtl->xlblocks[firstIdx], endOfRecoveryInfo->lastPageBeginPtr + XLOG_BLCKSZ);
6741 : 1027 : XLogCtl->InitializedUpTo = endOfRecoveryInfo->lastPageBeginPtr + XLOG_BLCKSZ;
6742 : : }
6743 : : else
6744 : : {
6745 : : /*
6746 : : * There is no partial block to copy. Just set InitializedUpTo, and
6747 : : * let the first attempt to insert a log record to initialize the next
6748 : : * buffer.
6749 : : */
6750 : 30 : XLogCtl->InitializedUpTo = EndOfLog;
6751 : : }
6752 : :
6753 : : /*
6754 : : * Update local and shared status. This is OK to do without any locks
6755 : : * because no other process can be reading or writing WAL yet.
6756 : : */
6757 : 1057 : LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
6758 : 1057 : pg_atomic_write_u64(&XLogCtl->logInsertResult, EndOfLog);
6759 : 1057 : pg_atomic_write_u64(&XLogCtl->logWriteResult, EndOfLog);
6760 : 1057 : pg_atomic_write_u64(&XLogCtl->logFlushResult, EndOfLog);
6761 : 1057 : XLogCtl->LogwrtRqst.Write = EndOfLog;
6762 : 1057 : XLogCtl->LogwrtRqst.Flush = EndOfLog;
6763 : :
6764 : : /*
6765 : : * Preallocate additional log files, if wanted.
6766 : : */
6767 : 1057 : PreallocXlogFiles(EndOfLog, newTLI);
6768 : :
6769 : : /*
6770 : : * Okay, we're officially UP.
6771 : : */
6772 : 1057 : InRecovery = false;
6773 : :
6774 : : /* start the archive_timeout timer and LSN running */
6775 : 1057 : XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL);
6776 : 1057 : XLogCtl->lastSegSwitchLSN = EndOfLog;
6777 : :
6778 : : /* also initialize latestCompletedXid, to nextXid - 1 */
6779 : 1057 : LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
6780 : 1057 : TransamVariables->latestCompletedXid = TransamVariables->nextXid;
6781 : 1057 : FullTransactionIdRetreat(&TransamVariables->latestCompletedXid);
6782 : 1057 : LWLockRelease(ProcArrayLock);
6783 : :
6784 : : /*
6785 : : * Start up subtrans, if not already done for hot standby. (commit
6786 : : * timestamps are started below, if necessary.)
6787 : : */
6788 [ + + ]: 1057 : if (standbyState == STANDBY_DISABLED)
6789 : 993 : StartupSUBTRANS(oldestActiveXID);
6790 : :
6791 : : /*
6792 : : * Perform end of recovery actions for any SLRUs that need it.
6793 : : */
6794 : 1057 : TrimCLOG();
6795 : 1057 : TrimMultiXact();
6796 : :
6797 : : /*
6798 : : * Reload shared-memory state for prepared transactions. This needs to
6799 : : * happen before renaming the last partial segment of the old timeline as
6800 : : * it may be possible that we have to recover some transactions from it.
6801 : : */
6802 : 1057 : RecoverPreparedTransactions();
6803 : :
6804 : : /* Shut down xlogreader */
6805 : 1057 : ShutdownWalRecovery();
6806 : :
6807 : : /* Enable WAL writes for this backend only. */
6808 : 1057 : LocalSetXLogInsertAllowed();
6809 : :
6810 : : /* If necessary, write overwrite-contrecord before doing anything else */
6811 [ + + ]: 1057 : if (XLogRecPtrIsValid(abortedRecPtr))
6812 : : {
6813 : : Assert(XLogRecPtrIsValid(missingContrecPtr));
6814 : 12 : CreateOverwriteContrecordRecord(abortedRecPtr, missingContrecPtr, newTLI);
6815 : : }
6816 : :
6817 : : /*
6818 : : * Update full_page_writes in shared memory and write an XLOG_FPW_CHANGE
6819 : : * record before resource manager writes cleanup WAL records or checkpoint
6820 : : * record is written.
6821 : : */
6822 : 1057 : Insert->fullPageWrites = lastFullPageWrites;
6823 : 1057 : UpdateFullPageWrites();
6824 : :
6825 : : /*
6826 : : * Emit checkpoint or end-of-recovery record in XLOG, if required.
6827 : : */
6828 [ + + ]: 1057 : if (performedWalRecovery)
6829 : 174 : promoted = PerformRecoveryXLogAction();
6830 : :
6831 : : /*
6832 : : * If any of the critical GUCs have changed, log them before we allow
6833 : : * backends to write WAL.
6834 : : */
6835 : 1057 : XLogReportParameters();
6836 : :
6837 : : /* If this is archive recovery, perform post-recovery cleanup actions. */
6838 [ + + ]: 1057 : if (ArchiveRecoveryRequested)
6839 : 64 : CleanupAfterArchiveRecovery(EndOfLogTLI, EndOfLog, newTLI);
6840 : :
6841 : 1057 : INJECTION_POINT("promotion-after-wal-segment-cleanup", NULL);
6842 : :
6843 : : /*
6844 : : * Local WAL inserts enabled, so it's time to finish initialization of
6845 : : * commit timestamp.
6846 : : */
6847 : 1057 : CompleteCommitTsInitialization();
6848 : :
6849 : : /*
6850 : : * Update logical decoding status in shared memory and write an
6851 : : * XLOG_LOGICAL_DECODING_STATUS_CHANGE, if necessary.
6852 : : */
6853 : 1057 : UpdateLogicalDecodingStatusEndOfRecovery();
6854 : :
6855 : : /* Clean up EndOfWalRecoveryInfo data to appease Valgrind leak checking */
6856 [ + + ]: 1057 : if (endOfRecoveryInfo->lastPage)
6857 : 1039 : pfree(endOfRecoveryInfo->lastPage);
6858 : 1057 : pfree(endOfRecoveryInfo->recoveryStopReason);
6859 : 1057 : pfree(endOfRecoveryInfo);
6860 : :
6861 : : /*
6862 : : * If we reach this point with checksums in the state inprogress-on, it
6863 : : * means that data checksums were in the process of being enabled when the
6864 : : * cluster shut down. Since processing didn't finish, the operation will
6865 : : * have to be restarted from scratch since there is no capability to
6866 : : * continue where it was when the cluster shut down. Thus, revert the
6867 : : * state back to off, and inform the user with a warning message. Being
6868 : : * able to restart processing is a TODO, but it wouldn't be possible to
6869 : : * restart here since we cannot launch a dynamic background worker
6870 : : * directly from here (it has to be from a regular backend).
6871 : : */
6872 [ + + ]: 1057 : if (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_ON)
6873 : : {
6874 : 1 : XLogChecksums(PG_DATA_CHECKSUM_OFF);
6875 : 1 : SetLocalDataChecksumState(PG_DATA_CHECKSUM_OFF);
6876 : :
6877 : 1 : EmitAndWaitDataChecksumsBarrier(PG_DATA_CHECKSUM_OFF);
6878 [ + - ]: 1 : ereport(WARNING,
6879 : : errmsg("enabling data checksums was interrupted"),
6880 : : errhint("Data checksum processing must be manually restarted for checksums to be enabled."));
6881 : : }
6882 : :
6883 : : /*
6884 : : * If data checksums were being disabled when the cluster was shut down,
6885 : : * we know that we have a state where all backends have stopped validating
6886 : : * checksums and we can move to off instead of prompting the user to
6887 : : * perform any action.
6888 : : */
6889 [ - + ]: 1056 : else if (XLogCtl->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_OFF)
6890 : : {
6891 : 0 : XLogChecksums(PG_DATA_CHECKSUM_OFF);
6892 : 0 : SetLocalDataChecksumState(PG_DATA_CHECKSUM_OFF);
6893 : :
6894 : 0 : EmitAndWaitDataChecksumsBarrier(PG_DATA_CHECKSUM_OFF);
6895 : : }
6896 : :
6897 : : /*
6898 : : * All done with end-of-recovery actions.
6899 : : *
6900 : : * Now allow backends to write WAL and update the control file status in
6901 : : * consequence. SharedRecoveryState, that controls if backends can write
6902 : : * WAL, is updated while holding ControlFileLock to prevent other backends
6903 : : * to look at an inconsistent state of the control file in shared memory.
6904 : : * There is still a small window during which backends can write WAL and
6905 : : * the control file is still referring to a system not in DB_IN_PRODUCTION
6906 : : * state while looking at the on-disk control file.
6907 : : *
6908 : : * Also, we use info_lck to update SharedRecoveryState to ensure that
6909 : : * there are no race conditions concerning visibility of other recent
6910 : : * updates to shared memory.
6911 : : */
6912 : 1057 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6913 : 1057 : ControlFile->state = DB_IN_PRODUCTION;
6914 : :
6915 : 1057 : SpinLockAcquire(&XLogCtl->info_lck);
6916 : 1057 : ControlFile->data_checksum_version = XLogCtl->data_checksum_version;
6917 : 1057 : ControlFile->data_checksum_lsn = XLogCtl->data_checksum_lsn;
6918 : 1057 : ControlFile->data_checksum_is_local = XLogCtl->data_checksum_is_local;
6919 : 1057 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_DONE;
6920 : 1057 : SpinLockRelease(&XLogCtl->info_lck);
6921 : :
6922 : 1057 : UpdateControlFile();
6923 : 1057 : LWLockRelease(ControlFileLock);
6924 : :
6925 : : /*
6926 : : * Wake up the checkpointer process as there might be a request to disable
6927 : : * logical decoding by concurrent slot drop.
6928 : : */
6929 : 1057 : WakeupCheckpointer();
6930 : :
6931 : : /*
6932 : : * Wake up all waiters. They need to report an error that recovery was
6933 : : * ended before reaching the target LSN.
6934 : : */
6935 : 1057 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_REPLAY, InvalidXLogRecPtr);
6936 : 1057 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_WRITE, InvalidXLogRecPtr);
6937 : 1057 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_FLUSH, InvalidXLogRecPtr);
6938 : :
6939 : : /*
6940 : : * Shutdown the recovery environment. This must occur after
6941 : : * RecoverPreparedTransactions() (see notes in lock_twophase_recover())
6942 : : * and after switching SharedRecoveryState to RECOVERY_STATE_DONE so as
6943 : : * any session building a snapshot will not rely on KnownAssignedXids as
6944 : : * RecoveryInProgress() would return false at this stage. This is
6945 : : * particularly critical for prepared 2PC transactions, that would still
6946 : : * need to be included in snapshots once recovery has ended.
6947 : : */
6948 [ + + ]: 1057 : if (standbyState != STANDBY_DISABLED)
6949 : 64 : ShutdownRecoveryTransactionEnvironment();
6950 : :
6951 : : /*
6952 : : * If there were cascading standby servers connected to us, nudge any wal
6953 : : * sender processes to notice that we've been promoted.
6954 : : */
6955 : 1057 : WalSndWakeup(true, true);
6956 : :
6957 : : /*
6958 : : * If this was a promotion, request an (online) checkpoint now. This isn't
6959 : : * required for consistency, but the last restartpoint might be far back,
6960 : : * and in case of a crash, recovering from it might take a longer than is
6961 : : * appropriate now that we're not in standby mode anymore.
6962 : : */
6963 [ + + ]: 1057 : if (promoted)
6964 : 56 : RequestCheckpoint(CHECKPOINT_FORCE);
6965 : 1057 : }
6966 : :
6967 : : /*
6968 : : * Callback from PerformWalRecovery(), called when we switch from crash
6969 : : * recovery to archive recovery mode. Updates the control file accordingly.
6970 : : */
6971 : : void
6972 : 1 : SwitchIntoArchiveRecovery(XLogRecPtr EndRecPtr, TimeLineID replayTLI)
6973 : : {
6974 : : /* initialize minRecoveryPoint to this record */
6975 : 1 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6976 : 1 : ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
6977 [ + - ]: 1 : if (ControlFile->minRecoveryPoint < EndRecPtr)
6978 : : {
6979 : 1 : ControlFile->minRecoveryPoint = EndRecPtr;
6980 : 1 : ControlFile->minRecoveryPointTLI = replayTLI;
6981 : : }
6982 : : /* update local copy */
6983 : 1 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
6984 : :
6985 : : /*
6986 : : * The startup process can update its local copy of minRecoveryPoint from
6987 : : * this point.
6988 : : */
6989 : 1 : updateMinRecoveryPoint = true;
6990 : :
6991 : 1 : UpdateControlFile();
6992 : :
6993 : : /*
6994 : : * We update SharedRecoveryState while holding the lock on ControlFileLock
6995 : : * so both states are consistent in shared memory.
6996 : : */
6997 : 1 : SpinLockAcquire(&XLogCtl->info_lck);
6998 : 1 : XLogCtl->SharedRecoveryState = RECOVERY_STATE_ARCHIVE;
6999 : 1 : SpinLockRelease(&XLogCtl->info_lck);
7000 : :
7001 : 1 : LWLockRelease(ControlFileLock);
7002 : 1 : }
7003 : :
7004 : : /*
7005 : : * Callback from PerformWalRecovery(), called when we reach the end of backup.
7006 : : * Updates the control file accordingly.
7007 : : */
7008 : : void
7009 : 97 : ReachedEndOfBackup(XLogRecPtr EndRecPtr, TimeLineID tli)
7010 : : {
7011 : : /*
7012 : : * We have reached the end of base backup, as indicated by pg_control. The
7013 : : * data on disk is now consistent (unless minRecoveryPoint is further
7014 : : * ahead, which can happen if we crashed during previous recovery). Reset
7015 : : * backupStartPoint and backupEndPoint, and update minRecoveryPoint to
7016 : : * make sure we don't allow starting up at an earlier point even if
7017 : : * recovery is stopped and restarted soon after this.
7018 : : */
7019 : 97 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7020 : :
7021 [ + + ]: 97 : if (ControlFile->minRecoveryPoint < EndRecPtr)
7022 : : {
7023 : 87 : ControlFile->minRecoveryPoint = EndRecPtr;
7024 : 87 : ControlFile->minRecoveryPointTLI = tli;
7025 : : }
7026 : :
7027 : 97 : ControlFile->backupStartPoint = InvalidXLogRecPtr;
7028 : 97 : ControlFile->backupEndPoint = InvalidXLogRecPtr;
7029 : 97 : ControlFile->backupEndRequired = false;
7030 : 97 : UpdateControlFile();
7031 : :
7032 : 97 : LWLockRelease(ControlFileLock);
7033 : 97 : }
7034 : :
7035 : : /*
7036 : : * Perform whatever XLOG actions are necessary at end of REDO.
7037 : : *
7038 : : * The goal here is to make sure that we'll be able to recover properly if
7039 : : * we crash again. If we choose to write a checkpoint, we'll write a shutdown
7040 : : * checkpoint rather than an on-line one. This is not particularly critical,
7041 : : * but since we may be assigning a new TLI, using a shutdown checkpoint allows
7042 : : * us to have the rule that TLI only changes in shutdown checkpoints, which
7043 : : * allows some extra error checking in xlog_redo.
7044 : : */
7045 : : static bool
7046 : 174 : PerformRecoveryXLogAction(void)
7047 : : {
7048 : 174 : bool promoted = false;
7049 : : bool flushForChecksums;
7050 : : uint32 checksum_state;
7051 : :
7052 : : /*
7053 : : * The end-of-recovery record persists the data checksum state without
7054 : : * flushing the buffer pool, but the control file may only claim "on" once
7055 : : * every page on disk carries a checksum. If replay entered that state
7056 : : * without a restartpoint following it, the pages rewritten by the
7057 : : * transition are still only in the buffer pool, so take the full
7058 : : * checkpoint below instead of the lightweight record.
7059 : : */
7060 : 174 : SpinLockAcquire(&XLogCtl->info_lck);
7061 : 174 : checksum_state = XLogCtl->data_checksum_version;
7062 : 174 : SpinLockRelease(&XLogCtl->info_lck);
7063 : :
7064 [ + + ]: 345 : flushForChecksums = (checksum_state == PG_DATA_CHECKSUM_VERSION &&
7065 [ + + ]: 171 : ControlFile->data_checksum_version != checksum_state);
7066 : :
7067 : : /*
7068 : : * Perform a checkpoint to update all our recovery activity to disk.
7069 : : *
7070 : : * Note that we write a shutdown checkpoint rather than an on-line one.
7071 : : * This is not particularly critical, but since we may be assigning a new
7072 : : * TLI, using a shutdown checkpoint allows us to have the rule that TLI
7073 : : * only changes in shutdown checkpoints, which allows some extra error
7074 : : * checking in xlog_redo.
7075 : : *
7076 : : * In promotion, only create a lightweight end-of-recovery record instead
7077 : : * of a full checkpoint. A checkpoint is requested later, after we're
7078 : : * fully out of recovery mode and already accepting queries.
7079 : : */
7080 [ + + + - : 238 : if (ArchiveRecoveryRequested && IsUnderPostmaster &&
+ + ]
7081 [ + + ]: 121 : PromoteIsTriggered() && !flushForChecksums)
7082 : : {
7083 : 56 : promoted = true;
7084 : :
7085 : : /*
7086 : : * Insert a special WAL record to mark the end of recovery, since we
7087 : : * aren't doing a checkpoint. That means that the checkpointer process
7088 : : * may likely be in the middle of a time-smoothed restartpoint and
7089 : : * could continue to be for minutes after this. That sounds strange,
7090 : : * but the effect is roughly the same and it would be stranger to try
7091 : : * to come out of the restartpoint and then checkpoint. We request a
7092 : : * checkpoint later anyway, just for safety.
7093 : : */
7094 : 56 : CreateEndOfRecoveryRecord();
7095 : : }
7096 : : else
7097 : : {
7098 : 118 : RequestCheckpoint(CHECKPOINT_END_OF_RECOVERY |
7099 : : CHECKPOINT_FAST |
7100 : : CHECKPOINT_WAIT);
7101 : : }
7102 : :
7103 : 174 : return promoted;
7104 : : }
7105 : :
7106 : : /*
7107 : : * Is the system still in recovery?
7108 : : *
7109 : : * Unlike testing InRecovery, this works in any process that's connected to
7110 : : * shared memory.
7111 : : */
7112 : : bool
7113 : 80195269 : RecoveryInProgress(void)
7114 : : {
7115 : : /*
7116 : : * We check shared state each time only until we leave recovery mode. We
7117 : : * can't re-enter recovery, so there's no need to keep checking after the
7118 : : * shared variable has once been seen false.
7119 : : */
7120 [ + + ]: 80195269 : if (!LocalRecoveryInProgress)
7121 : 77994838 : return false;
7122 : : else
7123 : : {
7124 : : /*
7125 : : * use volatile pointer to make sure we make a fresh read of the
7126 : : * shared variable.
7127 : : */
7128 : 2200431 : volatile XLogCtlData *xlogctl = XLogCtl;
7129 : :
7130 : 2200431 : LocalRecoveryInProgress = (xlogctl->SharedRecoveryState != RECOVERY_STATE_DONE);
7131 : :
7132 : : /*
7133 : : * Note: We don't need a memory barrier when we're still in recovery.
7134 : : * We might exit recovery immediately after return, so the caller
7135 : : * can't rely on 'true' meaning that we're still in recovery anyway.
7136 : : */
7137 : :
7138 : 2200431 : return LocalRecoveryInProgress;
7139 : : }
7140 : : }
7141 : :
7142 : : /*
7143 : : * Returns current recovery state from shared memory.
7144 : : *
7145 : : * This returned state is kept consistent with the contents of the control
7146 : : * file. See details about the possible values of RecoveryState in xlog.h.
7147 : : */
7148 : : RecoveryState
7149 : 30441 : GetRecoveryState(void)
7150 : : {
7151 : : RecoveryState retval;
7152 : :
7153 : 30441 : SpinLockAcquire(&XLogCtl->info_lck);
7154 : 30441 : retval = XLogCtl->SharedRecoveryState;
7155 : 30441 : SpinLockRelease(&XLogCtl->info_lck);
7156 : :
7157 : 30441 : return retval;
7158 : : }
7159 : :
7160 : : /*
7161 : : * Is this process allowed to insert new WAL records?
7162 : : *
7163 : : * Ordinarily this is essentially equivalent to !RecoveryInProgress().
7164 : : * But we also have provisions for forcing the result "true" or "false"
7165 : : * within specific processes regardless of the global state.
7166 : : */
7167 : : bool
7168 : 68737049 : XLogInsertAllowed(void)
7169 : : {
7170 : : /*
7171 : : * If value is "unconditionally true" or "unconditionally false", just
7172 : : * return it. This provides the normal fast path once recovery is known
7173 : : * done.
7174 : : */
7175 [ + + ]: 68737049 : if (LocalXLogInsertAllowed >= 0)
7176 : 67977998 : return (bool) LocalXLogInsertAllowed;
7177 : :
7178 : : /*
7179 : : * Else, must check to see if we're still in recovery.
7180 : : */
7181 [ + + ]: 759051 : if (RecoveryInProgress())
7182 : 748046 : return false;
7183 : :
7184 : : /*
7185 : : * On exit from recovery, reset to "unconditionally true", since there is
7186 : : * no need to keep checking.
7187 : : */
7188 : 11005 : LocalXLogInsertAllowed = 1;
7189 : 11005 : return true;
7190 : : }
7191 : :
7192 : : /*
7193 : : * Make XLogInsertAllowed() return true in the current process only.
7194 : : *
7195 : : * Note: it is allowed to switch LocalXLogInsertAllowed back to -1 later,
7196 : : * and even call LocalSetXLogInsertAllowed() again after that.
7197 : : *
7198 : : * Returns the previous value of LocalXLogInsertAllowed.
7199 : : */
7200 : : static int
7201 : 1089 : LocalSetXLogInsertAllowed(void)
7202 : : {
7203 : 1089 : int oldXLogAllowed = LocalXLogInsertAllowed;
7204 : :
7205 : 1089 : LocalXLogInsertAllowed = 1;
7206 : :
7207 : 1089 : return oldXLogAllowed;
7208 : : }
7209 : :
7210 : : /*
7211 : : * Return the current Redo pointer from shared memory.
7212 : : *
7213 : : * As a side-effect, the local RedoRecPtr copy is updated.
7214 : : */
7215 : : XLogRecPtr
7216 : 370818 : GetRedoRecPtr(void)
7217 : : {
7218 : : XLogRecPtr ptr;
7219 : :
7220 : : /*
7221 : : * The possibly not up-to-date copy in XLogCtl is enough. Even if we
7222 : : * grabbed a WAL insertion lock to read the authoritative value in
7223 : : * Insert->RedoRecPtr, someone might update it just after we've released
7224 : : * the lock.
7225 : : */
7226 : 370818 : SpinLockAcquire(&XLogCtl->info_lck);
7227 : 370818 : ptr = XLogCtl->RedoRecPtr;
7228 : 370818 : SpinLockRelease(&XLogCtl->info_lck);
7229 : :
7230 [ + + ]: 370818 : if (RedoRecPtr < ptr)
7231 : 1799 : RedoRecPtr = ptr;
7232 : :
7233 : 370818 : return RedoRecPtr;
7234 : : }
7235 : :
7236 : : /*
7237 : : * Return information needed to decide whether a modified block needs a
7238 : : * full-page image to be included in the WAL record.
7239 : : *
7240 : : * The returned values are cached copies from backend-private memory, and
7241 : : * possibly out-of-date or, indeed, uninitialized, in which case they will
7242 : : * be InvalidXLogRecPtr and false, respectively. XLogInsertRecord will
7243 : : * re-check them against up-to-date values, while holding the WAL insert lock.
7244 : : */
7245 : : void
7246 : 25409338 : GetFullPageWriteInfo(XLogRecPtr *RedoRecPtr_p, bool *doPageWrites_p)
7247 : : {
7248 : 25409338 : *RedoRecPtr_p = RedoRecPtr;
7249 : 25409338 : *doPageWrites_p = doPageWrites;
7250 : 25409338 : }
7251 : :
7252 : : /*
7253 : : * GetInsertRecPtr -- Returns the current insert position.
7254 : : *
7255 : : * NOTE: The value *actually* returned is the position of the last full
7256 : : * xlog page. It lags behind the real insert position by at most 1 page.
7257 : : * For that, we don't need to scan through WAL insertion locks, and an
7258 : : * approximation is enough for the current usage of this function.
7259 : : */
7260 : : XLogRecPtr
7261 : 7349 : GetInsertRecPtr(void)
7262 : : {
7263 : : XLogRecPtr recptr;
7264 : :
7265 : 7349 : SpinLockAcquire(&XLogCtl->info_lck);
7266 : 7349 : recptr = XLogCtl->LogwrtRqst.Write;
7267 : 7349 : SpinLockRelease(&XLogCtl->info_lck);
7268 : :
7269 : 7349 : return recptr;
7270 : : }
7271 : :
7272 : : /*
7273 : : * GetFlushRecPtr -- Returns the current flush position, ie, the last WAL
7274 : : * position known to be fsync'd to disk. This should only be used on a
7275 : : * system that is known not to be in recovery.
7276 : : */
7277 : : XLogRecPtr
7278 : 247669 : GetFlushRecPtr(TimeLineID *insertTLI)
7279 : : {
7280 : : Assert(XLogCtl->SharedRecoveryState == RECOVERY_STATE_DONE);
7281 : :
7282 : 247669 : RefreshXLogWriteResult(LogwrtResult);
7283 : :
7284 : : /*
7285 : : * If we're writing and flushing WAL, the time line can't be changing, so
7286 : : * no lock is required.
7287 : : */
7288 [ + + ]: 247669 : if (insertTLI)
7289 : 49975 : *insertTLI = XLogCtl->InsertTimeLineID;
7290 : :
7291 : 247669 : return LogwrtResult.Flush;
7292 : : }
7293 : :
7294 : : /*
7295 : : * GetWALInsertionTimeLine -- Returns the current timeline of a system that
7296 : : * is not in recovery.
7297 : : */
7298 : : TimeLineID
7299 : 120721 : GetWALInsertionTimeLine(void)
7300 : : {
7301 : : Assert(XLogCtl->SharedRecoveryState == RECOVERY_STATE_DONE);
7302 : :
7303 : : /* Since the value can't be changing, no lock is required. */
7304 : 120721 : return XLogCtl->InsertTimeLineID;
7305 : : }
7306 : :
7307 : : /*
7308 : : * GetWALInsertionTimeLineIfSet -- If the system is not in recovery, returns
7309 : : * the WAL insertion timeline; else, returns 0. Wherever possible, use
7310 : : * GetWALInsertionTimeLine() instead, since it's cheaper. Note that this
7311 : : * function decides recovery has ended as soon as the insert TLI is set, which
7312 : : * happens before we set XLogCtl->SharedRecoveryState to RECOVERY_STATE_DONE.
7313 : : */
7314 : : TimeLineID
7315 : 2028 : GetWALInsertionTimeLineIfSet(void)
7316 : : {
7317 : : TimeLineID insertTLI;
7318 : :
7319 : 2028 : SpinLockAcquire(&XLogCtl->info_lck);
7320 : 2028 : insertTLI = XLogCtl->InsertTimeLineID;
7321 : 2028 : SpinLockRelease(&XLogCtl->info_lck);
7322 : :
7323 : 2028 : return insertTLI;
7324 : : }
7325 : :
7326 : : /*
7327 : : * GetLastImportantRecPtr -- Returns the LSN of the last important record
7328 : : * inserted. All records not explicitly marked as unimportant are considered
7329 : : * important.
7330 : : *
7331 : : * The LSN is determined by computing the maximum of
7332 : : * WALInsertLocks[i].lastImportantAt.
7333 : : */
7334 : : XLogRecPtr
7335 : 1860 : GetLastImportantRecPtr(void)
7336 : : {
7337 : 1860 : XLogRecPtr res = InvalidXLogRecPtr;
7338 : : int i;
7339 : :
7340 [ + + ]: 16740 : for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
7341 : : {
7342 : : XLogRecPtr last_important;
7343 : :
7344 : : /*
7345 : : * Need to take a lock to prevent torn reads of the LSN, which are
7346 : : * possible on some of the supported platforms. WAL insert locks only
7347 : : * support exclusive mode, so we have to use that.
7348 : : */
7349 : 14880 : LWLockAcquire(&WALInsertLocks[i].l.lock, LW_EXCLUSIVE);
7350 : 14880 : last_important = WALInsertLocks[i].l.lastImportantAt;
7351 : 14880 : LWLockRelease(&WALInsertLocks[i].l.lock);
7352 : :
7353 [ + + ]: 14880 : if (res < last_important)
7354 : 3193 : res = last_important;
7355 : : }
7356 : :
7357 : 1860 : return res;
7358 : : }
7359 : :
7360 : : /*
7361 : : * Get the time and LSN of the last xlog segment switch
7362 : : */
7363 : : pg_time_t
7364 : 0 : GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
7365 : : {
7366 : : pg_time_t result;
7367 : :
7368 : : /* Need WALWriteLock, but shared lock is sufficient */
7369 : 0 : LWLockAcquire(WALWriteLock, LW_SHARED);
7370 : 0 : result = XLogCtl->lastSegSwitchTime;
7371 : 0 : *lastSwitchLSN = XLogCtl->lastSegSwitchLSN;
7372 : 0 : LWLockRelease(WALWriteLock);
7373 : :
7374 : 0 : return result;
7375 : : }
7376 : :
7377 : : /*
7378 : : * This must be called ONCE during postmaster or standalone-backend shutdown
7379 : : */
7380 : : void
7381 : 806 : ShutdownXLOG(int code, Datum arg)
7382 : : {
7383 : : /*
7384 : : * We should have an aux process resource owner to use, and we should not
7385 : : * be in a transaction that's installed some other resowner.
7386 : : */
7387 : : Assert(AuxProcessResourceOwner != NULL);
7388 : : Assert(CurrentResourceOwner == NULL ||
7389 : : CurrentResourceOwner == AuxProcessResourceOwner);
7390 : 806 : CurrentResourceOwner = AuxProcessResourceOwner;
7391 : :
7392 : : /* Don't be chatty in standalone mode */
7393 [ + + + + ]: 806 : ereport(IsPostmasterEnvironment ? LOG : NOTICE,
7394 : : (errmsg("shutting down")));
7395 : :
7396 : : /*
7397 : : * Signal walsenders to move to stopping state.
7398 : : */
7399 : 806 : WalSndInitStopping();
7400 : :
7401 : : /*
7402 : : * Wait for WAL senders to be in stopping state. This prevents commands
7403 : : * from writing new WAL.
7404 : : */
7405 : 806 : WalSndWaitStopping();
7406 : :
7407 [ + + ]: 806 : if (RecoveryInProgress())
7408 : 69 : CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FAST);
7409 : : else
7410 : : {
7411 : : /*
7412 : : * If archiving is enabled, rotate the last XLOG file so that all the
7413 : : * remaining records are archived (postmaster wakes up the archiver
7414 : : * process one more time at the end of shutdown). The checkpoint
7415 : : * record will go to the next XLOG file and won't be archived (yet).
7416 : : */
7417 [ + + ]: 737 : if (XLogArchivingActive())
7418 : 18 : RequestXLogSwitch(false);
7419 : :
7420 : 737 : CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FAST);
7421 : : }
7422 : 806 : }
7423 : :
7424 : : /*
7425 : : * Format checkpoint request flags as a space-separated string for
7426 : : * log messages.
7427 : : */
7428 : : static const char *
7429 : 3340 : CheckpointFlagsString(int flags)
7430 : : {
7431 : : static char buf[128];
7432 : :
7433 : 26720 : snprintf(buf, sizeof(buf), "%s%s%s%s%s%s%s%s",
7434 [ + + ]: 3340 : (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
7435 [ + + ]: 3340 : (flags & CHECKPOINT_END_OF_RECOVERY) ? " end-of-recovery" : "",
7436 [ + + ]: 3340 : (flags & CHECKPOINT_FAST) ? " fast" : "",
7437 [ + + ]: 3340 : (flags & CHECKPOINT_FORCE) ? " force" : "",
7438 [ + + ]: 3340 : (flags & CHECKPOINT_WAIT) ? " wait" : "",
7439 [ + + ]: 3340 : (flags & CHECKPOINT_CAUSE_XLOG) ? " wal" : "",
7440 [ + + ]: 3340 : (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "",
7441 [ + + ]: 3340 : (flags & CHECKPOINT_FLUSH_UNLOGGED) ? " flush-unlogged" : "");
7442 : :
7443 : 3340 : return buf;
7444 : : }
7445 : :
7446 : : /*
7447 : : * Log start of a checkpoint.
7448 : : */
7449 : : static void
7450 : 1670 : LogCheckpointStart(int flags, bool restartpoint)
7451 : : {
7452 [ + + ]: 1670 : if (restartpoint)
7453 [ + - ]: 212 : ereport(LOG,
7454 : : /* translator: the placeholder shows checkpoint options */
7455 : : (errmsg("restartpoint starting:%s",
7456 : : CheckpointFlagsString(flags))));
7457 : : else
7458 [ + - ]: 1458 : ereport(LOG,
7459 : : /* translator: the placeholder shows checkpoint options */
7460 : : (errmsg("checkpoint starting:%s",
7461 : : CheckpointFlagsString(flags))));
7462 : 1670 : }
7463 : :
7464 : : /*
7465 : : * Log end of a checkpoint.
7466 : : */
7467 : : static void
7468 : 2016 : LogCheckpointEnd(bool restartpoint, int flags)
7469 : : {
7470 : : long write_msecs,
7471 : : sync_msecs,
7472 : : total_msecs,
7473 : : longest_msecs,
7474 : : average_msecs;
7475 : : uint64 average_sync_time;
7476 : :
7477 : 2016 : CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
7478 : :
7479 : 2016 : write_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_write_t,
7480 : : CheckpointStats.ckpt_sync_t);
7481 : :
7482 : 2016 : sync_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_sync_t,
7483 : : CheckpointStats.ckpt_sync_end_t);
7484 : :
7485 : : /* Accumulate checkpoint timing summary data, in milliseconds. */
7486 : 2016 : PendingCheckpointerStats.write_time += write_msecs;
7487 : 2016 : PendingCheckpointerStats.sync_time += sync_msecs;
7488 : :
7489 : : /*
7490 : : * All of the published timing statistics are accounted for. Only
7491 : : * continue if a log message is to be written.
7492 : : */
7493 [ + + ]: 2016 : if (!log_checkpoints)
7494 : 346 : return;
7495 : :
7496 : 1670 : total_msecs = TimestampDifferenceMilliseconds(CheckpointStats.ckpt_start_t,
7497 : : CheckpointStats.ckpt_end_t);
7498 : :
7499 : : /*
7500 : : * Timing values returned from CheckpointStats are in microseconds.
7501 : : * Convert to milliseconds for consistent printing.
7502 : : */
7503 : 1670 : longest_msecs = (long) ((CheckpointStats.ckpt_longest_sync + 999) / 1000);
7504 : :
7505 : 1670 : average_sync_time = 0;
7506 [ - + ]: 1670 : if (CheckpointStats.ckpt_sync_rels > 0)
7507 : 0 : average_sync_time = CheckpointStats.ckpt_agg_sync_time /
7508 : 0 : CheckpointStats.ckpt_sync_rels;
7509 : 1670 : average_msecs = (long) ((average_sync_time + 999) / 1000);
7510 : :
7511 : : /*
7512 : : * ControlFileLock is not required to see ControlFile->checkPoint and
7513 : : * ->checkPointCopy here as we are the only updator of those variables at
7514 : : * this moment.
7515 : : */
7516 [ + + ]: 1670 : if (restartpoint)
7517 [ + - ]: 212 : ereport(LOG,
7518 : : (errmsg("restartpoint complete:%s: wrote %d buffers (%.1f%%), "
7519 : : "wrote %d SLRU buffers; %d WAL file(s) added, "
7520 : : "%d removed, %d recycled; write=%ld.%03d s, "
7521 : : "sync=%ld.%03d s, total=%ld.%03d s; sync files=%d, "
7522 : : "longest=%ld.%03d s, average=%ld.%03d s; distance=%d kB, "
7523 : : "estimate=%d kB; lsn=%X/%08X, redo lsn=%X/%08X",
7524 : : CheckpointFlagsString(flags),
7525 : : CheckpointStats.ckpt_bufs_written,
7526 : : (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
7527 : : CheckpointStats.ckpt_slru_written,
7528 : : CheckpointStats.ckpt_segs_added,
7529 : : CheckpointStats.ckpt_segs_removed,
7530 : : CheckpointStats.ckpt_segs_recycled,
7531 : : write_msecs / 1000, (int) (write_msecs % 1000),
7532 : : sync_msecs / 1000, (int) (sync_msecs % 1000),
7533 : : total_msecs / 1000, (int) (total_msecs % 1000),
7534 : : CheckpointStats.ckpt_sync_rels,
7535 : : longest_msecs / 1000, (int) (longest_msecs % 1000),
7536 : : average_msecs / 1000, (int) (average_msecs % 1000),
7537 : : (int) (PrevCheckPointDistance / 1024.0),
7538 : : (int) (CheckPointDistanceEstimate / 1024.0),
7539 : : LSN_FORMAT_ARGS(ControlFile->checkPoint),
7540 : : LSN_FORMAT_ARGS(ControlFile->checkPointCopy.redo))));
7541 : : else
7542 [ + - ]: 1458 : ereport(LOG,
7543 : : (errmsg("checkpoint complete:%s: wrote %d buffers (%.1f%%), "
7544 : : "wrote %d SLRU buffers; %d WAL file(s) added, "
7545 : : "%d removed, %d recycled; write=%ld.%03d s, "
7546 : : "sync=%ld.%03d s, total=%ld.%03d s; sync files=%d, "
7547 : : "longest=%ld.%03d s, average=%ld.%03d s; distance=%d kB, "
7548 : : "estimate=%d kB; lsn=%X/%08X, redo lsn=%X/%08X",
7549 : : CheckpointFlagsString(flags),
7550 : : CheckpointStats.ckpt_bufs_written,
7551 : : (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
7552 : : CheckpointStats.ckpt_slru_written,
7553 : : CheckpointStats.ckpt_segs_added,
7554 : : CheckpointStats.ckpt_segs_removed,
7555 : : CheckpointStats.ckpt_segs_recycled,
7556 : : write_msecs / 1000, (int) (write_msecs % 1000),
7557 : : sync_msecs / 1000, (int) (sync_msecs % 1000),
7558 : : total_msecs / 1000, (int) (total_msecs % 1000),
7559 : : CheckpointStats.ckpt_sync_rels,
7560 : : longest_msecs / 1000, (int) (longest_msecs % 1000),
7561 : : average_msecs / 1000, (int) (average_msecs % 1000),
7562 : : (int) (PrevCheckPointDistance / 1024.0),
7563 : : (int) (CheckPointDistanceEstimate / 1024.0),
7564 : : LSN_FORMAT_ARGS(ControlFile->checkPoint),
7565 : : LSN_FORMAT_ARGS(ControlFile->checkPointCopy.redo))));
7566 : : }
7567 : :
7568 : : /*
7569 : : * Update the estimate of distance between checkpoints.
7570 : : *
7571 : : * The estimate is used to calculate the number of WAL segments to keep
7572 : : * preallocated, see XLOGfileslop().
7573 : : */
7574 : : static void
7575 : 2016 : UpdateCheckPointDistanceEstimate(uint64 nbytes)
7576 : : {
7577 : : /*
7578 : : * To estimate the number of segments consumed between checkpoints, keep a
7579 : : * moving average of the amount of WAL generated in previous checkpoint
7580 : : * cycles. However, if the load is bursty, with quiet periods and busy
7581 : : * periods, we want to cater for the peak load. So instead of a plain
7582 : : * moving average, let the average decline slowly if the previous cycle
7583 : : * used less WAL than estimated, but bump it up immediately if it used
7584 : : * more.
7585 : : *
7586 : : * When checkpoints are triggered by max_wal_size, this should converge to
7587 : : * CheckpointSegments * wal_segment_size,
7588 : : *
7589 : : * Note: This doesn't pay any attention to what caused the checkpoint.
7590 : : * Checkpoints triggered manually with CHECKPOINT command, or by e.g.
7591 : : * starting a base backup, are counted the same as those created
7592 : : * automatically. The slow-decline will largely mask them out, if they are
7593 : : * not frequent. If they are frequent, it seems reasonable to count them
7594 : : * in as any others; if you issue a manual checkpoint every 5 minutes and
7595 : : * never let a timed checkpoint happen, it makes sense to base the
7596 : : * preallocation on that 5 minute interval rather than whatever
7597 : : * checkpoint_timeout is set to.
7598 : : */
7599 : 2016 : PrevCheckPointDistance = nbytes;
7600 [ + + ]: 2016 : if (CheckPointDistanceEstimate < nbytes)
7601 : 913 : CheckPointDistanceEstimate = nbytes;
7602 : : else
7603 : 1103 : CheckPointDistanceEstimate =
7604 : 1103 : (0.90 * CheckPointDistanceEstimate + 0.10 * (double) nbytes);
7605 : 2016 : }
7606 : :
7607 : : /*
7608 : : * Update the ps display for a process running a checkpoint. Note that
7609 : : * this routine should not do any allocations so as it can be called
7610 : : * from a critical section.
7611 : : */
7612 : : static void
7613 : 4032 : update_checkpoint_display(int flags, bool restartpoint, bool reset)
7614 : : {
7615 : : /*
7616 : : * The status is reported only for end-of-recovery and shutdown
7617 : : * checkpoints or shutdown restartpoints. Updating the ps display is
7618 : : * useful in those situations as it may not be possible to rely on
7619 : : * pg_stat_activity to see the status of the checkpointer or the startup
7620 : : * process.
7621 : : */
7622 [ + + ]: 4032 : if ((flags & (CHECKPOINT_END_OF_RECOVERY | CHECKPOINT_IS_SHUTDOWN)) == 0)
7623 : 2444 : return;
7624 : :
7625 [ + + ]: 1588 : if (reset)
7626 : 794 : set_ps_display("");
7627 : : else
7628 : : {
7629 : : char activitymsg[128];
7630 : :
7631 [ + + ]: 2382 : snprintf(activitymsg, sizeof(activitymsg), "performing %s%s%s",
7632 [ + + ]: 794 : (flags & CHECKPOINT_END_OF_RECOVERY) ? "end-of-recovery " : "",
7633 [ + + ]: 794 : (flags & CHECKPOINT_IS_SHUTDOWN) ? "shutdown " : "",
7634 : : restartpoint ? "restartpoint" : "checkpoint");
7635 : 794 : set_ps_display(activitymsg);
7636 : : }
7637 : : }
7638 : :
7639 : :
7640 : : /*
7641 : : * Perform a checkpoint --- either during shutdown, or on-the-fly
7642 : : *
7643 : : * flags is a bitwise OR of the following:
7644 : : * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
7645 : : * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
7646 : : * CHECKPOINT_FAST: finish the checkpoint ASAP, ignoring
7647 : : * checkpoint_completion_target parameter.
7648 : : * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
7649 : : * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
7650 : : * CHECKPOINT_END_OF_RECOVERY).
7651 : : * CHECKPOINT_FLUSH_UNLOGGED: also flush buffers of unlogged tables.
7652 : : *
7653 : : * Note: flags contains other bits, of interest here only for logging purposes.
7654 : : * In particular note that this routine is synchronous and does not pay
7655 : : * attention to CHECKPOINT_WAIT.
7656 : : *
7657 : : * If !shutdown then we are writing an online checkpoint. An XLOG_CHECKPOINT_REDO
7658 : : * record is inserted into WAL at the logical location of the checkpoint, before
7659 : : * flushing anything to disk, and when the checkpoint is eventually completed,
7660 : : * and it is from this point that WAL replay will begin in the case of a recovery
7661 : : * from this checkpoint. Once everything is written to disk, an
7662 : : * XLOG_CHECKPOINT_ONLINE record is written to complete the checkpoint, and
7663 : : * points back to the earlier XLOG_CHECKPOINT_REDO record. This mechanism allows
7664 : : * other write-ahead log records to be written while the checkpoint is in
7665 : : * progress, but we must be very careful about order of operations. This function
7666 : : * may take many minutes to execute on a busy system.
7667 : : *
7668 : : * On the other hand, when shutdown is true, concurrent insertion into the
7669 : : * write-ahead log is impossible, so there is no need for two separate records.
7670 : : * In this case, we only insert an XLOG_CHECKPOINT_SHUTDOWN record, and it's
7671 : : * both the record marking the completion of the checkpoint and the location
7672 : : * from which WAL replay would begin if needed.
7673 : : *
7674 : : * Returns true if a new checkpoint was performed, or false if it was skipped
7675 : : * because the system was idle.
7676 : : */
7677 : : bool
7678 : 1806 : CreateCheckPoint(int flags)
7679 : : {
7680 : : bool shutdown;
7681 : : CheckPoint checkPoint;
7682 : : XLogRecPtr recptr;
7683 : : XLogSegNo _logSegNo;
7684 : 1806 : XLogCtlInsert *Insert = &XLogCtl->Insert;
7685 : : uint32 freespace;
7686 : : XLogRecPtr PriorRedoPtr;
7687 : : XLogRecPtr last_important_lsn;
7688 : : XLogRecPtr checksumLsn;
7689 : : VirtualTransactionId *vxids;
7690 : : int nvxids;
7691 : 1806 : int oldXLogAllowed = 0;
7692 : :
7693 : : /*
7694 : : * An end-of-recovery checkpoint is really a shutdown checkpoint, just
7695 : : * issued at a different time.
7696 : : */
7697 [ + + ]: 1806 : if (flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY))
7698 : 769 : shutdown = true;
7699 : : else
7700 : 1037 : shutdown = false;
7701 : :
7702 : : /* sanity check */
7703 [ + + - + ]: 1806 : if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
7704 [ # # ]: 0 : elog(ERROR, "can't create a checkpoint during recovery");
7705 : :
7706 : : /*
7707 : : * Prepare to accumulate statistics.
7708 : : *
7709 : : * Note: because it is possible for log_checkpoints to change while a
7710 : : * checkpoint proceeds, we always accumulate stats, even if
7711 : : * log_checkpoints is currently off.
7712 : : */
7713 [ + - + - : 19866 : MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
+ - + - +
+ ]
7714 : 1806 : CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
7715 : :
7716 : : /*
7717 : : * Let smgr prepare for checkpoint; this has to happen outside the
7718 : : * critical section and before we determine the REDO pointer. Note that
7719 : : * smgr must not do anything that'd have to be undone if we decide no
7720 : : * checkpoint is needed.
7721 : : */
7722 : 1806 : SyncPreCheckpoint();
7723 : :
7724 : : /* Run these points outside the critical section. */
7725 : 1806 : INJECTION_POINT("create-checkpoint-initial", NULL);
7726 : 1806 : INJECTION_POINT_LOAD("create-checkpoint-run");
7727 : :
7728 : : /*
7729 : : * Use a critical section to force system panic if we have trouble.
7730 : : */
7731 : 1806 : START_CRIT_SECTION();
7732 : :
7733 [ + + ]: 1806 : if (shutdown)
7734 : : {
7735 : 769 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7736 : 769 : ControlFile->state = DB_SHUTDOWNING;
7737 : 769 : UpdateControlFile();
7738 : 769 : LWLockRelease(ControlFileLock);
7739 : : }
7740 : :
7741 : : /* Begin filling in the checkpoint WAL record */
7742 [ + - + - : 25284 : MemSet(&checkPoint, 0, sizeof(checkPoint));
+ - + - +
+ ]
7743 : 1806 : checkPoint.time = (pg_time_t) time(NULL);
7744 : :
7745 : : /*
7746 : : * For Hot Standby, derive the oldestActiveXid before we fix the redo
7747 : : * pointer. This allows us to begin accumulating changes to assemble our
7748 : : * starting snapshot of locks and transactions.
7749 : : */
7750 [ + + + + ]: 1806 : if (!shutdown && XLogStandbyInfoActive())
7751 : 975 : checkPoint.oldestActiveXid = GetOldestActiveTransactionId(false, true);
7752 : : else
7753 : 831 : checkPoint.oldestActiveXid = InvalidTransactionId;
7754 : :
7755 : : /*
7756 : : * Get location of last important record before acquiring insert locks (as
7757 : : * GetLastImportantRecPtr() also locks WAL locks).
7758 : : */
7759 : 1806 : last_important_lsn = GetLastImportantRecPtr();
7760 : :
7761 : : /*
7762 : : * If this isn't a shutdown or forced checkpoint, and if there has been no
7763 : : * WAL activity requiring a checkpoint, skip it. The idea here is to
7764 : : * avoid inserting duplicate checkpoints when the system is idle.
7765 : : */
7766 [ + + ]: 1806 : if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
7767 : : CHECKPOINT_FORCE)) == 0)
7768 : : {
7769 [ + + ]: 202 : if (last_important_lsn == ControlFile->checkPoint)
7770 : : {
7771 : 2 : END_CRIT_SECTION();
7772 [ - + ]: 2 : ereport(DEBUG1,
7773 : : (errmsg_internal("checkpoint skipped because system is idle")));
7774 : 2 : return false;
7775 : : }
7776 : : }
7777 : :
7778 : : /*
7779 : : * An end-of-recovery checkpoint is created before anyone is allowed to
7780 : : * write WAL. To allow us to write the checkpoint record, temporarily
7781 : : * enable XLogInsertAllowed.
7782 : : */
7783 [ + + ]: 1804 : if (flags & CHECKPOINT_END_OF_RECOVERY)
7784 : 32 : oldXLogAllowed = LocalSetXLogInsertAllowed();
7785 : :
7786 : 1804 : checkPoint.ThisTimeLineID = XLogCtl->InsertTimeLineID;
7787 [ + + ]: 1804 : if (flags & CHECKPOINT_END_OF_RECOVERY)
7788 : 32 : checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
7789 : : else
7790 : 1772 : checkPoint.PrevTimeLineID = checkPoint.ThisTimeLineID;
7791 : :
7792 : : /*
7793 : : * We must block concurrent insertions while examining insert state.
7794 : : */
7795 : 1804 : WALInsertLockAcquireExclusive();
7796 : :
7797 : 1804 : checkPoint.fullPageWrites = Insert->fullPageWrites;
7798 : 1804 : checkPoint.wal_level = wal_level;
7799 : :
7800 : : /*
7801 : : * Get the current data_checksum_version value from xlogctl. This is
7802 : : * final only for a shutdown checkpoint, where no concurrent transition is
7803 : : * possible; an online checkpoint resamples it together with the redo
7804 : : * record below.
7805 : : */
7806 : 1804 : SpinLockAcquire(&XLogCtl->info_lck);
7807 : 1804 : checkPoint.dataChecksumState = XLogCtl->data_checksum_version;
7808 : 1804 : checksumLsn = XLogCtl->data_checksum_lsn;
7809 : 1804 : SpinLockRelease(&XLogCtl->info_lck);
7810 : :
7811 [ + + ]: 1804 : if (shutdown)
7812 : : {
7813 : 769 : XLogRecPtr curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
7814 : :
7815 : : /*
7816 : : * Compute new REDO record ptr = location of next XLOG record.
7817 : : *
7818 : : * Since this is a shutdown checkpoint, there can't be any concurrent
7819 : : * WAL insertion.
7820 : : */
7821 [ + - ]: 769 : freespace = INSERT_FREESPACE(curInsert);
7822 [ - + ]: 769 : if (freespace == 0)
7823 : : {
7824 [ # # ]: 0 : if (XLogSegmentOffset(curInsert, wal_segment_size) == 0)
7825 : 0 : curInsert += SizeOfXLogLongPHD;
7826 : : else
7827 : 0 : curInsert += SizeOfXLogShortPHD;
7828 : : }
7829 : 769 : checkPoint.redo = curInsert;
7830 : :
7831 : : /*
7832 : : * Here we update the shared RedoRecPtr for future XLogInsert calls;
7833 : : * this must be done while holding all the insertion locks.
7834 : : *
7835 : : * Note: if we fail to complete the checkpoint, RedoRecPtr will be
7836 : : * left pointing past where it really needs to point. This is okay;
7837 : : * the only consequence is that XLogInsert might back up whole buffers
7838 : : * that it didn't really need to. We can't postpone advancing
7839 : : * RedoRecPtr because XLogInserts that happen while we are dumping
7840 : : * buffers must assume that their buffer changes are not included in
7841 : : * the checkpoint.
7842 : : */
7843 : 769 : RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
7844 : : }
7845 : :
7846 : : /*
7847 : : * Now we can release the WAL insertion locks, allowing other xacts to
7848 : : * proceed while we are flushing disk buffers.
7849 : : */
7850 : 1804 : WALInsertLockRelease();
7851 : :
7852 : : /*
7853 : : * If this is an online checkpoint, we have not yet determined the redo
7854 : : * point. We do so now by inserting the special XLOG_CHECKPOINT_REDO
7855 : : * record; the LSN at which it starts becomes the new redo pointer. We
7856 : : * don't do this for a shutdown checkpoint, because in that case no WAL
7857 : : * can be written between the redo point and the insertion of the
7858 : : * checkpoint record itself, so the checkpoint record itself serves to
7859 : : * mark the redo point.
7860 : : */
7861 [ + + ]: 1804 : if (!shutdown)
7862 : : {
7863 : : xl_checkpoint_redo redo_rec;
7864 : :
7865 : : /*
7866 : : * Sample the data checksum state and insert the redo record under
7867 : : * DataChecksumTransitionLock, so that a concurrent transition cannot
7868 : : * insert its XLOG2_CHECKSUMS record between the sampling and the
7869 : : * insertion below. Without this, the redo record could follow the
7870 : : * transition record in WAL while carrying the pre-transition state,
7871 : : * and recovery resuming here would never learn about the transition.
7872 : : * See XLogChecksums().
7873 : : */
7874 : 1035 : LWLockAcquire(DataChecksumTransitionLock, LW_EXCLUSIVE);
7875 : 1035 : WALInsertLockAcquire();
7876 : 1035 : redo_rec.wal_level = wal_level;
7877 : 1035 : SpinLockAcquire(&XLogCtl->info_lck);
7878 : 1035 : redo_rec.data_checksum_version = XLogCtl->data_checksum_version;
7879 : 1035 : checksumLsn = XLogCtl->data_checksum_lsn;
7880 : 1035 : SpinLockRelease(&XLogCtl->info_lck);
7881 : 1035 : WALInsertLockRelease();
7882 : :
7883 : : /* Include WAL level in record for WAL summarizer's benefit. */
7884 : 1035 : XLogBeginInsert();
7885 : 1035 : XLogRegisterData(&redo_rec, sizeof(xl_checkpoint_redo));
7886 : 1035 : (void) XLogInsert(RM_XLOG_ID, XLOG_CHECKPOINT_REDO);
7887 : 1035 : LWLockRelease(DataChecksumTransitionLock);
7888 : :
7889 : : /*
7890 : : * The checkpoint record must carry the same state as the redo record
7891 : : * just inserted: the sample taken before redo determination can be
7892 : : * stale by now, and the pair would otherwise disagree.
7893 : : */
7894 : 1035 : checkPoint.dataChecksumState = redo_rec.data_checksum_version;
7895 : :
7896 : : /*
7897 : : * XLogInsertRecord will have updated XLogCtl->Insert.RedoRecPtr in
7898 : : * shared memory and RedoRecPtr in backend-local memory, but we need
7899 : : * to copy that into the record that will be inserted when the
7900 : : * checkpoint is complete.
7901 : : */
7902 : 1035 : checkPoint.redo = RedoRecPtr;
7903 : : }
7904 : :
7905 : : /* Update the info_lck-protected copy of RedoRecPtr as well */
7906 : 1804 : SpinLockAcquire(&XLogCtl->info_lck);
7907 : 1804 : XLogCtl->RedoRecPtr = checkPoint.redo;
7908 : 1804 : SpinLockRelease(&XLogCtl->info_lck);
7909 : :
7910 : : /*
7911 : : * If enabled, log checkpoint start. We postpone this until now so as not
7912 : : * to log anything if we decided to skip the checkpoint.
7913 : : */
7914 [ + + ]: 1804 : if (log_checkpoints)
7915 : 1458 : LogCheckpointStart(flags, false);
7916 : :
7917 : 1804 : INJECTION_POINT_CACHED("create-checkpoint-run", NULL);
7918 : :
7919 : : /* Update the process title */
7920 : 1804 : update_checkpoint_display(flags, false, false);
7921 : :
7922 : : TRACE_POSTGRESQL_CHECKPOINT_START(flags);
7923 : :
7924 : : /*
7925 : : * Get the other info we need for the checkpoint record.
7926 : : *
7927 : : * We don't need to save oldestClogXid in the checkpoint, it only matters
7928 : : * for the short period in which clog is being truncated, and if we crash
7929 : : * during that we'll redo the clog truncation and fix up oldestClogXid
7930 : : * there.
7931 : : */
7932 : 1804 : LWLockAcquire(XidGenLock, LW_SHARED);
7933 : 1804 : checkPoint.nextXid = TransamVariables->nextXid;
7934 : 1804 : checkPoint.oldestXid = TransamVariables->oldestXid;
7935 : 1804 : checkPoint.oldestXidDB = TransamVariables->oldestXidDB;
7936 : 1804 : LWLockRelease(XidGenLock);
7937 : :
7938 : 1804 : LWLockAcquire(CommitTsLock, LW_SHARED);
7939 : 1804 : checkPoint.oldestCommitTsXid = TransamVariables->oldestCommitTsXid;
7940 : 1804 : checkPoint.newestCommitTsXid = TransamVariables->newestCommitTsXid;
7941 : 1804 : LWLockRelease(CommitTsLock);
7942 : :
7943 : 1804 : LWLockAcquire(OidGenLock, LW_SHARED);
7944 : 1804 : checkPoint.nextOid = TransamVariables->nextOid;
7945 [ + + ]: 1804 : if (!shutdown)
7946 : 1035 : checkPoint.nextOid += TransamVariables->oidCount;
7947 : 1804 : LWLockRelease(OidGenLock);
7948 : :
7949 : 1804 : checkPoint.logicalDecodingEnabled = IsLogicalDecodingEnabled();
7950 : :
7951 : 1804 : MultiXactGetCheckptMulti(shutdown,
7952 : : &checkPoint.nextMulti,
7953 : : &checkPoint.nextMultiOffset,
7954 : : &checkPoint.oldestMulti,
7955 : : &checkPoint.oldestMultiDB);
7956 : :
7957 : : /*
7958 : : * Having constructed the checkpoint record, ensure all shmem disk buffers
7959 : : * and commit-log buffers are flushed to disk.
7960 : : *
7961 : : * This I/O could fail for various reasons. If so, we will fail to
7962 : : * complete the checkpoint, but there is no reason to force a system
7963 : : * panic. Accordingly, exit critical section while doing it.
7964 : : */
7965 : 1804 : END_CRIT_SECTION();
7966 : :
7967 : : /*
7968 : : * In some cases there are groups of actions that must all occur on one
7969 : : * side or the other of a checkpoint record. Before flushing the
7970 : : * checkpoint record we must explicitly wait for any backend currently
7971 : : * performing those groups of actions.
7972 : : *
7973 : : * One example is end of transaction, so we must wait for any transactions
7974 : : * that are currently in commit critical sections. If an xact inserted
7975 : : * its commit record into XLOG just before the REDO point, then a crash
7976 : : * restart from the REDO point would not replay that record, which means
7977 : : * that our flushing had better include the xact's update of pg_xact. So
7978 : : * we wait till he's out of his commit critical section before proceeding.
7979 : : * See notes in RecordTransactionCommit().
7980 : : *
7981 : : * Because we've already released the insertion locks, this test is a bit
7982 : : * fuzzy: it is possible that we will wait for xacts we didn't really need
7983 : : * to wait for. But the delay should be short and it seems better to make
7984 : : * checkpoint take a bit longer than to hold off insertions longer than
7985 : : * necessary. (In fact, the whole reason we have this issue is that xact.c
7986 : : * does commit record XLOG insertion and clog update as two separate steps
7987 : : * protected by different locks, but again that seems best on grounds of
7988 : : * minimizing lock contention.)
7989 : : *
7990 : : * A transaction that has not yet set delayChkptFlags when we look cannot
7991 : : * be at risk, since it has not inserted its commit record yet; and one
7992 : : * that's already cleared it is not at risk either, since it's done fixing
7993 : : * clog and we will correctly flush the update below. So we cannot miss
7994 : : * any xacts we need to wait for.
7995 : : */
7996 : 1804 : vxids = GetVirtualXIDsDelayingChkpt(&nvxids, DELAY_CHKPT_START);
7997 [ + + ]: 1804 : if (nvxids > 0)
7998 : : {
7999 : : do
8000 : : {
8001 : : /*
8002 : : * Keep absorbing fsync requests while we wait. There could even
8003 : : * be a deadlock if we don't, if the process that prevents the
8004 : : * checkpoint is trying to add a request to the queue.
8005 : : */
8006 : 18 : AbsorbSyncRequests();
8007 : :
8008 : 18 : pgstat_report_wait_start(WAIT_EVENT_CHECKPOINT_DELAY_START);
8009 : 18 : pg_usleep(10000L); /* wait for 10 msec */
8010 : 18 : pgstat_report_wait_end();
8011 [ - + ]: 18 : } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids,
8012 : : DELAY_CHKPT_START));
8013 : : }
8014 : 1804 : pfree(vxids);
8015 : :
8016 : 1804 : CheckPointGuts(checkPoint.redo, flags);
8017 : :
8018 : 1804 : vxids = GetVirtualXIDsDelayingChkpt(&nvxids, DELAY_CHKPT_COMPLETE);
8019 [ - + ]: 1804 : if (nvxids > 0)
8020 : : {
8021 : : do
8022 : : {
8023 : 0 : AbsorbSyncRequests();
8024 : :
8025 : 0 : pgstat_report_wait_start(WAIT_EVENT_CHECKPOINT_DELAY_COMPLETE);
8026 : 0 : pg_usleep(10000L); /* wait for 10 msec */
8027 : 0 : pgstat_report_wait_end();
8028 [ # # ]: 0 : } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids,
8029 : : DELAY_CHKPT_COMPLETE));
8030 : : }
8031 : 1804 : pfree(vxids);
8032 : :
8033 : : /*
8034 : : * Take a snapshot of running transactions and write this to WAL. This
8035 : : * allows us to reconstruct the state of running transactions during
8036 : : * archive recovery, if required. Skip, if this info disabled.
8037 : : *
8038 : : * If we are shutting down, or Startup process is completing crash
8039 : : * recovery we don't need to write running xact data.
8040 : : */
8041 [ + + + + ]: 1804 : if (!shutdown && XLogStandbyInfoActive())
8042 : 973 : LogStandbySnapshot();
8043 : :
8044 : 1804 : START_CRIT_SECTION();
8045 : :
8046 : : /*
8047 : : * Now insert the checkpoint record into XLOG.
8048 : : */
8049 : 1804 : XLogBeginInsert();
8050 : 1804 : XLogRegisterData(&checkPoint, sizeof(checkPoint));
8051 [ + + ]: 1804 : recptr = XLogInsert(RM_XLOG_ID,
8052 : : shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
8053 : : XLOG_CHECKPOINT_ONLINE);
8054 : :
8055 : 1804 : XLogFlush(recptr);
8056 : :
8057 : : /*
8058 : : * We mustn't write any new WAL after a shutdown checkpoint, or it will be
8059 : : * overwritten at next startup. No-one should even try, this just allows
8060 : : * sanity-checking. In the case of an end-of-recovery checkpoint, we want
8061 : : * to just temporarily disable writing until the system has exited
8062 : : * recovery.
8063 : : */
8064 [ + + ]: 1804 : if (shutdown)
8065 : : {
8066 [ + + ]: 769 : if (flags & CHECKPOINT_END_OF_RECOVERY)
8067 : 32 : LocalXLogInsertAllowed = oldXLogAllowed;
8068 : : else
8069 : 737 : LocalXLogInsertAllowed = 0; /* never again write WAL */
8070 : : }
8071 : :
8072 : : /*
8073 : : * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
8074 : : * = end of actual checkpoint record.
8075 : : */
8076 [ + + - + ]: 1804 : if (shutdown && checkPoint.redo != ProcLastRecPtr)
8077 [ # # ]: 0 : ereport(PANIC,
8078 : : (errmsg("concurrent write-ahead log activity while database system is shutting down")));
8079 : :
8080 : : /*
8081 : : * Remember the prior checkpoint's redo ptr for
8082 : : * UpdateCheckPointDistanceEstimate()
8083 : : */
8084 : 1804 : PriorRedoPtr = ControlFile->checkPointCopy.redo;
8085 : :
8086 : : /*
8087 : : * Update the control file.
8088 : : */
8089 : 1804 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8090 [ + + ]: 1804 : if (shutdown)
8091 : 769 : ControlFile->state = DB_SHUTDOWNED;
8092 : 1804 : ControlFile->checkPoint = ProcLastRecPtr;
8093 : 1804 : ControlFile->checkPointCopy = checkPoint;
8094 : : /* crash recovery should always recover to the end of WAL */
8095 : 1804 : ControlFile->minRecoveryPoint = InvalidXLogRecPtr;
8096 : 1804 : ControlFile->minRecoveryPointTLI = 0;
8097 : :
8098 : : /*
8099 : : * Persist the data checksum state this node runs under into the control
8100 : : * file. Only the top-level field tracks this node, checkPointCopy is a
8101 : : * historical record used to resume replay.
8102 : : *
8103 : : * checkPoint.dataChecksumState was sampled while holding the
8104 : : * DataChecksumTransitionLock together with the redo record, so it is the
8105 : : * state in effect at the redo point. If it was "on", the XLOG2_CHECKSUMS
8106 : : * record announcing that precedes the redo point and every page the
8107 : : * transition rewrote was dirtied before it, so CheckPointGuts() has just
8108 : : * written all of them out. Recording the state here is what keeps a
8109 : : * finished transition from being resolved as interrupted when this
8110 : : * checkpoint is the one crash recovery resumes from: replay never sees
8111 : : * the record announcing it.
8112 : : *
8113 : : * Persist it only if the state did not change while the flush was in
8114 : : * progress. If it changed in between, the pages written out straddle two
8115 : : * states, and the newer one could claim checksums that pages already on
8116 : : * disk do not carry; leave the field to the next checkpoint then, the
8117 : : * transition itself has already persisted every state that is safe
8118 : : * without a flush.
8119 : : *
8120 : : * Compare the watermark rather than the state: record positions are
8121 : : * unique, so a full round trip back to the sampled state cannot alias,
8122 : : * while its flushed pages straddle the intermediate states all the same.
8123 : : */
8124 : 1804 : SpinLockAcquire(&XLogCtl->info_lck);
8125 [ + + ]: 1804 : if (checksumLsn == XLogCtl->data_checksum_lsn)
8126 : : {
8127 : 1800 : ControlFile->data_checksum_version = checkPoint.dataChecksumState;
8128 : 1800 : ControlFile->data_checksum_lsn = checksumLsn;
8129 : 1800 : ControlFile->data_checksum_is_local = XLogCtl->data_checksum_is_local;
8130 : : }
8131 : 1804 : SpinLockRelease(&XLogCtl->info_lck);
8132 : :
8133 : : /*
8134 : : * Persist unloggedLSN value. It's reset on crash recovery, so this goes
8135 : : * unused on non-shutdown checkpoints, but seems useful to store it always
8136 : : * for debugging purposes.
8137 : : */
8138 : 1804 : ControlFile->unloggedLSN = pg_atomic_read_membarrier_u64(&XLogCtl->unloggedLSN);
8139 : :
8140 : 1804 : UpdateControlFile();
8141 : 1804 : LWLockRelease(ControlFileLock);
8142 : :
8143 : : /*
8144 : : * We are now done with critical updates; no need for system panic if we
8145 : : * have trouble while fooling with old log segments.
8146 : : */
8147 : 1804 : END_CRIT_SECTION();
8148 : :
8149 : : /*
8150 : : * WAL summaries end when the next XLOG_CHECKPOINT_REDO or
8151 : : * XLOG_CHECKPOINT_SHUTDOWN record is reached. This is the first point
8152 : : * where (a) we're not inside of a critical section and (b) we can be
8153 : : * certain that the relevant record has been flushed to disk, which must
8154 : : * happen before it can be summarized.
8155 : : *
8156 : : * If this is a shutdown checkpoint, then this happens reasonably
8157 : : * promptly: we've only just inserted and flushed the
8158 : : * XLOG_CHECKPOINT_SHUTDOWN record. If this is not a shutdown checkpoint,
8159 : : * then this might not be very prompt at all: the XLOG_CHECKPOINT_REDO
8160 : : * record was written before we began flushing data to disk, and that
8161 : : * could be many minutes ago at this point. However, we don't XLogFlush()
8162 : : * after inserting that record, so we're not guaranteed that it's on disk
8163 : : * until after the above call that flushes the XLOG_CHECKPOINT_ONLINE
8164 : : * record.
8165 : : */
8166 : 1804 : WakeupWalSummarizer();
8167 : :
8168 : : /*
8169 : : * Let smgr do post-checkpoint cleanup (eg, deleting old files).
8170 : : */
8171 : 1804 : SyncPostCheckpoint();
8172 : :
8173 : : /*
8174 : : * Update the average distance between checkpoints if the prior checkpoint
8175 : : * exists.
8176 : : */
8177 [ + - ]: 1804 : if (XLogRecPtrIsValid(PriorRedoPtr))
8178 : 1804 : UpdateCheckPointDistanceEstimate(RedoRecPtr - PriorRedoPtr);
8179 : :
8180 : 1804 : INJECTION_POINT("checkpoint-before-old-wal-removal", NULL);
8181 : :
8182 : : /*
8183 : : * Delete old log files, those no longer needed for last checkpoint to
8184 : : * prevent the disk holding the xlog from growing full.
8185 : : */
8186 : 1804 : XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
8187 : 1804 : KeepLogSeg(recptr, &_logSegNo);
8188 [ + + ]: 1804 : if (InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_REMOVED | RS_INVAL_IDLE_TIMEOUT,
8189 : : _logSegNo, InvalidOid,
8190 : : InvalidTransactionId))
8191 : : {
8192 : : /*
8193 : : * Some slots have been invalidated; recalculate the old-segment
8194 : : * horizon, starting again from RedoRecPtr.
8195 : : */
8196 : 4 : XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
8197 : 4 : KeepLogSeg(recptr, &_logSegNo);
8198 : : }
8199 : 1804 : _logSegNo--;
8200 : 1804 : RemoveOldXlogFiles(_logSegNo, RedoRecPtr, recptr,
8201 : : checkPoint.ThisTimeLineID);
8202 : :
8203 : : /*
8204 : : * Make more log segments if needed. (Do this after recycling old log
8205 : : * segments, since that may supply some of the needed files.)
8206 : : */
8207 [ + + ]: 1804 : if (!shutdown)
8208 : 1035 : PreallocXlogFiles(recptr, checkPoint.ThisTimeLineID);
8209 : :
8210 : : /*
8211 : : * Truncate pg_subtrans if possible. We can throw away all data before
8212 : : * the oldest XMIN of any running transaction. No future transaction will
8213 : : * attempt to reference any pg_subtrans entry older than that (see Asserts
8214 : : * in subtrans.c). During recovery, though, we mustn't do this because
8215 : : * StartupSUBTRANS hasn't been called yet.
8216 : : */
8217 [ + + ]: 1804 : if (!RecoveryInProgress())
8218 : 1772 : TruncateSUBTRANS(GetOldestTransactionIdConsideredRunning());
8219 : :
8220 : : /* Real work is done; log and update stats. */
8221 : 1804 : LogCheckpointEnd(false, flags);
8222 : :
8223 : : /* Reset the process title */
8224 : 1804 : update_checkpoint_display(flags, false, true);
8225 : :
8226 : : TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
8227 : : NBuffers,
8228 : : CheckpointStats.ckpt_segs_added,
8229 : : CheckpointStats.ckpt_segs_removed,
8230 : : CheckpointStats.ckpt_segs_recycled);
8231 : :
8232 : 1804 : return true;
8233 : : }
8234 : :
8235 : : /*
8236 : : * Mark the end of recovery in WAL though without running a full checkpoint.
8237 : : * We can expect that a restartpoint is likely to be in progress as we
8238 : : * do this, though we are unwilling to wait for it to complete.
8239 : : *
8240 : : * CreateRestartPoint() allows for the case where recovery may end before
8241 : : * the restartpoint completes so there is no concern of concurrent behaviour.
8242 : : */
8243 : : static void
8244 : 56 : CreateEndOfRecoveryRecord(void)
8245 : : {
8246 : : xl_end_of_recovery xlrec;
8247 : : XLogRecPtr recptr;
8248 : :
8249 : : /* sanity check */
8250 [ - + ]: 56 : if (!RecoveryInProgress())
8251 [ # # ]: 0 : elog(ERROR, "can only be used to end recovery");
8252 : :
8253 : 56 : xlrec.end_time = GetCurrentTimestamp();
8254 : 56 : xlrec.wal_level = wal_level;
8255 : :
8256 : 56 : WALInsertLockAcquireExclusive();
8257 : 56 : xlrec.ThisTimeLineID = XLogCtl->InsertTimeLineID;
8258 : 56 : xlrec.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8259 : 56 : WALInsertLockRelease();
8260 : :
8261 : 56 : START_CRIT_SECTION();
8262 : :
8263 : 56 : XLogBeginInsert();
8264 : 56 : XLogRegisterData(&xlrec, sizeof(xl_end_of_recovery));
8265 : 56 : recptr = XLogInsert(RM_XLOG_ID, XLOG_END_OF_RECOVERY);
8266 : :
8267 : 56 : XLogFlush(recptr);
8268 : :
8269 : : /*
8270 : : * Update the control file so that crash recovery can follow the timeline
8271 : : * changes to this point.
8272 : : */
8273 : 56 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8274 : 56 : ControlFile->minRecoveryPoint = recptr;
8275 : 56 : ControlFile->minRecoveryPointTLI = xlrec.ThisTimeLineID;
8276 : :
8277 : : /* persist the data checksum state this node ended recovery with */
8278 : 56 : SpinLockAcquire(&XLogCtl->info_lck);
8279 : 56 : ControlFile->data_checksum_version = XLogCtl->data_checksum_version;
8280 : 56 : ControlFile->data_checksum_lsn = XLogCtl->data_checksum_lsn;
8281 : 56 : ControlFile->data_checksum_is_local = XLogCtl->data_checksum_is_local;
8282 : 56 : SpinLockRelease(&XLogCtl->info_lck);
8283 : :
8284 : 56 : UpdateControlFile();
8285 : 56 : LWLockRelease(ControlFileLock);
8286 : :
8287 : 56 : END_CRIT_SECTION();
8288 : 56 : }
8289 : :
8290 : : /*
8291 : : * Write an OVERWRITE_CONTRECORD message.
8292 : : *
8293 : : * When on WAL replay we expect a continuation record at the start of a page
8294 : : * that is not there, recovery ends and WAL writing resumes at that point.
8295 : : * But it's wrong to resume writing new WAL back at the start of the record
8296 : : * that was broken, because downstream consumers of that WAL (physical
8297 : : * replicas) are not prepared to "rewind". So the first action after
8298 : : * finishing replay of all valid WAL must be to write a record of this type
8299 : : * at the point where the contrecord was missing; to support xlogreader
8300 : : * detecting the special case, XLP_FIRST_IS_OVERWRITE_CONTRECORD is also added
8301 : : * to the page header where the record occurs. xlogreader has an ad-hoc
8302 : : * mechanism to report metadata about the broken record, which is what we
8303 : : * use here.
8304 : : *
8305 : : * At replay time, XLP_FIRST_IS_OVERWRITE_CONTRECORD instructs xlogreader to
8306 : : * skip the record it was reading, and pass back the LSN of the skipped
8307 : : * record, so that its caller can verify (on "replay" of that record) that the
8308 : : * XLOG_OVERWRITE_CONTRECORD matches what was effectively overwritten.
8309 : : *
8310 : : * 'aborted_lsn' is the beginning position of the record that was incomplete.
8311 : : * It is included in the WAL record. 'pagePtr' and 'newTLI' point to the
8312 : : * beginning of the XLOG page where the record is to be inserted. They must
8313 : : * match the current WAL insert position, they're passed here just so that we
8314 : : * can verify that.
8315 : : */
8316 : : static XLogRecPtr
8317 : 12 : CreateOverwriteContrecordRecord(XLogRecPtr aborted_lsn, XLogRecPtr pagePtr,
8318 : : TimeLineID newTLI)
8319 : : {
8320 : : xl_overwrite_contrecord xlrec;
8321 : : XLogRecPtr recptr;
8322 : : XLogPageHeader pagehdr;
8323 : : XLogRecPtr startPos;
8324 : :
8325 : : /* sanity checks */
8326 [ - + ]: 12 : if (!RecoveryInProgress())
8327 [ # # ]: 0 : elog(ERROR, "can only be used at end of recovery");
8328 [ - + ]: 12 : if (pagePtr % XLOG_BLCKSZ != 0)
8329 [ # # ]: 0 : elog(ERROR, "invalid position for missing continuation record %X/%08X",
8330 : : LSN_FORMAT_ARGS(pagePtr));
8331 : :
8332 : : /* The current WAL insert position should be right after the page header */
8333 : 12 : startPos = pagePtr;
8334 [ + + ]: 12 : if (XLogSegmentOffset(startPos, wal_segment_size) == 0)
8335 : 1 : startPos += SizeOfXLogLongPHD;
8336 : : else
8337 : 11 : startPos += SizeOfXLogShortPHD;
8338 : 12 : recptr = GetXLogInsertRecPtr();
8339 [ - + ]: 12 : if (recptr != startPos)
8340 [ # # ]: 0 : elog(ERROR, "invalid WAL insert position %X/%08X for OVERWRITE_CONTRECORD",
8341 : : LSN_FORMAT_ARGS(recptr));
8342 : :
8343 : 12 : START_CRIT_SECTION();
8344 : :
8345 : : /*
8346 : : * Initialize the XLOG page header (by GetXLogBuffer), and set the
8347 : : * XLP_FIRST_IS_OVERWRITE_CONTRECORD flag.
8348 : : *
8349 : : * No other backend is allowed to write WAL yet, so acquiring the WAL
8350 : : * insertion lock is just pro forma.
8351 : : */
8352 : 12 : WALInsertLockAcquire();
8353 : 12 : pagehdr = (XLogPageHeader) GetXLogBuffer(pagePtr, newTLI);
8354 : 12 : pagehdr->xlp_info |= XLP_FIRST_IS_OVERWRITE_CONTRECORD;
8355 : 12 : WALInsertLockRelease();
8356 : :
8357 : : /*
8358 : : * Insert the XLOG_OVERWRITE_CONTRECORD record as the first record on the
8359 : : * page. We know it becomes the first record, because no other backend is
8360 : : * allowed to write WAL yet.
8361 : : */
8362 : 12 : XLogBeginInsert();
8363 : 12 : xlrec.overwritten_lsn = aborted_lsn;
8364 : 12 : xlrec.overwrite_time = GetCurrentTimestamp();
8365 : 12 : XLogRegisterData(&xlrec, sizeof(xl_overwrite_contrecord));
8366 : 12 : recptr = XLogInsert(RM_XLOG_ID, XLOG_OVERWRITE_CONTRECORD);
8367 : :
8368 : : /* check that the record was inserted to the right place */
8369 [ - + ]: 12 : if (ProcLastRecPtr != startPos)
8370 [ # # ]: 0 : elog(ERROR, "OVERWRITE_CONTRECORD was inserted to unexpected position %X/%08X",
8371 : : LSN_FORMAT_ARGS(ProcLastRecPtr));
8372 : :
8373 : 12 : XLogFlush(recptr);
8374 : :
8375 : 12 : END_CRIT_SECTION();
8376 : :
8377 : 12 : return recptr;
8378 : : }
8379 : :
8380 : : /*
8381 : : * Flush all data in shared memory to disk, and fsync
8382 : : *
8383 : : * This is the common code shared between regular checkpoints and
8384 : : * recovery restartpoints.
8385 : : */
8386 : : static void
8387 : 2016 : CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
8388 : : {
8389 : 2016 : CheckPointRelationMap();
8390 : 2016 : CheckPointReplicationOrigin();
8391 : :
8392 : : /* Write out all dirty data in SLRUs and the main buffer pool */
8393 : : TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START(flags);
8394 : 2016 : CheckpointStats.ckpt_write_t = GetCurrentTimestamp();
8395 : 2016 : CheckPointCLOG();
8396 : 2016 : CheckPointCommitTs();
8397 : 2016 : CheckPointSUBTRANS();
8398 : 2016 : CheckPointMultiXact();
8399 : 2016 : CheckPointPredicate();
8400 : 2016 : CheckPointBuffers(flags);
8401 : :
8402 : : /* Perform all queued up fsyncs */
8403 : : TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START();
8404 : 2016 : CheckpointStats.ckpt_sync_t = GetCurrentTimestamp();
8405 : 2016 : ProcessSyncRequests();
8406 : 2016 : CheckpointStats.ckpt_sync_end_t = GetCurrentTimestamp();
8407 : : TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE();
8408 : :
8409 : : /*
8410 : : * Run replication slot checkpointing after buffer writes and
8411 : : * ProcessSyncRequests(), so WAL removal uses a fresher slot retention
8412 : : * horizon and avoids retaining WAL segments that slots no longer need.
8413 : : * Then clean up logical snapshots and rewrite mappings based on the
8414 : : * updated saved restart LSNs. Also delay 2PC checkpointing as long as
8415 : : * possible.
8416 : : */
8417 : 2016 : CheckPointReplicationSlots(flags & CHECKPOINT_IS_SHUTDOWN);
8418 : 2016 : CheckPointSnapBuild();
8419 : 2016 : CheckPointLogicalRewriteHeap();
8420 : 2016 : CheckPointTwoPhase(checkPointRedo);
8421 : 2016 : }
8422 : :
8423 : : /*
8424 : : * Save a checkpoint for recovery restart if appropriate
8425 : : *
8426 : : * This function is called each time a checkpoint record is read from XLOG.
8427 : : * It must determine whether the checkpoint represents a safe restartpoint or
8428 : : * not. If so, the checkpoint record is stashed in shared memory so that
8429 : : * CreateRestartPoint can consult it. (Note that the latter function is
8430 : : * executed by the checkpointer, while this one will be executed by the
8431 : : * startup process.)
8432 : : */
8433 : : static void
8434 : 772 : RecoveryRestartPoint(const CheckPoint *checkPoint, XLogReaderState *record)
8435 : : {
8436 : : /*
8437 : : * Also refrain from creating a restartpoint if we have seen any
8438 : : * references to non-existent pages. Restarting recovery from the
8439 : : * restartpoint would not see the references, so we would lose the
8440 : : * cross-check that the pages belonged to a relation that was dropped
8441 : : * later.
8442 : : */
8443 [ - + ]: 772 : if (XLogHaveInvalidPages())
8444 : : {
8445 [ # # ]: 0 : elog(DEBUG2,
8446 : : "could not record restart point at %X/%08X because there are unresolved references to invalid pages",
8447 : : LSN_FORMAT_ARGS(checkPoint->redo));
8448 : 0 : return;
8449 : : }
8450 : :
8451 : : /*
8452 : : * Copy the checkpoint record to shared memory, so that checkpointer can
8453 : : * work out the next time it wants to perform a restartpoint.
8454 : : */
8455 : 772 : SpinLockAcquire(&XLogCtl->info_lck);
8456 : 772 : XLogCtl->lastCheckPointRecPtr = record->ReadRecPtr;
8457 : 772 : XLogCtl->lastCheckPointEndPtr = record->EndRecPtr;
8458 : 772 : XLogCtl->lastCheckPoint = *checkPoint;
8459 : 772 : SpinLockRelease(&XLogCtl->info_lck);
8460 : : }
8461 : :
8462 : : /*
8463 : : * Establish a restartpoint if possible.
8464 : : *
8465 : : * This is similar to CreateCheckPoint, but is used during WAL recovery
8466 : : * to establish a point from which recovery can roll forward without
8467 : : * replaying the entire recovery log.
8468 : : *
8469 : : * Returns true if a new restartpoint was established. We can only establish
8470 : : * a restartpoint if we have replayed a safe checkpoint record since last
8471 : : * restartpoint.
8472 : : */
8473 : : bool
8474 : 633 : CreateRestartPoint(int flags)
8475 : : {
8476 : : XLogRecPtr lastCheckPointRecPtr;
8477 : : XLogRecPtr lastCheckPointEndPtr;
8478 : : CheckPoint lastCheckPoint;
8479 : : XLogRecPtr PriorRedoPtr;
8480 : : XLogRecPtr receivePtr;
8481 : : XLogRecPtr replayPtr;
8482 : : TimeLineID replayTLI;
8483 : : XLogRecPtr endptr;
8484 : : XLogSegNo _logSegNo;
8485 : : TimestampTz xtime;
8486 : : uint32 checksum_state;
8487 : : XLogRecPtr checksum_lsn;
8488 : : bool checksum_is_local;
8489 : :
8490 : : /* Concurrent checkpoint/restartpoint cannot happen */
8491 : : Assert(!IsUnderPostmaster || MyBackendType == B_CHECKPOINTER);
8492 : :
8493 : : /* Get a local copy of the last safe checkpoint record. */
8494 : 633 : SpinLockAcquire(&XLogCtl->info_lck);
8495 : 633 : lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
8496 : 633 : lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
8497 : 633 : lastCheckPoint = XLogCtl->lastCheckPoint;
8498 : 633 : SpinLockRelease(&XLogCtl->info_lck);
8499 : :
8500 : : /*
8501 : : * Check that we're still in recovery mode. It's ok if we exit recovery
8502 : : * mode after this check, the restart point is valid anyway.
8503 : : */
8504 [ - + ]: 633 : if (!RecoveryInProgress())
8505 : : {
8506 [ # # ]: 0 : ereport(DEBUG2,
8507 : : (errmsg_internal("skipping restartpoint, recovery has already ended")));
8508 : 0 : return false;
8509 : : }
8510 : :
8511 : : /*
8512 : : * If the last checkpoint record we've replayed is already our last
8513 : : * restartpoint, we can't perform a new restart point. We still update
8514 : : * minRecoveryPoint in that case, so that if this is a shutdown restart
8515 : : * point, we won't start up earlier than before. That's not strictly
8516 : : * necessary, but when hot standby is enabled, it would be rather weird if
8517 : : * the database opened up for read-only connections at a point-in-time
8518 : : * before the last shutdown. Such time travel is still possible in case of
8519 : : * immediate shutdown, though.
8520 : : *
8521 : : * We don't explicitly advance minRecoveryPoint when we do create a
8522 : : * restartpoint. It's assumed that flushing the buffers will do that as a
8523 : : * side-effect.
8524 : : */
8525 [ + + ]: 633 : if (!XLogRecPtrIsValid(lastCheckPointRecPtr) ||
8526 [ + + ]: 302 : lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
8527 : : {
8528 [ - + ]: 421 : ereport(DEBUG2,
8529 : : errmsg_internal("skipping restartpoint, already performed at %X/%08X",
8530 : : LSN_FORMAT_ARGS(lastCheckPoint.redo)));
8531 : :
8532 : 421 : UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
8533 [ + + ]: 421 : if (flags & CHECKPOINT_IS_SHUTDOWN)
8534 : : {
8535 : : bool catchUpChecksums;
8536 : :
8537 : : /*
8538 : : * There is no new restartpoint to persist the data checksum state
8539 : : * with, but a cleanly stopped node should not leave the control
8540 : : * file behind the state replay reached: pg_checksums and
8541 : : * pg_rewind read it, and an in-progress state there makes them
8542 : : * refuse to run. Catching it up needs the same guarantee a
8543 : : * restartpoint gives: that every page on disk carries a checksum,
8544 : : * so flush the buffer pool first. Only a transition to "on" that
8545 : : * no restartpoint followed can get here; the other states are
8546 : : * already persisted by XLOG2_CHECKSUMS replay. Replay has ended
8547 : : * by now, so the state cannot change under us.
8548 : : */
8549 : 44 : SpinLockAcquire(&XLogCtl->info_lck);
8550 : 44 : checksum_state = XLogCtl->data_checksum_version;
8551 : 44 : checksum_lsn = XLogCtl->data_checksum_lsn;
8552 : 44 : checksum_is_local = XLogCtl->data_checksum_is_local;
8553 : 44 : SpinLockRelease(&XLogCtl->info_lck);
8554 : :
8555 : 44 : LWLockAcquire(ControlFileLock, LW_SHARED);
8556 : 44 : catchUpChecksums =
8557 [ - + - - ]: 44 : (checksum_lsn != ControlFile->data_checksum_lsn &&
8558 : : XLogRecPtrIsValid(lastCheckPointRecPtr));
8559 : 44 : LWLockRelease(ControlFileLock);
8560 : :
8561 [ - + ]: 44 : if (catchUpChecksums)
8562 : : {
8563 [ # # # # : 0 : MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
# # # # #
# ]
8564 : 0 : CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
8565 : 0 : CheckPointGuts(lastCheckPoint.redo, flags);
8566 : : }
8567 : :
8568 : 44 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8569 : 44 : ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
8570 [ - + ]: 44 : if (catchUpChecksums)
8571 : : {
8572 : 0 : ControlFile->data_checksum_version = checksum_state;
8573 : 0 : ControlFile->data_checksum_lsn = checksum_lsn;
8574 : 0 : ControlFile->data_checksum_is_local = checksum_is_local;
8575 : : }
8576 : 44 : UpdateControlFile();
8577 : 44 : LWLockRelease(ControlFileLock);
8578 : : }
8579 : 421 : return false;
8580 : : }
8581 : :
8582 : : /*
8583 : : * Update the shared RedoRecPtr so that the startup process can calculate
8584 : : * the number of segments replayed since last restartpoint, and request a
8585 : : * restartpoint if it exceeds CheckPointSegments.
8586 : : *
8587 : : * Like in CreateCheckPoint(), hold off insertions to update it, although
8588 : : * during recovery this is just pro forma, because no WAL insertions are
8589 : : * happening.
8590 : : */
8591 : 212 : WALInsertLockAcquireExclusive();
8592 : 212 : RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
8593 : 212 : WALInsertLockRelease();
8594 : :
8595 : : /* Also update the info_lck-protected copy */
8596 : 212 : SpinLockAcquire(&XLogCtl->info_lck);
8597 : 212 : XLogCtl->RedoRecPtr = lastCheckPoint.redo;
8598 : 212 : SpinLockRelease(&XLogCtl->info_lck);
8599 : :
8600 : : /*
8601 : : * Prepare to accumulate statistics.
8602 : : *
8603 : : * Note: because it is possible for log_checkpoints to change while a
8604 : : * checkpoint proceeds, we always accumulate stats, even if
8605 : : * log_checkpoints is currently off.
8606 : : */
8607 [ + - + - : 2332 : MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
+ - + - +
+ ]
8608 : 212 : CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
8609 : :
8610 [ + - ]: 212 : if (log_checkpoints)
8611 : 212 : LogCheckpointStart(flags, true);
8612 : :
8613 : : /* Update the process title */
8614 : 212 : update_checkpoint_display(flags, true, false);
8615 : :
8616 : : /*
8617 : : * Note the data checksum state the flush below starts under. Replay runs
8618 : : * concurrently and can change the state while the flush is in progress,
8619 : : * in which case the flush covers pages written under both states; see
8620 : : * where the state is persisted further down.
8621 : : */
8622 : 212 : SpinLockAcquire(&XLogCtl->info_lck);
8623 : 212 : checksum_state = XLogCtl->data_checksum_version;
8624 : 212 : checksum_lsn = XLogCtl->data_checksum_lsn;
8625 : 212 : SpinLockRelease(&XLogCtl->info_lck);
8626 : :
8627 : 212 : CheckPointGuts(lastCheckPoint.redo, flags);
8628 : :
8629 : : /*
8630 : : * This location needs to be after CheckPointGuts() to ensure that some
8631 : : * work has already happened during this checkpoint.
8632 : : */
8633 : 212 : INJECTION_POINT("create-restart-point", NULL);
8634 : :
8635 : : /*
8636 : : * Remember the prior checkpoint's redo ptr for
8637 : : * UpdateCheckPointDistanceEstimate()
8638 : : */
8639 : 212 : PriorRedoPtr = ControlFile->checkPointCopy.redo;
8640 : :
8641 : : /*
8642 : : * Update pg_control, using current time. Check that it still shows an
8643 : : * older checkpoint, else do nothing; this is a quick hack to make sure
8644 : : * nothing really bad happens if somehow we get here after the
8645 : : * end-of-recovery checkpoint.
8646 : : */
8647 : 212 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8648 [ + - ]: 212 : if (ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
8649 : : {
8650 : : /*
8651 : : * Update the checkpoint information. We do this even if the cluster
8652 : : * does not show DB_IN_ARCHIVE_RECOVERY to match with the set of WAL
8653 : : * segments recycled below.
8654 : : */
8655 : 212 : ControlFile->checkPoint = lastCheckPointRecPtr;
8656 : 212 : ControlFile->checkPointCopy = lastCheckPoint;
8657 : :
8658 : : /*
8659 : : * Ensure minRecoveryPoint is past the checkpoint record and update it
8660 : : * if the control file still shows DB_IN_ARCHIVE_RECOVERY. Normally,
8661 : : * this will have happened already while writing out dirty buffers,
8662 : : * but not necessarily - e.g. because no buffers were dirtied. We do
8663 : : * this because a backup performed in recovery uses minRecoveryPoint
8664 : : * to determine which WAL files must be included in the backup, and
8665 : : * the file (or files) containing the checkpoint record must be
8666 : : * included, at a minimum. Note that for an ordinary restart of
8667 : : * recovery there's no value in having the minimum recovery point any
8668 : : * earlier than this anyway, because redo will begin just after the
8669 : : * checkpoint record.
8670 : : */
8671 [ + + ]: 212 : if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
8672 : : {
8673 [ + + ]: 211 : if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
8674 : : {
8675 : 18 : ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
8676 : 18 : ControlFile->minRecoveryPointTLI = lastCheckPoint.ThisTimeLineID;
8677 : :
8678 : : /* update local copy */
8679 : 18 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
8680 : : }
8681 [ + + ]: 211 : if (flags & CHECKPOINT_IS_SHUTDOWN)
8682 : 25 : ControlFile->state = DB_SHUTDOWNED_IN_RECOVERY;
8683 : : }
8684 : :
8685 : : /*
8686 : : * Persist the data checksum state of this node. Not the state of the
8687 : : * replayed checkpoint: that one belongs to the node that wrote it and
8688 : : * may differ after an offline change on either side.
8689 : : * ControlFile->checkPointCopy above keeps the replayed value on
8690 : : * purpose, being a historical record used to resume replay rather
8691 : : * than a tracker of node state.
8692 : : *
8693 : : * Persist only if the flush above ran under one state throughout; see
8694 : : * CreateCheckPoint() for why, including why this compares the
8695 : : * watermark and not the state.
8696 : : */
8697 : 212 : SpinLockAcquire(&XLogCtl->info_lck);
8698 [ + + ]: 212 : if (checksum_lsn == XLogCtl->data_checksum_lsn)
8699 : : {
8700 : 211 : ControlFile->data_checksum_version = checksum_state;
8701 : 211 : ControlFile->data_checksum_lsn = checksum_lsn;
8702 : 211 : ControlFile->data_checksum_is_local = XLogCtl->data_checksum_is_local;
8703 : : }
8704 : 212 : SpinLockRelease(&XLogCtl->info_lck);
8705 : :
8706 : 212 : UpdateControlFile();
8707 : : }
8708 : 212 : LWLockRelease(ControlFileLock);
8709 : :
8710 : : /*
8711 : : * Update the average distance between checkpoints/restartpoints if the
8712 : : * prior checkpoint exists.
8713 : : */
8714 [ + - ]: 212 : if (XLogRecPtrIsValid(PriorRedoPtr))
8715 : 212 : UpdateCheckPointDistanceEstimate(RedoRecPtr - PriorRedoPtr);
8716 : :
8717 : : /*
8718 : : * Delete old log files, those no longer needed for last restartpoint to
8719 : : * prevent the disk holding the xlog from growing full.
8720 : : */
8721 : 212 : XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
8722 : :
8723 : : /*
8724 : : * Retreat _logSegNo using the current end of xlog replayed or received,
8725 : : * whichever is later.
8726 : : */
8727 : 212 : receivePtr = GetWalRcvFlushRecPtr(NULL, NULL);
8728 : 212 : replayPtr = GetXLogReplayRecPtr(&replayTLI);
8729 : 212 : endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
8730 : 212 : KeepLogSeg(endptr, &_logSegNo);
8731 : :
8732 : 212 : INJECTION_POINT("restartpoint-before-slot-invalidation", NULL);
8733 : :
8734 [ + + ]: 212 : if (InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_REMOVED | RS_INVAL_IDLE_TIMEOUT,
8735 : : _logSegNo, InvalidOid,
8736 : : InvalidTransactionId))
8737 : : {
8738 : : /*
8739 : : * Some slots have been invalidated; recalculate the old-segment
8740 : : * horizon, starting again from RedoRecPtr.
8741 : : */
8742 : 1 : XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
8743 : 1 : KeepLogSeg(endptr, &_logSegNo);
8744 : : }
8745 : 212 : _logSegNo--;
8746 : :
8747 : : /*
8748 : : * Try to recycle segments on a useful timeline. If we've been promoted
8749 : : * since the beginning of this restartpoint, use the new timeline chosen
8750 : : * at end of recovery. If we're still in recovery, use the timeline we're
8751 : : * currently replaying.
8752 : : *
8753 : : * There is no guarantee that the WAL segments will be useful on the
8754 : : * current timeline; if recovery proceeds to a new timeline right after
8755 : : * this, the pre-allocated WAL segments on this timeline will not be used,
8756 : : * and will go wasted until recycled on the next restartpoint. We'll live
8757 : : * with that.
8758 : : */
8759 [ + + ]: 212 : if (!RecoveryInProgress())
8760 : 1 : replayTLI = XLogCtl->InsertTimeLineID;
8761 : :
8762 : 212 : RemoveOldXlogFiles(_logSegNo, RedoRecPtr, endptr, replayTLI);
8763 : :
8764 : : /*
8765 : : * Make more log segments if needed. (Do this after recycling old log
8766 : : * segments, since that may supply some of the needed files.)
8767 : : */
8768 : 212 : PreallocXlogFiles(endptr, replayTLI);
8769 : :
8770 : : /*
8771 : : * Truncate pg_subtrans if possible. We can throw away all data before
8772 : : * the oldest XMIN of any running transaction. No future transaction will
8773 : : * attempt to reference any pg_subtrans entry older than that (see Asserts
8774 : : * in subtrans.c). During recovery, don't truncate pg_subtrans until hot
8775 : : * standby initialization has started it.
8776 : : */
8777 [ + - ]: 212 : if (RecoverySubtransInitialized())
8778 : 212 : TruncateSUBTRANS(GetOldestTransactionIdConsideredRunning());
8779 : :
8780 : : /* Real work is done; log and update stats. */
8781 : 212 : LogCheckpointEnd(true, flags);
8782 : :
8783 : : /* Reset the process title */
8784 : 212 : update_checkpoint_display(flags, true, true);
8785 : :
8786 : 212 : xtime = GetLatestXTime();
8787 [ + - + - : 212 : ereport((log_checkpoints ? LOG : DEBUG2),
+ + ]
8788 : : errmsg("recovery restart point at %X/%08X",
8789 : : LSN_FORMAT_ARGS(lastCheckPoint.redo)),
8790 : : xtime ? errdetail("Last completed transaction was at log time %s.",
8791 : : timestamptz_to_str(xtime)) : 0);
8792 : :
8793 : : /*
8794 : : * Finally, execute archive_cleanup_command, if any.
8795 : : */
8796 [ + - - + ]: 212 : if (archiveCleanupCommand && strcmp(archiveCleanupCommand, "") != 0)
8797 : 0 : ExecuteRecoveryCommand(archiveCleanupCommand,
8798 : : "archive_cleanup_command",
8799 : : false,
8800 : : WAIT_EVENT_ARCHIVE_CLEANUP_COMMAND);
8801 : :
8802 : 212 : return true;
8803 : : }
8804 : :
8805 : : /*
8806 : : * Report availability of WAL for the given target LSN
8807 : : * (typically a slot's restart_lsn)
8808 : : *
8809 : : * Returns one of the following enum values:
8810 : : *
8811 : : * * WALAVAIL_RESERVED means targetLSN is available and it is in the range of
8812 : : * max_wal_size.
8813 : : *
8814 : : * * WALAVAIL_EXTENDED means it is still available by preserving extra
8815 : : * segments beyond max_wal_size. If max_slot_wal_keep_size is smaller
8816 : : * than max_wal_size, this state is not returned.
8817 : : *
8818 : : * * WALAVAIL_UNRESERVED means it is being lost and the next checkpoint will
8819 : : * remove reserved segments. The walsender using this slot may return to the
8820 : : * above.
8821 : : *
8822 : : * * WALAVAIL_REMOVED means it has been removed. A replication stream on
8823 : : * a slot with this LSN cannot continue. (Any associated walsender
8824 : : * processes should have been terminated already.)
8825 : : *
8826 : : * * WALAVAIL_INVALID_LSN means the slot hasn't been set to reserve WAL.
8827 : : */
8828 : : WALAvailability
8829 : 639 : GetWALAvailability(XLogRecPtr targetLSN)
8830 : : {
8831 : : XLogRecPtr currpos; /* current write LSN */
8832 : : XLogSegNo currSeg; /* segid of currpos */
8833 : : XLogSegNo targetSeg; /* segid of targetLSN */
8834 : : XLogSegNo oldestSeg; /* actual oldest segid */
8835 : : XLogSegNo oldestSegMaxWalSize; /* oldest segid kept by max_wal_size */
8836 : : XLogSegNo oldestSlotSeg; /* oldest segid kept by slot */
8837 : : uint64 keepSegs;
8838 : :
8839 : : /*
8840 : : * slot does not reserve WAL. Either deactivated, or has never been active
8841 : : */
8842 [ + + ]: 639 : if (!XLogRecPtrIsValid(targetLSN))
8843 : 35 : return WALAVAIL_INVALID_LSN;
8844 : :
8845 : : /*
8846 : : * Calculate the oldest segment currently reserved by all slots,
8847 : : * considering wal_keep_size and max_slot_wal_keep_size. Initialize
8848 : : * oldestSlotSeg to the current segment.
8849 : : */
8850 : 604 : currpos = GetXLogWriteRecPtr();
8851 : 604 : XLByteToSeg(currpos, oldestSlotSeg, wal_segment_size);
8852 : 604 : KeepLogSeg(currpos, &oldestSlotSeg);
8853 : :
8854 : : /*
8855 : : * Find the oldest extant segment file. We get 1 until checkpoint removes
8856 : : * the first WAL segment file since startup, which causes the status being
8857 : : * wrong under certain abnormal conditions but that doesn't actually harm.
8858 : : */
8859 : 604 : oldestSeg = XLogGetLastRemovedSegno() + 1;
8860 : :
8861 : : /* calculate oldest segment by max_wal_size */
8862 : 604 : XLByteToSeg(currpos, currSeg, wal_segment_size);
8863 : 604 : keepSegs = ConvertToXSegs(max_wal_size_mb, wal_segment_size) + 1;
8864 : :
8865 [ + + ]: 604 : if (currSeg > keepSegs)
8866 : 13 : oldestSegMaxWalSize = currSeg - keepSegs;
8867 : : else
8868 : 591 : oldestSegMaxWalSize = 1;
8869 : :
8870 : : /* the segment we care about */
8871 : 604 : XLByteToSeg(targetLSN, targetSeg, wal_segment_size);
8872 : :
8873 : : /*
8874 : : * No point in returning reserved or extended status values if the
8875 : : * targetSeg is known to be lost.
8876 : : */
8877 [ + + ]: 604 : if (targetSeg >= oldestSlotSeg)
8878 : : {
8879 : : /* show "reserved" when targetSeg is within max_wal_size */
8880 [ + + ]: 603 : if (targetSeg >= oldestSegMaxWalSize)
8881 : 601 : return WALAVAIL_RESERVED;
8882 : :
8883 : : /* being retained by slots exceeding max_wal_size */
8884 : 2 : return WALAVAIL_EXTENDED;
8885 : : }
8886 : :
8887 : : /* WAL segments are no longer retained but haven't been removed yet */
8888 [ + - ]: 1 : if (targetSeg >= oldestSeg)
8889 : 1 : return WALAVAIL_UNRESERVED;
8890 : :
8891 : : /* Definitely lost */
8892 : 0 : return WALAVAIL_REMOVED;
8893 : : }
8894 : :
8895 : :
8896 : : /*
8897 : : * Retreat *logSegNo to the last segment that we need to retain because of
8898 : : * either wal_keep_size or replication slots.
8899 : : *
8900 : : * This is calculated by subtracting wal_keep_size from the given xlog
8901 : : * location, recptr and by making sure that that result is below the
8902 : : * requirement of replication slots. For the latter criterion we do consider
8903 : : * the effects of max_slot_wal_keep_size: reserve at most that much space back
8904 : : * from recptr.
8905 : : *
8906 : : * Note about replication slots: if this function calculates a value
8907 : : * that's further ahead than what slots need reserved, then affected
8908 : : * slots need to be invalidated and this function invoked again.
8909 : : * XXX it might be a good idea to rewrite this function so that
8910 : : * invalidation is optionally done here, instead.
8911 : : */
8912 : : static void
8913 : 2625 : KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
8914 : : {
8915 : : XLogSegNo currSegNo;
8916 : : XLogSegNo segno;
8917 : : XLogRecPtr keep;
8918 : :
8919 : 2625 : XLByteToSeg(recptr, currSegNo, wal_segment_size);
8920 : 2625 : segno = currSegNo;
8921 : :
8922 : : /* Calculate how many segments are kept by slots. */
8923 : 2625 : keep = XLogGetReplicationSlotMinimumLSN();
8924 [ + + + + ]: 2625 : if (XLogRecPtrIsValid(keep) && keep < recptr)
8925 : : {
8926 : 754 : XLByteToSeg(keep, segno, wal_segment_size);
8927 : :
8928 : : /*
8929 : : * Account for max_slot_wal_keep_size to avoid keeping more than
8930 : : * configured. However, don't do that during a binary upgrade: if
8931 : : * slots were to be invalidated because of this, it would not be
8932 : : * possible to preserve logical ones during the upgrade.
8933 : : */
8934 [ + + + - ]: 754 : if (max_slot_wal_keep_size_mb >= 0 && !IsBinaryUpgrade)
8935 : : {
8936 : : uint64 slot_keep_segs;
8937 : :
8938 : 24 : slot_keep_segs =
8939 : 24 : ConvertToXSegs(max_slot_wal_keep_size_mb, wal_segment_size);
8940 : :
8941 [ + + ]: 24 : if (currSegNo - segno > slot_keep_segs)
8942 : 7 : segno = currSegNo - slot_keep_segs;
8943 : : }
8944 : : }
8945 : :
8946 : : /*
8947 : : * If WAL summarization is in use, don't remove WAL that has yet to be
8948 : : * summarized.
8949 : : */
8950 : 2625 : keep = GetOldestUnsummarizedLSN(NULL, NULL);
8951 [ + + ]: 2625 : if (XLogRecPtrIsValid(keep))
8952 : : {
8953 : : XLogSegNo unsummarized_segno;
8954 : :
8955 : 12 : XLByteToSeg(keep, unsummarized_segno, wal_segment_size);
8956 [ + + ]: 12 : if (unsummarized_segno < segno)
8957 : 11 : segno = unsummarized_segno;
8958 : : }
8959 : :
8960 : : /* but, keep at least wal_keep_size if that's set */
8961 [ + + ]: 2625 : if (wal_keep_size_mb > 0)
8962 : : {
8963 : : uint64 keep_segs;
8964 : :
8965 : 97 : keep_segs = ConvertToXSegs(wal_keep_size_mb, wal_segment_size);
8966 [ + - ]: 97 : if (currSegNo - segno < keep_segs)
8967 : : {
8968 : : /* avoid underflow, don't go below 1 */
8969 [ + + ]: 97 : if (currSegNo <= keep_segs)
8970 : 93 : segno = 1;
8971 : : else
8972 : 4 : segno = currSegNo - keep_segs;
8973 : : }
8974 : : }
8975 : :
8976 : : /* don't delete WAL segments newer than the calculated segment */
8977 [ + + ]: 2625 : if (segno < *logSegNo)
8978 : 287 : *logSegNo = segno;
8979 : 2625 : }
8980 : :
8981 : : /*
8982 : : * Write a NEXTOID log record
8983 : : */
8984 : : void
8985 : 723 : XLogPutNextOid(Oid8 nextOid)
8986 : : {
8987 : 723 : XLogBeginInsert();
8988 : 723 : XLogRegisterData(&nextOid, sizeof(Oid8));
8989 : 723 : (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID);
8990 : :
8991 : : /*
8992 : : * We need not flush the NEXTOID record immediately, because any of the
8993 : : * just-allocated OIDs could only reach disk as part of a tuple insert or
8994 : : * update that would have its own XLOG record that must follow the NEXTOID
8995 : : * record. Therefore, the standard buffer LSN interlock applied to those
8996 : : * records will ensure no such OID reaches disk before the NEXTOID record
8997 : : * does.
8998 : : *
8999 : : * Note, however, that the above statement only covers state "within" the
9000 : : * database. When we use a generated OID as a file or directory name, we
9001 : : * are in a sense violating the basic WAL rule, because that filesystem
9002 : : * change may reach disk before the NEXTOID WAL record does. The impact
9003 : : * of this is that if a database crash occurs immediately afterward, we
9004 : : * might after restart re-generate the same OID and find that it conflicts
9005 : : * with the leftover file or directory. But since for safety's sake we
9006 : : * always loop until finding a nonconflicting filename, this poses no real
9007 : : * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
9008 : : */
9009 : 723 : }
9010 : :
9011 : : /*
9012 : : * Write an XLOG SWITCH record.
9013 : : *
9014 : : * Here we just blindly issue an XLogInsert request for the record.
9015 : : * All the magic happens inside XLogInsert.
9016 : : *
9017 : : * The return value is either the end+1 address of the switch record,
9018 : : * or the end+1 address of the prior segment if we did not need to
9019 : : * write a switch record because we are already at segment start.
9020 : : */
9021 : : XLogRecPtr
9022 : 853 : RequestXLogSwitch(bool mark_unimportant)
9023 : : {
9024 : : XLogRecPtr RecPtr;
9025 : :
9026 : : /* XLOG SWITCH has no data */
9027 : 853 : XLogBeginInsert();
9028 : :
9029 [ - + ]: 853 : if (mark_unimportant)
9030 : 0 : XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
9031 : 853 : RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH);
9032 : :
9033 : 853 : return RecPtr;
9034 : : }
9035 : :
9036 : : /*
9037 : : * Write a RESTORE POINT record
9038 : : */
9039 : : XLogRecPtr
9040 : 3 : XLogRestorePoint(const char *rpName)
9041 : : {
9042 : : XLogRecPtr RecPtr;
9043 : : xl_restore_point xlrec;
9044 : :
9045 : 3 : xlrec.rp_time = GetCurrentTimestamp();
9046 : 3 : strlcpy(xlrec.rp_name, rpName, MAXFNAMELEN);
9047 : :
9048 : 3 : XLogBeginInsert();
9049 : 3 : XLogRegisterData(&xlrec, sizeof(xl_restore_point));
9050 : :
9051 : 3 : RecPtr = XLogInsert(RM_XLOG_ID, XLOG_RESTORE_POINT);
9052 : :
9053 [ + - ]: 3 : ereport(LOG,
9054 : : errmsg("restore point \"%s\" created at %X/%08X",
9055 : : rpName, LSN_FORMAT_ARGS(RecPtr)));
9056 : :
9057 : 3 : return RecPtr;
9058 : : }
9059 : :
9060 : : /*
9061 : : * Write an empty XLOG record to assign a distinct LSN.
9062 : : *
9063 : : * This is used by some index AMs when building indexes on permanent relations
9064 : : * with wal_level=minimal. In that scenario, WAL-logging will start after
9065 : : * commit, but the index AM needs distinct LSNs to detect concurrent page
9066 : : * modifications. When the current WAL insert position hasn't advanced since
9067 : : * the last call, we emit a dummy record to ensure we get a new, distinct LSN.
9068 : : */
9069 : : XLogRecPtr
9070 : 408 : XLogAssignLSN(void)
9071 : : {
9072 : 408 : int dummy = 0;
9073 : :
9074 : : /*
9075 : : * Records other than XLOG_SWITCH must have content. We use an integer 0
9076 : : * to satisfy this restriction.
9077 : : */
9078 : 408 : XLogBeginInsert();
9079 : 408 : XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
9080 : 408 : XLogRegisterData(&dummy, sizeof(dummy));
9081 : 408 : return XLogInsert(RM_XLOG_ID, XLOG_ASSIGN_LSN);
9082 : : }
9083 : :
9084 : : /*
9085 : : * Check if any of the GUC parameters that are critical for hot standby
9086 : : * have changed, and update the value in pg_control file if necessary.
9087 : : */
9088 : : static void
9089 : 1057 : XLogReportParameters(void)
9090 : : {
9091 [ + + ]: 1057 : if (wal_level != ControlFile->wal_level ||
9092 [ + + ]: 784 : wal_log_hints != ControlFile->wal_log_hints ||
9093 [ + + ]: 684 : MaxConnections != ControlFile->MaxConnections ||
9094 [ + + ]: 683 : max_worker_processes != ControlFile->max_worker_processes ||
9095 [ + + ]: 680 : max_wal_senders != ControlFile->max_wal_senders ||
9096 [ + + ]: 652 : max_prepared_xacts != ControlFile->max_prepared_xacts ||
9097 [ + - ]: 544 : max_locks_per_xact != ControlFile->max_locks_per_xact ||
9098 [ + + ]: 544 : track_commit_timestamp != ControlFile->track_commit_timestamp)
9099 : : {
9100 : : /*
9101 : : * The change in number of backend slots doesn't need to be WAL-logged
9102 : : * if archiving is not enabled, as you can't start archive recovery
9103 : : * with wal_level=minimal anyway. We don't really care about the
9104 : : * values in pg_control either if wal_level=minimal, but seems better
9105 : : * to keep them up-to-date to avoid confusion.
9106 : : */
9107 [ + + + + ]: 525 : if (wal_level != ControlFile->wal_level || XLogIsNeeded())
9108 : : {
9109 : : xl_parameter_change xlrec;
9110 : : XLogRecPtr recptr;
9111 : :
9112 : 497 : xlrec.MaxConnections = MaxConnections;
9113 : 497 : xlrec.max_worker_processes = max_worker_processes;
9114 : 497 : xlrec.max_wal_senders = max_wal_senders;
9115 : 497 : xlrec.max_prepared_xacts = max_prepared_xacts;
9116 : 497 : xlrec.max_locks_per_xact = max_locks_per_xact;
9117 : 497 : xlrec.wal_level = wal_level;
9118 : 497 : xlrec.wal_log_hints = wal_log_hints;
9119 : 497 : xlrec.track_commit_timestamp = track_commit_timestamp;
9120 : :
9121 : 497 : XLogBeginInsert();
9122 : 497 : XLogRegisterData(&xlrec, sizeof(xlrec));
9123 : :
9124 : 497 : recptr = XLogInsert(RM_XLOG_ID, XLOG_PARAMETER_CHANGE);
9125 : 497 : XLogFlush(recptr);
9126 : : }
9127 : :
9128 : 525 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9129 : :
9130 : 525 : ControlFile->MaxConnections = MaxConnections;
9131 : 525 : ControlFile->max_worker_processes = max_worker_processes;
9132 : 525 : ControlFile->max_wal_senders = max_wal_senders;
9133 : 525 : ControlFile->max_prepared_xacts = max_prepared_xacts;
9134 : 525 : ControlFile->max_locks_per_xact = max_locks_per_xact;
9135 : 525 : ControlFile->wal_level = wal_level;
9136 : 525 : ControlFile->wal_log_hints = wal_log_hints;
9137 : 525 : ControlFile->track_commit_timestamp = track_commit_timestamp;
9138 : 525 : UpdateControlFile();
9139 : :
9140 : 525 : LWLockRelease(ControlFileLock);
9141 : : }
9142 : 1057 : }
9143 : :
9144 : : /*
9145 : : * XLogChecksums
9146 : : * Log and publish the new state of checksums
9147 : : *
9148 : : * Inserting the record and publishing the new state must be atomic with
9149 : : * respect to a checkpoint sampling the state for its XLOG_CHECKPOINT_REDO
9150 : : * record: without that, a checkpoint could read the old state after the
9151 : : * record is already in WAL and insert a redo record that both follows the
9152 : : * transition in WAL order and carries the pre-transition state. Recovery
9153 : : * resuming from such a redo point would never replay the transition record
9154 : : * and resolve the finished transition as interrupted.
9155 : : * DataChecksumTransitionLock serializes the two; see CreateCheckPoint().
9156 : : *
9157 : : * Returns the end LSN of the inserted record, which the caller persists
9158 : : * together with the new state as the data checksum watermark.
9159 : : */
9160 : : static XLogRecPtr
9161 : 53 : XLogChecksums(uint32 new_type)
9162 : : {
9163 : : xl_checksum_state xlrec;
9164 : : XLogRecPtr recptr;
9165 : :
9166 : 53 : xlrec.new_checksum_state = new_type;
9167 : :
9168 : 53 : LWLockAcquire(DataChecksumTransitionLock, LW_EXCLUSIVE);
9169 : :
9170 : 53 : XLogBeginInsert();
9171 : 53 : XLogRegisterData((char *) &xlrec, sizeof(xl_checksum_state));
9172 : :
9173 : 53 : recptr = XLogInsert(RM_XLOG2_ID, XLOG2_CHECKSUMS);
9174 : 53 : pg_atomic_write_u64(&XLogCtl->lastChecksumChangeRecPtr, recptr);
9175 : :
9176 : : /* only loaded by SetDataChecksumsOn(), a no-op for the other callers */
9177 : 53 : INJECTION_POINT_CACHED("datachecksums-on-before-publish", NULL);
9178 : :
9179 : 53 : SpinLockAcquire(&XLogCtl->info_lck);
9180 : 53 : XLogCtl->data_checksum_version = new_type;
9181 : 53 : XLogCtl->data_checksum_lsn = recptr;
9182 : 53 : XLogCtl->data_checksum_is_local = false;
9183 : 53 : SpinLockRelease(&XLogCtl->info_lck);
9184 : :
9185 : 53 : LWLockRelease(DataChecksumTransitionLock);
9186 : :
9187 : 53 : XLogFlush(recptr);
9188 : :
9189 : 53 : return recptr;
9190 : : }
9191 : :
9192 : : /*
9193 : : * Update full_page_writes in shared memory, and write an
9194 : : * XLOG_FPW_CHANGE record if necessary.
9195 : : *
9196 : : * Note: this function assumes there is no other process running
9197 : : * concurrently that could update it.
9198 : : */
9199 : : void
9200 : 1816 : UpdateFullPageWrites(void)
9201 : : {
9202 : 1816 : XLogCtlInsert *Insert = &XLogCtl->Insert;
9203 : : bool recoveryInProgress;
9204 : :
9205 : : /*
9206 : : * Do nothing if full_page_writes has not been changed.
9207 : : *
9208 : : * It's safe to check the shared full_page_writes without the lock,
9209 : : * because we assume that there is no concurrently running process which
9210 : : * can update it.
9211 : : */
9212 [ + + ]: 1816 : if (fullPageWrites == Insert->fullPageWrites)
9213 : 1329 : return;
9214 : :
9215 : : /*
9216 : : * Perform this outside critical section so that the WAL insert
9217 : : * initialization done by RecoveryInProgress() doesn't trigger an
9218 : : * assertion failure.
9219 : : */
9220 : 487 : recoveryInProgress = RecoveryInProgress();
9221 : :
9222 : 487 : START_CRIT_SECTION();
9223 : :
9224 : : /*
9225 : : * It's always safe to take full page images, even when not strictly
9226 : : * required, but not the other way round. So if we're setting
9227 : : * full_page_writes to true, first set it true and then write the WAL
9228 : : * record. If we're setting it to false, first write the WAL record and
9229 : : * then set the global flag.
9230 : : */
9231 [ + + ]: 487 : if (fullPageWrites)
9232 : : {
9233 : 473 : WALInsertLockAcquireExclusive();
9234 : 473 : Insert->fullPageWrites = true;
9235 : 473 : WALInsertLockRelease();
9236 : : }
9237 : :
9238 : : /*
9239 : : * Write an XLOG_FPW_CHANGE record. This allows us to keep track of
9240 : : * full_page_writes during archive recovery, if required.
9241 : : */
9242 [ + + + + ]: 487 : if (XLogStandbyInfoActive() && !recoveryInProgress)
9243 : : {
9244 : 1 : XLogBeginInsert();
9245 : 1 : XLogRegisterData(&fullPageWrites, sizeof(bool));
9246 : :
9247 : 1 : XLogInsert(RM_XLOG_ID, XLOG_FPW_CHANGE);
9248 : : }
9249 : :
9250 [ + + ]: 487 : if (!fullPageWrites)
9251 : : {
9252 : 14 : WALInsertLockAcquireExclusive();
9253 : 14 : Insert->fullPageWrites = false;
9254 : 14 : WALInsertLockRelease();
9255 : : }
9256 : 487 : END_CRIT_SECTION();
9257 : : }
9258 : :
9259 : : /*
9260 : : * XLOG resource manager's routines
9261 : : *
9262 : : * Definitions of info values are in include/catalog/pg_control.h, though
9263 : : * not all record types are related to control file updates.
9264 : : *
9265 : : * NOTE: Some XLOG record types that are directly related to WAL recovery
9266 : : * are handled in xlogrecovery_redo().
9267 : : */
9268 : : void
9269 : 118819 : xlog_redo(XLogReaderState *record)
9270 : : {
9271 : 118819 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9272 : 118819 : XLogRecPtr lsn = record->EndRecPtr;
9273 : :
9274 : : /*
9275 : : * In XLOG rmgr, backup blocks are only used by XLOG_FPI and
9276 : : * XLOG_FPI_FOR_HINT records.
9277 : : */
9278 : : Assert(info == XLOG_FPI || info == XLOG_FPI_FOR_HINT ||
9279 : : !XLogRecHasAnyBlockRefs(record));
9280 : :
9281 [ + + ]: 118819 : if (info == XLOG_NEXTOID)
9282 : : {
9283 : : Oid8 nextOid;
9284 : :
9285 : : /*
9286 : : * We used to try to take the maximum of TransamVariables->nextOid and
9287 : : * the recorded nextOid, but that failed back when the counter was 4
9288 : : * bytes wide and could wrap around. Since no OID allocation should
9289 : : * be happening during replay anyway, better to just believe the
9290 : : * record exactly. We still take OidGenLock while setting the
9291 : : * variable, just in case.
9292 : : */
9293 : 104 : memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid8));
9294 : 104 : LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9295 : 104 : TransamVariables->nextOid = nextOid;
9296 : 104 : TransamVariables->oidCount = 0;
9297 : 104 : LWLockRelease(OidGenLock);
9298 : : }
9299 [ + + ]: 118715 : else if (info == XLOG_CHECKPOINT_SHUTDOWN)
9300 : : {
9301 : : CheckPoint checkPoint;
9302 : : TimeLineID replayTLI;
9303 : :
9304 : 48 : memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9305 : : /* In a SHUTDOWN checkpoint, believe the counters exactly */
9306 : 48 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
9307 : 48 : TransamVariables->nextXid = checkPoint.nextXid;
9308 : 48 : LWLockRelease(XidGenLock);
9309 : 48 : LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
9310 : 48 : TransamVariables->nextOid = checkPoint.nextOid;
9311 : 48 : TransamVariables->oidCount = 0;
9312 : 48 : LWLockRelease(OidGenLock);
9313 : 48 : MultiXactSetNextMXact(checkPoint.nextMulti,
9314 : : checkPoint.nextMultiOffset);
9315 : :
9316 : 48 : MultiXactAdvanceOldest(checkPoint.oldestMulti,
9317 : : checkPoint.oldestMultiDB);
9318 : :
9319 : : /*
9320 : : * No need to set oldestClogXid here as well; it'll be set when we
9321 : : * redo an xl_clog_truncate if it changed since initialization.
9322 : : */
9323 : 48 : SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
9324 : :
9325 : : /*
9326 : : * If we see a shutdown checkpoint while waiting for an end-of-backup
9327 : : * record, the backup was canceled and the end-of-backup record will
9328 : : * never arrive.
9329 : : */
9330 [ + - ]: 48 : if (ArchiveRecoveryRequested &&
9331 [ + + ]: 48 : XLogRecPtrIsValid(ControlFile->backupStartPoint) &&
9332 [ - + ]: 1 : !XLogRecPtrIsValid(ControlFile->backupEndPoint))
9333 [ # # ]: 0 : ereport(PANIC,
9334 : : (errmsg("online backup was canceled, recovery cannot continue")));
9335 : :
9336 : : /*
9337 : : * If we see a shutdown checkpoint, we know that nothing was running
9338 : : * on the primary at this point. So fake-up an empty running-xacts
9339 : : * record and use that here and now. Recover additional standby state
9340 : : * for prepared transactions.
9341 : : */
9342 [ + + ]: 48 : if (standbyState >= STANDBY_INITIALIZED)
9343 : : {
9344 : : TransactionId *xids;
9345 : : int nxids;
9346 : : TransactionId oldestActiveXID;
9347 : : TransactionId latestCompletedXid;
9348 : : RunningTransactionsData running;
9349 : :
9350 : 46 : oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
9351 : :
9352 : : /* Update pg_subtrans entries for any prepared transactions */
9353 : 46 : StandbyRecoverPreparedTransactions();
9354 : :
9355 : : /*
9356 : : * Construct a RunningTransactions snapshot representing a shut
9357 : : * down server, with only prepared transactions still alive. We're
9358 : : * never overflowed at this point because all subxids are listed
9359 : : * with their parent prepared transactions.
9360 : : */
9361 : 46 : running.xcnt = nxids;
9362 : 46 : running.subxcnt = 0;
9363 : 46 : running.subxid_status = SUBXIDS_IN_SUBTRANS;
9364 : 46 : running.nextXid = XidFromFullTransactionId(checkPoint.nextXid);
9365 : 46 : running.oldestRunningXid = oldestActiveXID;
9366 : 46 : latestCompletedXid = XidFromFullTransactionId(checkPoint.nextXid);
9367 [ - + ]: 46 : TransactionIdRetreat(latestCompletedXid);
9368 : : Assert(TransactionIdIsNormal(latestCompletedXid));
9369 : 46 : running.latestCompletedXid = latestCompletedXid;
9370 : 46 : running.xids = xids;
9371 : :
9372 : 46 : ProcArrayApplyRecoveryInfo(&running);
9373 : : }
9374 : :
9375 : : /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
9376 : 48 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9377 : 48 : ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
9378 : :
9379 : 48 : UpdateControlFile();
9380 : 48 : LWLockRelease(ControlFileLock);
9381 : :
9382 [ - + ]: 48 : if (adoptChecksumStateFromNextCheckpoint)
9383 : : {
9384 : 0 : adoptChecksumStateFromNextCheckpoint = false;
9385 : 0 : AdoptReplayedDataChecksumState(checkPoint.dataChecksumState,
9386 : : record->ReadRecPtr);
9387 : : }
9388 : : else
9389 : 48 : CheckReplayedDataChecksumState(checkPoint.dataChecksumState);
9390 : :
9391 : : /*
9392 : : * We should've already switched to the new TLI before replaying this
9393 : : * record.
9394 : : */
9395 : 48 : (void) GetCurrentReplayRecPtr(&replayTLI);
9396 [ - + ]: 48 : if (checkPoint.ThisTimeLineID != replayTLI)
9397 [ # # ]: 0 : ereport(PANIC,
9398 : : (errmsg("unexpected timeline ID %u (should be %u) in shutdown checkpoint record",
9399 : : checkPoint.ThisTimeLineID, replayTLI)));
9400 : :
9401 : 48 : RecoveryRestartPoint(&checkPoint, record);
9402 : :
9403 : : /*
9404 : : * After replaying a checkpoint record, free all smgr objects.
9405 : : * Otherwise we would never do so for dropped relations, as the
9406 : : * startup does not process shared invalidation messages or call
9407 : : * AtEOXact_SMgr().
9408 : : */
9409 : 48 : smgrdestroyall();
9410 : : }
9411 [ + + ]: 118667 : else if (info == XLOG_CHECKPOINT_ONLINE)
9412 : : {
9413 : : CheckPoint checkPoint;
9414 : : TimeLineID replayTLI;
9415 : :
9416 : 724 : memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
9417 : : /* In an ONLINE checkpoint, treat the XID counter as a minimum */
9418 : 724 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
9419 [ - + ]: 724 : if (FullTransactionIdPrecedes(TransamVariables->nextXid,
9420 : : checkPoint.nextXid))
9421 : 0 : TransamVariables->nextXid = checkPoint.nextXid;
9422 : 724 : LWLockRelease(XidGenLock);
9423 : :
9424 : : /*
9425 : : * We ignore the nextOid counter in an ONLINE checkpoint, preferring
9426 : : * to track OID assignment through XLOG_NEXTOID records. The nextOid
9427 : : * counter is from the start of the checkpoint and might well be stale
9428 : : * compared to later XLOG_NEXTOID records. We could try to take the
9429 : : * maximum of the nextOid counter and our latest value, but there is
9430 : : * no point in doing so: an online checkpoint records nextOid plus
9431 : : * oidCount, which is never ahead of the last XLOG_NEXTOID record that
9432 : : * replay has applied.
9433 : : */
9434 : :
9435 : : /* Handle multixact */
9436 : 724 : MultiXactAdvanceNextMXact(checkPoint.nextMulti,
9437 : : checkPoint.nextMultiOffset);
9438 : :
9439 : : /*
9440 : : * NB: This may perform multixact truncation when replaying WAL
9441 : : * generated by an older primary.
9442 : : */
9443 : 724 : MultiXactAdvanceOldest(checkPoint.oldestMulti,
9444 : : checkPoint.oldestMultiDB);
9445 [ - + ]: 724 : if (TransactionIdPrecedes(TransamVariables->oldestXid,
9446 : : checkPoint.oldestXid))
9447 : 0 : SetTransactionIdLimit(checkPoint.oldestXid,
9448 : : checkPoint.oldestXidDB);
9449 : : /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
9450 : 724 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9451 : 724 : ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
9452 : 724 : LWLockRelease(ControlFileLock);
9453 : :
9454 : : /* TLI should not change in an on-line checkpoint */
9455 : 724 : (void) GetCurrentReplayRecPtr(&replayTLI);
9456 [ - + ]: 724 : if (checkPoint.ThisTimeLineID != replayTLI)
9457 [ # # ]: 0 : ereport(PANIC,
9458 : : (errmsg("unexpected timeline ID %u (should be %u) in online checkpoint record",
9459 : : checkPoint.ThisTimeLineID, replayTLI)));
9460 : :
9461 : 724 : RecoveryRestartPoint(&checkPoint, record);
9462 : :
9463 : : /*
9464 : : * After replaying a checkpoint record, free all smgr objects.
9465 : : * Otherwise we would never do so for dropped relations, as the
9466 : : * startup does not process shared invalidation messages or call
9467 : : * AtEOXact_SMgr().
9468 : : */
9469 : 724 : smgrdestroyall();
9470 : : }
9471 [ + + ]: 117943 : else if (info == XLOG_OVERWRITE_CONTRECORD)
9472 : : {
9473 : : /* nothing to do here, handled in xlogrecovery_redo() */
9474 : : }
9475 [ + + ]: 117942 : else if (info == XLOG_END_OF_RECOVERY)
9476 : : {
9477 : : xl_end_of_recovery xlrec;
9478 : : TimeLineID replayTLI;
9479 : :
9480 : 14 : memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_end_of_recovery));
9481 : :
9482 : : /*
9483 : : * For Hot Standby, we could treat this like a Shutdown Checkpoint,
9484 : : * but this case is rarer and harder to test, so the benefit doesn't
9485 : : * outweigh the potential extra cost of maintenance.
9486 : : */
9487 : :
9488 : : /*
9489 : : * We should've already switched to the new TLI before replaying this
9490 : : * record.
9491 : : */
9492 : 14 : (void) GetCurrentReplayRecPtr(&replayTLI);
9493 [ - + ]: 14 : if (xlrec.ThisTimeLineID != replayTLI)
9494 [ # # ]: 0 : ereport(PANIC,
9495 : : (errmsg("unexpected timeline ID %u (should be %u) in end-of-recovery record",
9496 : : xlrec.ThisTimeLineID, replayTLI)));
9497 : : }
9498 [ + - ]: 117928 : else if (info == XLOG_NOOP)
9499 : : {
9500 : : /* nothing to do here */
9501 : : }
9502 [ + + ]: 117928 : else if (info == XLOG_SWITCH)
9503 : : {
9504 : : /* nothing to do here */
9505 : : }
9506 [ + + ]: 117454 : else if (info == XLOG_RESTORE_POINT)
9507 : : {
9508 : : /* nothing to do here, handled in xlogrecovery.c */
9509 : : }
9510 [ + + ]: 117449 : else if (info == XLOG_ASSIGN_LSN)
9511 : : {
9512 : : /* nothing to do here, see XLogGetFakeLSN() */
9513 : : }
9514 [ + + + + ]: 55122 : else if (info == XLOG_FPI || info == XLOG_FPI_FOR_HINT)
9515 : : {
9516 : : /*
9517 : : * XLOG_FPI records contain nothing else but one or more block
9518 : : * references. Every block reference must include a full-page image
9519 : : * even if full_page_writes was disabled when the record was generated
9520 : : * - otherwise there would be no point in this record.
9521 : : *
9522 : : * XLOG_FPI_FOR_HINT records are generated when a page needs to be
9523 : : * WAL-logged because of a hint bit update. They are only generated
9524 : : * when checksums and/or wal_log_hints are enabled. They may include
9525 : : * no full-page images if full_page_writes was disabled when they were
9526 : : * generated. In this case there is nothing to do here.
9527 : : *
9528 : : * No recovery conflicts are generated by these generic records - if a
9529 : : * resource manager needs to generate conflicts, it has to define a
9530 : : * separate WAL record type and redo routine.
9531 : : */
9532 [ + + ]: 113296 : for (uint8 block_id = 0; block_id <= XLogRecMaxBlockId(record); block_id++)
9533 : : {
9534 : : Buffer buffer;
9535 : :
9536 [ + + ]: 59081 : if (!XLogRecHasBlockImage(record, block_id))
9537 : : {
9538 [ - + ]: 70 : if (info == XLOG_FPI)
9539 [ # # ]: 0 : elog(ERROR, "XLOG_FPI record did not contain a full-page image");
9540 : 70 : continue;
9541 : : }
9542 : :
9543 [ - + ]: 59011 : if (XLogReadBufferForRedo(record, block_id, &buffer) != BLK_RESTORED)
9544 [ # # ]: 0 : elog(ERROR, "unexpected XLogReadBufferForRedo result when restoring backup block");
9545 : 59011 : UnlockReleaseBuffer(buffer);
9546 : : }
9547 : : }
9548 [ + + ]: 907 : else if (info == XLOG_BACKUP_END)
9549 : : {
9550 : : /* nothing to do here, handled in xlogrecovery_redo() */
9551 : : }
9552 [ + + ]: 796 : else if (info == XLOG_PARAMETER_CHANGE)
9553 : : {
9554 : : xl_parameter_change xlrec;
9555 : :
9556 : : /* Update our copy of the parameters in pg_control */
9557 : 40 : memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_parameter_change));
9558 : :
9559 : 40 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9560 : 40 : ControlFile->MaxConnections = xlrec.MaxConnections;
9561 : 40 : ControlFile->max_worker_processes = xlrec.max_worker_processes;
9562 : 40 : ControlFile->max_wal_senders = xlrec.max_wal_senders;
9563 : 40 : ControlFile->max_prepared_xacts = xlrec.max_prepared_xacts;
9564 : 40 : ControlFile->max_locks_per_xact = xlrec.max_locks_per_xact;
9565 : 40 : ControlFile->wal_level = xlrec.wal_level;
9566 : 40 : ControlFile->wal_log_hints = xlrec.wal_log_hints;
9567 : :
9568 : : /*
9569 : : * Update minRecoveryPoint to ensure that if recovery is aborted, we
9570 : : * recover back up to this point before allowing hot standby again.
9571 : : * This is important if the max_* settings are decreased, to ensure
9572 : : * you don't run queries against the WAL preceding the change. The
9573 : : * local copies cannot be updated as long as crash recovery is
9574 : : * happening and we expect all the WAL to be replayed.
9575 : : */
9576 [ + + ]: 40 : if (InArchiveRecovery)
9577 : : {
9578 : 25 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
9579 : : }
9580 [ + + + + ]: 40 : if (XLogRecPtrIsValid(LocalMinRecoveryPoint) && LocalMinRecoveryPoint < lsn)
9581 : : {
9582 : : TimeLineID replayTLI;
9583 : :
9584 : 14 : (void) GetCurrentReplayRecPtr(&replayTLI);
9585 : 14 : ControlFile->minRecoveryPoint = lsn;
9586 : 14 : ControlFile->minRecoveryPointTLI = replayTLI;
9587 : : }
9588 : :
9589 : 40 : CommitTsParameterChange(xlrec.track_commit_timestamp,
9590 : 40 : ControlFile->track_commit_timestamp);
9591 : 40 : ControlFile->track_commit_timestamp = xlrec.track_commit_timestamp;
9592 : :
9593 : 40 : UpdateControlFile();
9594 : 40 : LWLockRelease(ControlFileLock);
9595 : :
9596 : : /* Check to see if any parameter change gives a problem on recovery */
9597 : 40 : CheckRequiredParameterValues();
9598 : : }
9599 [ + + ]: 756 : else if (info == XLOG_FPW_CHANGE)
9600 : : {
9601 : : bool fpw;
9602 : :
9603 : 1 : memcpy(&fpw, XLogRecGetData(record), sizeof(bool));
9604 : :
9605 : : /*
9606 : : * Update the LSN of the last replayed XLOG_FPW_CHANGE record so that
9607 : : * do_pg_backup_start() and do_pg_backup_stop() can check whether
9608 : : * full_page_writes has been disabled during online backup.
9609 : : */
9610 [ - + ]: 1 : if (!fpw)
9611 : : {
9612 : 0 : SpinLockAcquire(&XLogCtl->info_lck);
9613 [ # # ]: 0 : if (XLogCtl->lastFpwDisableRecPtr < record->ReadRecPtr)
9614 : 0 : XLogCtl->lastFpwDisableRecPtr = record->ReadRecPtr;
9615 : 0 : SpinLockRelease(&XLogCtl->info_lck);
9616 : : }
9617 : :
9618 : : /* Keep track of full_page_writes */
9619 : 1 : lastFullPageWrites = fpw;
9620 : : }
9621 [ + + ]: 755 : else if (info == XLOG_CHECKPOINT_REDO)
9622 : : {
9623 : : xl_checkpoint_redo redo_rec;
9624 : :
9625 : 725 : memcpy(&redo_rec, XLogRecGetData(record), sizeof(xl_checkpoint_redo));
9626 : :
9627 [ + + ]: 725 : if (adoptChecksumStateFromNextCheckpoint)
9628 : : {
9629 : 88 : adoptChecksumStateFromNextCheckpoint = false;
9630 : 88 : AdoptReplayedDataChecksumState(redo_rec.data_checksum_version,
9631 : : record->ReadRecPtr);
9632 : : }
9633 : : else
9634 : 637 : CheckReplayedDataChecksumState(redo_rec.data_checksum_version);
9635 : : }
9636 [ + - ]: 30 : else if (info == XLOG_LOGICAL_DECODING_STATUS_CHANGE)
9637 : : {
9638 : : bool status;
9639 : :
9640 : 30 : memcpy(&status, XLogRecGetData(record), sizeof(bool));
9641 : :
9642 : : /*
9643 : : * We need to toggle the logical decoding status and update the
9644 : : * XLogLogicalInfo cache of processes synchronously because
9645 : : * XLogLogicalInfoActive() is used even during read-only queries
9646 : : * (e.g., via RelationIsAccessibleInLogicalDecoding()). In the
9647 : : * 'disable' case, it is safe to invalidate existing slots after
9648 : : * disabling logical decoding because logical decoding cannot process
9649 : : * subsequent WAL records, which may not contain logical information.
9650 : : */
9651 [ + + ]: 30 : if (status)
9652 : 15 : EnableLogicalDecoding();
9653 : : else
9654 : 15 : DisableLogicalDecoding();
9655 : :
9656 [ + + ]: 30 : elog(DEBUG1, "update logical decoding status to %d during recovery",
9657 : : status);
9658 : :
9659 [ + - + + ]: 30 : if (InRecovery && InHotStandby)
9660 : : {
9661 [ + + ]: 28 : if (!status)
9662 : : {
9663 : : /*
9664 : : * Invalidate logical slots if we are in hot standby and the
9665 : : * primary disabled logical decoding.
9666 : : */
9667 : 15 : InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_LEVEL,
9668 : : 0, InvalidOid,
9669 : : InvalidTransactionId);
9670 : : }
9671 [ - + ]: 13 : else if (sync_replication_slots)
9672 : : {
9673 : : /*
9674 : : * Signal the postmaster to launch the slotsync worker.
9675 : : *
9676 : : * XXX: For simplicity, we keep the slotsync worker running
9677 : : * even after logical decoding is disabled. A future
9678 : : * improvement can consider starting and stopping the worker
9679 : : * based on logical decoding status change.
9680 : : */
9681 : 0 : kill(PostmasterPid, SIGUSR1);
9682 : : }
9683 : : }
9684 : : }
9685 : 118817 : }
9686 : :
9687 : : void
9688 : 9 : xlog2_redo(XLogReaderState *record)
9689 : : {
9690 : 9 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9691 : :
9692 [ + - ]: 9 : if (info == XLOG2_CHECKSUMS)
9693 : : {
9694 : : xl_checksum_state state;
9695 : 9 : XLogRecPtr lsn = record->EndRecPtr;
9696 : : XLogRecPtr watermark;
9697 : :
9698 : 9 : memcpy(&state, XLogRecGetData(record), sizeof(xl_checksum_state));
9699 : :
9700 : 9 : SpinLockAcquire(&XLogCtl->info_lck);
9701 : 9 : watermark = XLogCtl->data_checksum_lsn;
9702 : 9 : SpinLockRelease(&XLogCtl->info_lck);
9703 : :
9704 : : /*
9705 : : * Skip records this node has already applied. The control file
9706 : : * carries the watermark, so this holds across restarts: recovery
9707 : : * resuming below a record whose effect the control file already
9708 : : * contains must not re-apply it, or it would revert a state change
9709 : : * made with pg_checksums in between, which moves the state without
9710 : : * writing any record of its own.
9711 : : */
9712 [ - + ]: 9 : if (lsn <= watermark)
9713 : 0 : return;
9714 : :
9715 : : /* advertise the location before the new state becomes visible */
9716 : 9 : pg_atomic_write_u64(&XLogCtl->lastChecksumChangeRecPtr, lsn);
9717 : :
9718 : 9 : SpinLockAcquire(&XLogCtl->info_lck);
9719 : 9 : XLogCtl->data_checksum_version = state.new_checksum_state;
9720 : 9 : XLogCtl->data_checksum_lsn = lsn;
9721 : 9 : XLogCtl->data_checksum_is_local = false;
9722 : 9 : SetLocalDataChecksumState(state.new_checksum_state);
9723 : 9 : SpinLockRelease(&XLogCtl->info_lck);
9724 : :
9725 : 9 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9726 : :
9727 : : /*
9728 : : * Persist the new state, except when it is "on". Only "on" verifies
9729 : : * checksums during reads, and between the last restartpoint and this
9730 : : * record there may be pages on disk flushed under the old state; a
9731 : : * crash-restart initializes verification from the control file and
9732 : : * replay reads those pages back, so the control file may only say
9733 : : * "on" once everything written under the transition has been flushed,
9734 : : * as restartpoints and the end of recovery do. The opposite direction
9735 : : * cannot wait for the restartpoint: once this record is replayed,
9736 : : * evicted pages are written without checksums, and a control file
9737 : : * still saying "on" would fail verification on exactly those pages
9738 : : * after a crash.
9739 : : */
9740 [ + + ]: 9 : if (state.new_checksum_state != PG_DATA_CHECKSUM_VERSION)
9741 : : {
9742 : 6 : ControlFile->data_checksum_version = state.new_checksum_state;
9743 : 6 : ControlFile->data_checksum_lsn = lsn;
9744 : 6 : ControlFile->data_checksum_is_local = false;
9745 : : }
9746 : :
9747 : : /*
9748 : : * Update minRecoveryPoint to ensure that if recovery is aborted, we
9749 : : * recover back up to this point before allowing hot standby again.
9750 : : * The change location is only tracked in shared memory and is lost
9751 : : * over a restart; a standby becoming consistent below this record
9752 : : * would let base backups resume checksum verification with the
9753 : : * location unknown. The local copies cannot be updated as long as
9754 : : * crash recovery is happening and we expect all the WAL to be
9755 : : * replayed.
9756 : : */
9757 [ + - ]: 9 : if (InArchiveRecovery)
9758 : : {
9759 : 9 : LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
9760 : : }
9761 [ + - + + ]: 9 : if (XLogRecPtrIsValid(LocalMinRecoveryPoint) && LocalMinRecoveryPoint < lsn)
9762 : : {
9763 : : TimeLineID replayTLI;
9764 : :
9765 : 7 : (void) GetCurrentReplayRecPtr(&replayTLI);
9766 : 7 : ControlFile->minRecoveryPoint = lsn;
9767 : 7 : ControlFile->minRecoveryPointTLI = replayTLI;
9768 : : }
9769 : :
9770 : 9 : UpdateControlFile();
9771 : 9 : LWLockRelease(ControlFileLock);
9772 : :
9773 : : /*
9774 : : * Block on a procsignalbarrier to await all processes having seen the
9775 : : * change to checksum status. Once the barrier has been passed we can
9776 : : * initiate the corresponding processing.
9777 : : */
9778 : 9 : EmitAndWaitDataChecksumsBarrier(state.new_checksum_state);
9779 : : }
9780 : : }
9781 : :
9782 : : /*
9783 : : * Return the extra open flags used for opening a file, depending on the
9784 : : * value of the GUCs wal_sync_method, fsync and debug_io_direct.
9785 : : */
9786 : : static int
9787 : 17877 : get_sync_bit(int method)
9788 : : {
9789 : 17877 : int o_direct_flag = 0;
9790 : :
9791 : : /*
9792 : : * Use O_DIRECT if requested, except in walreceiver process. The WAL
9793 : : * written by walreceiver is normally read by the startup process soon
9794 : : * after it's written. Also, walreceiver performs unaligned writes, which
9795 : : * don't work with O_DIRECT, so it is required for correctness too.
9796 : : */
9797 [ + + + - ]: 17877 : if ((io_direct_flags & IO_DIRECT_WAL) && !AmWalReceiverProcess())
9798 : 9 : o_direct_flag = PG_O_DIRECT;
9799 : :
9800 : : /* If fsync is disabled, never open in sync mode */
9801 [ + - ]: 17877 : if (!enableFsync)
9802 : 17877 : return o_direct_flag;
9803 : :
9804 [ # # # # ]: 0 : switch (method)
9805 : : {
9806 : : /*
9807 : : * enum values for all sync options are defined even if they are
9808 : : * not supported on the current platform. But if not, they are
9809 : : * not included in the enum option array, and therefore will never
9810 : : * be seen here.
9811 : : */
9812 : 0 : case WAL_SYNC_METHOD_FSYNC:
9813 : : case WAL_SYNC_METHOD_FSYNC_WRITETHROUGH:
9814 : : case WAL_SYNC_METHOD_FDATASYNC:
9815 : 0 : return o_direct_flag;
9816 : : #ifdef O_SYNC
9817 : 0 : case WAL_SYNC_METHOD_OPEN:
9818 : 0 : return O_SYNC | o_direct_flag;
9819 : : #endif
9820 : : #ifdef O_DSYNC
9821 : 0 : case WAL_SYNC_METHOD_OPEN_DSYNC:
9822 : 0 : return O_DSYNC | o_direct_flag;
9823 : : #endif
9824 : 0 : default:
9825 : : /* can't happen (unless we are out of sync with option array) */
9826 [ # # ]: 0 : elog(ERROR, "unrecognized \"wal_sync_method\": %d", method);
9827 : : return 0; /* silence warning */
9828 : : }
9829 : : }
9830 : :
9831 : : /*
9832 : : * GUC support
9833 : : */
9834 : : void
9835 : 1352 : assign_wal_sync_method(int new_wal_sync_method, void *extra)
9836 : : {
9837 [ - + ]: 1352 : if (wal_sync_method != new_wal_sync_method)
9838 : : {
9839 : : /*
9840 : : * To ensure that no blocks escape unsynced, force an fsync on the
9841 : : * currently open log segment (if any). Also, if the open flag is
9842 : : * changing, close the log file so it will be reopened (with new flag
9843 : : * bit) at next use.
9844 : : */
9845 [ # # ]: 0 : if (openLogFile >= 0)
9846 : : {
9847 : 0 : pgstat_report_wait_start(WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN);
9848 [ # # ]: 0 : if (pg_fsync(openLogFile) != 0)
9849 : : {
9850 : : char xlogfname[MAXFNAMELEN];
9851 : : int save_errno;
9852 : :
9853 : 0 : save_errno = errno;
9854 : 0 : XLogFileName(xlogfname, openLogTLI, openLogSegNo,
9855 : : wal_segment_size);
9856 : 0 : errno = save_errno;
9857 [ # # ]: 0 : ereport(PANIC,
9858 : : (errcode_for_file_access(),
9859 : : errmsg("could not fsync file \"%s\": %m", xlogfname)));
9860 : : }
9861 : :
9862 : 0 : pgstat_report_wait_end();
9863 [ # # ]: 0 : if (get_sync_bit(wal_sync_method) != get_sync_bit(new_wal_sync_method))
9864 : 0 : XLogFileClose();
9865 : : }
9866 : : }
9867 : 1352 : }
9868 : :
9869 : :
9870 : : /*
9871 : : * Issue appropriate kind of fsync (if any) for an XLOG output file.
9872 : : *
9873 : : * 'fd' is a file descriptor for the XLOG file to be fsync'd.
9874 : : * 'segno' is for error reporting purposes.
9875 : : */
9876 : : void
9877 : 207323 : issue_xlog_fsync(int fd, XLogSegNo segno, TimeLineID tli)
9878 : : {
9879 : 207323 : char *msg = NULL;
9880 : : instr_time start;
9881 : :
9882 : : Assert(tli != 0);
9883 : :
9884 : : /*
9885 : : * Quick exit if fsync is disabled or write() has already synced the WAL
9886 : : * file.
9887 : : */
9888 [ - + ]: 207323 : if (!enableFsync ||
9889 [ # # ]: 0 : wal_sync_method == WAL_SYNC_METHOD_OPEN ||
9890 [ # # ]: 0 : wal_sync_method == WAL_SYNC_METHOD_OPEN_DSYNC)
9891 : 207323 : return;
9892 : :
9893 : : /*
9894 : : * Measure I/O timing to sync the WAL file for pg_stat_io.
9895 : : */
9896 : 0 : start = pgstat_prepare_io_time(track_wal_io_timing);
9897 : :
9898 : 0 : pgstat_report_wait_start(WAIT_EVENT_WAL_SYNC);
9899 [ # # # # ]: 0 : switch (wal_sync_method)
9900 : : {
9901 : 0 : case WAL_SYNC_METHOD_FSYNC:
9902 [ # # ]: 0 : if (pg_fsync_no_writethrough(fd) != 0)
9903 : 0 : msg = _("could not fsync file \"%s\": %m");
9904 : 0 : break;
9905 : : #ifdef HAVE_FSYNC_WRITETHROUGH
9906 : : case WAL_SYNC_METHOD_FSYNC_WRITETHROUGH:
9907 : : if (pg_fsync_writethrough(fd) != 0)
9908 : : msg = _("could not fsync write-through file \"%s\": %m");
9909 : : break;
9910 : : #endif
9911 : 0 : case WAL_SYNC_METHOD_FDATASYNC:
9912 [ # # ]: 0 : if (pg_fdatasync(fd) != 0)
9913 : 0 : msg = _("could not fdatasync file \"%s\": %m");
9914 : 0 : break;
9915 : 0 : case WAL_SYNC_METHOD_OPEN:
9916 : : case WAL_SYNC_METHOD_OPEN_DSYNC:
9917 : : /* not reachable */
9918 : : Assert(false);
9919 : 0 : break;
9920 : 0 : default:
9921 [ # # ]: 0 : ereport(PANIC,
9922 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9923 : : errmsg_internal("unrecognized \"wal_sync_method\": %d", wal_sync_method));
9924 : : break;
9925 : : }
9926 : :
9927 : : /* PANIC if failed to fsync */
9928 [ # # ]: 0 : if (msg)
9929 : : {
9930 : : char xlogfname[MAXFNAMELEN];
9931 : 0 : int save_errno = errno;
9932 : :
9933 : 0 : XLogFileName(xlogfname, tli, segno, wal_segment_size);
9934 : 0 : errno = save_errno;
9935 [ # # ]: 0 : ereport(PANIC,
9936 : : (errcode_for_file_access(),
9937 : : errmsg(msg, xlogfname)));
9938 : : }
9939 : :
9940 : 0 : pgstat_report_wait_end();
9941 : :
9942 : 0 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL, IOOP_FSYNC,
9943 : : start, 1, 0);
9944 : : }
9945 : :
9946 : : /*
9947 : : * do_pg_backup_start is the workhorse of the user-visible pg_backup_start()
9948 : : * function. It creates the necessary starting checkpoint and constructs the
9949 : : * backup state and tablespace map.
9950 : : *
9951 : : * Input parameters are "state" (the backup state), "fast" (if true, we do
9952 : : * the checkpoint in fast mode), and "tablespaces" (if non-NULL, indicates a
9953 : : * list of tablespaceinfo structs describing the cluster's tablespaces.).
9954 : : *
9955 : : * The tablespace map contents are appended to passed-in parameter
9956 : : * tablespace_map and the caller is responsible for including it in the backup
9957 : : * archive as 'tablespace_map'. The tablespace_map file is required mainly for
9958 : : * tar format in windows as native windows utilities are not able to create
9959 : : * symlinks while extracting files from tar. However for consistency and
9960 : : * platform-independence, we do it the same way everywhere.
9961 : : *
9962 : : * It fills in "state" with the information required for the backup, such
9963 : : * as the minimum WAL location that must be present to restore from this
9964 : : * backup (starttli) and the corresponding timeline ID (starttli).
9965 : : *
9966 : : * Every successfully started backup must be stopped by calling
9967 : : * do_pg_backup_stop() or do_pg_abort_backup(). There can be many
9968 : : * backups active at the same time.
9969 : : *
9970 : : * It is the responsibility of the caller of this function to verify the
9971 : : * permissions of the calling user!
9972 : : */
9973 : : void
9974 : 194 : do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces,
9975 : : BackupState *state, StringInfo tblspcmapfile)
9976 : : {
9977 : : bool backup_started_in_recovery;
9978 : :
9979 : : Assert(state != NULL);
9980 : 194 : backup_started_in_recovery = RecoveryInProgress();
9981 : :
9982 : : /*
9983 : : * During recovery, we don't need to check WAL level. Because, if WAL
9984 : : * level is not sufficient, it's impossible to get here during recovery.
9985 : : */
9986 [ + + - + ]: 194 : if (!backup_started_in_recovery && !XLogIsNeeded())
9987 [ # # ]: 0 : ereport(ERROR,
9988 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9989 : : errmsg("WAL level not sufficient for making an online backup"),
9990 : : errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start.")));
9991 : :
9992 [ + + ]: 194 : if (strlen(backupidstr) > MAXPGPATH)
9993 [ + - ]: 1 : ereport(ERROR,
9994 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9995 : : errmsg("backup label too long (max %d bytes)",
9996 : : MAXPGPATH)));
9997 : :
9998 : 193 : strlcpy(state->name, backupidstr, sizeof(state->name));
9999 : :
10000 : : /*
10001 : : * Mark backup active in shared memory. We must do full-page WAL writes
10002 : : * during an on-line backup even if not doing so at other times, because
10003 : : * it's quite possible for the backup dump to obtain a "torn" (partially
10004 : : * written) copy of a database page if it reads the page concurrently with
10005 : : * our write to the same page. This can be fixed as long as the first
10006 : : * write to the page in the WAL sequence is a full-page write. Hence, we
10007 : : * increment runningBackups then force a CHECKPOINT, to ensure there are
10008 : : * no dirty pages in shared memory that might get dumped while the backup
10009 : : * is in progress without having a corresponding WAL record. (Once the
10010 : : * backup is complete, we need not force full-page writes anymore, since
10011 : : * we expect that any pages not modified during the backup interval must
10012 : : * have been correctly captured by the backup.)
10013 : : *
10014 : : * Note that forcing full-page writes has no effect during an online
10015 : : * backup from the standby.
10016 : : *
10017 : : * We must hold all the insertion locks to change the value of
10018 : : * runningBackups, to ensure adequate interlocking against
10019 : : * XLogInsertRecord().
10020 : : */
10021 : 193 : WALInsertLockAcquireExclusive();
10022 : 193 : XLogCtl->Insert.runningBackups++;
10023 : 193 : WALInsertLockRelease();
10024 : :
10025 : : /*
10026 : : * Ensure we decrement runningBackups if we fail below. NB -- for this to
10027 : : * work correctly, it is critical that sessionBackupState is only updated
10028 : : * after this block is over.
10029 : : */
10030 [ + - ]: 193 : PG_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(true));
10031 : : {
10032 : 193 : bool gotUniqueStartpoint = false;
10033 : : DIR *tblspcdir;
10034 : : struct dirent *de;
10035 : : tablespaceinfo *ti;
10036 : : int datadirpathlen;
10037 : :
10038 : : /*
10039 : : * Force an XLOG file switch before the checkpoint, to ensure that the
10040 : : * WAL segment the checkpoint is written to doesn't contain pages with
10041 : : * old timeline IDs. That would otherwise happen if you called
10042 : : * pg_backup_start() right after restoring from a PITR archive: the
10043 : : * first WAL segment containing the startup checkpoint has pages in
10044 : : * the beginning with the old timeline ID. That can cause trouble at
10045 : : * recovery: we won't have a history file covering the old timeline if
10046 : : * pg_wal directory was not included in the base backup and the WAL
10047 : : * archive was cleared too before starting the backup.
10048 : : *
10049 : : * During recovery, we skip forcing XLOG file switch, which means that
10050 : : * the backup taken during recovery is not available for the special
10051 : : * recovery case described above.
10052 : : */
10053 [ + + ]: 193 : if (!backup_started_in_recovery)
10054 : 182 : RequestXLogSwitch(false);
10055 : :
10056 : : do
10057 : : {
10058 : : bool checkpointfpw;
10059 : :
10060 : : /*
10061 : : * Force a CHECKPOINT. Aside from being necessary to prevent torn
10062 : : * page problems, this guarantees that two successive backup runs
10063 : : * will have different checkpoint positions and hence different
10064 : : * history file names, even if nothing happened in between.
10065 : : *
10066 : : * During recovery, establish a restartpoint if possible. We use
10067 : : * the last restartpoint as the backup starting checkpoint. This
10068 : : * means that two successive backup runs can have same checkpoint
10069 : : * positions.
10070 : : *
10071 : : * Since the fact that we are executing do_pg_backup_start()
10072 : : * during recovery means that checkpointer is running, we can use
10073 : : * RequestCheckpoint() to establish a restartpoint.
10074 : : *
10075 : : * We use CHECKPOINT_FAST only if requested by user (via passing
10076 : : * fast = true). Otherwise this can take awhile.
10077 : : */
10078 [ + + ]: 193 : RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT |
10079 : : (fast ? CHECKPOINT_FAST : 0));
10080 : :
10081 : : /*
10082 : : * Now we need to fetch the checkpoint record location, and also
10083 : : * its REDO pointer. The oldest point in WAL that would be needed
10084 : : * to restore starting from the checkpoint is precisely the REDO
10085 : : * pointer.
10086 : : */
10087 : 193 : LWLockAcquire(ControlFileLock, LW_SHARED);
10088 : 193 : state->checkpointloc = ControlFile->checkPoint;
10089 : 193 : state->startpoint = ControlFile->checkPointCopy.redo;
10090 : 193 : state->starttli = ControlFile->checkPointCopy.ThisTimeLineID;
10091 : 193 : checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
10092 : 193 : LWLockRelease(ControlFileLock);
10093 : :
10094 [ + + ]: 193 : if (backup_started_in_recovery)
10095 : : {
10096 : : XLogRecPtr recptr;
10097 : :
10098 : : /*
10099 : : * Check to see if all WAL replayed during online backup
10100 : : * (i.e., since last restartpoint used as backup starting
10101 : : * checkpoint) contain full-page writes.
10102 : : */
10103 : 11 : SpinLockAcquire(&XLogCtl->info_lck);
10104 : 11 : recptr = XLogCtl->lastFpwDisableRecPtr;
10105 : 11 : SpinLockRelease(&XLogCtl->info_lck);
10106 : :
10107 [ + - - + ]: 11 : if (!checkpointfpw || state->startpoint <= recptr)
10108 [ # # ]: 0 : ereport(ERROR,
10109 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10110 : : errmsg("WAL generated with \"full_page_writes=off\" was replayed "
10111 : : "since last restartpoint"),
10112 : : errhint("This means that the backup being taken on the standby "
10113 : : "is corrupt and should not be used. "
10114 : : "Enable \"full_page_writes\" and run CHECKPOINT on the primary, "
10115 : : "and then try an online backup again.")));
10116 : :
10117 : : /*
10118 : : * During recovery, since we don't use the end-of-backup WAL
10119 : : * record and don't write the backup history file, the
10120 : : * starting WAL location doesn't need to be unique. This means
10121 : : * that two base backups started at the same time might use
10122 : : * the same checkpoint as starting locations.
10123 : : */
10124 : 11 : gotUniqueStartpoint = true;
10125 : : }
10126 : :
10127 : : /*
10128 : : * If two base backups are started at the same time (in WAL sender
10129 : : * processes), we need to make sure that they use different
10130 : : * checkpoints as starting locations, because we use the starting
10131 : : * WAL location as a unique identifier for the base backup in the
10132 : : * end-of-backup WAL record and when we write the backup history
10133 : : * file. Perhaps it would be better generate a separate unique ID
10134 : : * for each backup instead of forcing another checkpoint, but
10135 : : * taking a checkpoint right after another is not that expensive
10136 : : * either because only few buffers have been dirtied yet.
10137 : : */
10138 : 193 : WALInsertLockAcquireExclusive();
10139 [ + - ]: 193 : if (XLogCtl->Insert.lastBackupStart < state->startpoint)
10140 : : {
10141 : 193 : XLogCtl->Insert.lastBackupStart = state->startpoint;
10142 : 193 : gotUniqueStartpoint = true;
10143 : : }
10144 : 193 : WALInsertLockRelease();
10145 [ - + ]: 193 : } while (!gotUniqueStartpoint);
10146 : :
10147 : : /*
10148 : : * Construct tablespace_map file.
10149 : : */
10150 : 193 : datadirpathlen = strlen(DataDir);
10151 : :
10152 : : /* Collect information about all tablespaces */
10153 : 193 : tblspcdir = AllocateDir(PG_TBLSPC_DIR);
10154 [ + + ]: 616 : while ((de = ReadDir(tblspcdir, PG_TBLSPC_DIR)) != NULL)
10155 : : {
10156 : : char fullpath[MAXPGPATH + sizeof(PG_TBLSPC_DIR)];
10157 : : char linkpath[MAXPGPATH];
10158 : 423 : char *relpath = NULL;
10159 : : char *s;
10160 : : PGFileType de_type;
10161 : : char *badp;
10162 : : Oid tsoid;
10163 : :
10164 : : /*
10165 : : * Try to parse the directory name as an unsigned integer.
10166 : : *
10167 : : * Tablespace directories should be positive integers that can be
10168 : : * represented in 32 bits, with no leading zeroes or trailing
10169 : : * garbage. If we come across a name that doesn't meet those
10170 : : * criteria, skip it.
10171 : : */
10172 [ + + - + ]: 423 : if (de->d_name[0] < '1' || de->d_name[1] > '9')
10173 : 386 : continue;
10174 : 37 : errno = 0;
10175 : 37 : tsoid = strtoul(de->d_name, &badp, 10);
10176 [ + - + - : 37 : if (*badp != '\0' || errno == EINVAL || errno == ERANGE)
- + ]
10177 : 0 : continue;
10178 : :
10179 : 37 : snprintf(fullpath, sizeof(fullpath), "%s/%s", PG_TBLSPC_DIR, de->d_name);
10180 : :
10181 : 37 : de_type = get_dirent_type(fullpath, de, false, ERROR);
10182 : :
10183 [ + + ]: 37 : if (de_type == PGFILETYPE_LNK)
10184 : : {
10185 : : StringInfoData escapedpath;
10186 : : ssize_t rllen;
10187 : :
10188 : 23 : rllen = readlink(fullpath, linkpath, sizeof(linkpath));
10189 [ - + ]: 23 : if (rllen < 0)
10190 : : {
10191 [ # # ]: 0 : ereport(WARNING,
10192 : : (errmsg("could not read symbolic link \"%s\": %m",
10193 : : fullpath)));
10194 : 0 : continue;
10195 : : }
10196 [ - + ]: 23 : else if (rllen >= sizeof(linkpath))
10197 : : {
10198 [ # # ]: 0 : ereport(WARNING,
10199 : : (errmsg("symbolic link \"%s\" target is too long",
10200 : : fullpath)));
10201 : 0 : continue;
10202 : : }
10203 : 23 : linkpath[rllen] = '\0';
10204 : :
10205 : : /*
10206 : : * Relpath holds the relative path of the tablespace directory
10207 : : * when it's located within PGDATA, or NULL if it's located
10208 : : * elsewhere.
10209 : : */
10210 [ + + ]: 23 : if (rllen > datadirpathlen &&
10211 [ - + ]: 1 : strncmp(linkpath, DataDir, datadirpathlen) == 0 &&
10212 [ # # ]: 0 : IS_DIR_SEP(linkpath[datadirpathlen]))
10213 : 0 : relpath = pstrdup(linkpath + datadirpathlen + 1);
10214 : :
10215 : : /*
10216 : : * Add a backslash-escaped version of the link path to the
10217 : : * tablespace map file.
10218 : : */
10219 : 23 : initStringInfo(&escapedpath);
10220 [ + + ]: 562 : for (s = linkpath; *s; s++)
10221 : : {
10222 [ + - + - : 539 : if (*s == '\n' || *s == '\r' || *s == '\\')
- + ]
10223 : 0 : appendStringInfoChar(&escapedpath, '\\');
10224 : 539 : appendStringInfoChar(&escapedpath, *s);
10225 : : }
10226 : 23 : appendStringInfo(tblspcmapfile, "%s %s\n",
10227 : 23 : de->d_name, escapedpath.data);
10228 : 23 : pfree(escapedpath.data);
10229 : : }
10230 [ + - ]: 14 : else if (de_type == PGFILETYPE_DIR)
10231 : : {
10232 : : /*
10233 : : * It's possible to use allow_in_place_tablespaces to create
10234 : : * directories directly under pg_tblspc, for testing purposes
10235 : : * only.
10236 : : *
10237 : : * In this case, we store a relative path rather than an
10238 : : * absolute path into the tablespaceinfo.
10239 : : */
10240 : 14 : snprintf(linkpath, sizeof(linkpath), "%s/%s",
10241 : 14 : PG_TBLSPC_DIR, de->d_name);
10242 : 14 : relpath = pstrdup(linkpath);
10243 : : }
10244 : : else
10245 : : {
10246 : : /* Skip any other file type that appears here. */
10247 : 0 : continue;
10248 : : }
10249 : :
10250 : 37 : ti = palloc_object(tablespaceinfo);
10251 : 37 : ti->oid = tsoid;
10252 : 37 : ti->path = pstrdup(linkpath);
10253 : 37 : ti->rpath = relpath;
10254 : 37 : ti->size = -1;
10255 : :
10256 [ + - ]: 37 : if (tablespaces)
10257 : 37 : *tablespaces = lappend(*tablespaces, ti);
10258 : : }
10259 : 193 : FreeDir(tblspcdir);
10260 : :
10261 : 193 : state->starttime = (pg_time_t) time(NULL);
10262 : : }
10263 [ - + ]: 193 : PG_END_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(true));
10264 : :
10265 : 193 : state->started_in_recovery = backup_started_in_recovery;
10266 : :
10267 : : /*
10268 : : * Mark that the start phase has correctly finished for the backup.
10269 : : */
10270 : 193 : sessionBackupState = SESSION_BACKUP_RUNNING;
10271 : 193 : }
10272 : :
10273 : : /*
10274 : : * Utility routine to fetch the session-level status of a backup running.
10275 : : */
10276 : : SessionBackupState
10277 : 215 : get_backup_status(void)
10278 : : {
10279 : 215 : return sessionBackupState;
10280 : : }
10281 : :
10282 : : /*
10283 : : * do_pg_backup_stop
10284 : : *
10285 : : * Utility function called at the end of an online backup. It creates history
10286 : : * file (if required), resets sessionBackupState and so on. It can optionally
10287 : : * wait for WAL segments to be archived.
10288 : : *
10289 : : * "state" is filled with the information necessary to restore from this
10290 : : * backup with its stop LSN (stoppoint), its timeline ID (stoptli), etc.
10291 : : *
10292 : : * It is the responsibility of the caller of this function to verify the
10293 : : * permissions of the calling user!
10294 : : */
10295 : : void
10296 : 187 : do_pg_backup_stop(BackupState *state, bool waitforarchive)
10297 : : {
10298 : 187 : bool backup_stopped_in_recovery = false;
10299 : : char histfilepath[MAXPGPATH];
10300 : : char lastxlogfilename[MAXFNAMELEN];
10301 : : char histfilename[MAXFNAMELEN];
10302 : : XLogSegNo _logSegNo;
10303 : : FILE *fp;
10304 : : int seconds_before_warning;
10305 : 187 : int waits = 0;
10306 : 187 : bool reported_waiting = false;
10307 : :
10308 : : Assert(state != NULL);
10309 : :
10310 : 187 : backup_stopped_in_recovery = RecoveryInProgress();
10311 : :
10312 : : /*
10313 : : * During recovery, we don't need to check WAL level. Because, if WAL
10314 : : * level is not sufficient, it's impossible to get here during recovery.
10315 : : */
10316 [ + + - + ]: 187 : if (!backup_stopped_in_recovery && !XLogIsNeeded())
10317 [ # # ]: 0 : ereport(ERROR,
10318 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10319 : : errmsg("WAL level not sufficient for making an online backup"),
10320 : : errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start.")));
10321 : :
10322 : : /*
10323 : : * OK to update backup counter and session-level lock.
10324 : : *
10325 : : * Note that CHECK_FOR_INTERRUPTS() must not occur while updating them,
10326 : : * otherwise they can be updated inconsistently, which might cause
10327 : : * do_pg_abort_backup() to fail.
10328 : : */
10329 : 187 : WALInsertLockAcquireExclusive();
10330 : :
10331 : : /*
10332 : : * It is expected that each do_pg_backup_start() call is matched by
10333 : : * exactly one do_pg_backup_stop() call.
10334 : : */
10335 : : Assert(XLogCtl->Insert.runningBackups > 0);
10336 : 187 : XLogCtl->Insert.runningBackups--;
10337 : :
10338 : : /*
10339 : : * Clean up session-level lock.
10340 : : *
10341 : : * You might think that WALInsertLockRelease() can be called before
10342 : : * cleaning up session-level lock because session-level lock doesn't need
10343 : : * to be protected with WAL insertion lock. But since
10344 : : * CHECK_FOR_INTERRUPTS() can occur in it, session-level lock must be
10345 : : * cleaned up before it.
10346 : : */
10347 : 187 : sessionBackupState = SESSION_BACKUP_NONE;
10348 : :
10349 : 187 : WALInsertLockRelease();
10350 : :
10351 : : /*
10352 : : * If we are taking an online backup from the standby, we confirm that the
10353 : : * standby has not been promoted during the backup.
10354 : : */
10355 [ + + - + ]: 187 : if (state->started_in_recovery && !backup_stopped_in_recovery)
10356 [ # # ]: 0 : ereport(ERROR,
10357 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10358 : : errmsg("the standby was promoted during online backup"),
10359 : : errhint("This means that the backup being taken is corrupt "
10360 : : "and should not be used. "
10361 : : "Try taking another online backup.")));
10362 : :
10363 : : /*
10364 : : * During recovery, we don't write an end-of-backup record. We assume that
10365 : : * pg_control was backed up last and its minimum recovery point can be
10366 : : * available as the backup end location. Since we don't have an
10367 : : * end-of-backup record, we use the pg_control value to check whether
10368 : : * we've reached the end of backup when starting recovery from this
10369 : : * backup. We have no way of checking if pg_control wasn't backed up last
10370 : : * however.
10371 : : *
10372 : : * We don't force a switch to new WAL file but it is still possible to
10373 : : * wait for all the required files to be archived if waitforarchive is
10374 : : * true. This is okay if we use the backup to start a standby and fetch
10375 : : * the missing WAL using streaming replication. But in the case of an
10376 : : * archive recovery, a user should set waitforarchive to true and wait for
10377 : : * them to be archived to ensure that all the required files are
10378 : : * available.
10379 : : *
10380 : : * We return the current minimum recovery point as the backup end
10381 : : * location. Note that it can be greater than the exact backup end
10382 : : * location if the minimum recovery point is updated after the backup of
10383 : : * pg_control. This is harmless for current uses.
10384 : : *
10385 : : * XXX currently a backup history file is for informational and debug
10386 : : * purposes only. It's not essential for an online backup. Furthermore,
10387 : : * even if it's created, it will not be archived during recovery because
10388 : : * an archiver is not invoked. So it doesn't seem worthwhile to write a
10389 : : * backup history file during recovery.
10390 : : */
10391 [ + + ]: 187 : if (backup_stopped_in_recovery)
10392 : : {
10393 : : XLogRecPtr recptr;
10394 : :
10395 : : /*
10396 : : * Check to see if all WAL replayed during online backup contain
10397 : : * full-page writes.
10398 : : */
10399 : 11 : SpinLockAcquire(&XLogCtl->info_lck);
10400 : 11 : recptr = XLogCtl->lastFpwDisableRecPtr;
10401 : 11 : SpinLockRelease(&XLogCtl->info_lck);
10402 : :
10403 [ - + ]: 11 : if (state->startpoint <= recptr)
10404 [ # # ]: 0 : ereport(ERROR,
10405 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10406 : : errmsg("WAL generated with \"full_page_writes=off\" was replayed "
10407 : : "during online backup"),
10408 : : errhint("This means that the backup being taken on the standby "
10409 : : "is corrupt and should not be used. "
10410 : : "Enable \"full_page_writes\" and run CHECKPOINT on the primary, "
10411 : : "and then try an online backup again.")));
10412 : :
10413 : :
10414 : 11 : LWLockAcquire(ControlFileLock, LW_SHARED);
10415 : 11 : state->stoppoint = ControlFile->minRecoveryPoint;
10416 : 11 : state->stoptli = ControlFile->minRecoveryPointTLI;
10417 : 11 : LWLockRelease(ControlFileLock);
10418 : : }
10419 : : else
10420 : : {
10421 : : char *history_file;
10422 : :
10423 : : /*
10424 : : * Write the backup-end xlog record
10425 : : */
10426 : 176 : XLogBeginInsert();
10427 : 176 : XLogRegisterData(&state->startpoint,
10428 : : sizeof(state->startpoint));
10429 : 176 : state->stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END);
10430 : :
10431 : : /*
10432 : : * Given that we're not in recovery, InsertTimeLineID is set and can't
10433 : : * change, so we can read it without a lock.
10434 : : */
10435 : 176 : state->stoptli = XLogCtl->InsertTimeLineID;
10436 : :
10437 : : /*
10438 : : * Force a switch to a new xlog segment file, so that the backup is
10439 : : * valid as soon as archiver moves out the current segment file.
10440 : : */
10441 : 176 : RequestXLogSwitch(false);
10442 : :
10443 : 176 : state->stoptime = (pg_time_t) time(NULL);
10444 : :
10445 : : /*
10446 : : * Write the backup history file
10447 : : */
10448 : 176 : XLByteToSeg(state->startpoint, _logSegNo, wal_segment_size);
10449 : 176 : BackupHistoryFilePath(histfilepath, state->stoptli, _logSegNo,
10450 : : state->startpoint, wal_segment_size);
10451 : 176 : fp = AllocateFile(histfilepath, "w");
10452 [ - + ]: 176 : if (!fp)
10453 [ # # ]: 0 : ereport(ERROR,
10454 : : (errcode_for_file_access(),
10455 : : errmsg("could not create file \"%s\": %m",
10456 : : histfilepath)));
10457 : :
10458 : : /* Build and save the contents of the backup history file */
10459 : 176 : history_file = build_backup_content(state, true);
10460 : 176 : fprintf(fp, "%s", history_file);
10461 : 176 : pfree(history_file);
10462 : :
10463 [ + - + - : 176 : if (fflush(fp) || ferror(fp) || FreeFile(fp))
- + ]
10464 [ # # ]: 0 : ereport(ERROR,
10465 : : (errcode_for_file_access(),
10466 : : errmsg("could not write file \"%s\": %m",
10467 : : histfilepath)));
10468 : :
10469 : : /*
10470 : : * Clean out any no-longer-needed history files. As a side effect,
10471 : : * this will post a .ready file for the newly created history file,
10472 : : * notifying the archiver that history file may be archived
10473 : : * immediately.
10474 : : */
10475 : 176 : CleanupBackupHistory();
10476 : : }
10477 : :
10478 : : /*
10479 : : * If archiving is enabled, wait for all the required WAL files to be
10480 : : * archived before returning. If archiving isn't enabled, the required WAL
10481 : : * needs to be transported via streaming replication (hopefully with
10482 : : * wal_keep_size set high enough), or some more exotic mechanism like
10483 : : * polling and copying files from pg_wal with script. We have no knowledge
10484 : : * of those mechanisms, so it's up to the user to ensure that he gets all
10485 : : * the required WAL.
10486 : : *
10487 : : * We wait until both the last WAL file filled during backup and the
10488 : : * history file have been archived, and assume that the alphabetic sorting
10489 : : * property of the WAL files ensures any earlier WAL files are safely
10490 : : * archived as well.
10491 : : *
10492 : : * We wait forever, since archive_command is supposed to work and we
10493 : : * assume the admin wanted his backup to work completely. If you don't
10494 : : * wish to wait, then either waitforarchive should be passed in as false,
10495 : : * or you can set statement_timeout. Also, some notices are issued to
10496 : : * clue in anyone who might be doing this interactively.
10497 : : */
10498 : :
10499 [ + + ]: 187 : if (waitforarchive &&
10500 [ + + + + : 11 : ((!backup_stopped_in_recovery && XLogArchivingActive()) ||
+ + ]
10501 [ - + ]: 1 : (backup_stopped_in_recovery && XLogArchivingAlways())))
10502 : : {
10503 : 5 : XLByteToPrevSeg(state->stoppoint, _logSegNo, wal_segment_size);
10504 : 5 : XLogFileName(lastxlogfilename, state->stoptli, _logSegNo,
10505 : : wal_segment_size);
10506 : :
10507 : 5 : XLByteToSeg(state->startpoint, _logSegNo, wal_segment_size);
10508 : 5 : BackupHistoryFileName(histfilename, state->stoptli, _logSegNo,
10509 : : state->startpoint, wal_segment_size);
10510 : :
10511 : 5 : seconds_before_warning = 60;
10512 : 5 : waits = 0;
10513 : :
10514 [ + + - + ]: 15 : while (XLogArchiveIsBusy(lastxlogfilename) ||
10515 : 5 : XLogArchiveIsBusy(histfilename))
10516 : : {
10517 [ - + ]: 5 : CHECK_FOR_INTERRUPTS();
10518 : :
10519 [ + - - + ]: 5 : if (!reported_waiting && waits > 5)
10520 : : {
10521 [ # # ]: 0 : ereport(NOTICE,
10522 : : (errmsg("base backup done, waiting for required WAL segments to be archived")));
10523 : 0 : reported_waiting = true;
10524 : : }
10525 : :
10526 : 5 : (void) WaitLatch(MyLatch,
10527 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
10528 : : 1000L,
10529 : : WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE);
10530 : 5 : ResetLatch(MyLatch);
10531 : :
10532 [ - + ]: 5 : if (++waits >= seconds_before_warning)
10533 : : {
10534 : 0 : seconds_before_warning *= 2; /* This wraps in >10 years... */
10535 [ # # ]: 0 : ereport(WARNING,
10536 : : (errmsg("still waiting for all required WAL segments to be archived (%d seconds elapsed)",
10537 : : waits),
10538 : : errhint("Check that your \"archive_command\" is executing properly. "
10539 : : "You can safely cancel this backup, "
10540 : : "but the database backup will not be usable without all the WAL segments.")));
10541 : : }
10542 : : }
10543 : :
10544 [ + + ]: 5 : ereport(NOTICE,
10545 : : (errmsg("all required WAL segments have been archived")));
10546 : : }
10547 [ + + ]: 182 : else if (waitforarchive)
10548 [ + - ]: 6 : ereport(NOTICE,
10549 : : (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
10550 : 187 : }
10551 : :
10552 : :
10553 : : /*
10554 : : * do_pg_abort_backup: abort a running backup
10555 : : *
10556 : : * This does just the most basic steps of do_pg_backup_stop(), by taking the
10557 : : * system out of backup mode, thus making it a lot more safe to call from
10558 : : * an error handler.
10559 : : *
10560 : : * 'arg' indicates that it's being called during backup setup; so
10561 : : * sessionBackupState has not been modified yet, but runningBackups has
10562 : : * already been incremented. When it's false, then it's invoked as a
10563 : : * before_shmem_exit handler, and therefore we must not change state
10564 : : * unless sessionBackupState indicates that a backup is actually running.
10565 : : *
10566 : : * NB: This gets used as a PG_ENSURE_ERROR_CLEANUP callback and
10567 : : * before_shmem_exit handler, hence the odd-looking signature.
10568 : : */
10569 : : void
10570 : 9 : do_pg_abort_backup(int code, Datum arg)
10571 : : {
10572 : 9 : bool during_backup_start = DatumGetBool(arg);
10573 : :
10574 : : /* If called during backup start, there shouldn't be one already running */
10575 : : Assert(!during_backup_start || sessionBackupState == SESSION_BACKUP_NONE);
10576 : :
10577 [ + - + + ]: 9 : if (during_backup_start || sessionBackupState != SESSION_BACKUP_NONE)
10578 : : {
10579 : 6 : WALInsertLockAcquireExclusive();
10580 : : Assert(XLogCtl->Insert.runningBackups > 0);
10581 : 6 : XLogCtl->Insert.runningBackups--;
10582 : :
10583 : 6 : sessionBackupState = SESSION_BACKUP_NONE;
10584 : 6 : WALInsertLockRelease();
10585 : :
10586 [ + - ]: 6 : if (!during_backup_start)
10587 [ + - ]: 6 : ereport(WARNING,
10588 : : errmsg("aborting backup due to backend exiting before pg_backup_stop was called"));
10589 : : }
10590 : 9 : }
10591 : :
10592 : : /*
10593 : : * Register a handler that will warn about unterminated backups at end of
10594 : : * session, unless this has already been done.
10595 : : */
10596 : : void
10597 : 5 : register_persistent_abort_backup_handler(void)
10598 : : {
10599 : : static bool already_done = false;
10600 : :
10601 [ + + ]: 5 : if (already_done)
10602 : 1 : return;
10603 : 4 : before_shmem_exit(do_pg_abort_backup, BoolGetDatum(false));
10604 : 4 : already_done = true;
10605 : : }
10606 : :
10607 : : /*
10608 : : * Get latest WAL insert pointer
10609 : : */
10610 : : XLogRecPtr
10611 : 2250 : GetXLogInsertRecPtr(void)
10612 : : {
10613 : 2250 : XLogCtlInsert *Insert = &XLogCtl->Insert;
10614 : : uint64 current_bytepos;
10615 : :
10616 : 2250 : SpinLockAcquire(&Insert->insertpos_lck);
10617 : 2250 : current_bytepos = Insert->CurrBytePos;
10618 : 2250 : SpinLockRelease(&Insert->insertpos_lck);
10619 : :
10620 : 2250 : return XLogBytePosToRecPtr(current_bytepos);
10621 : : }
10622 : :
10623 : : /*
10624 : : * Get latest WAL record end pointer
10625 : : */
10626 : : XLogRecPtr
10627 : 12217 : GetXLogInsertEndRecPtr(void)
10628 : : {
10629 : 12217 : XLogCtlInsert *Insert = &XLogCtl->Insert;
10630 : : uint64 current_bytepos;
10631 : :
10632 : 12217 : SpinLockAcquire(&Insert->insertpos_lck);
10633 : 12217 : current_bytepos = Insert->CurrBytePos;
10634 : 12217 : SpinLockRelease(&Insert->insertpos_lck);
10635 : :
10636 : 12217 : return XLogBytePosToEndRecPtr(current_bytepos);
10637 : : }
10638 : :
10639 : : /*
10640 : : * Get latest WAL write pointer
10641 : : */
10642 : : XLogRecPtr
10643 : 1786 : GetXLogWriteRecPtr(void)
10644 : : {
10645 : 1786 : RefreshXLogWriteResult(LogwrtResult);
10646 : :
10647 : 1786 : return LogwrtResult.Write;
10648 : : }
10649 : :
10650 : : /*
10651 : : * Returns the redo pointer of the last checkpoint or restartpoint. This is
10652 : : * the oldest point in WAL that we still need, if we have to restart recovery.
10653 : : */
10654 : : void
10655 : 407 : GetOldestRestartPoint(XLogRecPtr *oldrecptr, TimeLineID *oldtli)
10656 : : {
10657 : 407 : LWLockAcquire(ControlFileLock, LW_SHARED);
10658 : 407 : *oldrecptr = ControlFile->checkPointCopy.redo;
10659 : 407 : *oldtli = ControlFile->checkPointCopy.ThisTimeLineID;
10660 : 407 : LWLockRelease(ControlFileLock);
10661 : 407 : }
10662 : :
10663 : : /* Thin wrapper around ShutdownWalRcv(). */
10664 : : void
10665 : 1122 : XLogShutdownWalRcv(void)
10666 : : {
10667 : : Assert(AmStartupProcess() || !IsUnderPostmaster);
10668 : :
10669 : 1122 : ShutdownWalRcv();
10670 : 1122 : ResetInstallXLogFileSegmentActive();
10671 : 1122 : }
10672 : :
10673 : : /* Enable WAL file recycling and preallocation. */
10674 : : void
10675 : 1340 : SetInstallXLogFileSegmentActive(void)
10676 : : {
10677 : 1340 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
10678 : 1340 : XLogCtl->InstallXLogFileSegmentActive = true;
10679 : 1340 : LWLockRelease(ControlFileLock);
10680 : 1340 : }
10681 : :
10682 : : /* Disable WAL file recycling and preallocation. */
10683 : : void
10684 : 1298 : ResetInstallXLogFileSegmentActive(void)
10685 : : {
10686 : 1298 : LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
10687 : 1298 : XLogCtl->InstallXLogFileSegmentActive = false;
10688 : 1298 : LWLockRelease(ControlFileLock);
10689 : 1298 : }
10690 : :
10691 : : bool
10692 : 0 : IsInstallXLogFileSegmentActive(void)
10693 : : {
10694 : : bool result;
10695 : :
10696 : 0 : LWLockAcquire(ControlFileLock, LW_SHARED);
10697 : 0 : result = XLogCtl->InstallXLogFileSegmentActive;
10698 : 0 : LWLockRelease(ControlFileLock);
10699 : :
10700 : 0 : return result;
10701 : : }
10702 : :
10703 : : /*
10704 : : * Update the WalWriterSleeping flag.
10705 : : */
10706 : : void
10707 : 638 : SetWalWriterSleeping(bool sleeping)
10708 : : {
10709 : 638 : SpinLockAcquire(&XLogCtl->info_lck);
10710 : 638 : XLogCtl->WalWriterSleeping = sleeping;
10711 : 638 : SpinLockRelease(&XLogCtl->info_lck);
10712 : 638 : }
|