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