OSDN Git Service

pgindent run for 8.2.
[pg-rex/syncrep.git] / src / backend / access / transam / xlog.c
1 /*-------------------------------------------------------------------------
2  *
3  * xlog.c
4  *              PostgreSQL transaction log manager
5  *
6  *
7  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * $PostgreSQL: pgsql/src/backend/access/transam/xlog.c,v 1.250 2006/10/04 00:29:49 momjian Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14
15 #include "postgres.h"
16
17 #include <ctype.h>
18 #include <fcntl.h>
19 #include <signal.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <sys/stat.h>
23 #include <sys/time.h>
24
25 #include "access/clog.h"
26 #include "access/heapam.h"
27 #include "access/multixact.h"
28 #include "access/subtrans.h"
29 #include "access/transam.h"
30 #include "access/twophase.h"
31 #include "access/xact.h"
32 #include "access/xlog_internal.h"
33 #include "access/xlogutils.h"
34 #include "catalog/catversion.h"
35 #include "catalog/pg_control.h"
36 #include "catalog/pg_type.h"
37 #include "funcapi.h"
38 #include "miscadmin.h"
39 #include "pgstat.h"
40 #include "postmaster/bgwriter.h"
41 #include "storage/bufpage.h"
42 #include "storage/fd.h"
43 #include "storage/pmsignal.h"
44 #include "storage/procarray.h"
45 #include "storage/spin.h"
46 #include "utils/builtins.h"
47 #include "utils/nabstime.h"
48 #include "utils/pg_locale.h"
49
50
51 /*
52  *      Because O_DIRECT bypasses the kernel buffers, and because we never
53  *      read those buffers except during crash recovery, it is a win to use
54  *      it in all cases where we sync on each write().  We could allow O_DIRECT
55  *      with fsync(), but because skipping the kernel buffer forces writes out
56  *      quickly, it seems best just to use it for O_SYNC.  It is hard to imagine
57  *      how fsync() could be a win for O_DIRECT compared to O_SYNC and O_DIRECT.
58  *      Also, O_DIRECT is never enough to force data to the drives, it merely
59  *      tries to bypass the kernel cache, so we still need O_SYNC or fsync().
60  */
61 #ifdef O_DIRECT
62 #define PG_O_DIRECT                             O_DIRECT
63 #else
64 #define PG_O_DIRECT                             0
65 #endif
66
67 /*
68  * This chunk of hackery attempts to determine which file sync methods
69  * are available on the current platform, and to choose an appropriate
70  * default method.      We assume that fsync() is always available, and that
71  * configure determined whether fdatasync() is.
72  */
73 #if defined(O_SYNC)
74 #define BARE_OPEN_SYNC_FLAG             O_SYNC
75 #elif defined(O_FSYNC)
76 #define BARE_OPEN_SYNC_FLAG             O_FSYNC
77 #endif
78 #ifdef BARE_OPEN_SYNC_FLAG
79 #define OPEN_SYNC_FLAG                  (BARE_OPEN_SYNC_FLAG | PG_O_DIRECT)
80 #endif
81
82 #if defined(O_DSYNC)
83 #if defined(OPEN_SYNC_FLAG)
84 /* O_DSYNC is distinct? */
85 #if O_DSYNC != BARE_OPEN_SYNC_FLAG
86 #define OPEN_DATASYNC_FLAG              (O_DSYNC | PG_O_DIRECT)
87 #endif
88 #else                                                   /* !defined(OPEN_SYNC_FLAG) */
89 /* Win32 only has O_DSYNC */
90 #define OPEN_DATASYNC_FLAG              (O_DSYNC | PG_O_DIRECT)
91 #endif
92 #endif
93
94 #if defined(OPEN_DATASYNC_FLAG)
95 #define DEFAULT_SYNC_METHOD_STR "open_datasync"
96 #define DEFAULT_SYNC_METHOD             SYNC_METHOD_OPEN
97 #define DEFAULT_SYNC_FLAGBIT    OPEN_DATASYNC_FLAG
98 #elif defined(HAVE_FDATASYNC)
99 #define DEFAULT_SYNC_METHOD_STR "fdatasync"
100 #define DEFAULT_SYNC_METHOD             SYNC_METHOD_FDATASYNC
101 #define DEFAULT_SYNC_FLAGBIT    0
102 #elif defined(HAVE_FSYNC_WRITETHROUGH_ONLY)
103 #define DEFAULT_SYNC_METHOD_STR "fsync_writethrough"
104 #define DEFAULT_SYNC_METHOD             SYNC_METHOD_FSYNC_WRITETHROUGH
105 #define DEFAULT_SYNC_FLAGBIT    0
106 #else
107 #define DEFAULT_SYNC_METHOD_STR "fsync"
108 #define DEFAULT_SYNC_METHOD             SYNC_METHOD_FSYNC
109 #define DEFAULT_SYNC_FLAGBIT    0
110 #endif
111
112
113 /*
114  * Limitation of buffer-alignment for direct IO depends on OS and filesystem,
115  * but XLOG_BLCKSZ is assumed to be enough for it.
116  */
117 #ifdef O_DIRECT
118 #define ALIGNOF_XLOG_BUFFER             XLOG_BLCKSZ
119 #else
120 #define ALIGNOF_XLOG_BUFFER             ALIGNOF_BUFFER
121 #endif
122
123
124 /* File path names (all relative to $PGDATA) */
125 #define BACKUP_LABEL_FILE               "backup_label"
126 #define BACKUP_LABEL_OLD                "backup_label.old"
127 #define RECOVERY_COMMAND_FILE   "recovery.conf"
128 #define RECOVERY_COMMAND_DONE   "recovery.done"
129
130
131 /* User-settable parameters */
132 int                     CheckPointSegments = 3;
133 int                     XLOGbuffers = 8;
134 int                     XLogArchiveTimeout = 0;
135 char       *XLogArchiveCommand = NULL;
136 char       *XLOG_sync_method = NULL;
137 const char      XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
138 bool            fullPageWrites = true;
139
140 #ifdef WAL_DEBUG
141 bool            XLOG_DEBUG = false;
142 #endif
143
144 /*
145  * XLOGfileslop is used in the code as the allowed "fuzz" in the number of
146  * preallocated XLOG segments --- we try to have at least XLOGfiles advance
147  * segments but no more than XLOGfileslop segments.  This could
148  * be made a separate GUC variable, but at present I think it's sufficient
149  * to hardwire it as 2*CheckPointSegments+1.  Under normal conditions, a
150  * checkpoint will free no more than 2*CheckPointSegments log segments, and
151  * we want to recycle all of them; the +1 allows boundary cases to happen
152  * without wasting a delete/create-segment cycle.
153  */
154
155 #define XLOGfileslop    (2*CheckPointSegments + 1)
156
157
158 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
159 int                     sync_method = DEFAULT_SYNC_METHOD;
160 static int      open_sync_bit = DEFAULT_SYNC_FLAGBIT;
161
162 #define XLOG_SYNC_BIT  (enableFsync ? open_sync_bit : 0)
163
164
165 /*
166  * ThisTimeLineID will be same in all backends --- it identifies current
167  * WAL timeline for the database system.
168  */
169 TimeLineID      ThisTimeLineID = 0;
170
171 /* Are we doing recovery from XLOG? */
172 bool            InRecovery = false;
173
174 /* Are we recovering using offline XLOG archives? */
175 static bool InArchiveRecovery = false;
176
177 /* Was the last xlog file restored from archive, or local? */
178 static bool restoredFromArchive = false;
179
180 /* options taken from recovery.conf */
181 static char *recoveryRestoreCommand = NULL;
182 static bool recoveryTarget = false;
183 static bool recoveryTargetExact = false;
184 static bool recoveryTargetInclusive = true;
185 static TransactionId recoveryTargetXid;
186 static time_t recoveryTargetTime;
187
188 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
189 static TransactionId recoveryStopXid;
190 static time_t recoveryStopTime;
191 static bool recoveryStopAfter;
192
193 /*
194  * During normal operation, the only timeline we care about is ThisTimeLineID.
195  * During recovery, however, things are more complicated.  To simplify life
196  * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
197  * scan through the WAL history (that is, it is the line that was active when
198  * the currently-scanned WAL record was generated).  We also need these
199  * timeline values:
200  *
201  * recoveryTargetTLI: the desired timeline that we want to end in.
202  *
203  * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
204  * its known parents, newest first (so recoveryTargetTLI is always the
205  * first list member).  Only these TLIs are expected to be seen in the WAL
206  * segments we read, and indeed only these TLIs will be considered as
207  * candidate WAL files to open at all.
208  *
209  * curFileTLI: the TLI appearing in the name of the current input WAL file.
210  * (This is not necessarily the same as ThisTimeLineID, because we could
211  * be scanning data that was copied from an ancestor timeline when the current
212  * file was created.)  During a sequential scan we do not allow this value
213  * to decrease.
214  */
215 static TimeLineID recoveryTargetTLI;
216 static List *expectedTLIs;
217 static TimeLineID curFileTLI;
218
219 /*
220  * MyLastRecPtr points to the start of the last XLOG record inserted by the
221  * current transaction.  If MyLastRecPtr.xrecoff == 0, then the current
222  * xact hasn't yet inserted any transaction-controlled XLOG records.
223  *
224  * Note that XLOG records inserted outside transaction control are not
225  * reflected into MyLastRecPtr.  They do, however, cause MyXactMadeXLogEntry
226  * to be set true.      The latter can be used to test whether the current xact
227  * made any loggable changes (including out-of-xact changes, such as
228  * sequence updates).
229  *
230  * When we insert/update/delete a tuple in a temporary relation, we do not
231  * make any XLOG record, since we don't care about recovering the state of
232  * the temp rel after a crash.  However, we will still need to remember
233  * whether our transaction committed or aborted in that case.  So, we must
234  * set MyXactMadeTempRelUpdate true to indicate that the XID will be of
235  * interest later.
236  */
237 XLogRecPtr      MyLastRecPtr = {0, 0};
238
239 bool            MyXactMadeXLogEntry = false;
240
241 bool            MyXactMadeTempRelUpdate = false;
242
243 /*
244  * ProcLastRecPtr points to the start of the last XLOG record inserted by the
245  * current backend.  It is updated for all inserts, transaction-controlled
246  * or not.      ProcLastRecEnd is similar but points to end+1 of last record.
247  */
248 static XLogRecPtr ProcLastRecPtr = {0, 0};
249
250 XLogRecPtr      ProcLastRecEnd = {0, 0};
251
252 /*
253  * RedoRecPtr is this backend's local copy of the REDO record pointer
254  * (which is almost but not quite the same as a pointer to the most recent
255  * CHECKPOINT record).  We update this from the shared-memory copy,
256  * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
257  * hold the Insert lock).  See XLogInsert for details.  We are also allowed
258  * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
259  * see GetRedoRecPtr.  A freshly spawned backend obtains the value during
260  * InitXLOGAccess.
261  */
262 static XLogRecPtr RedoRecPtr;
263
264 /*----------
265  * Shared-memory data structures for XLOG control
266  *
267  * LogwrtRqst indicates a byte position that we need to write and/or fsync
268  * the log up to (all records before that point must be written or fsynced).
269  * LogwrtResult indicates the byte positions we have already written/fsynced.
270  * These structs are identical but are declared separately to indicate their
271  * slightly different functions.
272  *
273  * We do a lot of pushups to minimize the amount of access to lockable
274  * shared memory values.  There are actually three shared-memory copies of
275  * LogwrtResult, plus one unshared copy in each backend.  Here's how it works:
276  *              XLogCtl->LogwrtResult is protected by info_lck
277  *              XLogCtl->Write.LogwrtResult is protected by WALWriteLock
278  *              XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
279  * One must hold the associated lock to read or write any of these, but
280  * of course no lock is needed to read/write the unshared LogwrtResult.
281  *
282  * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
283  * right", since both are updated by a write or flush operation before
284  * it releases WALWriteLock.  The point of keeping XLogCtl->Write.LogwrtResult
285  * is that it can be examined/modified by code that already holds WALWriteLock
286  * without needing to grab info_lck as well.
287  *
288  * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
289  * but is updated when convenient.      Again, it exists for the convenience of
290  * code that is already holding WALInsertLock but not the other locks.
291  *
292  * The unshared LogwrtResult may lag behind any or all of these, and again
293  * is updated when convenient.
294  *
295  * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
296  * (protected by info_lck), but we don't need to cache any copies of it.
297  *
298  * Note that this all works because the request and result positions can only
299  * advance forward, never back up, and so we can easily determine which of two
300  * values is "more up to date".
301  *
302  * info_lck is only held long enough to read/update the protected variables,
303  * so it's a plain spinlock.  The other locks are held longer (potentially
304  * over I/O operations), so we use LWLocks for them.  These locks are:
305  *
306  * WALInsertLock: must be held to insert a record into the WAL buffers.
307  *
308  * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
309  * XLogFlush).
310  *
311  * ControlFileLock: must be held to read/update control file or create
312  * new log file.
313  *
314  * CheckpointLock: must be held to do a checkpoint (ensures only one
315  * checkpointer at a time; currently, with all checkpoints done by the
316  * bgwriter, this is just pro forma).
317  *
318  *----------
319  */
320
321 typedef struct XLogwrtRqst
322 {
323         XLogRecPtr      Write;                  /* last byte + 1 to write out */
324         XLogRecPtr      Flush;                  /* last byte + 1 to flush */
325 } XLogwrtRqst;
326
327 typedef struct XLogwrtResult
328 {
329         XLogRecPtr      Write;                  /* last byte + 1 written out */
330         XLogRecPtr      Flush;                  /* last byte + 1 flushed */
331 } XLogwrtResult;
332
333 /*
334  * Shared state data for XLogInsert.
335  */
336 typedef struct XLogCtlInsert
337 {
338         XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
339         XLogRecPtr      PrevRecord;             /* start of previously-inserted record */
340         int                     curridx;                /* current block index in cache */
341         XLogPageHeader currpage;        /* points to header of block in cache */
342         char       *currpos;            /* current insertion point in cache */
343         XLogRecPtr      RedoRecPtr;             /* current redo point for insertions */
344         bool            forcePageWrites;        /* forcing full-page writes for PITR? */
345 } XLogCtlInsert;
346
347 /*
348  * Shared state data for XLogWrite/XLogFlush.
349  */
350 typedef struct XLogCtlWrite
351 {
352         XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
353         int                     curridx;                /* cache index of next block to write */
354         time_t          lastSegSwitchTime;              /* time of last xlog segment switch */
355 } XLogCtlWrite;
356
357 /*
358  * Total shared-memory state for XLOG.
359  */
360 typedef struct XLogCtlData
361 {
362         /* Protected by WALInsertLock: */
363         XLogCtlInsert Insert;
364
365         /* Protected by info_lck: */
366         XLogwrtRqst LogwrtRqst;
367         XLogwrtResult LogwrtResult;
368         uint32          ckptXidEpoch;   /* nextXID & epoch of latest checkpoint */
369         TransactionId ckptXid;
370
371         /* Protected by WALWriteLock: */
372         XLogCtlWrite Write;
373
374         /*
375          * These values do not change after startup, although the pointed-to pages
376          * and xlblocks values certainly do.  Permission to read/write the pages
377          * and xlblocks values depends on WALInsertLock and WALWriteLock.
378          */
379         char       *pages;                      /* buffers for unwritten XLOG pages */
380         XLogRecPtr *xlblocks;           /* 1st byte ptr-s + XLOG_BLCKSZ */
381         Size            XLogCacheByte;  /* # bytes in xlog buffers */
382         int                     XLogCacheBlck;  /* highest allocated xlog buffer index */
383         TimeLineID      ThisTimeLineID;
384
385         slock_t         info_lck;               /* locks shared variables shown above */
386 } XLogCtlData;
387
388 static XLogCtlData *XLogCtl = NULL;
389
390 /*
391  * We maintain an image of pg_control in shared memory.
392  */
393 static ControlFileData *ControlFile = NULL;
394
395 /*
396  * Macros for managing XLogInsert state.  In most cases, the calling routine
397  * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
398  * so these are passed as parameters instead of being fetched via XLogCtl.
399  */
400
401 /* Free space remaining in the current xlog page buffer */
402 #define INSERT_FREESPACE(Insert)  \
403         (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
404
405 /* Construct XLogRecPtr value for current insertion point */
406 #define INSERT_RECPTR(recptr,Insert,curridx)  \
407         ( \
408           (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
409           (recptr).xrecoff = \
410                 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
411         )
412
413 #define PrevBufIdx(idx)         \
414                 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
415
416 #define NextBufIdx(idx)         \
417                 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
418
419 /*
420  * Private, possibly out-of-date copy of shared LogwrtResult.
421  * See discussion above.
422  */
423 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
424
425 /*
426  * openLogFile is -1 or a kernel FD for an open log file segment.
427  * When it's open, openLogOff is the current seek offset in the file.
428  * openLogId/openLogSeg identify the segment.  These variables are only
429  * used to write the XLOG, and so will normally refer to the active segment.
430  */
431 static int      openLogFile = -1;
432 static uint32 openLogId = 0;
433 static uint32 openLogSeg = 0;
434 static uint32 openLogOff = 0;
435
436 /*
437  * These variables are used similarly to the ones above, but for reading
438  * the XLOG.  Note, however, that readOff generally represents the offset
439  * of the page just read, not the seek position of the FD itself, which
440  * will be just past that page.
441  */
442 static int      readFile = -1;
443 static uint32 readId = 0;
444 static uint32 readSeg = 0;
445 static uint32 readOff = 0;
446
447 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
448 static char *readBuf = NULL;
449
450 /* Buffer for current ReadRecord result (expandable) */
451 static char *readRecordBuf = NULL;
452 static uint32 readRecordBufSize = 0;
453
454 /* State information for XLOG reading */
455 static XLogRecPtr ReadRecPtr;   /* start of last record read */
456 static XLogRecPtr EndRecPtr;    /* end+1 of last record read */
457 static XLogRecord *nextRecord = NULL;
458 static TimeLineID lastPageTLI = 0;
459
460 static bool InRedo = false;
461
462
463 static void XLogArchiveNotify(const char *xlog);
464 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
465 static bool XLogArchiveCheckDone(const char *xlog);
466 static void XLogArchiveCleanup(const char *xlog);
467 static void readRecoveryCommandFile(void);
468 static void exitArchiveRecovery(TimeLineID endTLI,
469                                         uint32 endLogId, uint32 endLogSeg);
470 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
471 static void CheckPointGuts(XLogRecPtr checkPointRedo);
472
473 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
474                                 XLogRecPtr *lsn, BkpBlock *bkpb);
475 static bool AdvanceXLInsertBuffer(bool new_segment);
476 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
477 static int XLogFileInit(uint32 log, uint32 seg,
478                          bool *use_existent, bool use_lock);
479 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
480                                            bool find_free, int *max_advance,
481                                            bool use_lock);
482 static int      XLogFileOpen(uint32 log, uint32 seg);
483 static int      XLogFileRead(uint32 log, uint32 seg, int emode);
484 static void XLogFileClose(void);
485 static bool RestoreArchivedFile(char *path, const char *xlogfname,
486                                         const char *recovername, off_t expectedSize);
487 static int      PreallocXlogFiles(XLogRecPtr endptr);
488 static void MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
489                                 int *nsegsremoved, int *nsegsrecycled);
490 static void CleanupBackupHistory(void);
491 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
492 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
493 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
494 static List *readTimeLineHistory(TimeLineID targetTLI);
495 static bool existsTimeLineHistory(TimeLineID probeTLI);
496 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
497 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
498                                          TimeLineID endTLI,
499                                          uint32 endLogId, uint32 endLogSeg);
500 static void WriteControlFile(void);
501 static void ReadControlFile(void);
502 static char *str_time(time_t tnow);
503 static void issue_xlog_fsync(void);
504
505 #ifdef WAL_DEBUG
506 static void xlog_outrec(StringInfo buf, XLogRecord *record);
507 #endif
508 static bool read_backup_label(XLogRecPtr *checkPointLoc,
509                                   XLogRecPtr *minRecoveryLoc);
510 static void rm_redo_error_callback(void *arg);
511
512
513 /*
514  * Insert an XLOG record having the specified RMID and info bytes,
515  * with the body of the record being the data chunk(s) described by
516  * the rdata chain (see xlog.h for notes about rdata).
517  *
518  * Returns XLOG pointer to end of record (beginning of next record).
519  * This can be used as LSN for data pages affected by the logged action.
520  * (LSN is the XLOG point up to which the XLOG must be flushed to disk
521  * before the data page can be written out.  This implements the basic
522  * WAL rule "write the log before the data".)
523  *
524  * NB: this routine feels free to scribble on the XLogRecData structs,
525  * though not on the data they reference.  This is OK since the XLogRecData
526  * structs are always just temporaries in the calling code.
527  */
528 XLogRecPtr
529 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
530 {
531         XLogCtlInsert *Insert = &XLogCtl->Insert;
532         XLogRecord *record;
533         XLogContRecord *contrecord;
534         XLogRecPtr      RecPtr;
535         XLogRecPtr      WriteRqst;
536         uint32          freespace;
537         int                     curridx;
538         XLogRecData *rdt;
539         Buffer          dtbuf[XLR_MAX_BKP_BLOCKS];
540         bool            dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
541         BkpBlock        dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
542         XLogRecPtr      dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
543         XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
544         XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
545         XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
546         pg_crc32        rdata_crc;
547         uint32          len,
548                                 write_len;
549         unsigned        i;
550         XLogwrtRqst LogwrtRqst;
551         bool            updrqst;
552         bool            doPageWrites;
553         bool            isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
554         bool            no_tran = (rmid == RM_XLOG_ID);
555
556         if (info & XLR_INFO_MASK)
557         {
558                 if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
559                         elog(PANIC, "invalid xlog info mask %02X", (info & XLR_INFO_MASK));
560                 no_tran = true;
561                 info &= ~XLR_INFO_MASK;
562         }
563
564         /*
565          * In bootstrap mode, we don't actually log anything but XLOG resources;
566          * return a phony record pointer.
567          */
568         if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
569         {
570                 RecPtr.xlogid = 0;
571                 RecPtr.xrecoff = SizeOfXLogLongPHD;             /* start of 1st chkpt record */
572                 return RecPtr;
573         }
574
575         /*
576          * Here we scan the rdata chain, determine which buffers must be backed
577          * up, and compute the CRC values for the data.  Note that the record
578          * header isn't added into the CRC initially since we don't know the final
579          * length or info bits quite yet.  Thus, the CRC will represent the CRC of
580          * the whole record in the order "rdata, then backup blocks, then record
581          * header".
582          *
583          * We may have to loop back to here if a race condition is detected below.
584          * We could prevent the race by doing all this work while holding the
585          * insert lock, but it seems better to avoid doing CRC calculations while
586          * holding the lock.  This means we have to be careful about modifying the
587          * rdata chain until we know we aren't going to loop back again.  The only
588          * change we allow ourselves to make earlier is to set rdt->data = NULL in
589          * chain items we have decided we will have to back up the whole buffer
590          * for.  This is OK because we will certainly decide the same thing again
591          * for those items if we do it over; doing it here saves an extra pass
592          * over the chain later.
593          */
594 begin:;
595         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
596         {
597                 dtbuf[i] = InvalidBuffer;
598                 dtbuf_bkp[i] = false;
599         }
600
601         /*
602          * Decide if we need to do full-page writes in this XLOG record: true if
603          * full_page_writes is on or we have a PITR request for it.  Since we
604          * don't yet have the insert lock, forcePageWrites could change under us,
605          * but we'll recheck it once we have the lock.
606          */
607         doPageWrites = fullPageWrites || Insert->forcePageWrites;
608
609         INIT_CRC32(rdata_crc);
610         len = 0;
611         for (rdt = rdata;;)
612         {
613                 if (rdt->buffer == InvalidBuffer)
614                 {
615                         /* Simple data, just include it */
616                         len += rdt->len;
617                         COMP_CRC32(rdata_crc, rdt->data, rdt->len);
618                 }
619                 else
620                 {
621                         /* Find info for buffer */
622                         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
623                         {
624                                 if (rdt->buffer == dtbuf[i])
625                                 {
626                                         /* Buffer already referenced by earlier chain item */
627                                         if (dtbuf_bkp[i])
628                                                 rdt->data = NULL;
629                                         else if (rdt->data)
630                                         {
631                                                 len += rdt->len;
632                                                 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
633                                         }
634                                         break;
635                                 }
636                                 if (dtbuf[i] == InvalidBuffer)
637                                 {
638                                         /* OK, put it in this slot */
639                                         dtbuf[i] = rdt->buffer;
640                                         if (XLogCheckBuffer(rdt, doPageWrites,
641                                                                                 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
642                                         {
643                                                 dtbuf_bkp[i] = true;
644                                                 rdt->data = NULL;
645                                         }
646                                         else if (rdt->data)
647                                         {
648                                                 len += rdt->len;
649                                                 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
650                                         }
651                                         break;
652                                 }
653                         }
654                         if (i >= XLR_MAX_BKP_BLOCKS)
655                                 elog(PANIC, "can backup at most %d blocks per xlog record",
656                                          XLR_MAX_BKP_BLOCKS);
657                 }
658                 /* Break out of loop when rdt points to last chain item */
659                 if (rdt->next == NULL)
660                         break;
661                 rdt = rdt->next;
662         }
663
664         /*
665          * Now add the backup block headers and data into the CRC
666          */
667         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
668         {
669                 if (dtbuf_bkp[i])
670                 {
671                         BkpBlock   *bkpb = &(dtbuf_xlg[i]);
672                         char       *page;
673
674                         COMP_CRC32(rdata_crc,
675                                            (char *) bkpb,
676                                            sizeof(BkpBlock));
677                         page = (char *) BufferGetBlock(dtbuf[i]);
678                         if (bkpb->hole_length == 0)
679                         {
680                                 COMP_CRC32(rdata_crc,
681                                                    page,
682                                                    BLCKSZ);
683                         }
684                         else
685                         {
686                                 /* must skip the hole */
687                                 COMP_CRC32(rdata_crc,
688                                                    page,
689                                                    bkpb->hole_offset);
690                                 COMP_CRC32(rdata_crc,
691                                                    page + (bkpb->hole_offset + bkpb->hole_length),
692                                                    BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
693                         }
694                 }
695         }
696
697         /*
698          * NOTE: We disallow len == 0 because it provides a useful bit of extra
699          * error checking in ReadRecord.  This means that all callers of
700          * XLogInsert must supply at least some not-in-a-buffer data.  However, we
701          * make an exception for XLOG SWITCH records because we don't want them to
702          * ever cross a segment boundary.
703          */
704         if (len == 0 && !isLogSwitch)
705                 elog(PANIC, "invalid xlog record length %u", len);
706
707         START_CRIT_SECTION();
708
709         /* update LogwrtResult before doing cache fill check */
710         {
711                 /* use volatile pointer to prevent code rearrangement */
712                 volatile XLogCtlData *xlogctl = XLogCtl;
713
714                 SpinLockAcquire(&xlogctl->info_lck);
715                 LogwrtRqst = xlogctl->LogwrtRqst;
716                 LogwrtResult = xlogctl->LogwrtResult;
717                 SpinLockRelease(&xlogctl->info_lck);
718         }
719
720         /*
721          * If cache is half filled then try to acquire write lock and do
722          * XLogWrite. Ignore any fractional blocks in performing this check.
723          */
724         LogwrtRqst.Write.xrecoff -= LogwrtRqst.Write.xrecoff % XLOG_BLCKSZ;
725         if (LogwrtRqst.Write.xlogid != LogwrtResult.Write.xlogid ||
726                 (LogwrtRqst.Write.xrecoff >= LogwrtResult.Write.xrecoff +
727                  XLogCtl->XLogCacheByte / 2))
728         {
729                 if (LWLockConditionalAcquire(WALWriteLock, LW_EXCLUSIVE))
730                 {
731                         /*
732                          * Since the amount of data we write here is completely optional
733                          * anyway, tell XLogWrite it can be "flexible" and stop at a
734                          * convenient boundary.  This allows writes triggered by this
735                          * mechanism to synchronize with the cache boundaries, so that in
736                          * a long transaction we'll basically dump alternating halves of
737                          * the buffer array.
738                          */
739                         LogwrtResult = XLogCtl->Write.LogwrtResult;
740                         if (XLByteLT(LogwrtResult.Write, LogwrtRqst.Write))
741                                 XLogWrite(LogwrtRqst, true, false);
742                         LWLockRelease(WALWriteLock);
743                 }
744         }
745
746         /* Now wait to get insert lock */
747         LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
748
749         /*
750          * Check to see if my RedoRecPtr is out of date.  If so, may have to go
751          * back and recompute everything.  This can only happen just after a
752          * checkpoint, so it's better to be slow in this case and fast otherwise.
753          *
754          * If we aren't doing full-page writes then RedoRecPtr doesn't actually
755          * affect the contents of the XLOG record, so we'll update our local copy
756          * but not force a recomputation.
757          */
758         if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
759         {
760                 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
761                 RedoRecPtr = Insert->RedoRecPtr;
762
763                 if (doPageWrites)
764                 {
765                         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
766                         {
767                                 if (dtbuf[i] == InvalidBuffer)
768                                         continue;
769                                 if (dtbuf_bkp[i] == false &&
770                                         XLByteLE(dtbuf_lsn[i], RedoRecPtr))
771                                 {
772                                         /*
773                                          * Oops, this buffer now needs to be backed up, but we
774                                          * didn't think so above.  Start over.
775                                          */
776                                         LWLockRelease(WALInsertLock);
777                                         END_CRIT_SECTION();
778                                         goto begin;
779                                 }
780                         }
781                 }
782         }
783
784         /*
785          * Also check to see if forcePageWrites was just turned on; if we weren't
786          * already doing full-page writes then go back and recompute. (If it was
787          * just turned off, we could recompute the record without full pages, but
788          * we choose not to bother.)
789          */
790         if (Insert->forcePageWrites && !doPageWrites)
791         {
792                 /* Oops, must redo it with full-page data */
793                 LWLockRelease(WALInsertLock);
794                 END_CRIT_SECTION();
795                 goto begin;
796         }
797
798         /*
799          * Make additional rdata chain entries for the backup blocks, so that we
800          * don't need to special-case them in the write loop.  Note that we have
801          * now irrevocably changed the input rdata chain.  At the exit of this
802          * loop, write_len includes the backup block data.
803          *
804          * Also set the appropriate info bits to show which buffers were backed
805          * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
806          * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
807          */
808         write_len = len;
809         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
810         {
811                 BkpBlock   *bkpb;
812                 char       *page;
813
814                 if (!dtbuf_bkp[i])
815                         continue;
816
817                 info |= XLR_SET_BKP_BLOCK(i);
818
819                 bkpb = &(dtbuf_xlg[i]);
820                 page = (char *) BufferGetBlock(dtbuf[i]);
821
822                 rdt->next = &(dtbuf_rdt1[i]);
823                 rdt = rdt->next;
824
825                 rdt->data = (char *) bkpb;
826                 rdt->len = sizeof(BkpBlock);
827                 write_len += sizeof(BkpBlock);
828
829                 rdt->next = &(dtbuf_rdt2[i]);
830                 rdt = rdt->next;
831
832                 if (bkpb->hole_length == 0)
833                 {
834                         rdt->data = page;
835                         rdt->len = BLCKSZ;
836                         write_len += BLCKSZ;
837                         rdt->next = NULL;
838                 }
839                 else
840                 {
841                         /* must skip the hole */
842                         rdt->data = page;
843                         rdt->len = bkpb->hole_offset;
844                         write_len += bkpb->hole_offset;
845
846                         rdt->next = &(dtbuf_rdt3[i]);
847                         rdt = rdt->next;
848
849                         rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
850                         rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
851                         write_len += rdt->len;
852                         rdt->next = NULL;
853                 }
854         }
855
856         /*
857          * If there isn't enough space on the current XLOG page for a record
858          * header, advance to the next page (leaving the unused space as zeroes).
859          */
860         updrqst = false;
861         freespace = INSERT_FREESPACE(Insert);
862         if (freespace < SizeOfXLogRecord)
863         {
864                 updrqst = AdvanceXLInsertBuffer(false);
865                 freespace = INSERT_FREESPACE(Insert);
866         }
867
868         /* Compute record's XLOG location */
869         curridx = Insert->curridx;
870         INSERT_RECPTR(RecPtr, Insert, curridx);
871
872         /*
873          * If the record is an XLOG_SWITCH, and we are exactly at the start of a
874          * segment, we need not insert it (and don't want to because we'd like
875          * consecutive switch requests to be no-ops).  Instead, make sure
876          * everything is written and flushed through the end of the prior segment,
877          * and return the prior segment's end address.
878          */
879         if (isLogSwitch &&
880                 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
881         {
882                 /* We can release insert lock immediately */
883                 LWLockRelease(WALInsertLock);
884
885                 RecPtr.xrecoff -= SizeOfXLogLongPHD;
886                 if (RecPtr.xrecoff == 0)
887                 {
888                         /* crossing a logid boundary */
889                         RecPtr.xlogid -= 1;
890                         RecPtr.xrecoff = XLogFileSize;
891                 }
892
893                 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
894                 LogwrtResult = XLogCtl->Write.LogwrtResult;
895                 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
896                 {
897                         XLogwrtRqst FlushRqst;
898
899                         FlushRqst.Write = RecPtr;
900                         FlushRqst.Flush = RecPtr;
901                         XLogWrite(FlushRqst, false, false);
902                 }
903                 LWLockRelease(WALWriteLock);
904
905                 END_CRIT_SECTION();
906
907                 return RecPtr;
908         }
909
910         /* Insert record header */
911
912         record = (XLogRecord *) Insert->currpos;
913         record->xl_prev = Insert->PrevRecord;
914         record->xl_xid = GetCurrentTransactionIdIfAny();
915         record->xl_tot_len = SizeOfXLogRecord + write_len;
916         record->xl_len = len;           /* doesn't include backup blocks */
917         record->xl_info = info;
918         record->xl_rmid = rmid;
919
920         /* Now we can finish computing the record's CRC */
921         COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
922                            SizeOfXLogRecord - sizeof(pg_crc32));
923         FIN_CRC32(rdata_crc);
924         record->xl_crc = rdata_crc;
925
926 #ifdef WAL_DEBUG
927         if (XLOG_DEBUG)
928         {
929                 StringInfoData buf;
930
931                 initStringInfo(&buf);
932                 appendStringInfo(&buf, "INSERT @ %X/%X: ",
933                                                  RecPtr.xlogid, RecPtr.xrecoff);
934                 xlog_outrec(&buf, record);
935                 if (rdata->data != NULL)
936                 {
937                         appendStringInfo(&buf, " - ");
938                         RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
939                 }
940                 elog(LOG, "%s", buf.data);
941                 pfree(buf.data);
942         }
943 #endif
944
945         /* Record begin of record in appropriate places */
946         if (!no_tran)
947                 MyLastRecPtr = RecPtr;
948         ProcLastRecPtr = RecPtr;
949         Insert->PrevRecord = RecPtr;
950         MyXactMadeXLogEntry = true;
951
952         Insert->currpos += SizeOfXLogRecord;
953         freespace -= SizeOfXLogRecord;
954
955         /*
956          * Append the data, including backup blocks if any
957          */
958         while (write_len)
959         {
960                 while (rdata->data == NULL)
961                         rdata = rdata->next;
962
963                 if (freespace > 0)
964                 {
965                         if (rdata->len > freespace)
966                         {
967                                 memcpy(Insert->currpos, rdata->data, freespace);
968                                 rdata->data += freespace;
969                                 rdata->len -= freespace;
970                                 write_len -= freespace;
971                         }
972                         else
973                         {
974                                 memcpy(Insert->currpos, rdata->data, rdata->len);
975                                 freespace -= rdata->len;
976                                 write_len -= rdata->len;
977                                 Insert->currpos += rdata->len;
978                                 rdata = rdata->next;
979                                 continue;
980                         }
981                 }
982
983                 /* Use next buffer */
984                 updrqst = AdvanceXLInsertBuffer(false);
985                 curridx = Insert->curridx;
986                 /* Insert cont-record header */
987                 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
988                 contrecord = (XLogContRecord *) Insert->currpos;
989                 contrecord->xl_rem_len = write_len;
990                 Insert->currpos += SizeOfXLogContRecord;
991                 freespace = INSERT_FREESPACE(Insert);
992         }
993
994         /* Ensure next record will be properly aligned */
995         Insert->currpos = (char *) Insert->currpage +
996                 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
997         freespace = INSERT_FREESPACE(Insert);
998
999         /*
1000          * The recptr I return is the beginning of the *next* record. This will be
1001          * stored as LSN for changed data pages...
1002          */
1003         INSERT_RECPTR(RecPtr, Insert, curridx);
1004
1005         /*
1006          * If the record is an XLOG_SWITCH, we must now write and flush all the
1007          * existing data, and then forcibly advance to the start of the next
1008          * segment.  It's not good to do this I/O while holding the insert lock,
1009          * but there seems too much risk of confusion if we try to release the
1010          * lock sooner.  Fortunately xlog switch needn't be a high-performance
1011          * operation anyway...
1012          */
1013         if (isLogSwitch)
1014         {
1015                 XLogCtlWrite *Write = &XLogCtl->Write;
1016                 XLogwrtRqst FlushRqst;
1017                 XLogRecPtr      OldSegEnd;
1018
1019                 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1020
1021                 /*
1022                  * Flush through the end of the page containing XLOG_SWITCH, and
1023                  * perform end-of-segment actions (eg, notifying archiver).
1024                  */
1025                 WriteRqst = XLogCtl->xlblocks[curridx];
1026                 FlushRqst.Write = WriteRqst;
1027                 FlushRqst.Flush = WriteRqst;
1028                 XLogWrite(FlushRqst, false, true);
1029
1030                 /* Set up the next buffer as first page of next segment */
1031                 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
1032                 (void) AdvanceXLInsertBuffer(true);
1033
1034                 /* There should be no unwritten data */
1035                 curridx = Insert->curridx;
1036                 Assert(curridx == Write->curridx);
1037
1038                 /* Compute end address of old segment */
1039                 OldSegEnd = XLogCtl->xlblocks[curridx];
1040                 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
1041                 if (OldSegEnd.xrecoff == 0)
1042                 {
1043                         /* crossing a logid boundary */
1044                         OldSegEnd.xlogid -= 1;
1045                         OldSegEnd.xrecoff = XLogFileSize;
1046                 }
1047
1048                 /* Make it look like we've written and synced all of old segment */
1049                 LogwrtResult.Write = OldSegEnd;
1050                 LogwrtResult.Flush = OldSegEnd;
1051
1052                 /*
1053                  * Update shared-memory status --- this code should match XLogWrite
1054                  */
1055                 {
1056                         /* use volatile pointer to prevent code rearrangement */
1057                         volatile XLogCtlData *xlogctl = XLogCtl;
1058
1059                         SpinLockAcquire(&xlogctl->info_lck);
1060                         xlogctl->LogwrtResult = LogwrtResult;
1061                         if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1062                                 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1063                         if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1064                                 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1065                         SpinLockRelease(&xlogctl->info_lck);
1066                 }
1067
1068                 Write->LogwrtResult = LogwrtResult;
1069
1070                 LWLockRelease(WALWriteLock);
1071
1072                 updrqst = false;                /* done already */
1073         }
1074         else
1075         {
1076                 /* normal case, ie not xlog switch */
1077
1078                 /* Need to update shared LogwrtRqst if some block was filled up */
1079                 if (freespace < SizeOfXLogRecord)
1080                 {
1081                         /* curridx is filled and available for writing out */
1082                         updrqst = true;
1083                 }
1084                 else
1085                 {
1086                         /* if updrqst already set, write through end of previous buf */
1087                         curridx = PrevBufIdx(curridx);
1088                 }
1089                 WriteRqst = XLogCtl->xlblocks[curridx];
1090         }
1091
1092         LWLockRelease(WALInsertLock);
1093
1094         if (updrqst)
1095         {
1096                 /* use volatile pointer to prevent code rearrangement */
1097                 volatile XLogCtlData *xlogctl = XLogCtl;
1098
1099                 SpinLockAcquire(&xlogctl->info_lck);
1100                 /* advance global request to include new block(s) */
1101                 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
1102                         xlogctl->LogwrtRqst.Write = WriteRqst;
1103                 /* update local result copy while I have the chance */
1104                 LogwrtResult = xlogctl->LogwrtResult;
1105                 SpinLockRelease(&xlogctl->info_lck);
1106         }
1107
1108         ProcLastRecEnd = RecPtr;
1109
1110         END_CRIT_SECTION();
1111
1112         return RecPtr;
1113 }
1114
1115 /*
1116  * Determine whether the buffer referenced by an XLogRecData item has to
1117  * be backed up, and if so fill a BkpBlock struct for it.  In any case
1118  * save the buffer's LSN at *lsn.
1119  */
1120 static bool
1121 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1122                                 XLogRecPtr *lsn, BkpBlock *bkpb)
1123 {
1124         PageHeader      page;
1125
1126         page = (PageHeader) BufferGetBlock(rdata->buffer);
1127
1128         /*
1129          * XXX We assume page LSN is first data on *every* page that can be passed
1130          * to XLogInsert, whether it otherwise has the standard page layout or
1131          * not.
1132          */
1133         *lsn = page->pd_lsn;
1134
1135         if (doPageWrites &&
1136                 XLByteLE(page->pd_lsn, RedoRecPtr))
1137         {
1138                 /*
1139                  * The page needs to be backed up, so set up *bkpb
1140                  */
1141                 bkpb->node = BufferGetFileNode(rdata->buffer);
1142                 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1143
1144                 if (rdata->buffer_std)
1145                 {
1146                         /* Assume we can omit data between pd_lower and pd_upper */
1147                         uint16          lower = page->pd_lower;
1148                         uint16          upper = page->pd_upper;
1149
1150                         if (lower >= SizeOfPageHeaderData &&
1151                                 upper > lower &&
1152                                 upper <= BLCKSZ)
1153                         {
1154                                 bkpb->hole_offset = lower;
1155                                 bkpb->hole_length = upper - lower;
1156                         }
1157                         else
1158                         {
1159                                 /* No "hole" to compress out */
1160                                 bkpb->hole_offset = 0;
1161                                 bkpb->hole_length = 0;
1162                         }
1163                 }
1164                 else
1165                 {
1166                         /* Not a standard page header, don't try to eliminate "hole" */
1167                         bkpb->hole_offset = 0;
1168                         bkpb->hole_length = 0;
1169                 }
1170
1171                 return true;                    /* buffer requires backup */
1172         }
1173
1174         return false;                           /* buffer does not need to be backed up */
1175 }
1176
1177 /*
1178  * XLogArchiveNotify
1179  *
1180  * Create an archive notification file
1181  *
1182  * The name of the notification file is the message that will be picked up
1183  * by the archiver, e.g. we write 0000000100000001000000C6.ready
1184  * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1185  * then when complete, rename it to 0000000100000001000000C6.done
1186  */
1187 static void
1188 XLogArchiveNotify(const char *xlog)
1189 {
1190         char            archiveStatusPath[MAXPGPATH];
1191         FILE       *fd;
1192
1193         /* insert an otherwise empty file called <XLOG>.ready */
1194         StatusFilePath(archiveStatusPath, xlog, ".ready");
1195         fd = AllocateFile(archiveStatusPath, "w");
1196         if (fd == NULL)
1197         {
1198                 ereport(LOG,
1199                                 (errcode_for_file_access(),
1200                                  errmsg("could not create archive status file \"%s\": %m",
1201                                                 archiveStatusPath)));
1202                 return;
1203         }
1204         if (FreeFile(fd))
1205         {
1206                 ereport(LOG,
1207                                 (errcode_for_file_access(),
1208                                  errmsg("could not write archive status file \"%s\": %m",
1209                                                 archiveStatusPath)));
1210                 return;
1211         }
1212
1213         /* Notify archiver that it's got something to do */
1214         if (IsUnderPostmaster)
1215                 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1216 }
1217
1218 /*
1219  * Convenience routine to notify using log/seg representation of filename
1220  */
1221 static void
1222 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1223 {
1224         char            xlog[MAXFNAMELEN];
1225
1226         XLogFileName(xlog, ThisTimeLineID, log, seg);
1227         XLogArchiveNotify(xlog);
1228 }
1229
1230 /*
1231  * XLogArchiveCheckDone
1232  *
1233  * This is called when we are ready to delete or recycle an old XLOG segment
1234  * file or backup history file.  If it is okay to delete it then return true.
1235  * If it is not time to delete it, make sure a .ready file exists, and return
1236  * false.
1237  *
1238  * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1239  * then return false; else create <XLOG>.ready and return false.
1240  *
1241  * The reason we do things this way is so that if the original attempt to
1242  * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1243  */
1244 static bool
1245 XLogArchiveCheckDone(const char *xlog)
1246 {
1247         char            archiveStatusPath[MAXPGPATH];
1248         struct stat stat_buf;
1249
1250         /* Always deletable if archiving is off */
1251         if (!XLogArchivingActive())
1252                 return true;
1253
1254         /* First check for .done --- this means archiver is done with it */
1255         StatusFilePath(archiveStatusPath, xlog, ".done");
1256         if (stat(archiveStatusPath, &stat_buf) == 0)
1257                 return true;
1258
1259         /* check for .ready --- this means archiver is still busy with it */
1260         StatusFilePath(archiveStatusPath, xlog, ".ready");
1261         if (stat(archiveStatusPath, &stat_buf) == 0)
1262                 return false;
1263
1264         /* Race condition --- maybe archiver just finished, so recheck */
1265         StatusFilePath(archiveStatusPath, xlog, ".done");
1266         if (stat(archiveStatusPath, &stat_buf) == 0)
1267                 return true;
1268
1269         /* Retry creation of the .ready file */
1270         XLogArchiveNotify(xlog);
1271         return false;
1272 }
1273
1274 /*
1275  * XLogArchiveCleanup
1276  *
1277  * Cleanup archive notification file(s) for a particular xlog segment
1278  */
1279 static void
1280 XLogArchiveCleanup(const char *xlog)
1281 {
1282         char            archiveStatusPath[MAXPGPATH];
1283
1284         /* Remove the .done file */
1285         StatusFilePath(archiveStatusPath, xlog, ".done");
1286         unlink(archiveStatusPath);
1287         /* should we complain about failure? */
1288
1289         /* Remove the .ready file if present --- normally it shouldn't be */
1290         StatusFilePath(archiveStatusPath, xlog, ".ready");
1291         unlink(archiveStatusPath);
1292         /* should we complain about failure? */
1293 }
1294
1295 /*
1296  * Advance the Insert state to the next buffer page, writing out the next
1297  * buffer if it still contains unwritten data.
1298  *
1299  * If new_segment is TRUE then we set up the next buffer page as the first
1300  * page of the next xlog segment file, possibly but not usually the next
1301  * consecutive file page.
1302  *
1303  * The global LogwrtRqst.Write pointer needs to be advanced to include the
1304  * just-filled page.  If we can do this for free (without an extra lock),
1305  * we do so here.  Otherwise the caller must do it.  We return TRUE if the
1306  * request update still needs to be done, FALSE if we did it internally.
1307  *
1308  * Must be called with WALInsertLock held.
1309  */
1310 static bool
1311 AdvanceXLInsertBuffer(bool new_segment)
1312 {
1313         XLogCtlInsert *Insert = &XLogCtl->Insert;
1314         XLogCtlWrite *Write = &XLogCtl->Write;
1315         int                     nextidx = NextBufIdx(Insert->curridx);
1316         bool            update_needed = true;
1317         XLogRecPtr      OldPageRqstPtr;
1318         XLogwrtRqst WriteRqst;
1319         XLogRecPtr      NewPageEndPtr;
1320         XLogPageHeader NewPage;
1321
1322         /* Use Insert->LogwrtResult copy if it's more fresh */
1323         if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1324                 LogwrtResult = Insert->LogwrtResult;
1325
1326         /*
1327          * Get ending-offset of the buffer page we need to replace (this may be
1328          * zero if the buffer hasn't been used yet).  Fall through if it's already
1329          * written out.
1330          */
1331         OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1332         if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1333         {
1334                 /* nope, got work to do... */
1335                 XLogRecPtr      FinishedPageRqstPtr;
1336
1337                 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1338
1339                 /* Before waiting, get info_lck and update LogwrtResult */
1340                 {
1341                         /* use volatile pointer to prevent code rearrangement */
1342                         volatile XLogCtlData *xlogctl = XLogCtl;
1343
1344                         SpinLockAcquire(&xlogctl->info_lck);
1345                         if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1346                                 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1347                         LogwrtResult = xlogctl->LogwrtResult;
1348                         SpinLockRelease(&xlogctl->info_lck);
1349                 }
1350
1351                 update_needed = false;  /* Did the shared-request update */
1352
1353                 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1354                 {
1355                         /* OK, someone wrote it already */
1356                         Insert->LogwrtResult = LogwrtResult;
1357                 }
1358                 else
1359                 {
1360                         /* Must acquire write lock */
1361                         LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1362                         LogwrtResult = Write->LogwrtResult;
1363                         if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1364                         {
1365                                 /* OK, someone wrote it already */
1366                                 LWLockRelease(WALWriteLock);
1367                                 Insert->LogwrtResult = LogwrtResult;
1368                         }
1369                         else
1370                         {
1371                                 /*
1372                                  * Have to write buffers while holding insert lock. This is
1373                                  * not good, so only write as much as we absolutely must.
1374                                  */
1375                                 WriteRqst.Write = OldPageRqstPtr;
1376                                 WriteRqst.Flush.xlogid = 0;
1377                                 WriteRqst.Flush.xrecoff = 0;
1378                                 XLogWrite(WriteRqst, false, false);
1379                                 LWLockRelease(WALWriteLock);
1380                                 Insert->LogwrtResult = LogwrtResult;
1381                         }
1382                 }
1383         }
1384
1385         /*
1386          * Now the next buffer slot is free and we can set it up to be the next
1387          * output page.
1388          */
1389         NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1390
1391         if (new_segment)
1392         {
1393                 /* force it to a segment start point */
1394                 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1395                 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1396         }
1397
1398         if (NewPageEndPtr.xrecoff >= XLogFileSize)
1399         {
1400                 /* crossing a logid boundary */
1401                 NewPageEndPtr.xlogid += 1;
1402                 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1403         }
1404         else
1405                 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1406         XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1407         NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1408
1409         Insert->curridx = nextidx;
1410         Insert->currpage = NewPage;
1411
1412         Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1413
1414         /*
1415          * Be sure to re-zero the buffer so that bytes beyond what we've written
1416          * will look like zeroes and not valid XLOG records...
1417          */
1418         MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1419
1420         /*
1421          * Fill the new page's header
1422          */
1423         NewPage   ->xlp_magic = XLOG_PAGE_MAGIC;
1424
1425         /* NewPage->xlp_info = 0; */    /* done by memset */
1426         NewPage   ->xlp_tli = ThisTimeLineID;
1427         NewPage   ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1428         NewPage   ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1429
1430         /*
1431          * If first page of an XLOG segment file, make it a long header.
1432          */
1433         if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1434         {
1435                 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1436
1437                 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1438                 NewLongPage->xlp_seg_size = XLogSegSize;
1439                 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1440                 NewPage   ->xlp_info |= XLP_LONG_HEADER;
1441
1442                 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1443         }
1444
1445         return update_needed;
1446 }
1447
1448 /*
1449  * Write and/or fsync the log at least as far as WriteRqst indicates.
1450  *
1451  * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1452  * may stop at any convenient boundary (such as a cache or logfile boundary).
1453  * This option allows us to avoid uselessly issuing multiple writes when a
1454  * single one would do.
1455  *
1456  * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1457  * perform end-of-segment actions after writing the last page, even if
1458  * it's not physically the end of its segment.  (NB: this will work properly
1459  * only if caller specifies WriteRqst == page-end and flexible == false,
1460  * and there is some data to write.)
1461  *
1462  * Must be called with WALWriteLock held.
1463  */
1464 static void
1465 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1466 {
1467         XLogCtlWrite *Write = &XLogCtl->Write;
1468         bool            ispartialpage;
1469         bool            last_iteration;
1470         bool            finishing_seg;
1471         bool            use_existent;
1472         int                     curridx;
1473         int                     npages;
1474         int                     startidx;
1475         uint32          startoffset;
1476
1477         /* We should always be inside a critical section here */
1478         Assert(CritSectionCount > 0);
1479
1480         /*
1481          * Update local LogwrtResult (caller probably did this already, but...)
1482          */
1483         LogwrtResult = Write->LogwrtResult;
1484
1485         /*
1486          * Since successive pages in the xlog cache are consecutively allocated,
1487          * we can usually gather multiple pages together and issue just one
1488          * write() call.  npages is the number of pages we have determined can be
1489          * written together; startidx is the cache block index of the first one,
1490          * and startoffset is the file offset at which it should go. The latter
1491          * two variables are only valid when npages > 0, but we must initialize
1492          * all of them to keep the compiler quiet.
1493          */
1494         npages = 0;
1495         startidx = 0;
1496         startoffset = 0;
1497
1498         /*
1499          * Within the loop, curridx is the cache block index of the page to
1500          * consider writing.  We advance Write->curridx only after successfully
1501          * writing pages.  (Right now, this refinement is useless since we are
1502          * going to PANIC if any error occurs anyway; but someday it may come in
1503          * useful.)
1504          */
1505         curridx = Write->curridx;
1506
1507         while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1508         {
1509                 /*
1510                  * Make sure we're not ahead of the insert process.  This could happen
1511                  * if we're passed a bogus WriteRqst.Write that is past the end of the
1512                  * last page that's been initialized by AdvanceXLInsertBuffer.
1513                  */
1514                 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1515                         elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1516                                  LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1517                                  XLogCtl->xlblocks[curridx].xlogid,
1518                                  XLogCtl->xlblocks[curridx].xrecoff);
1519
1520                 /* Advance LogwrtResult.Write to end of current buffer page */
1521                 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1522                 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1523
1524                 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1525                 {
1526                         /*
1527                          * Switch to new logfile segment.  We cannot have any pending
1528                          * pages here (since we dump what we have at segment end).
1529                          */
1530                         Assert(npages == 0);
1531                         if (openLogFile >= 0)
1532                                 XLogFileClose();
1533                         XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1534
1535                         /* create/use new log file */
1536                         use_existent = true;
1537                         openLogFile = XLogFileInit(openLogId, openLogSeg,
1538                                                                            &use_existent, true);
1539                         openLogOff = 0;
1540
1541                         /* update pg_control, unless someone else already did */
1542                         LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1543                         if (ControlFile->logId < openLogId ||
1544                                 (ControlFile->logId == openLogId &&
1545                                  ControlFile->logSeg < openLogSeg + 1))
1546                         {
1547                                 ControlFile->logId = openLogId;
1548                                 ControlFile->logSeg = openLogSeg + 1;
1549                                 ControlFile->time = time(NULL);
1550                                 UpdateControlFile();
1551
1552                                 /*
1553                                  * Signal bgwriter to start a checkpoint if it's been too long
1554                                  * since the last one.  (We look at local copy of RedoRecPtr
1555                                  * which might be a little out of date, but should be close
1556                                  * enough for this purpose.)
1557                                  *
1558                                  * A straight computation of segment number could overflow 32
1559                                  * bits.  Rather than assuming we have working 64-bit
1560                                  * arithmetic, we compare the highest-order bits separately,
1561                                  * and force a checkpoint immediately when they change.
1562                                  */
1563                                 if (IsUnderPostmaster)
1564                                 {
1565                                         uint32          old_segno,
1566                                                                 new_segno;
1567                                         uint32          old_highbits,
1568                                                                 new_highbits;
1569
1570                                         old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1571                                                 (RedoRecPtr.xrecoff / XLogSegSize);
1572                                         old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1573                                         new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile +
1574                                                 openLogSeg;
1575                                         new_highbits = openLogId / XLogSegSize;
1576                                         if (new_highbits != old_highbits ||
1577                                                 new_segno >= old_segno + (uint32) CheckPointSegments)
1578                                         {
1579 #ifdef WAL_DEBUG
1580                                                 if (XLOG_DEBUG)
1581                                                         elog(LOG, "time for a checkpoint, signaling bgwriter");
1582 #endif
1583                                                 RequestCheckpoint(false, true);
1584                                         }
1585                                 }
1586                         }
1587                         LWLockRelease(ControlFileLock);
1588                 }
1589
1590                 /* Make sure we have the current logfile open */
1591                 if (openLogFile < 0)
1592                 {
1593                         XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1594                         openLogFile = XLogFileOpen(openLogId, openLogSeg);
1595                         openLogOff = 0;
1596                 }
1597
1598                 /* Add current page to the set of pending pages-to-dump */
1599                 if (npages == 0)
1600                 {
1601                         /* first of group */
1602                         startidx = curridx;
1603                         startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1604                 }
1605                 npages++;
1606
1607                 /*
1608                  * Dump the set if this will be the last loop iteration, or if we are
1609                  * at the last page of the cache area (since the next page won't be
1610                  * contiguous in memory), or if we are at the end of the logfile
1611                  * segment.
1612                  */
1613                 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1614
1615                 finishing_seg = !ispartialpage &&
1616                         (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1617
1618                 if (last_iteration ||
1619                         curridx == XLogCtl->XLogCacheBlck ||
1620                         finishing_seg)
1621                 {
1622                         char       *from;
1623                         Size            nbytes;
1624
1625                         /* Need to seek in the file? */
1626                         if (openLogOff != startoffset)
1627                         {
1628                                 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1629                                         ereport(PANIC,
1630                                                         (errcode_for_file_access(),
1631                                                          errmsg("could not seek in log file %u, "
1632                                                                         "segment %u to offset %u: %m",
1633                                                                         openLogId, openLogSeg, startoffset)));
1634                                 openLogOff = startoffset;
1635                         }
1636
1637                         /* OK to write the page(s) */
1638                         from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1639                         nbytes = npages * (Size) XLOG_BLCKSZ;
1640                         errno = 0;
1641                         if (write(openLogFile, from, nbytes) != nbytes)
1642                         {
1643                                 /* if write didn't set errno, assume no disk space */
1644                                 if (errno == 0)
1645                                         errno = ENOSPC;
1646                                 ereport(PANIC,
1647                                                 (errcode_for_file_access(),
1648                                                  errmsg("could not write to log file %u, segment %u "
1649                                                                 "at offset %u, length %lu: %m",
1650                                                                 openLogId, openLogSeg,
1651                                                                 openLogOff, (unsigned long) nbytes)));
1652                         }
1653
1654                         /* Update state for write */
1655                         openLogOff += nbytes;
1656                         Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1657                         npages = 0;
1658
1659                         /*
1660                          * If we just wrote the whole last page of a logfile segment,
1661                          * fsync the segment immediately.  This avoids having to go back
1662                          * and re-open prior segments when an fsync request comes along
1663                          * later. Doing it here ensures that one and only one backend will
1664                          * perform this fsync.
1665                          *
1666                          * We also do this if this is the last page written for an xlog
1667                          * switch.
1668                          *
1669                          * This is also the right place to notify the Archiver that the
1670                          * segment is ready to copy to archival storage, and to update the
1671                          * timer for archive_timeout.
1672                          */
1673                         if (finishing_seg || (xlog_switch && last_iteration))
1674                         {
1675                                 issue_xlog_fsync();
1676                                 LogwrtResult.Flush = LogwrtResult.Write;                /* end of page */
1677
1678                                 if (XLogArchivingActive())
1679                                         XLogArchiveNotifySeg(openLogId, openLogSeg);
1680
1681                                 Write->lastSegSwitchTime = time(NULL);
1682                         }
1683                 }
1684
1685                 if (ispartialpage)
1686                 {
1687                         /* Only asked to write a partial page */
1688                         LogwrtResult.Write = WriteRqst.Write;
1689                         break;
1690                 }
1691                 curridx = NextBufIdx(curridx);
1692
1693                 /* If flexible, break out of loop as soon as we wrote something */
1694                 if (flexible && npages == 0)
1695                         break;
1696         }
1697
1698         Assert(npages == 0);
1699         Assert(curridx == Write->curridx);
1700
1701         /*
1702          * If asked to flush, do so
1703          */
1704         if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1705                 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1706         {
1707                 /*
1708                  * Could get here without iterating above loop, in which case we might
1709                  * have no open file or the wrong one.  However, we do not need to
1710                  * fsync more than one file.
1711                  */
1712                 if (sync_method != SYNC_METHOD_OPEN)
1713                 {
1714                         if (openLogFile >= 0 &&
1715                                 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1716                                 XLogFileClose();
1717                         if (openLogFile < 0)
1718                         {
1719                                 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1720                                 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1721                                 openLogOff = 0;
1722                         }
1723                         issue_xlog_fsync();
1724                 }
1725                 LogwrtResult.Flush = LogwrtResult.Write;
1726         }
1727
1728         /*
1729          * Update shared-memory status
1730          *
1731          * We make sure that the shared 'request' values do not fall behind the
1732          * 'result' values.  This is not absolutely essential, but it saves some
1733          * code in a couple of places.
1734          */
1735         {
1736                 /* use volatile pointer to prevent code rearrangement */
1737                 volatile XLogCtlData *xlogctl = XLogCtl;
1738
1739                 SpinLockAcquire(&xlogctl->info_lck);
1740                 xlogctl->LogwrtResult = LogwrtResult;
1741                 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1742                         xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1743                 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1744                         xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1745                 SpinLockRelease(&xlogctl->info_lck);
1746         }
1747
1748         Write->LogwrtResult = LogwrtResult;
1749 }
1750
1751 /*
1752  * Ensure that all XLOG data through the given position is flushed to disk.
1753  *
1754  * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1755  * already held, and we try to avoid acquiring it if possible.
1756  */
1757 void
1758 XLogFlush(XLogRecPtr record)
1759 {
1760         XLogRecPtr      WriteRqstPtr;
1761         XLogwrtRqst WriteRqst;
1762
1763         /* Disabled during REDO */
1764         if (InRedo)
1765                 return;
1766
1767         /* Quick exit if already known flushed */
1768         if (XLByteLE(record, LogwrtResult.Flush))
1769                 return;
1770
1771 #ifdef WAL_DEBUG
1772         if (XLOG_DEBUG)
1773                 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1774                          record.xlogid, record.xrecoff,
1775                          LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1776                          LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1777 #endif
1778
1779         START_CRIT_SECTION();
1780
1781         /*
1782          * Since fsync is usually a horribly expensive operation, we try to
1783          * piggyback as much data as we can on each fsync: if we see any more data
1784          * entered into the xlog buffer, we'll write and fsync that too, so that
1785          * the final value of LogwrtResult.Flush is as large as possible. This
1786          * gives us some chance of avoiding another fsync immediately after.
1787          */
1788
1789         /* initialize to given target; may increase below */
1790         WriteRqstPtr = record;
1791
1792         /* read LogwrtResult and update local state */
1793         {
1794                 /* use volatile pointer to prevent code rearrangement */
1795                 volatile XLogCtlData *xlogctl = XLogCtl;
1796
1797                 SpinLockAcquire(&xlogctl->info_lck);
1798                 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1799                         WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1800                 LogwrtResult = xlogctl->LogwrtResult;
1801                 SpinLockRelease(&xlogctl->info_lck);
1802         }
1803
1804         /* done already? */
1805         if (!XLByteLE(record, LogwrtResult.Flush))
1806         {
1807                 /* now wait for the write lock */
1808                 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1809                 LogwrtResult = XLogCtl->Write.LogwrtResult;
1810                 if (!XLByteLE(record, LogwrtResult.Flush))
1811                 {
1812                         /* try to write/flush later additions to XLOG as well */
1813                         if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1814                         {
1815                                 XLogCtlInsert *Insert = &XLogCtl->Insert;
1816                                 uint32          freespace = INSERT_FREESPACE(Insert);
1817
1818                                 if (freespace < SizeOfXLogRecord)               /* buffer is full */
1819                                         WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1820                                 else
1821                                 {
1822                                         WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1823                                         WriteRqstPtr.xrecoff -= freespace;
1824                                 }
1825                                 LWLockRelease(WALInsertLock);
1826                                 WriteRqst.Write = WriteRqstPtr;
1827                                 WriteRqst.Flush = WriteRqstPtr;
1828                         }
1829                         else
1830                         {
1831                                 WriteRqst.Write = WriteRqstPtr;
1832                                 WriteRqst.Flush = record;
1833                         }
1834                         XLogWrite(WriteRqst, false, false);
1835                 }
1836                 LWLockRelease(WALWriteLock);
1837         }
1838
1839         END_CRIT_SECTION();
1840
1841         /*
1842          * If we still haven't flushed to the request point then we have a
1843          * problem; most likely, the requested flush point is past end of XLOG.
1844          * This has been seen to occur when a disk page has a corrupted LSN.
1845          *
1846          * Formerly we treated this as a PANIC condition, but that hurts the
1847          * system's robustness rather than helping it: we do not want to take down
1848          * the whole system due to corruption on one data page.  In particular, if
1849          * the bad page is encountered again during recovery then we would be
1850          * unable to restart the database at all!  (This scenario has actually
1851          * happened in the field several times with 7.1 releases. Note that we
1852          * cannot get here while InRedo is true, but if the bad page is brought in
1853          * and marked dirty during recovery then CreateCheckPoint will try to
1854          * flush it at the end of recovery.)
1855          *
1856          * The current approach is to ERROR under normal conditions, but only
1857          * WARNING during recovery, so that the system can be brought up even if
1858          * there's a corrupt LSN.  Note that for calls from xact.c, the ERROR will
1859          * be promoted to PANIC since xact.c calls this routine inside a critical
1860          * section.  However, calls from bufmgr.c are not within critical sections
1861          * and so we will not force a restart for a bad LSN on a data page.
1862          */
1863         if (XLByteLT(LogwrtResult.Flush, record))
1864                 elog(InRecovery ? WARNING : ERROR,
1865                 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1866                          record.xlogid, record.xrecoff,
1867                          LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1868 }
1869
1870 /*
1871  * Create a new XLOG file segment, or open a pre-existing one.
1872  *
1873  * log, seg: identify segment to be created/opened.
1874  *
1875  * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1876  * pre-existing file will be deleted).  On return, TRUE if a pre-existing
1877  * file was used.
1878  *
1879  * use_lock: if TRUE, acquire ControlFileLock while moving file into
1880  * place.  This should be TRUE except during bootstrap log creation.  The
1881  * caller must *not* hold the lock at call.
1882  *
1883  * Returns FD of opened file.
1884  *
1885  * Note: errors here are ERROR not PANIC because we might or might not be
1886  * inside a critical section (eg, during checkpoint there is no reason to
1887  * take down the system on failure).  They will promote to PANIC if we are
1888  * in a critical section.
1889  */
1890 static int
1891 XLogFileInit(uint32 log, uint32 seg,
1892                          bool *use_existent, bool use_lock)
1893 {
1894         char            path[MAXPGPATH];
1895         char            tmppath[MAXPGPATH];
1896         char            zbuffer[XLOG_BLCKSZ];
1897         uint32          installed_log;
1898         uint32          installed_seg;
1899         int                     max_advance;
1900         int                     fd;
1901         int                     nbytes;
1902
1903         XLogFilePath(path, ThisTimeLineID, log, seg);
1904
1905         /*
1906          * Try to use existent file (checkpoint maker may have created it already)
1907          */
1908         if (*use_existent)
1909         {
1910                 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1911                                                    S_IRUSR | S_IWUSR);
1912                 if (fd < 0)
1913                 {
1914                         if (errno != ENOENT)
1915                                 ereport(ERROR,
1916                                                 (errcode_for_file_access(),
1917                                                  errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1918                                                                 path, log, seg)));
1919                 }
1920                 else
1921                         return fd;
1922         }
1923
1924         /*
1925          * Initialize an empty (all zeroes) segment.  NOTE: it is possible that
1926          * another process is doing the same thing.  If so, we will end up
1927          * pre-creating an extra log segment.  That seems OK, and better than
1928          * holding the lock throughout this lengthy process.
1929          */
1930         snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1931
1932         unlink(tmppath);
1933
1934         /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1935         fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1936                                            S_IRUSR | S_IWUSR);
1937         if (fd < 0)
1938                 ereport(ERROR,
1939                                 (errcode_for_file_access(),
1940                                  errmsg("could not create file \"%s\": %m", tmppath)));
1941
1942         /*
1943          * Zero-fill the file.  We have to do this the hard way to ensure that all
1944          * the file space has really been allocated --- on platforms that allow
1945          * "holes" in files, just seeking to the end doesn't allocate intermediate
1946          * space.  This way, we know that we have all the space and (after the
1947          * fsync below) that all the indirect blocks are down on disk.  Therefore,
1948          * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
1949          * log file.
1950          */
1951         MemSet(zbuffer, 0, sizeof(zbuffer));
1952         for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(zbuffer))
1953         {
1954                 errno = 0;
1955                 if ((int) write(fd, zbuffer, sizeof(zbuffer)) != (int) sizeof(zbuffer))
1956                 {
1957                         int                     save_errno = errno;
1958
1959                         /*
1960                          * If we fail to make the file, delete it to release disk space
1961                          */
1962                         unlink(tmppath);
1963                         /* if write didn't set errno, assume problem is no disk space */
1964                         errno = save_errno ? save_errno : ENOSPC;
1965
1966                         ereport(ERROR,
1967                                         (errcode_for_file_access(),
1968                                          errmsg("could not write to file \"%s\": %m", tmppath)));
1969                 }
1970         }
1971
1972         if (pg_fsync(fd) != 0)
1973                 ereport(ERROR,
1974                                 (errcode_for_file_access(),
1975                                  errmsg("could not fsync file \"%s\": %m", tmppath)));
1976
1977         if (close(fd))
1978                 ereport(ERROR,
1979                                 (errcode_for_file_access(),
1980                                  errmsg("could not close file \"%s\": %m", tmppath)));
1981
1982         /*
1983          * Now move the segment into place with its final name.
1984          *
1985          * If caller didn't want to use a pre-existing file, get rid of any
1986          * pre-existing file.  Otherwise, cope with possibility that someone else
1987          * has created the file while we were filling ours: if so, use ours to
1988          * pre-create a future log segment.
1989          */
1990         installed_log = log;
1991         installed_seg = seg;
1992         max_advance = XLOGfileslop;
1993         if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
1994                                                                 *use_existent, &max_advance,
1995                                                                 use_lock))
1996         {
1997                 /* No need for any more future segments... */
1998                 unlink(tmppath);
1999         }
2000
2001         /* Set flag to tell caller there was no existent file */
2002         *use_existent = false;
2003
2004         /* Now open original target segment (might not be file I just made) */
2005         fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2006                                            S_IRUSR | S_IWUSR);
2007         if (fd < 0)
2008                 ereport(ERROR,
2009                                 (errcode_for_file_access(),
2010                    errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2011                                   path, log, seg)));
2012
2013         return fd;
2014 }
2015
2016 /*
2017  * Create a new XLOG file segment by copying a pre-existing one.
2018  *
2019  * log, seg: identify segment to be created.
2020  *
2021  * srcTLI, srclog, srcseg: identify segment to be copied (could be from
2022  *              a different timeline)
2023  *
2024  * Currently this is only used during recovery, and so there are no locking
2025  * considerations.      But we should be just as tense as XLogFileInit to avoid
2026  * emplacing a bogus file.
2027  */
2028 static void
2029 XLogFileCopy(uint32 log, uint32 seg,
2030                          TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
2031 {
2032         char            path[MAXPGPATH];
2033         char            tmppath[MAXPGPATH];
2034         char            buffer[XLOG_BLCKSZ];
2035         int                     srcfd;
2036         int                     fd;
2037         int                     nbytes;
2038
2039         /*
2040          * Open the source file
2041          */
2042         XLogFilePath(path, srcTLI, srclog, srcseg);
2043         srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2044         if (srcfd < 0)
2045                 ereport(ERROR,
2046                                 (errcode_for_file_access(),
2047                                  errmsg("could not open file \"%s\": %m", path)));
2048
2049         /*
2050          * Copy into a temp file name.
2051          */
2052         snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2053
2054         unlink(tmppath);
2055
2056         /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2057         fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2058                                            S_IRUSR | S_IWUSR);
2059         if (fd < 0)
2060                 ereport(ERROR,
2061                                 (errcode_for_file_access(),
2062                                  errmsg("could not create file \"%s\": %m", tmppath)));
2063
2064         /*
2065          * Do the data copying.
2066          */
2067         for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2068         {
2069                 errno = 0;
2070                 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2071                 {
2072                         if (errno != 0)
2073                                 ereport(ERROR,
2074                                                 (errcode_for_file_access(),
2075                                                  errmsg("could not read file \"%s\": %m", path)));
2076                         else
2077                                 ereport(ERROR,
2078                                                 (errmsg("not enough data in file \"%s\"", path)));
2079                 }
2080                 errno = 0;
2081                 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2082                 {
2083                         int                     save_errno = errno;
2084
2085                         /*
2086                          * If we fail to make the file, delete it to release disk space
2087                          */
2088                         unlink(tmppath);
2089                         /* if write didn't set errno, assume problem is no disk space */
2090                         errno = save_errno ? save_errno : ENOSPC;
2091
2092                         ereport(ERROR,
2093                                         (errcode_for_file_access(),
2094                                          errmsg("could not write to file \"%s\": %m", tmppath)));
2095                 }
2096         }
2097
2098         if (pg_fsync(fd) != 0)
2099                 ereport(ERROR,
2100                                 (errcode_for_file_access(),
2101                                  errmsg("could not fsync file \"%s\": %m", tmppath)));
2102
2103         if (close(fd))
2104                 ereport(ERROR,
2105                                 (errcode_for_file_access(),
2106                                  errmsg("could not close file \"%s\": %m", tmppath)));
2107
2108         close(srcfd);
2109
2110         /*
2111          * Now move the segment into place with its final name.
2112          */
2113         if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2114                 elog(ERROR, "InstallXLogFileSegment should not have failed");
2115 }
2116
2117 /*
2118  * Install a new XLOG segment file as a current or future log segment.
2119  *
2120  * This is used both to install a newly-created segment (which has a temp
2121  * filename while it's being created) and to recycle an old segment.
2122  *
2123  * *log, *seg: identify segment to install as (or first possible target).
2124  * When find_free is TRUE, these are modified on return to indicate the
2125  * actual installation location or last segment searched.
2126  *
2127  * tmppath: initial name of file to install.  It will be renamed into place.
2128  *
2129  * find_free: if TRUE, install the new segment at the first empty log/seg
2130  * number at or after the passed numbers.  If FALSE, install the new segment
2131  * exactly where specified, deleting any existing segment file there.
2132  *
2133  * *max_advance: maximum number of log/seg slots to advance past the starting
2134  * point.  Fail if no free slot is found in this range.  On return, reduced
2135  * by the number of slots skipped over.  (Irrelevant, and may be NULL,
2136  * when find_free is FALSE.)
2137  *
2138  * use_lock: if TRUE, acquire ControlFileLock while moving file into
2139  * place.  This should be TRUE except during bootstrap log creation.  The
2140  * caller must *not* hold the lock at call.
2141  *
2142  * Returns TRUE if file installed, FALSE if not installed because of
2143  * exceeding max_advance limit.  (Any other kind of failure causes ereport().)
2144  */
2145 static bool
2146 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2147                                            bool find_free, int *max_advance,
2148                                            bool use_lock)
2149 {
2150         char            path[MAXPGPATH];
2151         struct stat stat_buf;
2152
2153         XLogFilePath(path, ThisTimeLineID, *log, *seg);
2154
2155         /*
2156          * We want to be sure that only one process does this at a time.
2157          */
2158         if (use_lock)
2159                 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2160
2161         if (!find_free)
2162         {
2163                 /* Force installation: get rid of any pre-existing segment file */
2164                 unlink(path);
2165         }
2166         else
2167         {
2168                 /* Find a free slot to put it in */
2169                 while (stat(path, &stat_buf) == 0)
2170                 {
2171                         if (*max_advance <= 0)
2172                         {
2173                                 /* Failed to find a free slot within specified range */
2174                                 if (use_lock)
2175                                         LWLockRelease(ControlFileLock);
2176                                 return false;
2177                         }
2178                         NextLogSeg(*log, *seg);
2179                         (*max_advance)--;
2180                         XLogFilePath(path, ThisTimeLineID, *log, *seg);
2181                 }
2182         }
2183
2184         /*
2185          * Prefer link() to rename() here just to be really sure that we don't
2186          * overwrite an existing logfile.  However, there shouldn't be one, so
2187          * rename() is an acceptable substitute except for the truly paranoid.
2188          */
2189 #if HAVE_WORKING_LINK
2190         if (link(tmppath, path) < 0)
2191                 ereport(ERROR,
2192                                 (errcode_for_file_access(),
2193                                  errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2194                                                 tmppath, path, *log, *seg)));
2195         unlink(tmppath);
2196 #else
2197         if (rename(tmppath, path) < 0)
2198                 ereport(ERROR,
2199                                 (errcode_for_file_access(),
2200                                  errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2201                                                 tmppath, path, *log, *seg)));
2202 #endif
2203
2204         if (use_lock)
2205                 LWLockRelease(ControlFileLock);
2206
2207         return true;
2208 }
2209
2210 /*
2211  * Open a pre-existing logfile segment for writing.
2212  */
2213 static int
2214 XLogFileOpen(uint32 log, uint32 seg)
2215 {
2216         char            path[MAXPGPATH];
2217         int                     fd;
2218
2219         XLogFilePath(path, ThisTimeLineID, log, seg);
2220
2221         fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2222                                            S_IRUSR | S_IWUSR);
2223         if (fd < 0)
2224                 ereport(PANIC,
2225                                 (errcode_for_file_access(),
2226                    errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2227                                   path, log, seg)));
2228
2229         return fd;
2230 }
2231
2232 /*
2233  * Open a logfile segment for reading (during recovery).
2234  */
2235 static int
2236 XLogFileRead(uint32 log, uint32 seg, int emode)
2237 {
2238         char            path[MAXPGPATH];
2239         char            xlogfname[MAXFNAMELEN];
2240         ListCell   *cell;
2241         int                     fd;
2242
2243         /*
2244          * Loop looking for a suitable timeline ID: we might need to read any of
2245          * the timelines listed in expectedTLIs.
2246          *
2247          * We expect curFileTLI on entry to be the TLI of the preceding file in
2248          * sequence, or 0 if there was no predecessor.  We do not allow curFileTLI
2249          * to go backwards; this prevents us from picking up the wrong file when a
2250          * parent timeline extends to higher segment numbers than the child we
2251          * want to read.
2252          */
2253         foreach(cell, expectedTLIs)
2254         {
2255                 TimeLineID      tli = (TimeLineID) lfirst_int(cell);
2256
2257                 if (tli < curFileTLI)
2258                         break;                          /* don't bother looking at too-old TLIs */
2259
2260                 if (InArchiveRecovery)
2261                 {
2262                         XLogFileName(xlogfname, tli, log, seg);
2263                         restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2264                                                                                                           "RECOVERYXLOG",
2265                                                                                                           XLogSegSize);
2266                 }
2267                 else
2268                         XLogFilePath(path, tli, log, seg);
2269
2270                 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2271                 if (fd >= 0)
2272                 {
2273                         /* Success! */
2274                         curFileTLI = tli;
2275                         return fd;
2276                 }
2277                 if (errno != ENOENT)    /* unexpected failure? */
2278                         ereport(PANIC,
2279                                         (errcode_for_file_access(),
2280                         errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2281                                    path, log, seg)));
2282         }
2283
2284         /* Couldn't find it.  For simplicity, complain about front timeline */
2285         XLogFilePath(path, recoveryTargetTLI, log, seg);
2286         errno = ENOENT;
2287         ereport(emode,
2288                         (errcode_for_file_access(),
2289                    errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2290                                   path, log, seg)));
2291         return -1;
2292 }
2293
2294 /*
2295  * Close the current logfile segment for writing.
2296  */
2297 static void
2298 XLogFileClose(void)
2299 {
2300         Assert(openLogFile >= 0);
2301
2302         /*
2303          * posix_fadvise is problematic on many platforms: on older x86 Linux it
2304          * just dumps core, and there are reports of problems on PPC platforms as
2305          * well.  The following is therefore disabled for the time being. We could
2306          * consider some kind of configure test to see if it's safe to use, but
2307          * since we lack hard evidence that there's any useful performance gain to
2308          * be had, spending time on that seems unprofitable for now.
2309          */
2310 #ifdef NOT_USED
2311
2312         /*
2313          * WAL segment files will not be re-read in normal operation, so we advise
2314          * OS to release any cached pages.      But do not do so if WAL archiving is
2315          * active, because archiver process could use the cache to read the WAL
2316          * segment.
2317          *
2318          * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
2319          * O_SYNC, and some platforms only have posix_fadvise().
2320          */
2321 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2322         if (!XLogArchivingActive())
2323                 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2324 #endif
2325 #endif   /* NOT_USED */
2326
2327         if (close(openLogFile))
2328                 ereport(PANIC,
2329                                 (errcode_for_file_access(),
2330                                  errmsg("could not close log file %u, segment %u: %m",
2331                                                 openLogId, openLogSeg)));
2332         openLogFile = -1;
2333 }
2334
2335 /*
2336  * Attempt to retrieve the specified file from off-line archival storage.
2337  * If successful, fill "path" with its complete path (note that this will be
2338  * a temp file name that doesn't follow the normal naming convention), and
2339  * return TRUE.
2340  *
2341  * If not successful, fill "path" with the name of the normal on-line file
2342  * (which may or may not actually exist, but we'll try to use it), and return
2343  * FALSE.
2344  *
2345  * For fixed-size files, the caller may pass the expected size as an
2346  * additional crosscheck on successful recovery.  If the file size is not
2347  * known, set expectedSize = 0.
2348  */
2349 static bool
2350 RestoreArchivedFile(char *path, const char *xlogfname,
2351                                         const char *recovername, off_t expectedSize)
2352 {
2353         char            xlogpath[MAXPGPATH];
2354         char            xlogRestoreCmd[MAXPGPATH];
2355         char       *dp;
2356         char       *endp;
2357         const char *sp;
2358         int                     rc;
2359         struct stat stat_buf;
2360
2361         /*
2362          * When doing archive recovery, we always prefer an archived log file even
2363          * if a file of the same name exists in XLOGDIR.  The reason is that the
2364          * file in XLOGDIR could be an old, un-filled or partly-filled version
2365          * that was copied and restored as part of backing up $PGDATA.
2366          *
2367          * We could try to optimize this slightly by checking the local copy
2368          * lastchange timestamp against the archived copy, but we have no API to
2369          * do this, nor can we guarantee that the lastchange timestamp was
2370          * preserved correctly when we copied to archive. Our aim is robustness,
2371          * so we elect not to do this.
2372          *
2373          * If we cannot obtain the log file from the archive, however, we will try
2374          * to use the XLOGDIR file if it exists.  This is so that we can make use
2375          * of log segments that weren't yet transferred to the archive.
2376          *
2377          * Notice that we don't actually overwrite any files when we copy back
2378          * from archive because the recoveryRestoreCommand may inadvertently
2379          * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2380          * fallback to the segments remaining in current XLOGDIR later. The
2381          * copy-from-archive filename is always the same, ensuring that we don't
2382          * run out of disk space on long recoveries.
2383          */
2384         snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2385
2386         /*
2387          * Make sure there is no existing file named recovername.
2388          */
2389         if (stat(xlogpath, &stat_buf) != 0)
2390         {
2391                 if (errno != ENOENT)
2392                         ereport(FATAL,
2393                                         (errcode_for_file_access(),
2394                                          errmsg("could not stat file \"%s\": %m",
2395                                                         xlogpath)));
2396         }
2397         else
2398         {
2399                 if (unlink(xlogpath) != 0)
2400                         ereport(FATAL,
2401                                         (errcode_for_file_access(),
2402                                          errmsg("could not remove file \"%s\": %m",
2403                                                         xlogpath)));
2404         }
2405
2406         /*
2407          * construct the command to be executed
2408          */
2409         dp = xlogRestoreCmd;
2410         endp = xlogRestoreCmd + MAXPGPATH - 1;
2411         *endp = '\0';
2412
2413         for (sp = recoveryRestoreCommand; *sp; sp++)
2414         {
2415                 if (*sp == '%')
2416                 {
2417                         switch (sp[1])
2418                         {
2419                                 case 'p':
2420                                         /* %p: full path of target file */
2421                                         sp++;
2422                                         StrNCpy(dp, xlogpath, endp - dp);
2423                                         make_native_path(dp);
2424                                         dp += strlen(dp);
2425                                         break;
2426                                 case 'f':
2427                                         /* %f: filename of desired file */
2428                                         sp++;
2429                                         StrNCpy(dp, xlogfname, endp - dp);
2430                                         dp += strlen(dp);
2431                                         break;
2432                                 case '%':
2433                                         /* convert %% to a single % */
2434                                         sp++;
2435                                         if (dp < endp)
2436                                                 *dp++ = *sp;
2437                                         break;
2438                                 default:
2439                                         /* otherwise treat the % as not special */
2440                                         if (dp < endp)
2441                                                 *dp++ = *sp;
2442                                         break;
2443                         }
2444                 }
2445                 else
2446                 {
2447                         if (dp < endp)
2448                                 *dp++ = *sp;
2449                 }
2450         }
2451         *dp = '\0';
2452
2453         ereport(DEBUG3,
2454                         (errmsg_internal("executing restore command \"%s\"",
2455                                                          xlogRestoreCmd)));
2456
2457         /*
2458          * Copy xlog from archival storage to XLOGDIR
2459          */
2460         rc = system(xlogRestoreCmd);
2461         if (rc == 0)
2462         {
2463                 /*
2464                  * command apparently succeeded, but let's make sure the file is
2465                  * really there now and has the correct size.
2466                  *
2467                  * XXX I made wrong-size a fatal error to ensure the DBA would notice
2468                  * it, but is that too strong?  We could try to plow ahead with a
2469                  * local copy of the file ... but the problem is that there probably
2470                  * isn't one, and we'd incorrectly conclude we've reached the end of
2471                  * WAL and we're done recovering ...
2472                  */
2473                 if (stat(xlogpath, &stat_buf) == 0)
2474                 {
2475                         if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2476                                 ereport(FATAL,
2477                                                 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2478                                                                 xlogfname,
2479                                                                 (unsigned long) stat_buf.st_size,
2480                                                                 (unsigned long) expectedSize)));
2481                         else
2482                         {
2483                                 ereport(LOG,
2484                                                 (errmsg("restored log file \"%s\" from archive",
2485                                                                 xlogfname)));
2486                                 strcpy(path, xlogpath);
2487                                 return true;
2488                         }
2489                 }
2490                 else
2491                 {
2492                         /* stat failed */
2493                         if (errno != ENOENT)
2494                                 ereport(FATAL,
2495                                                 (errcode_for_file_access(),
2496                                                  errmsg("could not stat file \"%s\": %m",
2497                                                                 xlogpath)));
2498                 }
2499         }
2500
2501         /*
2502          * remember, we rollforward UNTIL the restore fails so failure here is
2503          * just part of the process... that makes it difficult to determine
2504          * whether the restore failed because there isn't an archive to restore,
2505          * or because the administrator has specified the restore program
2506          * incorrectly.  We have to assume the former.
2507          */
2508         ereport(DEBUG2,
2509                 (errmsg("could not restore file \"%s\" from archive: return code %d",
2510                                 xlogfname, rc)));
2511
2512         /*
2513          * if an archived file is not available, there might still be a version of
2514          * this file in XLOGDIR, so return that as the filename to open.
2515          *
2516          * In many recovery scenarios we expect this to fail also, but if so that
2517          * just means we've reached the end of WAL.
2518          */
2519         snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2520         return false;
2521 }
2522
2523 /*
2524  * Preallocate log files beyond the specified log endpoint, according to
2525  * the XLOGfile user parameter.
2526  */
2527 static int
2528 PreallocXlogFiles(XLogRecPtr endptr)
2529 {
2530         int                     nsegsadded = 0;
2531         uint32          _logId;
2532         uint32          _logSeg;
2533         int                     lf;
2534         bool            use_existent;
2535
2536         XLByteToPrevSeg(endptr, _logId, _logSeg);
2537         if ((endptr.xrecoff - 1) % XLogSegSize >=
2538                 (uint32) (0.75 * XLogSegSize))
2539         {
2540                 NextLogSeg(_logId, _logSeg);
2541                 use_existent = true;
2542                 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2543                 close(lf);
2544                 if (!use_existent)
2545                         nsegsadded++;
2546         }
2547         return nsegsadded;
2548 }
2549
2550 /*
2551  * Remove or move offline all log files older or equal to passed log/seg#
2552  *
2553  * endptr is current (or recent) end of xlog; this is used to determine
2554  * whether we want to recycle rather than delete no-longer-wanted log files.
2555  */
2556 static void
2557 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
2558                                 int *nsegsremoved, int *nsegsrecycled)
2559 {
2560         uint32          endlogId;
2561         uint32          endlogSeg;
2562         int                     max_advance;
2563         DIR                *xldir;
2564         struct dirent *xlde;
2565         char            lastoff[MAXFNAMELEN];
2566         char            path[MAXPGPATH];
2567
2568         *nsegsremoved = 0;
2569         *nsegsrecycled = 0;
2570
2571         /*
2572          * Initialize info about where to try to recycle to.  We allow recycling
2573          * segments up to XLOGfileslop segments beyond the current XLOG location.
2574          */
2575         XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2576         max_advance = XLOGfileslop;
2577
2578         xldir = AllocateDir(XLOGDIR);
2579         if (xldir == NULL)
2580                 ereport(ERROR,
2581                                 (errcode_for_file_access(),
2582                                  errmsg("could not open transaction log directory \"%s\": %m",
2583                                                 XLOGDIR)));
2584
2585         XLogFileName(lastoff, ThisTimeLineID, log, seg);
2586
2587         while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2588         {
2589                 /*
2590                  * We ignore the timeline part of the XLOG segment identifiers in
2591                  * deciding whether a segment is still needed.  This ensures that we
2592                  * won't prematurely remove a segment from a parent timeline. We could
2593                  * probably be a little more proactive about removing segments of
2594                  * non-parent timelines, but that would be a whole lot more
2595                  * complicated.
2596                  *
2597                  * We use the alphanumeric sorting property of the filenames to decide
2598                  * which ones are earlier than the lastoff segment.
2599                  */
2600                 if (strlen(xlde->d_name) == 24 &&
2601                         strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2602                         strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2603                 {
2604                         if (XLogArchiveCheckDone(xlde->d_name))
2605                         {
2606                                 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2607
2608                                 /*
2609                                  * Before deleting the file, see if it can be recycled as a
2610                                  * future log segment.
2611                                  */
2612                                 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2613                                                                                    true, &max_advance,
2614                                                                                    true))
2615                                 {
2616                                         ereport(DEBUG2,
2617                                                         (errmsg("recycled transaction log file \"%s\"",
2618                                                                         xlde->d_name)));
2619                                         (*nsegsrecycled)++;
2620                                         /* Needn't recheck that slot on future iterations */
2621                                         if (max_advance > 0)
2622                                         {
2623                                                 NextLogSeg(endlogId, endlogSeg);
2624                                                 max_advance--;
2625                                         }
2626                                 }
2627                                 else
2628                                 {
2629                                         /* No need for any more future segments... */
2630                                         ereport(DEBUG2,
2631                                                         (errmsg("removing transaction log file \"%s\"",
2632                                                                         xlde->d_name)));
2633                                         unlink(path);
2634                                         (*nsegsremoved)++;
2635                                 }
2636
2637                                 XLogArchiveCleanup(xlde->d_name);
2638                         }
2639                 }
2640         }
2641
2642         FreeDir(xldir);
2643 }
2644
2645 /*
2646  * Remove previous backup history files.  This also retries creation of
2647  * .ready files for any backup history files for which XLogArchiveNotify
2648  * failed earlier.
2649  */
2650 static void
2651 CleanupBackupHistory(void)
2652 {
2653         DIR                *xldir;
2654         struct dirent *xlde;
2655         char            path[MAXPGPATH];
2656
2657         xldir = AllocateDir(XLOGDIR);
2658         if (xldir == NULL)
2659                 ereport(ERROR,
2660                                 (errcode_for_file_access(),
2661                                  errmsg("could not open transaction log directory \"%s\": %m",
2662                                                 XLOGDIR)));
2663
2664         while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2665         {
2666                 if (strlen(xlde->d_name) > 24 &&
2667                         strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2668                         strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2669                                    ".backup") == 0)
2670                 {
2671                         if (XLogArchiveCheckDone(xlde->d_name))
2672                         {
2673                                 ereport(DEBUG2,
2674                                 (errmsg("removing transaction log backup history file \"%s\"",
2675                                                 xlde->d_name)));
2676                                 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2677                                 unlink(path);
2678                                 XLogArchiveCleanup(xlde->d_name);
2679                         }
2680                 }
2681         }
2682
2683         FreeDir(xldir);
2684 }
2685
2686 /*
2687  * Restore the backup blocks present in an XLOG record, if any.
2688  *
2689  * We assume all of the record has been read into memory at *record.
2690  *
2691  * Note: when a backup block is available in XLOG, we restore it
2692  * unconditionally, even if the page in the database appears newer.
2693  * This is to protect ourselves against database pages that were partially
2694  * or incorrectly written during a crash.  We assume that the XLOG data
2695  * must be good because it has passed a CRC check, while the database
2696  * page might not be.  This will force us to replay all subsequent
2697  * modifications of the page that appear in XLOG, rather than possibly
2698  * ignoring them as already applied, but that's not a huge drawback.
2699  */
2700 static void
2701 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2702 {
2703         Relation        reln;
2704         Buffer          buffer;
2705         Page            page;
2706         BkpBlock        bkpb;
2707         char       *blk;
2708         int                     i;
2709
2710         blk = (char *) XLogRecGetData(record) + record->xl_len;
2711         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2712         {
2713                 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2714                         continue;
2715
2716                 memcpy(&bkpb, blk, sizeof(BkpBlock));
2717                 blk += sizeof(BkpBlock);
2718
2719                 reln = XLogOpenRelation(bkpb.node);
2720                 buffer = XLogReadBuffer(reln, bkpb.block, true);
2721                 Assert(BufferIsValid(buffer));
2722                 page = (Page) BufferGetPage(buffer);
2723
2724                 if (bkpb.hole_length == 0)
2725                 {
2726                         memcpy((char *) page, blk, BLCKSZ);
2727                 }
2728                 else
2729                 {
2730                         /* must zero-fill the hole */
2731                         MemSet((char *) page, 0, BLCKSZ);
2732                         memcpy((char *) page, blk, bkpb.hole_offset);
2733                         memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2734                                    blk + bkpb.hole_offset,
2735                                    BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2736                 }
2737
2738                 PageSetLSN(page, lsn);
2739                 PageSetTLI(page, ThisTimeLineID);
2740                 MarkBufferDirty(buffer);
2741                 UnlockReleaseBuffer(buffer);
2742
2743                 blk += BLCKSZ - bkpb.hole_length;
2744         }
2745 }
2746
2747 /*
2748  * CRC-check an XLOG record.  We do not believe the contents of an XLOG
2749  * record (other than to the minimal extent of computing the amount of
2750  * data to read in) until we've checked the CRCs.
2751  *
2752  * We assume all of the record has been read into memory at *record.
2753  */
2754 static bool
2755 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2756 {
2757         pg_crc32        crc;
2758         int                     i;
2759         uint32          len = record->xl_len;
2760         BkpBlock        bkpb;
2761         char       *blk;
2762
2763         /* First the rmgr data */
2764         INIT_CRC32(crc);
2765         COMP_CRC32(crc, XLogRecGetData(record), len);
2766
2767         /* Add in the backup blocks, if any */
2768         blk = (char *) XLogRecGetData(record) + len;
2769         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2770         {
2771                 uint32          blen;
2772
2773                 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2774                         continue;
2775
2776                 memcpy(&bkpb, blk, sizeof(BkpBlock));
2777                 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2778                 {
2779                         ereport(emode,
2780                                         (errmsg("incorrect hole size in record at %X/%X",
2781                                                         recptr.xlogid, recptr.xrecoff)));
2782                         return false;
2783                 }
2784                 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2785                 COMP_CRC32(crc, blk, blen);
2786                 blk += blen;
2787         }
2788
2789         /* Check that xl_tot_len agrees with our calculation */
2790         if (blk != (char *) record + record->xl_tot_len)
2791         {
2792                 ereport(emode,
2793                                 (errmsg("incorrect total length in record at %X/%X",
2794                                                 recptr.xlogid, recptr.xrecoff)));
2795                 return false;
2796         }
2797
2798         /* Finally include the record header */
2799         COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2800                            SizeOfXLogRecord - sizeof(pg_crc32));
2801         FIN_CRC32(crc);
2802
2803         if (!EQ_CRC32(record->xl_crc, crc))
2804         {
2805                 ereport(emode,
2806                 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2807                                 recptr.xlogid, recptr.xrecoff)));
2808                 return false;
2809         }
2810
2811         return true;
2812 }
2813
2814 /*
2815  * Attempt to read an XLOG record.
2816  *
2817  * If RecPtr is not NULL, try to read a record at that position.  Otherwise
2818  * try to read a record just after the last one previously read.
2819  *
2820  * If no valid record is available, returns NULL, or fails if emode is PANIC.
2821  * (emode must be either PANIC or LOG.)
2822  *
2823  * The record is copied into readRecordBuf, so that on successful return,
2824  * the returned record pointer always points there.
2825  */
2826 static XLogRecord *
2827 ReadRecord(XLogRecPtr *RecPtr, int emode)
2828 {
2829         XLogRecord *record;
2830         char       *buffer;
2831         XLogRecPtr      tmpRecPtr = EndRecPtr;
2832         bool            randAccess = false;
2833         uint32          len,
2834                                 total_len;
2835         uint32          targetPageOff;
2836         uint32          targetRecOff;
2837         uint32          pageHeaderSize;
2838
2839         if (readBuf == NULL)
2840         {
2841                 /*
2842                  * First time through, permanently allocate readBuf.  We do it this
2843                  * way, rather than just making a static array, for two reasons: (1)
2844                  * no need to waste the storage in most instantiations of the backend;
2845                  * (2) a static char array isn't guaranteed to have any particular
2846                  * alignment, whereas malloc() will provide MAXALIGN'd storage.
2847                  */
2848                 readBuf = (char *) malloc(XLOG_BLCKSZ);
2849                 Assert(readBuf != NULL);
2850         }
2851
2852         if (RecPtr == NULL)
2853         {
2854                 RecPtr = &tmpRecPtr;
2855                 /* fast case if next record is on same page */
2856                 if (nextRecord != NULL)
2857                 {
2858                         record = nextRecord;
2859                         goto got_record;
2860                 }
2861                 /* align old recptr to next page */
2862                 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2863                         tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2864                 if (tmpRecPtr.xrecoff >= XLogFileSize)
2865                 {
2866                         (tmpRecPtr.xlogid)++;
2867                         tmpRecPtr.xrecoff = 0;
2868                 }
2869                 /* We will account for page header size below */
2870         }
2871         else
2872         {
2873                 if (!XRecOffIsValid(RecPtr->xrecoff))
2874                         ereport(PANIC,
2875                                         (errmsg("invalid record offset at %X/%X",
2876                                                         RecPtr->xlogid, RecPtr->xrecoff)));
2877
2878                 /*
2879                  * Since we are going to a random position in WAL, forget any prior
2880                  * state about what timeline we were in, and allow it to be any
2881                  * timeline in expectedTLIs.  We also set a flag to allow curFileTLI
2882                  * to go backwards (but we can't reset that variable right here, since
2883                  * we might not change files at all).
2884                  */
2885                 lastPageTLI = 0;                /* see comment in ValidXLOGHeader */
2886                 randAccess = true;              /* allow curFileTLI to go backwards too */
2887         }
2888
2889         if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2890         {
2891                 close(readFile);
2892                 readFile = -1;
2893         }
2894         XLByteToSeg(*RecPtr, readId, readSeg);
2895         if (readFile < 0)
2896         {
2897                 /* Now it's okay to reset curFileTLI if random fetch */
2898                 if (randAccess)
2899                         curFileTLI = 0;
2900
2901                 readFile = XLogFileRead(readId, readSeg, emode);
2902                 if (readFile < 0)
2903                         goto next_record_is_invalid;
2904
2905                 /*
2906                  * Whenever switching to a new WAL segment, we read the first page of
2907                  * the file and validate its header, even if that's not where the
2908                  * target record is.  This is so that we can check the additional
2909                  * identification info that is present in the first page's "long"
2910                  * header.
2911                  */
2912                 readOff = 0;
2913                 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2914                 {
2915                         ereport(emode,
2916                                         (errcode_for_file_access(),
2917                                          errmsg("could not read from log file %u, segment %u, offset %u: %m",
2918                                                         readId, readSeg, readOff)));
2919                         goto next_record_is_invalid;
2920                 }
2921                 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2922                         goto next_record_is_invalid;
2923         }
2924
2925         targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2926         if (readOff != targetPageOff)
2927         {
2928                 readOff = targetPageOff;
2929                 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2930                 {
2931                         ereport(emode,
2932                                         (errcode_for_file_access(),
2933                                          errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2934                                                         readId, readSeg, readOff)));
2935                         goto next_record_is_invalid;
2936                 }
2937                 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2938                 {
2939                         ereport(emode,
2940                                         (errcode_for_file_access(),
2941                                          errmsg("could not read from log file %u, segment %u at offset %u: %m",
2942                                                         readId, readSeg, readOff)));
2943                         goto next_record_is_invalid;
2944                 }
2945                 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2946                         goto next_record_is_invalid;
2947         }
2948         pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2949         targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
2950         if (targetRecOff == 0)
2951         {
2952                 /*
2953                  * Can only get here in the continuing-from-prev-page case, because
2954                  * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
2955                  * to skip over the new page's header.
2956                  */
2957                 tmpRecPtr.xrecoff += pageHeaderSize;
2958                 targetRecOff = pageHeaderSize;
2959         }
2960         else if (targetRecOff < pageHeaderSize)
2961         {
2962                 ereport(emode,
2963                                 (errmsg("invalid record offset at %X/%X",
2964                                                 RecPtr->xlogid, RecPtr->xrecoff)));
2965                 goto next_record_is_invalid;
2966         }
2967         if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
2968                 targetRecOff == pageHeaderSize)
2969         {
2970                 ereport(emode,
2971                                 (errmsg("contrecord is requested by %X/%X",
2972                                                 RecPtr->xlogid, RecPtr->xrecoff)));
2973                 goto next_record_is_invalid;
2974         }
2975         record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
2976
2977 got_record:;
2978
2979         /*
2980          * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
2981          * required.
2982          */
2983         if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
2984         {
2985                 if (record->xl_len != 0)
2986                 {
2987                         ereport(emode,
2988                                         (errmsg("invalid xlog switch record at %X/%X",
2989                                                         RecPtr->xlogid, RecPtr->xrecoff)));
2990                         goto next_record_is_invalid;
2991                 }
2992         }
2993         else if (record->xl_len == 0)
2994         {
2995                 ereport(emode,
2996                                 (errmsg("record with zero length at %X/%X",
2997                                                 RecPtr->xlogid, RecPtr->xrecoff)));
2998                 goto next_record_is_invalid;
2999         }
3000         if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3001                 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3002                 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3003         {
3004                 ereport(emode,
3005                                 (errmsg("invalid record length at %X/%X",
3006                                                 RecPtr->xlogid, RecPtr->xrecoff)));
3007                 goto next_record_is_invalid;
3008         }
3009         if (record->xl_rmid > RM_MAX_ID)
3010         {
3011                 ereport(emode,
3012                                 (errmsg("invalid resource manager ID %u at %X/%X",
3013                                                 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3014                 goto next_record_is_invalid;
3015         }
3016         if (randAccess)
3017         {
3018                 /*
3019                  * We can't exactly verify the prev-link, but surely it should be less
3020                  * than the record's own address.
3021                  */
3022                 if (!XLByteLT(record->xl_prev, *RecPtr))
3023                 {
3024                         ereport(emode,
3025                                         (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3026                                                         record->xl_prev.xlogid, record->xl_prev.xrecoff,
3027                                                         RecPtr->xlogid, RecPtr->xrecoff)));
3028                         goto next_record_is_invalid;
3029                 }
3030         }
3031         else
3032         {
3033                 /*
3034                  * Record's prev-link should exactly match our previous location. This
3035                  * check guards against torn WAL pages where a stale but valid-looking
3036                  * WAL record starts on a sector boundary.
3037                  */
3038                 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3039                 {
3040                         ereport(emode,
3041                                         (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3042                                                         record->xl_prev.xlogid, record->xl_prev.xrecoff,
3043                                                         RecPtr->xlogid, RecPtr->xrecoff)));
3044                         goto next_record_is_invalid;
3045                 }
3046         }
3047
3048         /*
3049          * Allocate or enlarge readRecordBuf as needed.  To avoid useless small
3050          * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3051          * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with.  (That is
3052          * enough for all "normal" records, but very large commit or abort records
3053          * might need more space.)
3054          */
3055         total_len = record->xl_tot_len;
3056         if (total_len > readRecordBufSize)
3057         {
3058                 uint32          newSize = total_len;
3059
3060                 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3061                 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3062                 if (readRecordBuf)
3063                         free(readRecordBuf);
3064                 readRecordBuf = (char *) malloc(newSize);
3065                 if (!readRecordBuf)
3066                 {
3067                         readRecordBufSize = 0;
3068                         /* We treat this as a "bogus data" condition */
3069                         ereport(emode,
3070                                         (errmsg("record length %u at %X/%X too long",
3071                                                         total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3072                         goto next_record_is_invalid;
3073                 }
3074                 readRecordBufSize = newSize;
3075         }
3076
3077         buffer = readRecordBuf;
3078         nextRecord = NULL;
3079         len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3080         if (total_len > len)
3081         {
3082                 /* Need to reassemble record */
3083                 XLogContRecord *contrecord;
3084                 uint32          gotlen = len;
3085
3086                 memcpy(buffer, record, len);
3087                 record = (XLogRecord *) buffer;
3088                 buffer += len;
3089                 for (;;)
3090                 {
3091                         readOff += XLOG_BLCKSZ;
3092                         if (readOff >= XLogSegSize)
3093                         {
3094                                 close(readFile);
3095                                 readFile = -1;
3096                                 NextLogSeg(readId, readSeg);
3097                                 readFile = XLogFileRead(readId, readSeg, emode);
3098                                 if (readFile < 0)
3099                                         goto next_record_is_invalid;
3100                                 readOff = 0;
3101                         }
3102                         if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3103                         {
3104                                 ereport(emode,
3105                                                 (errcode_for_file_access(),
3106                                                  errmsg("could not read from log file %u, segment %u, offset %u: %m",
3107                                                                 readId, readSeg, readOff)));
3108                                 goto next_record_is_invalid;
3109                         }
3110                         if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3111                                 goto next_record_is_invalid;
3112                         if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3113                         {
3114                                 ereport(emode,
3115                                                 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3116                                                                 readId, readSeg, readOff)));
3117                                 goto next_record_is_invalid;
3118                         }
3119                         pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3120                         contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3121                         if (contrecord->xl_rem_len == 0 ||
3122                                 total_len != (contrecord->xl_rem_len + gotlen))
3123                         {
3124                                 ereport(emode,
3125                                                 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3126                                                                 contrecord->xl_rem_len,
3127                                                                 readId, readSeg, readOff)));
3128                                 goto next_record_is_invalid;
3129                         }
3130                         len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3131                         if (contrecord->xl_rem_len > len)
3132                         {
3133                                 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3134                                 gotlen += len;
3135                                 buffer += len;
3136                                 continue;
3137                         }
3138                         memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3139                                    contrecord->xl_rem_len);
3140                         break;
3141                 }
3142                 if (!RecordIsValid(record, *RecPtr, emode))
3143                         goto next_record_is_invalid;
3144                 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3145                 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3146                         MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3147                 {
3148                         nextRecord = (XLogRecord *) ((char *) contrecord +
3149                                         MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3150                 }
3151                 EndRecPtr.xlogid = readId;
3152                 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3153                         pageHeaderSize +
3154                         MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3155                 ReadRecPtr = *RecPtr;
3156                 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3157                 return record;
3158         }
3159
3160         /* Record does not cross a page boundary */
3161         if (!RecordIsValid(record, *RecPtr, emode))
3162                 goto next_record_is_invalid;
3163         if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3164                 MAXALIGN(total_len))
3165                 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3166         EndRecPtr.xlogid = RecPtr->xlogid;
3167         EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3168         ReadRecPtr = *RecPtr;
3169         memcpy(buffer, record, total_len);
3170
3171         /*
3172          * Special processing if it's an XLOG SWITCH record
3173          */
3174         if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3175         {
3176                 /* Pretend it extends to end of segment */
3177                 EndRecPtr.xrecoff += XLogSegSize - 1;
3178                 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3179                 nextRecord = NULL;              /* definitely not on same page */
3180
3181                 /*
3182                  * Pretend that readBuf contains the last page of the segment. This is
3183                  * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3184                  * segment.
3185                  */
3186                 readOff = XLogSegSize - XLOG_BLCKSZ;
3187         }
3188         return (XLogRecord *) buffer;
3189
3190 next_record_is_invalid:;
3191         close(readFile);
3192         readFile = -1;
3193         nextRecord = NULL;
3194         return NULL;
3195 }
3196
3197 /*
3198  * Check whether the xlog header of a page just read in looks valid.
3199  *
3200  * This is just a convenience subroutine to avoid duplicated code in
3201  * ReadRecord.  It's not intended for use from anywhere else.
3202  */
3203 static bool
3204 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3205 {
3206         XLogRecPtr      recaddr;
3207
3208         if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3209         {
3210                 ereport(emode,
3211                                 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3212                                                 hdr->xlp_magic, readId, readSeg, readOff)));
3213                 return false;
3214         }
3215         if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3216         {
3217                 ereport(emode,
3218                                 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3219                                                 hdr->xlp_info, readId, readSeg, readOff)));
3220                 return false;
3221         }
3222         if (hdr->xlp_info & XLP_LONG_HEADER)
3223         {
3224                 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3225
3226                 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3227                 {
3228                         char            fhdrident_str[32];
3229                         char            sysident_str[32];
3230
3231                         /*
3232                          * Format sysids separately to keep platform-dependent format code
3233                          * out of the translatable message string.
3234                          */
3235                         snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3236                                          longhdr->xlp_sysid);
3237                         snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3238                                          ControlFile->system_identifier);
3239                         ereport(emode,
3240                                         (errmsg("WAL file is from different system"),
3241                                          errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3242                                                            fhdrident_str, sysident_str)));
3243                         return false;
3244                 }
3245                 if (longhdr->xlp_seg_size != XLogSegSize)
3246                 {
3247                         ereport(emode,
3248                                         (errmsg("WAL file is from different system"),
3249                                          errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3250                         return false;
3251                 }
3252                 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3253                 {
3254                         ereport(emode,
3255                                         (errmsg("WAL file is from different system"),
3256                                          errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3257                         return false;
3258                 }
3259         }
3260         else if (readOff == 0)
3261         {
3262                 /* hmm, first page of file doesn't have a long header? */
3263                 ereport(emode,
3264                                 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3265                                                 hdr->xlp_info, readId, readSeg, readOff)));
3266                 return false;
3267         }
3268
3269         recaddr.xlogid = readId;
3270         recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3271         if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3272         {
3273                 ereport(emode,
3274                                 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3275                                                 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3276                                                 readId, readSeg, readOff)));
3277                 return false;
3278         }
3279
3280         /*
3281          * Check page TLI is one of the expected values.
3282          */
3283         if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3284         {
3285                 ereport(emode,
3286                                 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3287                                                 hdr->xlp_tli,
3288                                                 readId, readSeg, readOff)));
3289                 return false;
3290         }
3291
3292         /*
3293          * Since child timelines are always assigned a TLI greater than their
3294          * immediate parent's TLI, we should never see TLI go backwards across
3295          * successive pages of a consistent WAL sequence.
3296          *
3297          * Of course this check should only be applied when advancing sequentially
3298          * across pages; therefore ReadRecord resets lastPageTLI to zero when
3299          * going to a random page.
3300          */
3301         if (hdr->xlp_tli < lastPageTLI)
3302         {
3303                 ereport(emode,
3304                                 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3305                                                 hdr->xlp_tli, lastPageTLI,
3306                                                 readId, readSeg, readOff)));
3307                 return false;
3308         }
3309         lastPageTLI = hdr->xlp_tli;
3310         return true;
3311 }
3312
3313 /*
3314  * Try to read a timeline's history file.
3315  *
3316  * If successful, return the list of component TLIs (the given TLI followed by
3317  * its ancestor TLIs).  If we can't find the history file, assume that the
3318  * timeline has no parents, and return a list of just the specified timeline
3319  * ID.
3320  */
3321 static List *
3322 readTimeLineHistory(TimeLineID targetTLI)
3323 {
3324         List       *result;
3325         char            path[MAXPGPATH];
3326         char            histfname[MAXFNAMELEN];
3327         char            fline[MAXPGPATH];
3328         FILE       *fd;
3329
3330         if (InArchiveRecovery)
3331         {
3332                 TLHistoryFileName(histfname, targetTLI);
3333                 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3334         }
3335         else
3336                 TLHistoryFilePath(path, targetTLI);
3337
3338         fd = AllocateFile(path, "r");
3339         if (fd == NULL)
3340         {
3341                 if (errno != ENOENT)
3342                         ereport(FATAL,
3343                                         (errcode_for_file_access(),
3344                                          errmsg("could not open file \"%s\": %m", path)));
3345                 /* Not there, so assume no parents */
3346                 return list_make1_int((int) targetTLI);
3347         }
3348
3349         result = NIL;
3350
3351         /*
3352          * Parse the file...
3353          */
3354         while (fgets(fline, MAXPGPATH, fd) != NULL)
3355         {
3356                 /* skip leading whitespace and check for # comment */
3357                 char       *ptr;
3358                 char       *endptr;
3359                 TimeLineID      tli;
3360
3361                 for (ptr = fline; *ptr; ptr++)
3362                 {
3363                         if (!isspace((unsigned char) *ptr))
3364                                 break;
3365                 }
3366                 if (*ptr == '\0' || *ptr == '#')
3367                         continue;
3368
3369                 /* expect a numeric timeline ID as first field of line */
3370                 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3371                 if (endptr == ptr)
3372                         ereport(FATAL,
3373                                         (errmsg("syntax error in history file: %s", fline),
3374                                          errhint("Expected a numeric timeline ID.")));
3375
3376                 if (result &&
3377                         tli <= (TimeLineID) linitial_int(result))
3378                         ereport(FATAL,
3379                                         (errmsg("invalid data in history file: %s", fline),
3380                                    errhint("Timeline IDs must be in increasing sequence.")));
3381
3382                 /* Build list with newest item first */
3383                 result = lcons_int((int) tli, result);
3384
3385                 /* we ignore the remainder of each line */
3386         }
3387
3388         FreeFile(fd);
3389
3390         if (result &&
3391                 targetTLI <= (TimeLineID) linitial_int(result))
3392                 ereport(FATAL,
3393                                 (errmsg("invalid data in history file \"%s\"", path),
3394                         errhint("Timeline IDs must be less than child timeline's ID.")));
3395
3396         result = lcons_int((int) targetTLI, result);
3397
3398         ereport(DEBUG3,
3399                         (errmsg_internal("history of timeline %u is %s",
3400                                                          targetTLI, nodeToString(result))));
3401
3402         return result;
3403 }
3404
3405 /*
3406  * Probe whether a timeline history file exists for the given timeline ID
3407  */
3408 static bool
3409 existsTimeLineHistory(TimeLineID probeTLI)
3410 {
3411         char            path[MAXPGPATH];
3412         char            histfname[MAXFNAMELEN];
3413         FILE       *fd;
3414
3415         if (InArchiveRecovery)
3416         {
3417                 TLHistoryFileName(histfname, probeTLI);
3418                 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3419         }
3420         else
3421                 TLHistoryFilePath(path, probeTLI);
3422
3423         fd = AllocateFile(path, "r");
3424         if (fd != NULL)
3425         {
3426                 FreeFile(fd);
3427                 return true;
3428         }
3429         else
3430         {
3431                 if (errno != ENOENT)
3432                         ereport(FATAL,
3433                                         (errcode_for_file_access(),
3434                                          errmsg("could not open file \"%s\": %m", path)));
3435                 return false;
3436         }
3437 }
3438
3439 /*
3440  * Find the newest existing timeline, assuming that startTLI exists.
3441  *
3442  * Note: while this is somewhat heuristic, it does positively guarantee
3443  * that (result + 1) is not a known timeline, and therefore it should
3444  * be safe to assign that ID to a new timeline.
3445  */
3446 static TimeLineID
3447 findNewestTimeLine(TimeLineID startTLI)
3448 {
3449         TimeLineID      newestTLI;
3450         TimeLineID      probeTLI;
3451
3452         /*
3453          * The algorithm is just to probe for the existence of timeline history
3454          * files.  XXX is it useful to allow gaps in the sequence?
3455          */
3456         newestTLI = startTLI;
3457
3458         for (probeTLI = startTLI + 1;; probeTLI++)
3459         {
3460                 if (existsTimeLineHistory(probeTLI))
3461                 {
3462                         newestTLI = probeTLI;           /* probeTLI exists */
3463                 }
3464                 else
3465                 {
3466                         /* doesn't exist, assume we're done */
3467                         break;
3468                 }
3469         }
3470
3471         return newestTLI;
3472 }
3473
3474 /*
3475  * Create a new timeline history file.
3476  *
3477  *      newTLI: ID of the new timeline
3478  *      parentTLI: ID of its immediate parent
3479  *      endTLI et al: ID of the last used WAL file, for annotation purposes
3480  *
3481  * Currently this is only used during recovery, and so there are no locking
3482  * considerations.      But we should be just as tense as XLogFileInit to avoid
3483  * emplacing a bogus file.
3484  */
3485 static void
3486 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3487                                          TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3488 {
3489         char            path[MAXPGPATH];
3490         char            tmppath[MAXPGPATH];
3491         char            histfname[MAXFNAMELEN];
3492         char            xlogfname[MAXFNAMELEN];
3493         char            buffer[BLCKSZ];
3494         int                     srcfd;
3495         int                     fd;
3496         int                     nbytes;
3497
3498         Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3499
3500         /*
3501          * Write into a temp file name.
3502          */
3503         snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3504
3505         unlink(tmppath);
3506
3507         /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3508         fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3509                                            S_IRUSR | S_IWUSR);
3510         if (fd < 0)
3511                 ereport(ERROR,
3512                                 (errcode_for_file_access(),
3513                                  errmsg("could not create file \"%s\": %m", tmppath)));
3514
3515         /*
3516          * If a history file exists for the parent, copy it verbatim
3517          */
3518         if (InArchiveRecovery)
3519         {
3520                 TLHistoryFileName(histfname, parentTLI);
3521                 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3522         }
3523         else
3524                 TLHistoryFilePath(path, parentTLI);
3525
3526         srcfd = BasicOpenFile(path, O_RDONLY, 0);
3527         if (srcfd < 0)
3528         {
3529                 if (errno != ENOENT)
3530                         ereport(ERROR,
3531                                         (errcode_for_file_access(),
3532                                          errmsg("could not open file \"%s\": %m", path)));
3533                 /* Not there, so assume parent has no parents */
3534         }
3535         else
3536         {
3537                 for (;;)
3538                 {
3539                         errno = 0;
3540                         nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3541                         if (nbytes < 0 || errno != 0)
3542                                 ereport(ERROR,
3543                                                 (errcode_for_file_access(),
3544                                                  errmsg("could not read file \"%s\": %m", path)));
3545                         if (nbytes == 0)
3546                                 break;
3547                         errno = 0;
3548                         if ((int) write(fd, buffer, nbytes) != nbytes)
3549                         {
3550                                 int                     save_errno = errno;
3551
3552                                 /*
3553                                  * If we fail to make the file, delete it to release disk
3554                                  * space
3555                                  */
3556                                 unlink(tmppath);
3557
3558                                 /*
3559                                  * if write didn't set errno, assume problem is no disk space
3560                                  */
3561                                 errno = save_errno ? save_errno : ENOSPC;
3562
3563                                 ereport(ERROR,
3564                                                 (errcode_for_file_access(),
3565                                          errmsg("could not write to file \"%s\": %m", tmppath)));
3566                         }
3567                 }
3568                 close(srcfd);
3569         }
3570
3571         /*
3572          * Append one line with the details of this timeline split.
3573          *
3574          * If we did have a parent file, insert an extra newline just in case the
3575          * parent file failed to end with one.
3576          */
3577         XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3578
3579         snprintf(buffer, sizeof(buffer),
3580                          "%s%u\t%s\t%s transaction %u at %s\n",
3581                          (srcfd < 0) ? "" : "\n",
3582                          parentTLI,
3583                          xlogfname,
3584                          recoveryStopAfter ? "after" : "before",
3585                          recoveryStopXid,
3586                          str_time(recoveryStopTime));
3587
3588         nbytes = strlen(buffer);
3589         errno = 0;
3590         if ((int) write(fd, buffer, nbytes) != nbytes)
3591         {
3592                 int                     save_errno = errno;
3593
3594                 /*
3595                  * If we fail to make the file, delete it to release disk space
3596                  */
3597                 unlink(tmppath);
3598                 /* if write didn't set errno, assume problem is no disk space */
3599                 errno = save_errno ? save_errno : ENOSPC;
3600
3601                 ereport(ERROR,
3602                                 (errcode_for_file_access(),
3603                                  errmsg("could not write to file \"%s\": %m", tmppath)));
3604         }
3605
3606         if (pg_fsync(fd) != 0)
3607                 ereport(ERROR,
3608                                 (errcode_for_file_access(),
3609                                  errmsg("could not fsync file \"%s\": %m", tmppath)));
3610
3611         if (close(fd))
3612                 ereport(ERROR,
3613                                 (errcode_for_file_access(),
3614                                  errmsg("could not close file \"%s\": %m", tmppath)));
3615
3616
3617         /*
3618          * Now move the completed history file into place with its final name.
3619          */
3620         TLHistoryFilePath(path, newTLI);
3621
3622         /*
3623          * Prefer link() to rename() here just to be really sure that we don't
3624          * overwrite an existing logfile.  However, there shouldn't be one, so
3625          * rename() is an acceptable substitute except for the truly paranoid.
3626          */
3627 #if HAVE_WORKING_LINK
3628         if (link(tmppath, path) < 0)
3629                 ereport(ERROR,
3630                                 (errcode_for_file_access(),
3631                                  errmsg("could not link file \"%s\" to \"%s\": %m",
3632                                                 tmppath, path)));
3633         unlink(tmppath);
3634 #else
3635         if (rename(tmppath, path) < 0)
3636                 ereport(ERROR,
3637                                 (errcode_for_file_access(),
3638                                  errmsg("could not rename file \"%s\" to \"%s\": %m",
3639                                                 tmppath, path)));
3640 #endif
3641
3642         /* The history file can be archived immediately. */
3643         TLHistoryFileName(histfname, newTLI);
3644         XLogArchiveNotify(histfname);
3645 }
3646
3647 /*
3648  * I/O routines for pg_control
3649  *
3650  * *ControlFile is a buffer in shared memory that holds an image of the
3651  * contents of pg_control.      WriteControlFile() initializes pg_control
3652  * given a preloaded buffer, ReadControlFile() loads the buffer from
3653  * the pg_control file (during postmaster or standalone-backend startup),
3654  * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3655  *
3656  * For simplicity, WriteControlFile() initializes the fields of pg_control
3657  * that are related to checking backend/database compatibility, and
3658  * ReadControlFile() verifies they are correct.  We could split out the
3659  * I/O and compatibility-check functions, but there seems no need currently.
3660  */
3661 static void
3662 WriteControlFile(void)
3663 {
3664         int                     fd;
3665         char            buffer[PG_CONTROL_SIZE];                /* need not be aligned */
3666         char       *localeptr;
3667
3668         /*
3669          * Initialize version and compatibility-check fields
3670          */
3671         ControlFile->pg_control_version = PG_CONTROL_VERSION;
3672         ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3673
3674         ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3675         ControlFile->floatFormat = FLOATFORMAT_VALUE;
3676
3677         ControlFile->blcksz = BLCKSZ;
3678         ControlFile->relseg_size = RELSEG_SIZE;
3679         ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3680         ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3681
3682         ControlFile->nameDataLen = NAMEDATALEN;
3683         ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3684
3685 #ifdef HAVE_INT64_TIMESTAMP
3686         ControlFile->enableIntTimes = TRUE;
3687 #else
3688         ControlFile->enableIntTimes = FALSE;
3689 #endif
3690
3691         ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3692         localeptr = setlocale(LC_COLLATE, NULL);
3693         if (!localeptr)
3694                 ereport(PANIC,
3695                                 (errmsg("invalid LC_COLLATE setting")));
3696         StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3697         localeptr = setlocale(LC_CTYPE, NULL);
3698         if (!localeptr)
3699                 ereport(PANIC,
3700                                 (errmsg("invalid LC_CTYPE setting")));
3701         StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3702
3703         /* Contents are protected with a CRC */
3704         INIT_CRC32(ControlFile->crc);
3705         COMP_CRC32(ControlFile->crc,
3706                            (char *) ControlFile,
3707                            offsetof(ControlFileData, crc));
3708         FIN_CRC32(ControlFile->crc);
3709
3710         /*
3711          * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3712          * excess over sizeof(ControlFileData).  This reduces the odds of
3713          * premature-EOF errors when reading pg_control.  We'll still fail when we
3714          * check the contents of the file, but hopefully with a more specific
3715          * error than "couldn't read pg_control".
3716          */
3717         if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3718                 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3719
3720         memset(buffer, 0, PG_CONTROL_SIZE);
3721         memcpy(buffer, ControlFile, sizeof(ControlFileData));
3722
3723         fd = BasicOpenFile(XLOG_CONTROL_FILE,
3724                                            O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3725                                            S_IRUSR | S_IWUSR);
3726         if (fd < 0)
3727                 ereport(PANIC,
3728                                 (errcode_for_file_access(),
3729                                  errmsg("could not create control file \"%s\": %m",
3730                                                 XLOG_CONTROL_FILE)));
3731
3732         errno = 0;
3733         if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3734         {
3735                 /* if write didn't set errno, assume problem is no disk space */
3736                 if (errno == 0)
3737                         errno = ENOSPC;
3738                 ereport(PANIC,
3739                                 (errcode_for_file_access(),
3740                                  errmsg("could not write to control file: %m")));
3741         }
3742
3743         if (pg_fsync(fd) != 0)
3744                 ereport(PANIC,
3745                                 (errcode_for_file_access(),
3746                                  errmsg("could not fsync control file: %m")));
3747
3748         if (close(fd))
3749                 ereport(PANIC,
3750                                 (errcode_for_file_access(),
3751                                  errmsg("could not close control file: %m")));
3752 }
3753
3754 static void
3755 ReadControlFile(void)
3756 {
3757         pg_crc32        crc;
3758         int                     fd;
3759
3760         /*
3761          * Read data...
3762          */
3763         fd = BasicOpenFile(XLOG_CONTROL_FILE,
3764                                            O_RDWR | PG_BINARY,
3765                                            S_IRUSR | S_IWUSR);
3766         if (fd < 0)
3767                 ereport(PANIC,
3768                                 (errcode_for_file_access(),
3769                                  errmsg("could not open control file \"%s\": %m",
3770                                                 XLOG_CONTROL_FILE)));
3771
3772         if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3773                 ereport(PANIC,
3774                                 (errcode_for_file_access(),
3775                                  errmsg("could not read from control file: %m")));
3776
3777         close(fd);
3778
3779         /*
3780          * Check for expected pg_control format version.  If this is wrong, the
3781          * CRC check will likely fail because we'll be checking the wrong number
3782          * of bytes.  Complaining about wrong version will probably be more
3783          * enlightening than complaining about wrong CRC.
3784          */
3785         if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3786                 ereport(FATAL,
3787                                 (errmsg("database files are incompatible with server"),
3788                                  errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3789                                   " but the server was compiled with PG_CONTROL_VERSION %d.",
3790                                                 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3791                                  errhint("It looks like you need to initdb.")));
3792         /* Now check the CRC. */
3793         INIT_CRC32(crc);
3794         COMP_CRC32(crc,
3795                            (char *) ControlFile,
3796                            offsetof(ControlFileData, crc));
3797         FIN_CRC32(crc);
3798
3799         if (!EQ_CRC32(crc, ControlFile->crc))
3800                 ereport(FATAL,
3801                                 (errmsg("incorrect checksum in control file")));
3802
3803         /*
3804          * Do compatibility checking immediately.  We do this here for 2 reasons:
3805          *
3806          * (1) if the database isn't compatible with the backend executable, we
3807          * want to abort before we can possibly do any damage;
3808          *
3809          * (2) this code is executed in the postmaster, so the setlocale() will
3810          * propagate to forked backends, which aren't going to read this file for
3811          * themselves.  (These locale settings are considered critical
3812          * compatibility items because they can affect sort order of indexes.)
3813          */
3814         if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3815                 ereport(FATAL,
3816                                 (errmsg("database files are incompatible with server"),
3817                                  errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3818                                   " but the server was compiled with CATALOG_VERSION_NO %d.",
3819                                                 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3820                                  errhint("It looks like you need to initdb.")));
3821         if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3822                 ereport(FATAL,
3823                                 (errmsg("database files are incompatible with server"),
3824                    errdetail("The database cluster was initialized with MAXALIGN %d,"
3825                                          " but the server was compiled with MAXALIGN %d.",
3826                                          ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3827                                  errhint("It looks like you need to initdb.")));
3828         if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3829                 ereport(FATAL,
3830                                 (errmsg("database files are incompatible with server"),
3831                                  errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3832                                  errhint("It looks like you need to initdb.")));
3833         if (ControlFile->blcksz != BLCKSZ)
3834                 ereport(FATAL,
3835                                 (errmsg("database files are incompatible with server"),
3836                          errdetail("The database cluster was initialized with BLCKSZ %d,"
3837                                            " but the server was compiled with BLCKSZ %d.",
3838                                            ControlFile->blcksz, BLCKSZ),
3839                                  errhint("It looks like you need to recompile or initdb.")));
3840         if (ControlFile->relseg_size != RELSEG_SIZE)
3841                 ereport(FATAL,
3842                                 (errmsg("database files are incompatible with server"),
3843                 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3844                                   " but the server was compiled with RELSEG_SIZE %d.",
3845                                   ControlFile->relseg_size, RELSEG_SIZE),
3846                                  errhint("It looks like you need to recompile or initdb.")));
3847         if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3848                 ereport(FATAL,
3849                                 (errmsg("database files are incompatible with server"),
3850                 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3851                                   " but the server was compiled with XLOG_BLCKSZ %d.",
3852                                   ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3853                                  errhint("It looks like you need to recompile or initdb.")));
3854         if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3855                 ereport(FATAL,
3856                                 (errmsg("database files are incompatible with server"),
3857                                  errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3858                                            " but the server was compiled with XLOG_SEG_SIZE %d.",
3859                                                    ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3860                                  errhint("It looks like you need to recompile or initdb.")));
3861         if (ControlFile->nameDataLen != NAMEDATALEN)
3862                 ereport(FATAL,
3863                                 (errmsg("database files are incompatible with server"),
3864                 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3865                                   " but the server was compiled with NAMEDATALEN %d.",
3866                                   ControlFile->nameDataLen, NAMEDATALEN),
3867                                  errhint("It looks like you need to recompile or initdb.")));
3868         if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3869                 ereport(FATAL,
3870                                 (errmsg("database files are incompatible with server"),
3871                                  errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3872                                           " but the server was compiled with INDEX_MAX_KEYS %d.",
3873                                                    ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3874                                  errhint("It looks like you need to recompile or initdb.")));
3875
3876 #ifdef HAVE_INT64_TIMESTAMP
3877         if (ControlFile->enableIntTimes != TRUE)
3878                 ereport(FATAL,
3879                                 (errmsg("database files are incompatible with server"),
3880                                  errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3881                                   " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3882                                  errhint("It looks like you need to recompile or initdb.")));
3883 #else
3884         if (ControlFile->enableIntTimes != FALSE)
3885                 ereport(FATAL,
3886                                 (errmsg("database files are incompatible with server"),
3887                                  errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3888                            " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3889                                  errhint("It looks like you need to recompile or initdb.")));
3890 #endif
3891
3892         if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3893                 ereport(FATAL,
3894                                 (errmsg("database files are incompatible with server"),
3895                                  errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3896                                   " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3897                                                    ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3898                                  errhint("It looks like you need to recompile or initdb.")));
3899         if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3900                 ereport(FATAL,
3901                         (errmsg("database files are incompatible with operating system"),
3902                          errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3903                                            " which is not recognized by setlocale().",
3904                                            ControlFile->lc_collate),
3905                          errhint("It looks like you need to initdb or install locale support.")));
3906         if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3907                 ereport(FATAL,
3908                         (errmsg("database files are incompatible with operating system"),
3909                 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3910                                   " which is not recognized by setlocale().",
3911                                   ControlFile->lc_ctype),
3912                          errhint("It looks like you need to initdb or install locale support.")));
3913
3914         /* Make the fixed locale settings visible as GUC variables, too */
3915         SetConfigOption("lc_collate", ControlFile->lc_collate,
3916                                         PGC_INTERNAL, PGC_S_OVERRIDE);
3917         SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3918                                         PGC_INTERNAL, PGC_S_OVERRIDE);
3919 }
3920
3921 void
3922 UpdateControlFile(void)
3923 {
3924         int                     fd;
3925
3926         INIT_CRC32(ControlFile->crc);
3927         COMP_CRC32(ControlFile->crc,
3928                            (char *) ControlFile,
3929                            offsetof(ControlFileData, crc));
3930         FIN_CRC32(ControlFile->crc);
3931
3932         fd = BasicOpenFile(XLOG_CONTROL_FILE,
3933                                            O_RDWR | PG_BINARY,
3934                                            S_IRUSR | S_IWUSR);
3935         if (fd < 0)
3936                 ereport(PANIC,
3937                                 (errcode_for_file_access(),
3938                                  errmsg("could not open control file \"%s\": %m",
3939                                                 XLOG_CONTROL_FILE)));
3940
3941         errno = 0;
3942         if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3943         {
3944                 /* if write didn't set errno, assume problem is no disk space */
3945                 if (errno == 0)
3946                         errno = ENOSPC;
3947                 ereport(PANIC,
3948                                 (errcode_for_file_access(),
3949                                  errmsg("could not write to control file: %m")));
3950         }
3951
3952         if (pg_fsync(fd) != 0)
3953                 ereport(PANIC,
3954                                 (errcode_for_file_access(),
3955                                  errmsg("could not fsync control file: %m")));
3956
3957         if (close(fd))
3958                 ereport(PANIC,
3959                                 (errcode_for_file_access(),
3960                                  errmsg("could not close control file: %m")));
3961 }
3962
3963 /*
3964  * Initialization of shared memory for XLOG
3965  */
3966 Size
3967 XLOGShmemSize(void)
3968 {
3969         Size            size;
3970
3971         /* XLogCtl */
3972         size = sizeof(XLogCtlData);
3973         /* xlblocks array */
3974         size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
3975         /* extra alignment padding for XLOG I/O buffers */
3976         size = add_size(size, ALIGNOF_XLOG_BUFFER);
3977         /* and the buffers themselves */
3978         size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
3979
3980         /*
3981          * Note: we don't count ControlFileData, it comes out of the "slop factor"
3982          * added by CreateSharedMemoryAndSemaphores.  This lets us use this
3983          * routine again below to compute the actual allocation size.
3984          */
3985
3986         return size;
3987 }
3988
3989 void
3990 XLOGShmemInit(void)
3991 {
3992         bool            foundCFile,
3993                                 foundXLog;
3994         char       *allocptr;
3995
3996         ControlFile = (ControlFileData *)
3997                 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
3998         XLogCtl = (XLogCtlData *)
3999                 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4000
4001         if (foundCFile || foundXLog)
4002         {
4003                 /* both should be present or neither */
4004                 Assert(foundCFile && foundXLog);
4005                 return;
4006         }
4007
4008         memset(XLogCtl, 0, sizeof(XLogCtlData));
4009
4010         /*
4011          * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4012          * multiple of the alignment for same, so no extra alignment padding is
4013          * needed here.
4014          */
4015         allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4016         XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4017         memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4018         allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4019
4020         /*
4021          * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4022          */
4023         allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4024         XLogCtl->pages = allocptr;
4025         memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4026
4027         /*
4028          * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4029          * in additional info.)
4030          */
4031         XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
4032
4033         XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4034         XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4035         SpinLockInit(&XLogCtl->info_lck);
4036
4037         /*
4038          * If we are not in bootstrap mode, pg_control should already exist. Read
4039          * and validate it immediately (see comments in ReadControlFile() for the
4040          * reasons why).
4041          */
4042         if (!IsBootstrapProcessingMode())
4043                 ReadControlFile();
4044 }
4045
4046 /*
4047  * This func must be called ONCE on system install.  It creates pg_control
4048  * and the initial XLOG segment.
4049  */
4050 void
4051 BootStrapXLOG(void)
4052 {
4053         CheckPoint      checkPoint;
4054         char       *buffer;
4055         XLogPageHeader page;
4056         XLogLongPageHeader longpage;
4057         XLogRecord *record;
4058         bool            use_existent;
4059         uint64          sysidentifier;
4060         struct timeval tv;
4061         pg_crc32        crc;
4062
4063         /*
4064          * Select a hopefully-unique system identifier code for this installation.
4065          * We use the result of gettimeofday(), including the fractional seconds
4066          * field, as being about as unique as we can easily get.  (Think not to
4067          * use random(), since it hasn't been seeded and there's no portable way
4068          * to seed it other than the system clock value...)  The upper half of the
4069          * uint64 value is just the tv_sec part, while the lower half is the XOR
4070          * of tv_sec and tv_usec.  This is to ensure that we don't lose uniqueness
4071          * unnecessarily if "uint64" is really only 32 bits wide.  A person
4072          * knowing this encoding can determine the initialization time of the
4073          * installation, which could perhaps be useful sometimes.
4074          */
4075         gettimeofday(&tv, NULL);
4076         sysidentifier = ((uint64) tv.tv_sec) << 32;
4077         sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4078
4079         /* First timeline ID is always 1 */
4080         ThisTimeLineID = 1;
4081
4082         /* page buffer must be aligned suitably for O_DIRECT */
4083         buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4084         page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4085         memset(page, 0, XLOG_BLCKSZ);
4086
4087         /* Set up information for the initial checkpoint record */
4088         checkPoint.redo.xlogid = 0;
4089         checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4090         checkPoint.undo = checkPoint.redo;
4091         checkPoint.ThisTimeLineID = ThisTimeLineID;
4092         checkPoint.nextXidEpoch = 0;
4093         checkPoint.nextXid = FirstNormalTransactionId;
4094         checkPoint.nextOid = FirstBootstrapObjectId;
4095         checkPoint.nextMulti = FirstMultiXactId;
4096         checkPoint.nextMultiOffset = 0;
4097         checkPoint.time = time(NULL);
4098
4099         ShmemVariableCache->nextXid = checkPoint.nextXid;
4100         ShmemVariableCache->nextOid = checkPoint.nextOid;
4101         ShmemVariableCache->oidCount = 0;
4102         MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4103
4104         /* Set up the XLOG page header */
4105         page->xlp_magic = XLOG_PAGE_MAGIC;
4106         page->xlp_info = XLP_LONG_HEADER;
4107         page->xlp_tli = ThisTimeLineID;
4108         page->xlp_pageaddr.xlogid = 0;
4109         page->xlp_pageaddr.xrecoff = 0;
4110         longpage = (XLogLongPageHeader) page;
4111         longpage->xlp_sysid = sysidentifier;
4112         longpage->xlp_seg_size = XLogSegSize;
4113         longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4114
4115         /* Insert the initial checkpoint record */
4116         record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4117         record->xl_prev.xlogid = 0;
4118         record->xl_prev.xrecoff = 0;
4119         record->xl_xid = InvalidTransactionId;
4120         record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4121         record->xl_len = sizeof(checkPoint);
4122         record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4123         record->xl_rmid = RM_XLOG_ID;
4124         memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4125
4126         INIT_CRC32(crc);
4127         COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4128         COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4129                            SizeOfXLogRecord - sizeof(pg_crc32));
4130         FIN_CRC32(crc);
4131         record->xl_crc = crc;
4132
4133         /* Create first XLOG segment file */
4134         use_existent = false;
4135         openLogFile = XLogFileInit(0, 0, &use_existent, false);
4136
4137         /* Write the first page with the initial record */
4138         errno = 0;
4139         if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4140         {
4141                 /* if write didn't set errno, assume problem is no disk space */
4142                 if (errno == 0)
4143                         errno = ENOSPC;
4144                 ereport(PANIC,
4145                                 (errcode_for_file_access(),
4146                           errmsg("could not write bootstrap transaction log file: %m")));
4147         }
4148
4149         if (pg_fsync(openLogFile) != 0)
4150                 ereport(PANIC,
4151                                 (errcode_for_file_access(),
4152                           errmsg("could not fsync bootstrap transaction log file: %m")));
4153
4154         if (close(openLogFile))
4155                 ereport(PANIC,
4156                                 (errcode_for_file_access(),
4157                           errmsg("could not close bootstrap transaction log file: %m")));
4158
4159         openLogFile = -1;
4160
4161         /* Now create pg_control */
4162
4163         memset(ControlFile, 0, sizeof(ControlFileData));
4164         /* Initialize pg_control status fields */
4165         ControlFile->system_identifier = sysidentifier;
4166         ControlFile->state = DB_SHUTDOWNED;
4167         ControlFile->time = checkPoint.time;
4168         ControlFile->logId = 0;
4169         ControlFile->logSeg = 1;
4170         ControlFile->checkPoint = checkPoint.redo;
4171         ControlFile->checkPointCopy = checkPoint;
4172         /* some additional ControlFile fields are set in WriteControlFile() */
4173
4174         WriteControlFile();
4175
4176         /* Bootstrap the commit log, too */
4177         BootStrapCLOG();
4178         BootStrapSUBTRANS();
4179         BootStrapMultiXact();
4180
4181         pfree(buffer);
4182 }
4183
4184 static char *
4185 str_time(time_t tnow)
4186 {
4187         static char buf[128];
4188
4189         strftime(buf, sizeof(buf),
4190                          "%Y-%m-%d %H:%M:%S %Z",
4191                          localtime(&tnow));
4192
4193         return buf;
4194 }
4195
4196 /*
4197  * See if there is a recovery command file (recovery.conf), and if so
4198  * read in parameters for archive recovery.
4199  *
4200  * XXX longer term intention is to expand this to
4201  * cater for additional parameters and controls
4202  * possibly use a flex lexer similar to the GUC one
4203  */
4204 static void
4205 readRecoveryCommandFile(void)
4206 {
4207         FILE       *fd;
4208         char            cmdline[MAXPGPATH];
4209         TimeLineID      rtli = 0;
4210         bool            rtliGiven = false;
4211         bool            syntaxError = false;
4212
4213         fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4214         if (fd == NULL)
4215         {
4216                 if (errno == ENOENT)
4217                         return;                         /* not there, so no archive recovery */
4218                 ereport(FATAL,
4219                                 (errcode_for_file_access(),
4220                                  errmsg("could not open recovery command file \"%s\": %m",
4221                                                 RECOVERY_COMMAND_FILE)));
4222         }
4223
4224         ereport(LOG,
4225                         (errmsg("starting archive recovery")));
4226
4227         /*
4228          * Parse the file...
4229          */
4230         while (fgets(cmdline, MAXPGPATH, fd) != NULL)
4231         {
4232                 /* skip leading whitespace and check for # comment */
4233                 char       *ptr;
4234                 char       *tok1;
4235                 char       *tok2;
4236
4237                 for (ptr = cmdline; *ptr; ptr++)
4238                 {
4239                         if (!isspace((unsigned char) *ptr))
4240                                 break;
4241                 }
4242                 if (*ptr == '\0' || *ptr == '#')
4243                         continue;
4244
4245                 /* identify the quoted parameter value */
4246                 tok1 = strtok(ptr, "'");
4247                 if (!tok1)
4248                 {
4249                         syntaxError = true;
4250                         break;
4251                 }
4252                 tok2 = strtok(NULL, "'");
4253                 if (!tok2)
4254                 {
4255                         syntaxError = true;
4256                         break;
4257                 }
4258                 /* reparse to get just the parameter name */
4259                 tok1 = strtok(ptr, " \t=");
4260                 if (!tok1)
4261                 {
4262                         syntaxError = true;
4263                         break;
4264                 }
4265
4266                 if (strcmp(tok1, "restore_command") == 0)
4267                 {
4268                         recoveryRestoreCommand = pstrdup(tok2);
4269                         ereport(LOG,
4270                                         (errmsg("restore_command = \"%s\"",
4271                                                         recoveryRestoreCommand)));
4272                 }
4273                 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4274                 {
4275                         rtliGiven = true;
4276                         if (strcmp(tok2, "latest") == 0)
4277                                 rtli = 0;
4278                         else
4279                         {
4280                                 errno = 0;
4281                                 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4282                                 if (errno == EINVAL || errno == ERANGE)
4283                                         ereport(FATAL,
4284                                                         (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4285                                                                         tok2)));
4286                         }
4287                         if (rtli)
4288                                 ereport(LOG,
4289                                                 (errmsg("recovery_target_timeline = %u", rtli)));
4290                         else
4291                                 ereport(LOG,
4292                                                 (errmsg("recovery_target_timeline = latest")));
4293                 }
4294                 else if (strcmp(tok1, "recovery_target_xid") == 0)
4295                 {
4296                         errno = 0;
4297                         recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4298                         if (errno == EINVAL || errno == ERANGE)
4299                                 ereport(FATAL,
4300                                  (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4301                                                  tok2)));
4302                         ereport(LOG,
4303                                         (errmsg("recovery_target_xid = %u",
4304                                                         recoveryTargetXid)));
4305                         recoveryTarget = true;
4306                         recoveryTargetExact = true;
4307                 }
4308                 else if (strcmp(tok1, "recovery_target_time") == 0)
4309                 {
4310                         /*
4311                          * if recovery_target_xid specified, then this overrides
4312                          * recovery_target_time
4313                          */
4314                         if (recoveryTargetExact)
4315                                 continue;
4316                         recoveryTarget = true;
4317                         recoveryTargetExact = false;
4318
4319                         /*
4320                          * Convert the time string given by the user to the time_t format.
4321                          * We use type abstime's input converter because we know abstime
4322                          * has the same representation as time_t.
4323                          */
4324                         recoveryTargetTime = (time_t)
4325                                 DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
4326                                                                                                          CStringGetDatum(tok2)));
4327                         ereport(LOG,
4328                                         (errmsg("recovery_target_time = %s",
4329                                                         DatumGetCString(DirectFunctionCall1(abstimeout,
4330                                 AbsoluteTimeGetDatum((AbsoluteTime) recoveryTargetTime))))));
4331                 }
4332                 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4333                 {
4334                         /*
4335                          * does nothing if a recovery_target is not also set
4336                          */
4337                         if (strcmp(tok2, "true") == 0)
4338                                 recoveryTargetInclusive = true;
4339                         else
4340                         {
4341                                 recoveryTargetInclusive = false;
4342                                 tok2 = "false";
4343                         }
4344                         ereport(LOG,
4345                                         (errmsg("recovery_target_inclusive = %s", tok2)));
4346                 }
4347                 else
4348                         ereport(FATAL,
4349                                         (errmsg("unrecognized recovery parameter \"%s\"",
4350                                                         tok1)));
4351         }
4352
4353         FreeFile(fd);
4354
4355         if (syntaxError)
4356                 ereport(FATAL,
4357                                 (errmsg("syntax error in recovery command file: %s",
4358                                                 cmdline),
4359                           errhint("Lines should have the format parameter = 'value'.")));
4360
4361         /* Check that required parameters were supplied */
4362         if (recoveryRestoreCommand == NULL)
4363                 ereport(FATAL,
4364                                 (errmsg("recovery command file \"%s\" did not specify restore_command",
4365                                                 RECOVERY_COMMAND_FILE)));
4366
4367         /* Enable fetching from archive recovery area */
4368         InArchiveRecovery = true;
4369
4370         /*
4371          * If user specified recovery_target_timeline, validate it or compute the
4372          * "latest" value.      We can't do this until after we've gotten the restore
4373          * command and set InArchiveRecovery, because we need to fetch timeline
4374          * history files from the archive.
4375          */
4376         if (rtliGiven)
4377         {
4378                 if (rtli)
4379                 {
4380                         /* Timeline 1 does not have a history file, all else should */
4381                         if (rtli != 1 && !existsTimeLineHistory(rtli))
4382                                 ereport(FATAL,
4383                                                 (errmsg("recovery_target_timeline %u does not exist",
4384                                                                 rtli)));
4385                         recoveryTargetTLI = rtli;
4386                 }
4387                 else
4388                 {
4389                         /* We start the "latest" search from pg_control's timeline */
4390                         recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4391                 }
4392         }
4393 }
4394
4395 /*
4396  * Exit archive-recovery state
4397  */
4398 static void
4399 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4400 {
4401         char            recoveryPath[MAXPGPATH];
4402         char            xlogpath[MAXPGPATH];
4403
4404         /*
4405          * We are no longer in archive recovery state.
4406          */
4407         InArchiveRecovery = false;
4408
4409         /*
4410          * We should have the ending log segment currently open.  Verify, and then
4411          * close it (to avoid problems on Windows with trying to rename or delete
4412          * an open file).
4413          */
4414         Assert(readFile >= 0);
4415         Assert(readId == endLogId);
4416         Assert(readSeg == endLogSeg);
4417
4418         close(readFile);
4419         readFile = -1;
4420
4421         /*
4422          * If the segment was fetched from archival storage, we want to replace
4423          * the existing xlog segment (if any) with the archival version.  This is
4424          * because whatever is in XLOGDIR is very possibly older than what we have
4425          * from the archives, since it could have come from restoring a PGDATA
4426          * backup.      In any case, the archival version certainly is more
4427          * descriptive of what our current database state is, because that is what
4428          * we replayed from.
4429          *
4430          * Note that if we are establishing a new timeline, ThisTimeLineID is
4431          * already set to the new value, and so we will create a new file instead
4432          * of overwriting any existing file.
4433          */
4434         snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4435         XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4436
4437         if (restoredFromArchive)
4438         {
4439                 ereport(DEBUG3,
4440                                 (errmsg_internal("moving last restored xlog to \"%s\"",
4441                                                                  xlogpath)));
4442                 unlink(xlogpath);               /* might or might not exist */
4443                 if (rename(recoveryPath, xlogpath) != 0)
4444                         ereport(FATAL,
4445                                         (errcode_for_file_access(),
4446                                          errmsg("could not rename file \"%s\" to \"%s\": %m",
4447                                                         recoveryPath, xlogpath)));
4448                 /* XXX might we need to fix permissions on the file? */
4449         }
4450         else
4451         {
4452                 /*
4453                  * If the latest segment is not archival, but there's still a
4454                  * RECOVERYXLOG laying about, get rid of it.
4455                  */
4456                 unlink(recoveryPath);   /* ignore any error */
4457
4458                 /*
4459                  * If we are establishing a new timeline, we have to copy data from
4460                  * the last WAL segment of the old timeline to create a starting WAL
4461                  * segment for the new timeline.
4462                  */
4463                 if (endTLI != ThisTimeLineID)
4464                         XLogFileCopy(endLogId, endLogSeg,
4465                                                  endTLI, endLogId, endLogSeg);
4466         }
4467
4468         /*
4469          * Let's just make real sure there are not .ready or .done flags posted
4470          * for the new segment.
4471          */
4472         XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4473         XLogArchiveCleanup(xlogpath);
4474
4475         /* Get rid of any remaining recovered timeline-history file, too */
4476         snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4477         unlink(recoveryPath);           /* ignore any error */
4478
4479         /*
4480          * Rename the config file out of the way, so that we don't accidentally
4481          * re-enter archive recovery mode in a subsequent crash.
4482          */
4483         unlink(RECOVERY_COMMAND_DONE);
4484         if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4485                 ereport(FATAL,
4486                                 (errcode_for_file_access(),
4487                                  errmsg("could not rename file \"%s\" to \"%s\": %m",
4488                                                 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4489
4490         ereport(LOG,
4491                         (errmsg("archive recovery complete")));
4492 }
4493
4494 /*
4495  * For point-in-time recovery, this function decides whether we want to
4496  * stop applying the XLOG at or after the current record.
4497  *
4498  * Returns TRUE if we are stopping, FALSE otherwise.  On TRUE return,
4499  * *includeThis is set TRUE if we should apply this record before stopping.
4500  * Also, some information is saved in recoveryStopXid et al for use in
4501  * annotating the new timeline's history file.
4502  */
4503 static bool
4504 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4505 {
4506         bool            stopsHere;
4507         uint8           record_info;
4508         time_t          recordXtime;
4509
4510         /* Do we have a PITR target at all? */
4511         if (!recoveryTarget)
4512                 return false;
4513
4514         /* We only consider stopping at COMMIT or ABORT records */
4515         if (record->xl_rmid != RM_XACT_ID)
4516                 return false;
4517         record_info = record->xl_info & ~XLR_INFO_MASK;
4518         if (record_info == XLOG_XACT_COMMIT)
4519         {
4520                 xl_xact_commit *recordXactCommitData;
4521
4522                 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4523                 recordXtime = recordXactCommitData->xtime;
4524         }
4525         else if (record_info == XLOG_XACT_ABORT)
4526         {
4527                 xl_xact_abort *recordXactAbortData;
4528
4529                 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4530                 recordXtime = recordXactAbortData->xtime;
4531         }
4532         else
4533                 return false;
4534
4535         if (recoveryTargetExact)
4536         {
4537                 /*
4538                  * there can be only one transaction end record with this exact
4539                  * transactionid
4540                  *
4541                  * when testing for an xid, we MUST test for equality only, since
4542                  * transactions are numbered in the order they start, not the order
4543                  * they complete. A higher numbered xid will complete before you about
4544                  * 50% of the time...
4545                  */
4546                 stopsHere = (record->xl_xid == recoveryTargetXid);
4547                 if (stopsHere)
4548                         *includeThis = recoveryTargetInclusive;
4549         }
4550         else
4551         {
4552                 /*
4553                  * there can be many transactions that share the same commit time, so
4554                  * we stop after the last one, if we are inclusive, or stop at the
4555                  * first one if we are exclusive
4556                  */
4557                 if (recoveryTargetInclusive)
4558                         stopsHere = (recordXtime > recoveryTargetTime);
4559                 else
4560                         stopsHere = (recordXtime >= recoveryTargetTime);
4561                 if (stopsHere)
4562                         *includeThis = false;
4563         }
4564
4565         if (stopsHere)
4566         {
4567                 recoveryStopXid = record->xl_xid;
4568                 recoveryStopTime = recordXtime;
4569                 recoveryStopAfter = *includeThis;
4570
4571                 if (record_info == XLOG_XACT_COMMIT)
4572                 {
4573                         if (recoveryStopAfter)
4574                                 ereport(LOG,
4575                                                 (errmsg("recovery stopping after commit of transaction %u, time %s",
4576                                                           recoveryStopXid, str_time(recoveryStopTime))));
4577                         else
4578                                 ereport(LOG,
4579                                                 (errmsg("recovery stopping before commit of transaction %u, time %s",
4580                                                           recoveryStopXid, str_time(recoveryStopTime))));
4581                 }
4582                 else
4583                 {
4584                         if (recoveryStopAfter)
4585                                 ereport(LOG,
4586                                                 (errmsg("recovery stopping after abort of transaction %u, time %s",
4587                                                           recoveryStopXid, str_time(recoveryStopTime))));
4588                         else
4589                                 ereport(LOG,
4590                                                 (errmsg("recovery stopping before abort of transaction %u, time %s",
4591                                                           recoveryStopXid, str_time(recoveryStopTime))));
4592                 }
4593         }
4594
4595         return stopsHere;
4596 }
4597
4598 /*
4599  * This must be called ONCE during postmaster or standalone-backend startup
4600  */
4601 void
4602 StartupXLOG(void)
4603 {
4604         XLogCtlInsert *Insert;
4605         CheckPoint      checkPoint;
4606         bool            wasShutdown;
4607         bool            needNewTimeLine = false;
4608         bool            haveBackupLabel = false;
4609         XLogRecPtr      RecPtr,
4610                                 LastRec,
4611                                 checkPointLoc,
4612                                 minRecoveryLoc,
4613                                 EndOfLog;
4614         uint32          endLogId;
4615         uint32          endLogSeg;
4616         XLogRecord *record;
4617         uint32          freespace;
4618         TransactionId oldestActiveXID;
4619
4620         CritSectionCount++;
4621
4622         /*
4623          * Read control file and check XLOG status looks valid.
4624          *
4625          * Note: in most control paths, *ControlFile is already valid and we need
4626          * not do ReadControlFile() here, but might as well do it to be sure.
4627          */
4628         ReadControlFile();
4629
4630         if (ControlFile->logSeg == 0 ||
4631                 ControlFile->state < DB_SHUTDOWNED ||
4632                 ControlFile->state > DB_IN_PRODUCTION ||
4633                 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4634                 ereport(FATAL,
4635                                 (errmsg("control file contains invalid data")));
4636
4637         if (ControlFile->state == DB_SHUTDOWNED)
4638                 ereport(LOG,
4639                                 (errmsg("database system was shut down at %s",
4640                                                 str_time(ControlFile->time))));
4641         else if (ControlFile->state == DB_SHUTDOWNING)
4642                 ereport(LOG,
4643                                 (errmsg("database system shutdown was interrupted at %s",
4644                                                 str_time(ControlFile->time))));
4645         else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4646                 ereport(LOG,
4647                    (errmsg("database system was interrupted while in recovery at %s",
4648                                    str_time(ControlFile->time)),
4649                         errhint("This probably means that some data is corrupted and"
4650                                         " you will have to use the last backup for recovery.")));
4651         else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4652                 ereport(LOG,
4653                                 (errmsg("database system was interrupted while in recovery at log time %s",
4654                                                 str_time(ControlFile->checkPointCopy.time)),
4655                                  errhint("If this has occurred more than once some data may be corrupted"
4656                                 " and you may need to choose an earlier recovery target.")));
4657         else if (ControlFile->state == DB_IN_PRODUCTION)
4658                 ereport(LOG,
4659                                 (errmsg("database system was interrupted at %s",
4660                                                 str_time(ControlFile->time))));
4661
4662         /* This is just to allow attaching to startup process with a debugger */
4663 #ifdef XLOG_REPLAY_DELAY
4664         if (ControlFile->state != DB_SHUTDOWNED)
4665                 pg_usleep(60000000L);
4666 #endif
4667
4668         /*
4669          * Initialize on the assumption we want to recover to the same timeline
4670          * that's active according to pg_control.
4671          */
4672         recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4673
4674         /*
4675          * Check for recovery control file, and if so set up state for offline
4676          * recovery
4677          */
4678         readRecoveryCommandFile();
4679
4680         /* Now we can determine the list of expected TLIs */
4681         expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4682
4683         /*
4684          * If pg_control's timeline is not in expectedTLIs, then we cannot
4685          * proceed: the backup is not part of the history of the requested
4686          * timeline.
4687          */
4688         if (!list_member_int(expectedTLIs,
4689                                                  (int) ControlFile->checkPointCopy.ThisTimeLineID))
4690                 ereport(FATAL,
4691                                 (errmsg("requested timeline %u is not a child of database system timeline %u",
4692                                                 recoveryTargetTLI,
4693                                                 ControlFile->checkPointCopy.ThisTimeLineID)));
4694
4695         if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4696         {
4697                 /*
4698                  * When a backup_label file is present, we want to roll forward from
4699                  * the checkpoint it identifies, rather than using pg_control.
4700                  */
4701                 record = ReadCheckpointRecord(checkPointLoc, 0);
4702                 if (record != NULL)
4703                 {
4704                         ereport(LOG,
4705                                         (errmsg("checkpoint record is at %X/%X",
4706                                                         checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4707                         InRecovery = true;      /* force recovery even if SHUTDOWNED */
4708                 }
4709                 else
4710                 {
4711                         ereport(PANIC,
4712                                         (errmsg("could not locate required checkpoint record"),
4713                                          errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4714                 }
4715                 /* set flag to delete it later */
4716                 haveBackupLabel = true;
4717         }
4718         else
4719         {
4720                 /*
4721                  * Get the last valid checkpoint record.  If the latest one according
4722                  * to pg_control is broken, try the next-to-last one.
4723                  */
4724                 checkPointLoc = ControlFile->checkPoint;
4725                 record = ReadCheckpointRecord(checkPointLoc, 1);
4726                 if (record != NULL)
4727                 {
4728                         ereport(LOG,
4729                                         (errmsg("checkpoint record is at %X/%X",
4730                                                         checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4731                 }
4732                 else
4733                 {
4734                         checkPointLoc = ControlFile->prevCheckPoint;
4735                         record = ReadCheckpointRecord(checkPointLoc, 2);
4736                         if (record != NULL)
4737                         {
4738                                 ereport(LOG,
4739                                                 (errmsg("using previous checkpoint record at %X/%X",
4740                                                           checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4741                                 InRecovery = true;              /* force recovery even if SHUTDOWNED */
4742                         }
4743                         else
4744                                 ereport(PANIC,
4745                                          (errmsg("could not locate a valid checkpoint record")));
4746                 }
4747         }
4748
4749         LastRec = RecPtr = checkPointLoc;
4750         memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4751         wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4752
4753         ereport(LOG,
4754          (errmsg("redo record is at %X/%X; undo record is at %X/%X; shutdown %s",
4755                          checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4756                          checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
4757                          wasShutdown ? "TRUE" : "FALSE")));
4758         ereport(LOG,
4759                         (errmsg("next transaction ID: %u/%u; next OID: %u",
4760                                         checkPoint.nextXidEpoch, checkPoint.nextXid,
4761                                         checkPoint.nextOid)));
4762         ereport(LOG,
4763                         (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4764                                         checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4765         if (!TransactionIdIsNormal(checkPoint.nextXid))
4766                 ereport(PANIC,
4767                                 (errmsg("invalid next transaction ID")));
4768
4769         ShmemVariableCache->nextXid = checkPoint.nextXid;
4770         ShmemVariableCache->nextOid = checkPoint.nextOid;
4771         ShmemVariableCache->oidCount = 0;
4772         MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4773
4774         /*
4775          * We must replay WAL entries using the same TimeLineID they were created
4776          * under, so temporarily adopt the TLI indicated by the checkpoint (see
4777          * also xlog_redo()).
4778          */
4779         ThisTimeLineID = checkPoint.ThisTimeLineID;
4780
4781         RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4782
4783         if (XLByteLT(RecPtr, checkPoint.redo))
4784                 ereport(PANIC,
4785                                 (errmsg("invalid redo in checkpoint record")));
4786         if (checkPoint.undo.xrecoff == 0)
4787                 checkPoint.undo = RecPtr;
4788
4789         /*
4790          * Check whether we need to force recovery from WAL.  If it appears to
4791          * have been a clean shutdown and we did not have a recovery.conf file,
4792          * then assume no recovery needed.
4793          */
4794         if (XLByteLT(checkPoint.undo, RecPtr) ||
4795                 XLByteLT(checkPoint.redo, RecPtr))
4796         {
4797                 if (wasShutdown)
4798                         ereport(PANIC,
4799                                 (errmsg("invalid redo/undo record in shutdown checkpoint")));
4800                 InRecovery = true;
4801         }
4802         else if (ControlFile->state != DB_SHUTDOWNED)
4803                 InRecovery = true;
4804         else if (InArchiveRecovery)
4805         {
4806                 /* force recovery due to presence of recovery.conf */
4807                 InRecovery = true;
4808         }
4809
4810         /* REDO */
4811         if (InRecovery)
4812         {
4813                 int                     rmid;
4814
4815                 /*
4816                  * Update pg_control to show that we are recovering and to show the
4817                  * selected checkpoint as the place we are starting from. We also mark
4818                  * pg_control with any minimum recovery stop point obtained from a
4819                  * backup history file.
4820                  */
4821                 if (InArchiveRecovery)
4822                 {
4823                         ereport(LOG,
4824                                         (errmsg("automatic recovery in progress")));
4825                         ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4826                 }
4827                 else
4828                 {
4829                         ereport(LOG,
4830                                         (errmsg("database system was not properly shut down; "
4831                                                         "automatic recovery in progress")));
4832                         ControlFile->state = DB_IN_CRASH_RECOVERY;
4833                 }
4834                 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4835                 ControlFile->checkPoint = checkPointLoc;
4836                 ControlFile->checkPointCopy = checkPoint;
4837                 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4838                         ControlFile->minRecoveryPoint = minRecoveryLoc;
4839                 ControlFile->time = time(NULL);
4840                 UpdateControlFile();
4841
4842                 /*
4843                  * If there was a backup label file, it's done its job and the info
4844                  * has now been propagated into pg_control.  We must get rid of the
4845                  * label file so that if we crash during recovery, we'll pick up at
4846                  * the latest recovery restartpoint instead of going all the way back
4847                  * to the backup start point.  It seems prudent though to just rename
4848                  * the file out of the way rather than delete it completely.
4849                  */
4850                 if (haveBackupLabel)
4851                 {
4852                         unlink(BACKUP_LABEL_OLD);
4853                         if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4854                                 ereport(FATAL,
4855                                                 (errcode_for_file_access(),
4856                                                  errmsg("could not rename file \"%s\" to \"%s\": %m",
4857                                                                 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4858                 }
4859
4860                 /* Start up the recovery environment */
4861                 XLogInitRelationCache();
4862
4863                 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4864                 {
4865                         if (RmgrTable[rmid].rm_startup != NULL)
4866                                 RmgrTable[rmid].rm_startup();
4867                 }
4868
4869                 /*
4870                  * Find the first record that logically follows the checkpoint --- it
4871                  * might physically precede it, though.
4872                  */
4873                 if (XLByteLT(checkPoint.redo, RecPtr))
4874                 {
4875                         /* back up to find the record */
4876                         record = ReadRecord(&(checkPoint.redo), PANIC);
4877                 }
4878                 else
4879                 {
4880                         /* just have to read next record after CheckPoint */
4881                         record = ReadRecord(NULL, LOG);
4882                 }
4883
4884                 if (record != NULL)
4885                 {
4886                         bool            recoveryContinue = true;
4887                         bool            recoveryApply = true;
4888                         ErrorContextCallback errcontext;
4889
4890                         InRedo = true;
4891                         ereport(LOG,
4892                                         (errmsg("redo starts at %X/%X",
4893                                                         ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4894
4895                         /*
4896                          * main redo apply loop
4897                          */
4898                         do
4899                         {
4900 #ifdef WAL_DEBUG
4901                                 if (XLOG_DEBUG)
4902                                 {
4903                                         StringInfoData buf;
4904
4905                                         initStringInfo(&buf);
4906                                         appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4907                                                                          ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4908                                                                          EndRecPtr.xlogid, EndRecPtr.xrecoff);
4909                                         xlog_outrec(&buf, record);
4910                                         appendStringInfo(&buf, " - ");
4911                                         RmgrTable[record->xl_rmid].rm_desc(&buf,
4912                                                                                                            record->xl_info,
4913                                                                                                          XLogRecGetData(record));
4914                                         elog(LOG, "%s", buf.data);
4915                                         pfree(buf.data);
4916                                 }
4917 #endif
4918
4919                                 /*
4920                                  * Have we reached our recovery target?
4921                                  */
4922                                 if (recoveryStopsHere(record, &recoveryApply))
4923                                 {
4924                                         needNewTimeLine = true;         /* see below */
4925                                         recoveryContinue = false;
4926                                         if (!recoveryApply)
4927                                                 break;
4928                                 }
4929
4930                                 /* Setup error traceback support for ereport() */
4931                                 errcontext.callback = rm_redo_error_callback;
4932                                 errcontext.arg = (void *) record;
4933                                 errcontext.previous = error_context_stack;
4934                                 error_context_stack = &errcontext;
4935
4936                                 /* nextXid must be beyond record's xid */
4937                                 if (TransactionIdFollowsOrEquals(record->xl_xid,
4938                                                                                                  ShmemVariableCache->nextXid))
4939                                 {
4940                                         ShmemVariableCache->nextXid = record->xl_xid;
4941                                         TransactionIdAdvance(ShmemVariableCache->nextXid);
4942                                 }
4943
4944                                 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4945                                         RestoreBkpBlocks(record, EndRecPtr);
4946
4947                                 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4948
4949                                 /* Pop the error context stack */
4950                                 error_context_stack = errcontext.previous;
4951
4952                                 LastRec = ReadRecPtr;
4953
4954                                 record = ReadRecord(NULL, LOG);
4955                         } while (record != NULL && recoveryContinue);
4956
4957                         /*
4958                          * end of main redo apply loop
4959                          */
4960
4961                         ereport(LOG,
4962                                         (errmsg("redo done at %X/%X",
4963                                                         ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4964                         InRedo = false;
4965                 }
4966                 else
4967                 {
4968                         /* there are no WAL records following the checkpoint */
4969                         ereport(LOG,
4970                                         (errmsg("redo is not required")));
4971                 }
4972         }
4973
4974         /*
4975          * Re-fetch the last valid or last applied record, so we can identify the
4976          * exact endpoint of what we consider the valid portion of WAL.
4977          */
4978         record = ReadRecord(&LastRec, PANIC);
4979         EndOfLog = EndRecPtr;
4980         XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4981
4982         /*
4983          * Complain if we did not roll forward far enough to render the backup
4984          * dump consistent.
4985          */
4986         if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
4987         {
4988                 if (needNewTimeLine)    /* stopped because of stop request */
4989                         ereport(FATAL,
4990                                         (errmsg("requested recovery stop point is before end time of backup dump")));
4991                 else
4992                         /* ran off end of WAL */
4993                         ereport(FATAL,
4994                                         (errmsg("WAL ends before end time of backup dump")));
4995         }
4996
4997         /*
4998          * Consider whether we need to assign a new timeline ID.
4999          *
5000          * If we stopped short of the end of WAL during recovery, then we are
5001          * generating a new timeline and must assign it a unique new ID.
5002          * Otherwise, we can just extend the timeline we were in when we ran out
5003          * of WAL.
5004          */
5005         if (needNewTimeLine)
5006         {
5007                 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5008                 ereport(LOG,
5009                                 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5010                 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5011                                                          curFileTLI, endLogId, endLogSeg);
5012         }
5013
5014         /* Save the selected TimeLineID in shared memory, too */
5015         XLogCtl->ThisTimeLineID = ThisTimeLineID;
5016
5017         /*
5018          * We are now done reading the old WAL.  Turn off archive fetching if it
5019          * was active, and make a writable copy of the last WAL segment. (Note
5020          * that we also have a copy of the last block of the old WAL in readBuf;
5021          * we will use that below.)
5022          */
5023         if (InArchiveRecovery)
5024                 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5025
5026         /*
5027          * Prepare to write WAL starting at EndOfLog position, and init xlog
5028          * buffer cache using the block containing the last record from the
5029          * previous incarnation.
5030          */
5031         openLogId = endLogId;
5032         openLogSeg = endLogSeg;
5033         openLogFile = XLogFileOpen(openLogId, openLogSeg);
5034         openLogOff = 0;
5035         ControlFile->logId = openLogId;
5036         ControlFile->logSeg = openLogSeg + 1;
5037         Insert = &XLogCtl->Insert;
5038         Insert->PrevRecord = LastRec;
5039         XLogCtl->xlblocks[0].xlogid = openLogId;
5040         XLogCtl->xlblocks[0].xrecoff =
5041                 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5042
5043         /*
5044          * Tricky point here: readBuf contains the *last* block that the LastRec
5045          * record spans, not the one it starts in.      The last block is indeed the
5046          * one we want to use.
5047          */
5048         Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5049         memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5050         Insert->currpos = (char *) Insert->currpage +
5051                 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5052
5053         LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5054
5055         XLogCtl->Write.LogwrtResult = LogwrtResult;
5056         Insert->LogwrtResult = LogwrtResult;
5057         XLogCtl->LogwrtResult = LogwrtResult;
5058
5059         XLogCtl->LogwrtRqst.Write = EndOfLog;
5060         XLogCtl->LogwrtRqst.Flush = EndOfLog;
5061
5062         freespace = INSERT_FREESPACE(Insert);
5063         if (freespace > 0)
5064         {
5065                 /* Make sure rest of page is zero */
5066                 MemSet(Insert->currpos, 0, freespace);
5067                 XLogCtl->Write.curridx = 0;
5068         }
5069         else
5070         {
5071                 /*
5072                  * Whenever Write.LogwrtResult points to exactly the end of a page,
5073                  * Write.curridx must point to the *next* page (see XLogWrite()).
5074                  *
5075                  * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5076                  * this is sufficient.  The first actual attempt to insert a log
5077                  * record will advance the insert state.
5078                  */
5079                 XLogCtl->Write.curridx = NextBufIdx(0);
5080         }
5081
5082         /* Pre-scan prepared transactions to find out the range of XIDs present */
5083         oldestActiveXID = PrescanPreparedTransactions();
5084
5085         if (InRecovery)
5086         {
5087                 int                     rmid;
5088
5089                 /*
5090                  * Allow resource managers to do any required cleanup.
5091                  */
5092                 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5093                 {
5094                         if (RmgrTable[rmid].rm_cleanup != NULL)
5095                                 RmgrTable[rmid].rm_cleanup();
5096                 }
5097
5098                 /*
5099                  * Check to see if the XLOG sequence contained any unresolved
5100                  * references to uninitialized pages.
5101                  */
5102                 XLogCheckInvalidPages();
5103
5104                 /*
5105                  * Reset pgstat data, because it may be invalid after recovery.
5106                  */
5107                 pgstat_reset_all();
5108
5109                 /*
5110                  * Perform a checkpoint to update all our recovery activity to disk.
5111                  *
5112                  * Note that we write a shutdown checkpoint rather than an on-line
5113                  * one. This is not particularly critical, but since we may be
5114                  * assigning a new TLI, using a shutdown checkpoint allows us to have
5115                  * the rule that TLI only changes in shutdown checkpoints, which
5116                  * allows some extra error checking in xlog_redo.
5117                  */
5118                 CreateCheckPoint(true, true);
5119
5120                 /*
5121                  * Close down recovery environment
5122                  */
5123                 XLogCloseRelationCache();
5124         }
5125
5126         /*
5127          * Preallocate additional log files, if wanted.
5128          */
5129         (void) PreallocXlogFiles(EndOfLog);
5130
5131         /*
5132          * Okay, we're officially UP.
5133          */
5134         InRecovery = false;
5135
5136         ControlFile->state = DB_IN_PRODUCTION;
5137         ControlFile->time = time(NULL);
5138         UpdateControlFile();
5139
5140         /* start the archive_timeout timer running */
5141         XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5142
5143         /* initialize shared-memory copy of latest checkpoint XID/epoch */
5144         XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5145         XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5146
5147         /* Start up the commit log and related stuff, too */
5148         StartupCLOG();
5149         StartupSUBTRANS(oldestActiveXID);
5150         StartupMultiXact();
5151
5152         /* Reload shared-memory state for prepared transactions */
5153         RecoverPreparedTransactions();
5154
5155         ereport(LOG,
5156                         (errmsg("database system is ready")));
5157         CritSectionCount--;
5158
5159         /* Shut down readFile facility, free space */
5160         if (readFile >= 0)
5161         {
5162                 close(readFile);
5163                 readFile = -1;
5164         }
5165         if (readBuf)
5166         {
5167                 free(readBuf);
5168                 readBuf = NULL;
5169         }
5170         if (readRecordBuf)
5171         {
5172                 free(readRecordBuf);
5173                 readRecordBuf = NULL;
5174                 readRecordBufSize = 0;
5175         }
5176 }
5177
5178 /*
5179  * Subroutine to try to fetch and validate a prior checkpoint record.
5180  *
5181  * whichChkpt identifies the checkpoint (merely for reporting purposes).
5182  * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5183  */
5184 static XLogRecord *
5185 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5186 {
5187         XLogRecord *record;
5188
5189         if (!XRecOffIsValid(RecPtr.xrecoff))
5190         {
5191                 switch (whichChkpt)
5192                 {
5193                         case 1:
5194                                 ereport(LOG,
5195                                 (errmsg("invalid primary checkpoint link in control file")));
5196                                 break;
5197                         case 2:
5198                                 ereport(LOG,
5199                                                 (errmsg("invalid secondary checkpoint link in control file")));
5200                                 break;
5201                         default:
5202                                 ereport(LOG,
5203                                    (errmsg("invalid checkpoint link in backup_label file")));
5204                                 break;
5205                 }
5206                 return NULL;
5207         }
5208
5209         record = ReadRecord(&RecPtr, LOG);
5210
5211         if (record == NULL)
5212         {
5213                 switch (whichChkpt)
5214                 {
5215                         case 1:
5216                                 ereport(LOG,
5217                                                 (errmsg("invalid primary checkpoint record")));
5218                                 break;
5219                         case 2:
5220                                 ereport(LOG,
5221                                                 (errmsg("invalid secondary checkpoint record")));
5222                                 break;
5223                         default:
5224                                 ereport(LOG,
5225                                                 (errmsg("invalid checkpoint record")));
5226                                 break;
5227                 }
5228                 return NULL;
5229         }
5230         if (record->xl_rmid != RM_XLOG_ID)
5231         {
5232                 switch (whichChkpt)
5233                 {
5234                         case 1:
5235                                 ereport(LOG,
5236                                                 (errmsg("invalid resource manager ID in primary checkpoint record")));
5237                                 break;
5238                         case 2:
5239                                 ereport(LOG,
5240                                                 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5241                                 break;
5242                         default:
5243                                 ereport(LOG,
5244                                 (errmsg("invalid resource manager ID in checkpoint record")));
5245                                 break;
5246                 }
5247                 return NULL;
5248         }
5249         if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5250                 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5251         {
5252                 switch (whichChkpt)
5253                 {
5254                         case 1:
5255                                 ereport(LOG,
5256                                    (errmsg("invalid xl_info in primary checkpoint record")));
5257                                 break;
5258                         case 2:
5259                                 ereport(LOG,
5260                                  (errmsg("invalid xl_info in secondary checkpoint record")));
5261                                 break;
5262                         default:
5263                                 ereport(LOG,
5264                                                 (errmsg("invalid xl_info in checkpoint record")));
5265                                 break;
5266                 }
5267                 return NULL;
5268         }
5269         if (record->xl_len != sizeof(CheckPoint) ||
5270                 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5271         {
5272                 switch (whichChkpt)
5273                 {
5274                         case 1:
5275                                 ereport(LOG,
5276                                         (errmsg("invalid length of primary checkpoint record")));
5277                                 break;
5278                         case 2:
5279                                 ereport(LOG,
5280                                   (errmsg("invalid length of secondary checkpoint record")));
5281                                 break;
5282                         default:
5283                                 ereport(LOG,
5284                                                 (errmsg("invalid length of checkpoint record")));
5285                                 break;
5286                 }
5287                 return NULL;
5288         }
5289         return record;
5290 }
5291
5292 /*
5293  * This must be called during startup of a backend process, except that
5294  * it need not be called in a standalone backend (which does StartupXLOG
5295  * instead).  We need to initialize the local copies of ThisTimeLineID and
5296  * RedoRecPtr.
5297  *
5298  * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5299  * process's copies of ThisTimeLineID and RedoRecPtr valid too.  This was
5300  * unnecessary however, since the postmaster itself never touches XLOG anyway.
5301  */
5302 void
5303 InitXLOGAccess(void)
5304 {
5305         /* ThisTimeLineID doesn't change so we need no lock to copy it */
5306         ThisTimeLineID = XLogCtl->ThisTimeLineID;
5307         /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5308         (void) GetRedoRecPtr();
5309 }
5310
5311 /*
5312  * Once spawned, a backend may update its local RedoRecPtr from
5313  * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5314  * to do so.  This is done in XLogInsert() or GetRedoRecPtr().
5315  */
5316 XLogRecPtr
5317 GetRedoRecPtr(void)
5318 {
5319         /* use volatile pointer to prevent code rearrangement */
5320         volatile XLogCtlData *xlogctl = XLogCtl;
5321
5322         SpinLockAcquire(&xlogctl->info_lck);
5323         Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5324         RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5325         SpinLockRelease(&xlogctl->info_lck);
5326
5327         return RedoRecPtr;
5328 }
5329
5330 /*
5331  * Get the time of the last xlog segment switch
5332  */
5333 time_t
5334 GetLastSegSwitchTime(void)
5335 {
5336         time_t          result;
5337
5338         /* Need WALWriteLock, but shared lock is sufficient */
5339         LWLockAcquire(WALWriteLock, LW_SHARED);
5340         result = XLogCtl->Write.lastSegSwitchTime;
5341         LWLockRelease(WALWriteLock);
5342
5343         return result;
5344 }
5345
5346 /*
5347  * GetRecentNextXid - get the nextXid value saved by the most recent checkpoint
5348  *
5349  * This is currently used only by the autovacuum daemon.  To check for
5350  * impending XID wraparound, autovac needs an approximate idea of the current
5351  * XID counter, and it needs it before choosing which DB to attach to, hence
5352  * before it sets up a PGPROC, hence before it can take any LWLocks.  But it
5353  * has attached to shared memory, and so we can let it reach into the shared
5354  * ControlFile structure and pull out the last checkpoint nextXID.
5355  *
5356  * Since we don't take any sort of lock, we have to assume that reading a
5357  * TransactionId is atomic ... but that assumption is made elsewhere, too,
5358  * and in any case the worst possible consequence of a bogus result is that
5359  * autovac issues an unnecessary database-wide VACUUM.
5360  *
5361  * Note: we could also choose to read ShmemVariableCache->nextXid in an
5362  * unlocked fashion, thus getting a more up-to-date result; but since that
5363  * changes far more frequently than the controlfile checkpoint copy, it would
5364  * pose a far higher risk of bogus result if we did have a nonatomic-read
5365  * problem.
5366  *
5367  * A (theoretically) completely safe answer is to read the actual pg_control
5368  * file into local process memory, but that certainly seems like overkill.
5369  */
5370 TransactionId
5371 GetRecentNextXid(void)
5372 {
5373         return ControlFile->checkPointCopy.nextXid;
5374 }
5375
5376 /*
5377  * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5378  *
5379  * This is exported for use by code that would like to have 64-bit XIDs.
5380  * We don't really support such things, but all XIDs within the system
5381  * can be presumed "close to" the result, and thus the epoch associated
5382  * with them can be determined.
5383  */
5384 void
5385 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5386 {
5387         uint32          ckptXidEpoch;
5388         TransactionId ckptXid;
5389         TransactionId nextXid;
5390
5391         /* Must read checkpoint info first, else have race condition */
5392         {
5393                 /* use volatile pointer to prevent code rearrangement */
5394                 volatile XLogCtlData *xlogctl = XLogCtl;
5395
5396                 SpinLockAcquire(&xlogctl->info_lck);
5397                 ckptXidEpoch = xlogctl->ckptXidEpoch;
5398                 ckptXid = xlogctl->ckptXid;
5399                 SpinLockRelease(&xlogctl->info_lck);
5400         }
5401
5402         /* Now fetch current nextXid */
5403         nextXid = ReadNewTransactionId();
5404
5405         /*
5406          * nextXid is certainly logically later than ckptXid.  So if it's
5407          * numerically less, it must have wrapped into the next epoch.
5408          */
5409         if (nextXid < ckptXid)
5410                 ckptXidEpoch++;
5411
5412         *xid = nextXid;
5413         *epoch = ckptXidEpoch;
5414 }
5415
5416 /*
5417  * This must be called ONCE during postmaster or standalone-backend shutdown
5418  */
5419 void
5420 ShutdownXLOG(int code, Datum arg)
5421 {
5422         ereport(LOG,
5423                         (errmsg("shutting down")));
5424
5425         CritSectionCount++;
5426         CreateCheckPoint(true, true);
5427         ShutdownCLOG();
5428         ShutdownSUBTRANS();
5429         ShutdownMultiXact();
5430         CritSectionCount--;
5431
5432         ereport(LOG,
5433                         (errmsg("database system is shut down")));
5434 }
5435
5436 /*
5437  * Perform a checkpoint --- either during shutdown, or on-the-fly
5438  *
5439  * If force is true, we force a checkpoint regardless of whether any XLOG
5440  * activity has occurred since the last one.
5441  */
5442 void
5443 CreateCheckPoint(bool shutdown, bool force)
5444 {
5445         CheckPoint      checkPoint;
5446         XLogRecPtr      recptr;
5447         XLogCtlInsert *Insert = &XLogCtl->Insert;
5448         XLogRecData rdata;
5449         uint32          freespace;
5450         uint32          _logId;
5451         uint32          _logSeg;
5452         int                     nsegsadded = 0;
5453         int                     nsegsremoved = 0;
5454         int                     nsegsrecycled = 0;
5455
5456         /*
5457          * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5458          * (This is just pro forma, since in the present system structure there is
5459          * only one process that is allowed to issue checkpoints at any given
5460          * time.)
5461          */
5462         LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5463
5464         /*
5465          * Use a critical section to force system panic if we have trouble.
5466          */
5467         START_CRIT_SECTION();
5468
5469         if (shutdown)
5470         {
5471                 ControlFile->state = DB_SHUTDOWNING;
5472                 ControlFile->time = time(NULL);
5473                 UpdateControlFile();
5474         }
5475
5476         MemSet(&checkPoint, 0, sizeof(checkPoint));
5477         checkPoint.ThisTimeLineID = ThisTimeLineID;
5478         checkPoint.time = time(NULL);
5479
5480         /*
5481          * We must hold CheckpointStartLock while determining the checkpoint REDO
5482          * pointer.  This ensures that any concurrent transaction commits will be
5483          * either not yet logged, or logged and recorded in pg_clog. See notes in
5484          * RecordTransactionCommit().
5485          */
5486         LWLockAcquire(CheckpointStartLock, LW_EXCLUSIVE);
5487
5488         /* And we need WALInsertLock too */
5489         LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5490
5491         /*
5492          * If this isn't a shutdown or forced checkpoint, and we have not inserted
5493          * any XLOG records since the start of the last checkpoint, skip the
5494          * checkpoint.  The idea here is to avoid inserting duplicate checkpoints
5495          * when the system is idle. That wastes log space, and more importantly it
5496          * exposes us to possible loss of both current and previous checkpoint
5497          * records if the machine crashes just as we're writing the update.
5498          * (Perhaps it'd make even more sense to checkpoint only when the previous
5499          * checkpoint record is in a different xlog page?)
5500          *
5501          * We have to make two tests to determine that nothing has happened since
5502          * the start of the last checkpoint: current insertion point must match
5503          * the end of the last checkpoint record, and its redo pointer must point
5504          * to itself.
5505          */
5506         if (!shutdown && !force)
5507         {
5508                 XLogRecPtr      curInsert;
5509
5510                 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5511                 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5512                         curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5513                         MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5514                         ControlFile->checkPoint.xlogid ==
5515                         ControlFile->checkPointCopy.redo.xlogid &&
5516                         ControlFile->checkPoint.xrecoff ==
5517                         ControlFile->checkPointCopy.redo.xrecoff)
5518                 {
5519                         LWLockRelease(WALInsertLock);
5520                         LWLockRelease(CheckpointStartLock);
5521                         LWLockRelease(CheckpointLock);
5522                         END_CRIT_SECTION();
5523                         return;
5524                 }
5525         }
5526
5527         /*
5528          * Compute new REDO record ptr = location of next XLOG record.
5529          *
5530          * NB: this is NOT necessarily where the checkpoint record itself will be,
5531          * since other backends may insert more XLOG records while we're off doing
5532          * the buffer flush work.  Those XLOG records are logically after the
5533          * checkpoint, even though physically before it.  Got that?
5534          */
5535         freespace = INSERT_FREESPACE(Insert);
5536         if (freespace < SizeOfXLogRecord)
5537         {
5538                 (void) AdvanceXLInsertBuffer(false);
5539                 /* OK to ignore update return flag, since we will do flush anyway */
5540                 freespace = INSERT_FREESPACE(Insert);
5541         }
5542         INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5543
5544         /*
5545          * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5546          * must be done while holding the insert lock AND the info_lck.
5547          *
5548          * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5549          * pointing past where it really needs to point.  This is okay; the only
5550          * consequence is that XLogInsert might back up whole buffers that it
5551          * didn't really need to.  We can't postpone advancing RedoRecPtr because
5552          * XLogInserts that happen while we are dumping buffers must assume that
5553          * their buffer changes are not included in the checkpoint.
5554          */
5555         {
5556                 /* use volatile pointer to prevent code rearrangement */
5557                 volatile XLogCtlData *xlogctl = XLogCtl;
5558
5559                 SpinLockAcquire(&xlogctl->info_lck);
5560                 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5561                 SpinLockRelease(&xlogctl->info_lck);
5562         }
5563
5564         /*
5565          * Now we can release insert lock and checkpoint start lock, allowing
5566          * other xacts to proceed even while we are flushing disk buffers.
5567          */
5568         LWLockRelease(WALInsertLock);
5569
5570         LWLockRelease(CheckpointStartLock);
5571
5572         if (!shutdown)
5573                 ereport(DEBUG2,
5574                                 (errmsg("checkpoint starting")));
5575
5576         /*
5577          * Get the other info we need for the checkpoint record.
5578          */
5579         LWLockAcquire(XidGenLock, LW_SHARED);
5580         checkPoint.nextXid = ShmemVariableCache->nextXid;
5581         LWLockRelease(XidGenLock);
5582
5583         /* Increase XID epoch if we've wrapped around since last checkpoint */
5584         checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5585         if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5586                 checkPoint.nextXidEpoch++;
5587
5588         LWLockAcquire(OidGenLock, LW_SHARED);
5589         checkPoint.nextOid = ShmemVariableCache->nextOid;
5590         if (!shutdown)
5591                 checkPoint.nextOid += ShmemVariableCache->oidCount;
5592         LWLockRelease(OidGenLock);
5593
5594         MultiXactGetCheckptMulti(shutdown,
5595                                                          &checkPoint.nextMulti,
5596                                                          &checkPoint.nextMultiOffset);
5597
5598         /*
5599          * Having constructed the checkpoint record, ensure all shmem disk buffers
5600          * and commit-log buffers are flushed to disk.
5601          *
5602          * This I/O could fail for various reasons.  If so, we will fail to
5603          * complete the checkpoint, but there is no reason to force a system
5604          * panic. Accordingly, exit critical section while doing it.  (If we are
5605          * doing a shutdown checkpoint, we probably *should* panic --- but that
5606          * will happen anyway because we'll still be inside the critical section
5607          * established by ShutdownXLOG.)
5608          */
5609         END_CRIT_SECTION();
5610
5611         CheckPointGuts(checkPoint.redo);
5612
5613         START_CRIT_SECTION();
5614
5615         /*
5616          * Now insert the checkpoint record into XLOG.
5617          */
5618         rdata.data = (char *) (&checkPoint);
5619         rdata.len = sizeof(checkPoint);
5620         rdata.buffer = InvalidBuffer;
5621         rdata.next = NULL;
5622
5623         recptr = XLogInsert(RM_XLOG_ID,
5624                                                 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5625                                                 XLOG_CHECKPOINT_ONLINE,
5626                                                 &rdata);
5627
5628         XLogFlush(recptr);
5629
5630         /*
5631          * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5632          * = end of actual checkpoint record.
5633          */
5634         if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5635                 ereport(PANIC,
5636                                 (errmsg("concurrent transaction log activity while database system is shutting down")));
5637
5638         /*
5639          * Select point at which we can truncate the log, which we base on the
5640          * prior checkpoint's earliest info.
5641          */
5642         XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5643
5644         /*
5645          * Update the control file.
5646          */
5647         LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5648         if (shutdown)
5649                 ControlFile->state = DB_SHUTDOWNED;
5650         ControlFile->prevCheckPoint = ControlFile->checkPoint;
5651         ControlFile->checkPoint = ProcLastRecPtr;
5652         ControlFile->checkPointCopy = checkPoint;
5653         ControlFile->time = time(NULL);
5654         UpdateControlFile();
5655         LWLockRelease(ControlFileLock);
5656
5657         /* Update shared-memory copy of checkpoint XID/epoch */
5658         {
5659                 /* use volatile pointer to prevent code rearrangement */
5660                 volatile XLogCtlData *xlogctl = XLogCtl;
5661
5662                 SpinLockAcquire(&xlogctl->info_lck);
5663                 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5664                 xlogctl->ckptXid = checkPoint.nextXid;
5665                 SpinLockRelease(&xlogctl->info_lck);
5666         }
5667
5668         /*
5669          * We are now done with critical updates; no need for system panic if we
5670          * have trouble while fooling with offline log segments.
5671          */
5672         END_CRIT_SECTION();
5673
5674         /*
5675          * Delete offline log files (those no longer needed even for previous
5676          * checkpoint).
5677          */
5678         if (_logId || _logSeg)
5679         {
5680                 PrevLogSeg(_logId, _logSeg);
5681                 MoveOfflineLogs(_logId, _logSeg, recptr,
5682                                                 &nsegsremoved, &nsegsrecycled);
5683         }
5684
5685         /*
5686          * Make more log segments if needed.  (Do this after deleting offline log
5687          * segments, to avoid having peak disk space usage higher than necessary.)
5688          */
5689         if (!shutdown)
5690                 nsegsadded = PreallocXlogFiles(recptr);
5691
5692         /*
5693          * Truncate pg_subtrans if possible.  We can throw away all data before
5694          * the oldest XMIN of any running transaction.  No future transaction will
5695          * attempt to reference any pg_subtrans entry older than that (see Asserts
5696          * in subtrans.c).      During recovery, though, we mustn't do this because
5697          * StartupSUBTRANS hasn't been called yet.
5698          */
5699         if (!InRecovery)
5700                 TruncateSUBTRANS(GetOldestXmin(true, false));
5701
5702         if (!shutdown)
5703                 ereport(DEBUG2,
5704                                 (errmsg("checkpoint complete; %d transaction log file(s) added, %d removed, %d recycled",
5705                                                 nsegsadded, nsegsremoved, nsegsrecycled)));
5706
5707         LWLockRelease(CheckpointLock);
5708 }
5709
5710 /*
5711  * Flush all data in shared memory to disk, and fsync
5712  *
5713  * This is the common code shared between regular checkpoints and
5714  * recovery restartpoints.
5715  */
5716 static void
5717 CheckPointGuts(XLogRecPtr checkPointRedo)
5718 {
5719         CheckPointCLOG();
5720         CheckPointSUBTRANS();
5721         CheckPointMultiXact();
5722         FlushBufferPool();                      /* performs all required fsyncs */
5723         /* We deliberately delay 2PC checkpointing as long as possible */
5724         CheckPointTwoPhase(checkPointRedo);
5725 }
5726
5727 /*
5728  * Set a recovery restart point if appropriate
5729  *
5730  * This is similar to CreateCheckpoint, but is used during WAL recovery
5731  * to establish a point from which recovery can roll forward without
5732  * replaying the entire recovery log.  This function is called each time
5733  * a checkpoint record is read from XLOG; it must determine whether a
5734  * restartpoint is needed or not.
5735  */
5736 static void
5737 RecoveryRestartPoint(const CheckPoint *checkPoint)
5738 {
5739         int                     elapsed_secs;
5740         int                     rmid;
5741
5742         /*
5743          * Do nothing if the elapsed time since the last restartpoint is less than
5744          * half of checkpoint_timeout.  (We use a value less than
5745          * checkpoint_timeout so that variations in the timing of checkpoints on
5746          * the master, or speed of transmission of WAL segments to a slave, won't
5747          * make the slave skip a restartpoint once it's synced with the master.)
5748          * Checking true elapsed time keeps us from doing restartpoints too often
5749          * while rapidly scanning large amounts of WAL.
5750          */
5751         elapsed_secs = time(NULL) - ControlFile->time;
5752         if (elapsed_secs < CheckPointTimeout / 2)
5753                 return;
5754
5755         /*
5756          * Is it safe to checkpoint?  We must ask each of the resource managers
5757          * whether they have any partial state information that might prevent a
5758          * correct restart from this point.  If so, we skip this opportunity, but
5759          * return at the next checkpoint record for another try.
5760          */
5761         for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5762         {
5763                 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5764                         if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5765                                 return;
5766         }
5767
5768         /*
5769          * OK, force data out to disk
5770          */
5771         CheckPointGuts(checkPoint->redo);
5772
5773         /*
5774          * Update pg_control so that any subsequent crash will restart from this
5775          * checkpoint.  Note: ReadRecPtr gives the XLOG address of the checkpoint
5776          * record itself.
5777          */
5778         ControlFile->prevCheckPoint = ControlFile->checkPoint;
5779         ControlFile->checkPoint = ReadRecPtr;
5780         ControlFile->checkPointCopy = *checkPoint;
5781         ControlFile->time = time(NULL);
5782         UpdateControlFile();
5783
5784         ereport(DEBUG2,
5785                         (errmsg("recovery restart point at %X/%X",
5786                                         checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5787 }
5788
5789 /*
5790  * Write a NEXTOID log record
5791  */
5792 void
5793 XLogPutNextOid(Oid nextOid)
5794 {
5795         XLogRecData rdata;
5796
5797         rdata.data = (char *) (&nextOid);
5798         rdata.len = sizeof(Oid);
5799         rdata.buffer = InvalidBuffer;
5800         rdata.next = NULL;
5801         (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5802
5803         /*
5804          * We need not flush the NEXTOID record immediately, because any of the
5805          * just-allocated OIDs could only reach disk as part of a tuple insert or
5806          * update that would have its own XLOG record that must follow the NEXTOID
5807          * record.      Therefore, the standard buffer LSN interlock applied to those
5808          * records will ensure no such OID reaches disk before the NEXTOID record
5809          * does.
5810          */
5811 }
5812
5813 /*
5814  * Write an XLOG SWITCH record.
5815  *
5816  * Here we just blindly issue an XLogInsert request for the record.
5817  * All the magic happens inside XLogInsert.
5818  *
5819  * The return value is either the end+1 address of the switch record,
5820  * or the end+1 address of the prior segment if we did not need to
5821  * write a switch record because we are already at segment start.
5822  */
5823 XLogRecPtr
5824 RequestXLogSwitch(void)
5825 {
5826         XLogRecPtr      RecPtr;
5827         XLogRecData rdata;
5828
5829         /* XLOG SWITCH, alone among xlog record types, has no data */
5830         rdata.buffer = InvalidBuffer;
5831         rdata.data = NULL;
5832         rdata.len = 0;
5833         rdata.next = NULL;
5834
5835         RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5836
5837         return RecPtr;
5838 }
5839
5840 /*
5841  * XLOG resource manager's routines
5842  */
5843 void
5844 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5845 {
5846         uint8           info = record->xl_info & ~XLR_INFO_MASK;
5847
5848         if (info == XLOG_NEXTOID)
5849         {
5850                 Oid                     nextOid;
5851
5852                 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5853                 if (ShmemVariableCache->nextOid < nextOid)
5854                 {
5855                         ShmemVariableCache->nextOid = nextOid;
5856                         ShmemVariableCache->oidCount = 0;
5857                 }
5858         }
5859         else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5860         {
5861                 CheckPoint      checkPoint;
5862
5863                 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5864                 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5865                 ShmemVariableCache->nextXid = checkPoint.nextXid;
5866                 ShmemVariableCache->nextOid = checkPoint.nextOid;
5867                 ShmemVariableCache->oidCount = 0;
5868                 MultiXactSetNextMXact(checkPoint.nextMulti,
5869                                                           checkPoint.nextMultiOffset);
5870
5871                 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5872                 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5873                 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5874
5875                 /*
5876                  * TLI may change in a shutdown checkpoint, but it shouldn't decrease
5877                  */
5878                 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5879                 {
5880                         if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5881                                 !list_member_int(expectedTLIs,
5882                                                                  (int) checkPoint.ThisTimeLineID))
5883                                 ereport(PANIC,
5884                                                 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5885                                                                 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5886                         /* Following WAL records should be run with new TLI */
5887                         ThisTimeLineID = checkPoint.ThisTimeLineID;
5888                 }
5889
5890                 RecoveryRestartPoint(&checkPoint);
5891         }
5892         else if (info == XLOG_CHECKPOINT_ONLINE)
5893         {
5894                 CheckPoint      checkPoint;
5895
5896                 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5897                 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5898                 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5899                                                                   checkPoint.nextXid))
5900                         ShmemVariableCache->nextXid = checkPoint.nextXid;
5901                 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5902                 {
5903                         ShmemVariableCache->nextOid = checkPoint.nextOid;
5904                         ShmemVariableCache->oidCount = 0;
5905                 }
5906                 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
5907                                                                   checkPoint.nextMultiOffset);
5908
5909                 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5910                 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5911                 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5912
5913                 /* TLI should not change in an on-line checkpoint */
5914                 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5915                         ereport(PANIC,
5916                                         (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5917                                                         checkPoint.ThisTimeLineID, ThisTimeLineID)));
5918
5919                 RecoveryRestartPoint(&checkPoint);
5920         }
5921         else if (info == XLOG_SWITCH)
5922         {
5923                 /* nothing to do here */
5924         }
5925 }
5926
5927 void
5928 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
5929 {
5930         uint8           info = xl_info & ~XLR_INFO_MASK;
5931
5932         if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5933                 info == XLOG_CHECKPOINT_ONLINE)
5934         {
5935                 CheckPoint *checkpoint = (CheckPoint *) rec;
5936
5937                 appendStringInfo(buf, "checkpoint: redo %X/%X; undo %X/%X; "
5938                                                  "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
5939                                                  checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5940                                                  checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
5941                                                  checkpoint->ThisTimeLineID,
5942                                                  checkpoint->nextXidEpoch, checkpoint->nextXid,
5943                                                  checkpoint->nextOid,
5944                                                  checkpoint->nextMulti,
5945                                                  checkpoint->nextMultiOffset,
5946                                  (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
5947         }
5948         else if (info == XLOG_NEXTOID)
5949         {
5950                 Oid                     nextOid;
5951
5952                 memcpy(&nextOid, rec, sizeof(Oid));
5953                 appendStringInfo(buf, "nextOid: %u", nextOid);
5954         }
5955         else if (info == XLOG_SWITCH)
5956         {
5957                 appendStringInfo(buf, "xlog switch");
5958         }
5959         else
5960                 appendStringInfo(buf, "UNKNOWN");
5961 }
5962
5963 #ifdef WAL_DEBUG
5964
5965 static void
5966 xlog_outrec(StringInfo buf, XLogRecord *record)
5967 {
5968         int                     i;
5969
5970         appendStringInfo(buf, "prev %X/%X; xid %u",
5971                                          record->xl_prev.xlogid, record->xl_prev.xrecoff,
5972                                          record->xl_xid);
5973
5974         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
5975         {
5976                 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
5977                         appendStringInfo(buf, "; bkpb%d", i + 1);
5978         }
5979
5980         appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
5981 }
5982 #endif   /* WAL_DEBUG */
5983
5984
5985 /*
5986  * GUC support
5987  */
5988 const char *
5989 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
5990 {
5991         int                     new_sync_method;
5992         int                     new_sync_bit;
5993
5994         if (pg_strcasecmp(method, "fsync") == 0)
5995         {
5996                 new_sync_method = SYNC_METHOD_FSYNC;
5997                 new_sync_bit = 0;
5998         }
5999 #ifdef HAVE_FSYNC_WRITETHROUGH
6000         else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
6001         {
6002                 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
6003                 new_sync_bit = 0;
6004         }
6005 #endif
6006 #ifdef HAVE_FDATASYNC
6007         else if (pg_strcasecmp(method, "fdatasync") == 0)
6008         {
6009                 new_sync_method = SYNC_METHOD_FDATASYNC;
6010                 new_sync_bit = 0;
6011         }
6012 #endif
6013 #ifdef OPEN_SYNC_FLAG
6014         else if (pg_strcasecmp(method, "open_sync") == 0)
6015         {
6016                 new_sync_method = SYNC_METHOD_OPEN;
6017                 new_sync_bit = OPEN_SYNC_FLAG;
6018         }
6019 #endif
6020 #ifdef OPEN_DATASYNC_FLAG
6021         else if (pg_strcasecmp(method, "open_datasync") == 0)
6022         {
6023                 new_sync_method = SYNC_METHOD_OPEN;
6024                 new_sync_bit = OPEN_DATASYNC_FLAG;
6025         }
6026 #endif
6027         else
6028                 return NULL;
6029
6030         if (!doit)
6031                 return method;
6032
6033         if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
6034         {
6035                 /*
6036                  * To ensure that no blocks escape unsynced, force an fsync on the
6037                  * currently open log segment (if any).  Also, if the open flag is
6038                  * changing, close the log file so it will be reopened (with new flag
6039                  * bit) at next use.
6040                  */
6041                 if (openLogFile >= 0)
6042                 {
6043                         if (pg_fsync(openLogFile) != 0)
6044                                 ereport(PANIC,
6045                                                 (errcode_for_file_access(),
6046                                                  errmsg("could not fsync log file %u, segment %u: %m",
6047                                                                 openLogId, openLogSeg)));
6048                         if (open_sync_bit != new_sync_bit)
6049                                 XLogFileClose();
6050                 }
6051                 sync_method = new_sync_method;
6052                 open_sync_bit = new_sync_bit;
6053         }
6054
6055         return method;
6056 }
6057
6058
6059 /*
6060  * Issue appropriate kind of fsync (if any) on the current XLOG output file
6061  */
6062 static void
6063 issue_xlog_fsync(void)
6064 {
6065         switch (sync_method)
6066         {
6067                 case SYNC_METHOD_FSYNC:
6068                         if (pg_fsync_no_writethrough(openLogFile) != 0)
6069                                 ereport(PANIC,
6070                                                 (errcode_for_file_access(),
6071                                                  errmsg("could not fsync log file %u, segment %u: %m",
6072                                                                 openLogId, openLogSeg)));
6073                         break;
6074 #ifdef HAVE_FSYNC_WRITETHROUGH
6075                 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6076                         if (pg_fsync_writethrough(openLogFile) != 0)
6077                                 ereport(PANIC,
6078                                                 (errcode_for_file_access(),
6079                                                  errmsg("could not fsync write-through log file %u, segment %u: %m",
6080                                                                 openLogId, openLogSeg)));
6081                         break;
6082 #endif
6083 #ifdef HAVE_FDATASYNC
6084                 case SYNC_METHOD_FDATASYNC:
6085                         if (pg_fdatasync(openLogFile) != 0)
6086                                 ereport(PANIC,
6087                                                 (errcode_for_file_access(),
6088                                         errmsg("could not fdatasync log file %u, segment %u: %m",
6089                                                    openLogId, openLogSeg)));
6090                         break;
6091 #endif
6092                 case SYNC_METHOD_OPEN:
6093                         /* write synced it already */
6094                         break;
6095                 default:
6096                         elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6097                         break;
6098         }
6099 }
6100
6101
6102 /*
6103  * pg_start_backup: set up for taking an on-line backup dump
6104  *
6105  * Essentially what this does is to create a backup label file in $PGDATA,
6106  * where it will be archived as part of the backup dump.  The label file
6107  * contains the user-supplied label string (typically this would be used
6108  * to tell where the backup dump will be stored) and the starting time and
6109  * starting WAL location for the dump.
6110  */
6111 Datum
6112 pg_start_backup(PG_FUNCTION_ARGS)
6113 {
6114         text       *backupid = PG_GETARG_TEXT_P(0);
6115         text       *result;
6116         char       *backupidstr;
6117         XLogRecPtr      checkpointloc;
6118         XLogRecPtr      startpoint;
6119         time_t          stamp_time;
6120         char            strfbuf[128];
6121         char            xlogfilename[MAXFNAMELEN];
6122         uint32          _logId;
6123         uint32          _logSeg;
6124         struct stat stat_buf;
6125         FILE       *fp;
6126
6127         if (!superuser())
6128                 ereport(ERROR,
6129                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6130                                  (errmsg("must be superuser to run a backup"))));
6131
6132         if (!XLogArchivingActive())
6133                 ereport(ERROR,
6134                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6135                                  (errmsg("WAL archiving is not active"),
6136                                   (errhint("archive_command must be defined before "
6137                                                    "online backups can be made safely.")))));
6138
6139         backupidstr = DatumGetCString(DirectFunctionCall1(textout,
6140                                                                                                  PointerGetDatum(backupid)));
6141
6142         /*
6143          * Mark backup active in shared memory.  We must do full-page WAL writes
6144          * during an on-line backup even if not doing so at other times, because
6145          * it's quite possible for the backup dump to obtain a "torn" (partially
6146          * written) copy of a database page if it reads the page concurrently with
6147          * our write to the same page.  This can be fixed as long as the first
6148          * write to the page in the WAL sequence is a full-page write. Hence, we
6149          * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6150          * are no dirty pages in shared memory that might get dumped while the
6151          * backup is in progress without having a corresponding WAL record.  (Once
6152          * the backup is complete, we need not force full-page writes anymore,
6153          * since we expect that any pages not modified during the backup interval
6154          * must have been correctly captured by the backup.)
6155          *
6156          * We must hold WALInsertLock to change the value of forcePageWrites, to
6157          * ensure adequate interlocking against XLogInsert().
6158          */
6159         LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6160         if (XLogCtl->Insert.forcePageWrites)
6161         {
6162                 LWLockRelease(WALInsertLock);
6163                 ereport(ERROR,
6164                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6165                                  errmsg("a backup is already in progress"),
6166                                  errhint("Run pg_stop_backup() and try again.")));
6167         }
6168         XLogCtl->Insert.forcePageWrites = true;
6169         LWLockRelease(WALInsertLock);
6170
6171         /* Use a TRY block to ensure we release forcePageWrites if fail below */
6172         PG_TRY();
6173         {
6174                 /*
6175                  * Force a CHECKPOINT.  Aside from being necessary to prevent torn
6176                  * page problems, this guarantees that two successive backup runs will
6177                  * have different checkpoint positions and hence different history
6178                  * file names, even if nothing happened in between.
6179                  */
6180                 RequestCheckpoint(true, false);
6181
6182                 /*
6183                  * Now we need to fetch the checkpoint record location, and also its
6184                  * REDO pointer.  The oldest point in WAL that would be needed to
6185                  * restore starting from the checkpoint is precisely the REDO pointer.
6186                  */
6187                 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6188                 checkpointloc = ControlFile->checkPoint;
6189                 startpoint = ControlFile->checkPointCopy.redo;
6190                 LWLockRelease(ControlFileLock);
6191
6192                 XLByteToSeg(startpoint, _logId, _logSeg);
6193                 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6194
6195                 /*
6196                  * We deliberately use strftime/localtime not the src/timezone
6197                  * functions, so that backup labels will consistently be recorded in
6198                  * the same timezone regardless of TimeZone setting.  This matches
6199                  * elog.c's practice.
6200                  */
6201                 stamp_time = time(NULL);
6202                 strftime(strfbuf, sizeof(strfbuf),
6203                                  "%Y-%m-%d %H:%M:%S %Z",
6204                                  localtime(&stamp_time));
6205
6206                 /*
6207                  * Check for existing backup label --- implies a backup is already
6208                  * running.  (XXX given that we checked forcePageWrites above, maybe
6209                  * it would be OK to just unlink any such label file?)
6210                  */
6211                 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6212                 {
6213                         if (errno != ENOENT)
6214                                 ereport(ERROR,
6215                                                 (errcode_for_file_access(),
6216                                                  errmsg("could not stat file \"%s\": %m",
6217                                                                 BACKUP_LABEL_FILE)));
6218                 }
6219                 else
6220                         ereport(ERROR,
6221                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6222                                          errmsg("a backup is already in progress"),
6223                                          errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6224                                                          BACKUP_LABEL_FILE)));
6225
6226                 /*
6227                  * Okay, write the file
6228                  */
6229                 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6230                 if (!fp)
6231                         ereport(ERROR,
6232                                         (errcode_for_file_access(),
6233                                          errmsg("could not create file \"%s\": %m",
6234                                                         BACKUP_LABEL_FILE)));
6235                 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6236                                 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6237                 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6238                                 checkpointloc.xlogid, checkpointloc.xrecoff);
6239                 fprintf(fp, "START TIME: %s\n", strfbuf);
6240                 fprintf(fp, "LABEL: %s\n", backupidstr);
6241                 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6242                         ereport(ERROR,
6243                                         (errcode_for_file_access(),
6244                                          errmsg("could not write file \"%s\": %m",
6245                                                         BACKUP_LABEL_FILE)));
6246         }
6247         PG_CATCH();
6248         {
6249                 /* Turn off forcePageWrites on failure */
6250                 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6251                 XLogCtl->Insert.forcePageWrites = false;
6252                 LWLockRelease(WALInsertLock);
6253
6254                 PG_RE_THROW();
6255         }
6256         PG_END_TRY();
6257
6258         /*
6259          * We're done.  As a convenience, return the starting WAL location.
6260          */
6261         snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6262                          startpoint.xlogid, startpoint.xrecoff);
6263         result = DatumGetTextP(DirectFunctionCall1(textin,
6264                                                                                          CStringGetDatum(xlogfilename)));
6265         PG_RETURN_TEXT_P(result);
6266 }
6267
6268 /*
6269  * pg_stop_backup: finish taking an on-line backup dump
6270  *
6271  * We remove the backup label file created by pg_start_backup, and instead
6272  * create a backup history file in pg_xlog (whence it will immediately be
6273  * archived).  The backup history file contains the same info found in
6274  * the label file, plus the backup-end time and WAL location.
6275  */
6276 Datum
6277 pg_stop_backup(PG_FUNCTION_ARGS)
6278 {
6279         text       *result;
6280         XLogRecPtr      startpoint;
6281         XLogRecPtr      stoppoint;
6282         time_t          stamp_time;
6283         char            strfbuf[128];
6284         char            histfilepath[MAXPGPATH];
6285         char            startxlogfilename[MAXFNAMELEN];
6286         char            stopxlogfilename[MAXFNAMELEN];
6287         uint32          _logId;
6288         uint32          _logSeg;
6289         FILE       *lfp;
6290         FILE       *fp;
6291         char            ch;
6292         int                     ich;
6293
6294         if (!superuser())
6295                 ereport(ERROR,
6296                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6297                                  (errmsg("must be superuser to run a backup"))));
6298
6299         /*
6300          * OK to clear forcePageWrites
6301          */
6302         LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6303         XLogCtl->Insert.forcePageWrites = false;
6304         LWLockRelease(WALInsertLock);
6305
6306         /*
6307          * Force a switch to a new xlog segment file, so that the backup is valid
6308          * as soon as archiver moves out the current segment file. We'll report
6309          * the end address of the XLOG SWITCH record as the backup stopping point.
6310          */
6311         stoppoint = RequestXLogSwitch();
6312
6313         XLByteToSeg(stoppoint, _logId, _logSeg);
6314         XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
6315
6316         /*
6317          * We deliberately use strftime/localtime not the src/timezone functions,
6318          * so that backup labels will consistently be recorded in the same
6319          * timezone regardless of TimeZone setting.  This matches elog.c's
6320          * practice.
6321          */
6322         stamp_time = time(NULL);
6323         strftime(strfbuf, sizeof(strfbuf),
6324                          "%Y-%m-%d %H:%M:%S %Z",
6325                          localtime(&stamp_time));
6326
6327         /*
6328          * Open the existing label file
6329          */
6330         lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6331         if (!lfp)
6332         {
6333                 if (errno != ENOENT)
6334                         ereport(ERROR,
6335                                         (errcode_for_file_access(),
6336                                          errmsg("could not read file \"%s\": %m",
6337                                                         BACKUP_LABEL_FILE)));
6338                 ereport(ERROR,
6339                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6340                                  errmsg("a backup is not in progress")));
6341         }
6342
6343         /*
6344          * Read and parse the START WAL LOCATION line (this code is pretty crude,
6345          * but we are not expecting any variability in the file format).
6346          */
6347         if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
6348                            &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6349                            &ch) != 4 || ch != '\n')
6350                 ereport(ERROR,
6351                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6352                                  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6353
6354         /*
6355          * Write the backup history file
6356          */
6357         XLByteToSeg(startpoint, _logId, _logSeg);
6358         BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6359                                                   startpoint.xrecoff % XLogSegSize);
6360         fp = AllocateFile(histfilepath, "w");
6361         if (!fp)
6362                 ereport(ERROR,
6363                                 (errcode_for_file_access(),
6364                                  errmsg("could not create file \"%s\": %m",
6365                                                 histfilepath)));
6366         fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6367                         startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
6368         fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
6369                         stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
6370         /* transfer remaining lines from label to history file */
6371         while ((ich = fgetc(lfp)) != EOF)
6372                 fputc(ich, fp);
6373         fprintf(fp, "STOP TIME: %s\n", strfbuf);
6374         if (fflush(fp) || ferror(fp) || FreeFile(fp))
6375                 ereport(ERROR,
6376                                 (errcode_for_file_access(),
6377                                  errmsg("could not write file \"%s\": %m",
6378                                                 histfilepath)));
6379
6380         /*
6381          * Close and remove the backup label file
6382          */
6383         if (ferror(lfp) || FreeFile(lfp))
6384                 ereport(ERROR,
6385                                 (errcode_for_file_access(),
6386                                  errmsg("could not read file \"%s\": %m",
6387                                                 BACKUP_LABEL_FILE)));
6388         if (unlink(BACKUP_LABEL_FILE) != 0)
6389                 ereport(ERROR,
6390                                 (errcode_for_file_access(),
6391                                  errmsg("could not remove file \"%s\": %m",
6392                                                 BACKUP_LABEL_FILE)));
6393
6394         /*
6395          * Clean out any no-longer-needed history files.  As a side effect, this
6396          * will post a .ready file for the newly created history file, notifying
6397          * the archiver that history file may be archived immediately.
6398          */
6399         CleanupBackupHistory();
6400
6401         /*
6402          * We're done.  As a convenience, return the ending WAL location.
6403          */
6404         snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
6405                          stoppoint.xlogid, stoppoint.xrecoff);
6406         result = DatumGetTextP(DirectFunctionCall1(textin,
6407                                                                                  CStringGetDatum(stopxlogfilename)));
6408         PG_RETURN_TEXT_P(result);
6409 }
6410
6411 /*
6412  * pg_switch_xlog: switch to next xlog file
6413  */
6414 Datum
6415 pg_switch_xlog(PG_FUNCTION_ARGS)
6416 {
6417         text       *result;
6418         XLogRecPtr      switchpoint;
6419         char            location[MAXFNAMELEN];
6420
6421         if (!superuser())
6422                 ereport(ERROR,
6423                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6424                                  (errmsg("must be superuser to switch xlog files"))));
6425
6426         switchpoint = RequestXLogSwitch();
6427
6428         /*
6429          * As a convenience, return the WAL location of the switch record
6430          */
6431         snprintf(location, sizeof(location), "%X/%X",
6432                          switchpoint.xlogid, switchpoint.xrecoff);
6433         result = DatumGetTextP(DirectFunctionCall1(textin,
6434                                                                                            CStringGetDatum(location)));
6435         PG_RETURN_TEXT_P(result);
6436 }
6437
6438 /*
6439  * Report the current WAL write location (same format as pg_start_backup etc)
6440  *
6441  * This is useful for determining how much of WAL is visible to an external
6442  * archiving process.  Note that the data before this point is written out
6443  * to the kernel, but is not necessarily synced to disk.
6444  */
6445 Datum
6446 pg_current_xlog_location(PG_FUNCTION_ARGS)
6447 {
6448         text       *result;
6449         char            location[MAXFNAMELEN];
6450
6451         /* Make sure we have an up-to-date local LogwrtResult */
6452         {
6453                 /* use volatile pointer to prevent code rearrangement */
6454                 volatile XLogCtlData *xlogctl = XLogCtl;
6455
6456                 SpinLockAcquire(&xlogctl->info_lck);
6457                 LogwrtResult = xlogctl->LogwrtResult;
6458                 SpinLockRelease(&xlogctl->info_lck);
6459         }
6460
6461         snprintf(location, sizeof(location), "%X/%X",
6462                          LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
6463
6464         result = DatumGetTextP(DirectFunctionCall1(textin,
6465                                                                                            CStringGetDatum(location)));
6466         PG_RETURN_TEXT_P(result);
6467 }
6468
6469 /*
6470  * Report the current WAL insert location (same format as pg_start_backup etc)
6471  *
6472  * This function is mostly for debugging purposes.
6473  */
6474 Datum
6475 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
6476 {
6477         text       *result;
6478         XLogCtlInsert *Insert = &XLogCtl->Insert;
6479         XLogRecPtr      current_recptr;
6480         char            location[MAXFNAMELEN];
6481
6482         /*
6483          * Get the current end-of-WAL position ... shared lock is sufficient
6484          */
6485         LWLockAcquire(WALInsertLock, LW_SHARED);
6486         INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
6487         LWLockRelease(WALInsertLock);
6488
6489         snprintf(location, sizeof(location), "%X/%X",
6490                          current_recptr.xlogid, current_recptr.xrecoff);
6491
6492         result = DatumGetTextP(DirectFunctionCall1(textin,
6493                                                                                            CStringGetDatum(location)));
6494         PG_RETURN_TEXT_P(result);
6495 }
6496
6497 /*
6498  * Compute an xlog file name and decimal byte offset given a WAL location,
6499  * such as is returned by pg_stop_backup() or pg_xlog_switch().
6500  *
6501  * Note that a location exactly at a segment boundary is taken to be in
6502  * the previous segment.  This is usually the right thing, since the
6503  * expected usage is to determine which xlog file(s) are ready to archive.
6504  */
6505 Datum
6506 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
6507 {
6508         text       *location = PG_GETARG_TEXT_P(0);
6509         char       *locationstr;
6510         unsigned int uxlogid;
6511         unsigned int uxrecoff;
6512         uint32          xlogid;
6513         uint32          xlogseg;
6514         uint32          xrecoff;
6515         XLogRecPtr      locationpoint;
6516         char            xlogfilename[MAXFNAMELEN];
6517         Datum           values[2];
6518         bool            isnull[2];
6519         TupleDesc       resultTupleDesc;
6520         HeapTuple       resultHeapTuple;
6521         Datum           result;
6522
6523         /*
6524          * Read input and parse
6525          */
6526         locationstr = DatumGetCString(DirectFunctionCall1(textout,
6527                                                                                                  PointerGetDatum(location)));
6528
6529         if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6530                 ereport(ERROR,
6531                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6532                                  errmsg("could not parse xlog location \"%s\"",
6533                                                 locationstr)));
6534
6535         locationpoint.xlogid = uxlogid;
6536         locationpoint.xrecoff = uxrecoff;
6537
6538         /*
6539          * Construct a tuple descriptor for the result row.  This must match this
6540          * function's pg_proc entry!
6541          */
6542         resultTupleDesc = CreateTemplateTupleDesc(2, false);
6543         TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
6544                                            TEXTOID, -1, 0);
6545         TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
6546                                            INT4OID, -1, 0);
6547
6548         resultTupleDesc = BlessTupleDesc(resultTupleDesc);
6549
6550         /*
6551          * xlogfilename
6552          */
6553         XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6554         XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6555
6556         values[0] = DirectFunctionCall1(textin,
6557                                                                         CStringGetDatum(xlogfilename));
6558         isnull[0] = false;
6559
6560         /*
6561          * offset
6562          */
6563         xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
6564
6565         values[1] = UInt32GetDatum(xrecoff);
6566         isnull[1] = false;
6567
6568         /*
6569          * Tuple jam: Having first prepared your Datums, then squash together
6570          */
6571         resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
6572
6573         result = HeapTupleGetDatum(resultHeapTuple);
6574
6575         PG_RETURN_DATUM(result);
6576 }
6577
6578 /*
6579  * Compute an xlog file name given a WAL location,
6580  * such as is returned by pg_stop_backup() or pg_xlog_switch().
6581  */
6582 Datum
6583 pg_xlogfile_name(PG_FUNCTION_ARGS)
6584 {
6585         text       *location = PG_GETARG_TEXT_P(0);
6586         text       *result;
6587         char       *locationstr;
6588         unsigned int uxlogid;
6589         unsigned int uxrecoff;
6590         uint32          xlogid;
6591         uint32          xlogseg;
6592         XLogRecPtr      locationpoint;
6593         char            xlogfilename[MAXFNAMELEN];
6594
6595         locationstr = DatumGetCString(DirectFunctionCall1(textout,
6596                                                                                                  PointerGetDatum(location)));
6597
6598         if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6599                 ereport(ERROR,
6600                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6601                                  errmsg("could not parse xlog location \"%s\"",
6602                                                 locationstr)));
6603
6604         locationpoint.xlogid = uxlogid;
6605         locationpoint.xrecoff = uxrecoff;
6606
6607         XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6608         XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6609
6610         result = DatumGetTextP(DirectFunctionCall1(textin,
6611                                                                                          CStringGetDatum(xlogfilename)));
6612         PG_RETURN_TEXT_P(result);
6613 }
6614
6615 /*
6616  * read_backup_label: check to see if a backup_label file is present
6617  *
6618  * If we see a backup_label during recovery, we assume that we are recovering
6619  * from a backup dump file, and we therefore roll forward from the checkpoint
6620  * identified by the label file, NOT what pg_control says.      This avoids the
6621  * problem that pg_control might have been archived one or more checkpoints
6622  * later than the start of the dump, and so if we rely on it as the start
6623  * point, we will fail to restore a consistent database state.
6624  *
6625  * We also attempt to retrieve the corresponding backup history file.
6626  * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6627  * points.
6628  *
6629  * Returns TRUE if a backup_label was found (and fills the checkpoint
6630  * location into *checkPointLoc); returns FALSE if not.
6631  */
6632 static bool
6633 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6634 {
6635         XLogRecPtr      startpoint;
6636         XLogRecPtr      stoppoint;
6637         char            histfilename[MAXFNAMELEN];
6638         char            histfilepath[MAXPGPATH];
6639         char            startxlogfilename[MAXFNAMELEN];
6640         char            stopxlogfilename[MAXFNAMELEN];
6641         TimeLineID      tli;
6642         uint32          _logId;
6643         uint32          _logSeg;
6644         FILE       *lfp;
6645         FILE       *fp;
6646         char            ch;
6647
6648         /* Default is to not constrain recovery stop point */
6649         minRecoveryLoc->xlogid = 0;
6650         minRecoveryLoc->xrecoff = 0;
6651
6652         /*
6653          * See if label file is present
6654          */
6655         lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6656         if (!lfp)
6657         {
6658                 if (errno != ENOENT)
6659                         ereport(FATAL,
6660                                         (errcode_for_file_access(),
6661                                          errmsg("could not read file \"%s\": %m",
6662                                                         BACKUP_LABEL_FILE)));
6663                 return false;                   /* it's not there, all is fine */
6664         }
6665
6666         /*
6667          * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
6668          * is pretty crude, but we are not expecting any variability in the file
6669          * format).
6670          */
6671         if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
6672                            &startpoint.xlogid, &startpoint.xrecoff, &tli,
6673                            startxlogfilename, &ch) != 5 || ch != '\n')
6674                 ereport(FATAL,
6675                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6676                                  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6677         if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
6678                            &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
6679                            &ch) != 3 || ch != '\n')
6680                 ereport(FATAL,
6681                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6682                                  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6683         if (ferror(lfp) || FreeFile(lfp))
6684                 ereport(FATAL,
6685                                 (errcode_for_file_access(),
6686                                  errmsg("could not read file \"%s\": %m",
6687                                                 BACKUP_LABEL_FILE)));
6688
6689         /*
6690          * Try to retrieve the backup history file (no error if we can't)
6691          */
6692         XLByteToSeg(startpoint, _logId, _logSeg);
6693         BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
6694                                                   startpoint.xrecoff % XLogSegSize);
6695
6696         if (InArchiveRecovery)
6697                 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
6698         else
6699                 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
6700                                                           startpoint.xrecoff % XLogSegSize);
6701
6702         fp = AllocateFile(histfilepath, "r");
6703         if (fp)
6704         {
6705                 /*
6706                  * Parse history file to identify stop point.
6707                  */
6708                 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
6709                                    &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6710                                    &ch) != 4 || ch != '\n')
6711                         ereport(FATAL,
6712                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6713                                          errmsg("invalid data in file \"%s\"", histfilename)));
6714                 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
6715                                    &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6716                                    &ch) != 4 || ch != '\n')
6717                         ereport(FATAL,
6718                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6719                                          errmsg("invalid data in file \"%s\"", histfilename)));
6720                 *minRecoveryLoc = stoppoint;
6721                 if (ferror(fp) || FreeFile(fp))
6722                         ereport(FATAL,
6723                                         (errcode_for_file_access(),
6724                                          errmsg("could not read file \"%s\": %m",
6725                                                         histfilepath)));
6726         }
6727
6728         return true;
6729 }
6730
6731 /*
6732  * Error context callback for errors occurring during rm_redo().
6733  */
6734 static void
6735 rm_redo_error_callback(void *arg)
6736 {
6737         XLogRecord *record = (XLogRecord *) arg;
6738         StringInfoData buf;
6739
6740         initStringInfo(&buf);
6741         RmgrTable[record->xl_rmid].rm_desc(&buf,
6742                                                                            record->xl_info,
6743                                                                            XLogRecGetData(record));
6744
6745         /* don't bother emitting empty description */
6746         if (buf.len > 0)
6747                 errcontext("xlog redo %s", buf.data);
6748
6749         pfree(buf.data);
6750 }