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