Coverage Report

Created: 2026-12-01 07:00

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