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