OSDN Git Service

Make the server track an 'XID epoch', that is, maintain higher-order bits
[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.249 2006/08/21 16:16:31 tgl 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,
701          * we make an exception for XLOG SWITCH records because we don't want
702          * them to 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
756          * copy 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
786          * weren't already doing full-page writes then go back and recompute.
787          * (If it was just turned off, we could recompute the record without
788          * full pages, but 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
874          * of a segment, we need not insert it (and don't want to because
875          * we'd like consecutive switch requests to be no-ops).  Instead,
876          * make sure everything is written and flushed through the end of
877          * the prior segment, 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,
1023                  * and 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
1671                          * the 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
2304          * it just dumps core, and there are reports of problems on PPC platforms
2305          * as well.  The following is therefore disabled for the time being.
2306          * We could consider some kind of configure test to see if it's safe to
2307          * use, but since we lack hard evidence that there's any useful performance
2308          * gain to 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()
2319          * and 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
2326 #endif /* NOT_USED */
2327
2328         if (close(openLogFile))
2329                 ereport(PANIC,
2330                         (errcode_for_file_access(),
2331                         errmsg("could not close log file %u, segment %u: %m",
2332                                    openLogId, openLogSeg)));
2333         openLogFile = -1;
2334 }
2335
2336 /*
2337  * Attempt to retrieve the specified file from off-line archival storage.
2338  * If successful, fill "path" with its complete path (note that this will be
2339  * a temp file name that doesn't follow the normal naming convention), and
2340  * return TRUE.
2341  *
2342  * If not successful, fill "path" with the name of the normal on-line file
2343  * (which may or may not actually exist, but we'll try to use it), and return
2344  * FALSE.
2345  *
2346  * For fixed-size files, the caller may pass the expected size as an
2347  * additional crosscheck on successful recovery.  If the file size is not
2348  * known, set expectedSize = 0.
2349  */
2350 static bool
2351 RestoreArchivedFile(char *path, const char *xlogfname,
2352                                         const char *recovername, off_t expectedSize)
2353 {
2354         char            xlogpath[MAXPGPATH];
2355         char            xlogRestoreCmd[MAXPGPATH];
2356         char       *dp;
2357         char       *endp;
2358         const char *sp;
2359         int                     rc;
2360         struct stat stat_buf;
2361
2362         /*
2363          * When doing archive recovery, we always prefer an archived log file even
2364          * if a file of the same name exists in XLOGDIR.  The reason is that the
2365          * file in XLOGDIR could be an old, un-filled or partly-filled version
2366          * that was copied and restored as part of backing up $PGDATA.
2367          *
2368          * We could try to optimize this slightly by checking the local copy
2369          * lastchange timestamp against the archived copy, but we have no API to
2370          * do this, nor can we guarantee that the lastchange timestamp was
2371          * preserved correctly when we copied to archive. Our aim is robustness,
2372          * so we elect not to do this.
2373          *
2374          * If we cannot obtain the log file from the archive, however, we will try
2375          * to use the XLOGDIR file if it exists.  This is so that we can make use
2376          * of log segments that weren't yet transferred to the archive.
2377          *
2378          * Notice that we don't actually overwrite any files when we copy back
2379          * from archive because the recoveryRestoreCommand may inadvertently
2380          * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2381          * fallback to the segments remaining in current XLOGDIR later. The
2382          * copy-from-archive filename is always the same, ensuring that we don't
2383          * run out of disk space on long recoveries.
2384          */
2385         snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2386
2387         /*
2388          * Make sure there is no existing file named recovername.
2389          */
2390         if (stat(xlogpath, &stat_buf) != 0)
2391         {
2392                 if (errno != ENOENT)
2393                         ereport(FATAL,
2394                                         (errcode_for_file_access(),
2395                                          errmsg("could not stat file \"%s\": %m",
2396                                                         xlogpath)));
2397         }
2398         else
2399         {
2400                 if (unlink(xlogpath) != 0)
2401                         ereport(FATAL,
2402                                         (errcode_for_file_access(),
2403                                          errmsg("could not remove file \"%s\": %m",
2404                                                         xlogpath)));
2405         }
2406
2407         /*
2408          * construct the command to be executed
2409          */
2410         dp = xlogRestoreCmd;
2411         endp = xlogRestoreCmd + MAXPGPATH - 1;
2412         *endp = '\0';
2413
2414         for (sp = recoveryRestoreCommand; *sp; sp++)
2415         {
2416                 if (*sp == '%')
2417                 {
2418                         switch (sp[1])
2419                         {
2420                                 case 'p':
2421                                         /* %p: full path of target file */
2422                                         sp++;
2423                                         StrNCpy(dp, xlogpath, endp - dp);
2424                                         make_native_path(dp);
2425                                         dp += strlen(dp);
2426                                         break;
2427                                 case 'f':
2428                                         /* %f: filename of desired file */
2429                                         sp++;
2430                                         StrNCpy(dp, xlogfname, endp - dp);
2431                                         dp += strlen(dp);
2432                                         break;
2433                                 case '%':
2434                                         /* convert %% to a single % */
2435                                         sp++;
2436                                         if (dp < endp)
2437                                                 *dp++ = *sp;
2438                                         break;
2439                                 default:
2440                                         /* otherwise treat the % as not special */
2441                                         if (dp < endp)
2442                                                 *dp++ = *sp;
2443                                         break;
2444                         }
2445                 }
2446                 else
2447                 {
2448                         if (dp < endp)
2449                                 *dp++ = *sp;
2450                 }
2451         }
2452         *dp = '\0';
2453
2454         ereport(DEBUG3,
2455                         (errmsg_internal("executing restore command \"%s\"",
2456                                                          xlogRestoreCmd)));
2457
2458         /*
2459          * Copy xlog from archival storage to XLOGDIR
2460          */
2461         rc = system(xlogRestoreCmd);
2462         if (rc == 0)
2463         {
2464                 /*
2465                  * command apparently succeeded, but let's make sure the file is
2466                  * really there now and has the correct size.
2467                  *
2468                  * XXX I made wrong-size a fatal error to ensure the DBA would notice
2469                  * it, but is that too strong?  We could try to plow ahead with a
2470                  * local copy of the file ... but the problem is that there probably
2471                  * isn't one, and we'd incorrectly conclude we've reached the end of
2472                  * WAL and we're done recovering ...
2473                  */
2474                 if (stat(xlogpath, &stat_buf) == 0)
2475                 {
2476                         if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2477                                 ereport(FATAL,
2478                                                 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2479                                                                 xlogfname,
2480                                                                 (unsigned long) stat_buf.st_size,
2481                                                                 (unsigned long) expectedSize)));
2482                         else
2483                         {
2484                                 ereport(LOG,
2485                                                 (errmsg("restored log file \"%s\" from archive",
2486                                                                 xlogfname)));
2487                                 strcpy(path, xlogpath);
2488                                 return true;
2489                         }
2490                 }
2491                 else
2492                 {
2493                         /* stat failed */
2494                         if (errno != ENOENT)
2495                                 ereport(FATAL,
2496                                                 (errcode_for_file_access(),
2497                                                  errmsg("could not stat file \"%s\": %m",
2498                                                                 xlogpath)));
2499                 }
2500         }
2501
2502         /*
2503          * remember, we rollforward UNTIL the restore fails so failure here is
2504          * just part of the process... that makes it difficult to determine
2505          * whether the restore failed because there isn't an archive to restore,
2506          * or because the administrator has specified the restore program
2507          * incorrectly.  We have to assume the former.
2508          */
2509         ereport(DEBUG2,
2510                 (errmsg("could not restore file \"%s\" from archive: return code %d",
2511                                 xlogfname, rc)));
2512
2513         /*
2514          * if an archived file is not available, there might still be a version of
2515          * this file in XLOGDIR, so return that as the filename to open.
2516          *
2517          * In many recovery scenarios we expect this to fail also, but if so that
2518          * just means we've reached the end of WAL.
2519          */
2520         snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2521         return false;
2522 }
2523
2524 /*
2525  * Preallocate log files beyond the specified log endpoint, according to
2526  * the XLOGfile user parameter.
2527  */
2528 static int
2529 PreallocXlogFiles(XLogRecPtr endptr)
2530 {
2531         int                     nsegsadded = 0;
2532         uint32          _logId;
2533         uint32          _logSeg;
2534         int                     lf;
2535         bool            use_existent;
2536
2537         XLByteToPrevSeg(endptr, _logId, _logSeg);
2538         if ((endptr.xrecoff - 1) % XLogSegSize >=
2539                 (uint32) (0.75 * XLogSegSize))
2540         {
2541                 NextLogSeg(_logId, _logSeg);
2542                 use_existent = true;
2543                 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2544                 close(lf);
2545                 if (!use_existent)
2546                         nsegsadded++;
2547         }
2548         return nsegsadded;
2549 }
2550
2551 /*
2552  * Remove or move offline all log files older or equal to passed log/seg#
2553  *
2554  * endptr is current (or recent) end of xlog; this is used to determine
2555  * whether we want to recycle rather than delete no-longer-wanted log files.
2556  */
2557 static void
2558 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
2559                                 int *nsegsremoved, int *nsegsrecycled)
2560 {
2561         uint32          endlogId;
2562         uint32          endlogSeg;
2563         int                     max_advance;
2564         DIR                *xldir;
2565         struct dirent *xlde;
2566         char            lastoff[MAXFNAMELEN];
2567         char            path[MAXPGPATH];
2568
2569         *nsegsremoved = 0;
2570         *nsegsrecycled = 0;
2571
2572         /*
2573          * Initialize info about where to try to recycle to.  We allow recycling
2574          * segments up to XLOGfileslop segments beyond the current XLOG location.
2575          */
2576         XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2577         max_advance = XLOGfileslop;
2578
2579         xldir = AllocateDir(XLOGDIR);
2580         if (xldir == NULL)
2581                 ereport(ERROR,
2582                                 (errcode_for_file_access(),
2583                                  errmsg("could not open transaction log directory \"%s\": %m",
2584                                                 XLOGDIR)));
2585
2586         XLogFileName(lastoff, ThisTimeLineID, log, seg);
2587
2588         while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2589         {
2590                 /*
2591                  * We ignore the timeline part of the XLOG segment identifiers in
2592                  * deciding whether a segment is still needed.  This ensures that we
2593                  * won't prematurely remove a segment from a parent timeline. We could
2594                  * probably be a little more proactive about removing segments of
2595                  * non-parent timelines, but that would be a whole lot more
2596                  * complicated.
2597                  *
2598                  * We use the alphanumeric sorting property of the filenames to decide
2599                  * which ones are earlier than the lastoff segment.
2600                  */
2601                 if (strlen(xlde->d_name) == 24 &&
2602                         strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2603                         strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2604                 {
2605                         if (XLogArchiveCheckDone(xlde->d_name))
2606                         {
2607                                 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2608
2609                                 /*
2610                                  * Before deleting the file, see if it can be recycled as a
2611                                  * future log segment.
2612                                  */
2613                                 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2614                                                                                    true, &max_advance,
2615                                                                                    true))
2616                                 {
2617                                         ereport(DEBUG2,
2618                                                         (errmsg("recycled transaction log file \"%s\"",
2619                                                                         xlde->d_name)));
2620                                         (*nsegsrecycled)++;
2621                                         /* Needn't recheck that slot on future iterations */
2622                                         if (max_advance > 0)
2623                                         {
2624                                                 NextLogSeg(endlogId, endlogSeg);
2625                                                 max_advance--;
2626                                         }
2627                                 }
2628                                 else
2629                                 {
2630                                         /* No need for any more future segments... */
2631                                         ereport(DEBUG2,
2632                                                         (errmsg("removing transaction log file \"%s\"",
2633                                                                         xlde->d_name)));
2634                                         unlink(path);
2635                                         (*nsegsremoved)++;
2636                                 }
2637
2638                                 XLogArchiveCleanup(xlde->d_name);
2639                         }
2640                 }
2641         }
2642
2643         FreeDir(xldir);
2644 }
2645
2646 /*
2647  * Remove previous backup history files.  This also retries creation of
2648  * .ready files for any backup history files for which XLogArchiveNotify
2649  * failed earlier.
2650  */
2651 static void
2652 CleanupBackupHistory(void)
2653 {
2654         DIR                *xldir;
2655         struct dirent *xlde;
2656         char            path[MAXPGPATH];
2657
2658         xldir = AllocateDir(XLOGDIR);
2659         if (xldir == NULL)
2660                 ereport(ERROR,
2661                                 (errcode_for_file_access(),
2662                                  errmsg("could not open transaction log directory \"%s\": %m",
2663                                                 XLOGDIR)));
2664
2665         while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2666         {
2667                 if (strlen(xlde->d_name) > 24 &&
2668                         strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2669                         strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2670                                    ".backup") == 0)
2671                 {
2672                         if (XLogArchiveCheckDone(xlde->d_name))
2673                         {
2674                                 ereport(DEBUG2,
2675                                 (errmsg("removing transaction log backup history file \"%s\"",
2676                                                 xlde->d_name)));
2677                                 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2678                                 unlink(path);
2679                                 XLogArchiveCleanup(xlde->d_name);
2680                         }
2681                 }
2682         }
2683
2684         FreeDir(xldir);
2685 }
2686
2687 /*
2688  * Restore the backup blocks present in an XLOG record, if any.
2689  *
2690  * We assume all of the record has been read into memory at *record.
2691  *
2692  * Note: when a backup block is available in XLOG, we restore it
2693  * unconditionally, even if the page in the database appears newer.
2694  * This is to protect ourselves against database pages that were partially
2695  * or incorrectly written during a crash.  We assume that the XLOG data
2696  * must be good because it has passed a CRC check, while the database
2697  * page might not be.  This will force us to replay all subsequent
2698  * modifications of the page that appear in XLOG, rather than possibly
2699  * ignoring them as already applied, but that's not a huge drawback.
2700  */
2701 static void
2702 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2703 {
2704         Relation        reln;
2705         Buffer          buffer;
2706         Page            page;
2707         BkpBlock        bkpb;
2708         char       *blk;
2709         int                     i;
2710
2711         blk = (char *) XLogRecGetData(record) + record->xl_len;
2712         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2713         {
2714                 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2715                         continue;
2716
2717                 memcpy(&bkpb, blk, sizeof(BkpBlock));
2718                 blk += sizeof(BkpBlock);
2719
2720                 reln = XLogOpenRelation(bkpb.node);
2721                 buffer = XLogReadBuffer(reln, bkpb.block, true);
2722                 Assert(BufferIsValid(buffer));
2723                 page = (Page) BufferGetPage(buffer);
2724
2725                 if (bkpb.hole_length == 0)
2726                 {
2727                         memcpy((char *) page, blk, BLCKSZ);
2728                 }
2729                 else
2730                 {
2731                         /* must zero-fill the hole */
2732                         MemSet((char *) page, 0, BLCKSZ);
2733                         memcpy((char *) page, blk, bkpb.hole_offset);
2734                         memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2735                                    blk + bkpb.hole_offset,
2736                                    BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2737                 }
2738
2739                 PageSetLSN(page, lsn);
2740                 PageSetTLI(page, ThisTimeLineID);
2741                 MarkBufferDirty(buffer);
2742                 UnlockReleaseBuffer(buffer);
2743
2744                 blk += BLCKSZ - bkpb.hole_length;
2745         }
2746 }
2747
2748 /*
2749  * CRC-check an XLOG record.  We do not believe the contents of an XLOG
2750  * record (other than to the minimal extent of computing the amount of
2751  * data to read in) until we've checked the CRCs.
2752  *
2753  * We assume all of the record has been read into memory at *record.
2754  */
2755 static bool
2756 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2757 {
2758         pg_crc32        crc;
2759         int                     i;
2760         uint32          len = record->xl_len;
2761         BkpBlock        bkpb;
2762         char       *blk;
2763
2764         /* First the rmgr data */
2765         INIT_CRC32(crc);
2766         COMP_CRC32(crc, XLogRecGetData(record), len);
2767
2768         /* Add in the backup blocks, if any */
2769         blk = (char *) XLogRecGetData(record) + len;
2770         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2771         {
2772                 uint32          blen;
2773
2774                 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2775                         continue;
2776
2777                 memcpy(&bkpb, blk, sizeof(BkpBlock));
2778                 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2779                 {
2780                         ereport(emode,
2781                                         (errmsg("incorrect hole size in record at %X/%X",
2782                                                         recptr.xlogid, recptr.xrecoff)));
2783                         return false;
2784                 }
2785                 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2786                 COMP_CRC32(crc, blk, blen);
2787                 blk += blen;
2788         }
2789
2790         /* Check that xl_tot_len agrees with our calculation */
2791         if (blk != (char *) record + record->xl_tot_len)
2792         {
2793                 ereport(emode,
2794                                 (errmsg("incorrect total length in record at %X/%X",
2795                                                 recptr.xlogid, recptr.xrecoff)));
2796                 return false;
2797         }
2798
2799         /* Finally include the record header */
2800         COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2801                            SizeOfXLogRecord - sizeof(pg_crc32));
2802         FIN_CRC32(crc);
2803
2804         if (!EQ_CRC32(record->xl_crc, crc))
2805         {
2806                 ereport(emode,
2807                 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2808                                 recptr.xlogid, recptr.xrecoff)));
2809                 return false;
2810         }
2811
2812         return true;
2813 }
2814
2815 /*
2816  * Attempt to read an XLOG record.
2817  *
2818  * If RecPtr is not NULL, try to read a record at that position.  Otherwise
2819  * try to read a record just after the last one previously read.
2820  *
2821  * If no valid record is available, returns NULL, or fails if emode is PANIC.
2822  * (emode must be either PANIC or LOG.)
2823  *
2824  * The record is copied into readRecordBuf, so that on successful return,
2825  * the returned record pointer always points there.
2826  */
2827 static XLogRecord *
2828 ReadRecord(XLogRecPtr *RecPtr, int emode)
2829 {
2830         XLogRecord *record;
2831         char       *buffer;
2832         XLogRecPtr      tmpRecPtr = EndRecPtr;
2833         bool            randAccess = false;
2834         uint32          len,
2835                                 total_len;
2836         uint32          targetPageOff;
2837         uint32          targetRecOff;
2838         uint32          pageHeaderSize;
2839
2840         if (readBuf == NULL)
2841         {
2842                 /*
2843                  * First time through, permanently allocate readBuf.  We do it this
2844                  * way, rather than just making a static array, for two reasons: (1)
2845                  * no need to waste the storage in most instantiations of the backend;
2846                  * (2) a static char array isn't guaranteed to have any particular
2847                  * alignment, whereas malloc() will provide MAXALIGN'd storage.
2848                  */
2849                 readBuf = (char *) malloc(XLOG_BLCKSZ);
2850                 Assert(readBuf != NULL);
2851         }
2852
2853         if (RecPtr == NULL)
2854         {
2855                 RecPtr = &tmpRecPtr;
2856                 /* fast case if next record is on same page */
2857                 if (nextRecord != NULL)
2858                 {
2859                         record = nextRecord;
2860                         goto got_record;
2861                 }
2862                 /* align old recptr to next page */
2863                 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2864                         tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2865                 if (tmpRecPtr.xrecoff >= XLogFileSize)
2866                 {
2867                         (tmpRecPtr.xlogid)++;
2868                         tmpRecPtr.xrecoff = 0;
2869                 }
2870                 /* We will account for page header size below */
2871         }
2872         else
2873         {
2874                 if (!XRecOffIsValid(RecPtr->xrecoff))
2875                         ereport(PANIC,
2876                                         (errmsg("invalid record offset at %X/%X",
2877                                                         RecPtr->xlogid, RecPtr->xrecoff)));
2878
2879                 /*
2880                  * Since we are going to a random position in WAL, forget any prior
2881                  * state about what timeline we were in, and allow it to be any
2882                  * timeline in expectedTLIs.  We also set a flag to allow curFileTLI
2883                  * to go backwards (but we can't reset that variable right here, since
2884                  * we might not change files at all).
2885                  */
2886                 lastPageTLI = 0;                /* see comment in ValidXLOGHeader */
2887                 randAccess = true;              /* allow curFileTLI to go backwards too */
2888         }
2889
2890         if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2891         {
2892                 close(readFile);
2893                 readFile = -1;
2894         }
2895         XLByteToSeg(*RecPtr, readId, readSeg);
2896         if (readFile < 0)
2897         {
2898                 /* Now it's okay to reset curFileTLI if random fetch */
2899                 if (randAccess)
2900                         curFileTLI = 0;
2901
2902                 readFile = XLogFileRead(readId, readSeg, emode);
2903                 if (readFile < 0)
2904                         goto next_record_is_invalid;
2905
2906                 /*
2907                  * Whenever switching to a new WAL segment, we read the first page of
2908                  * the file and validate its header, even if that's not where the
2909                  * target record is.  This is so that we can check the additional
2910                  * identification info that is present in the first page's "long"
2911                  * header.
2912                  */
2913                 readOff = 0;
2914                 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2915                 {
2916                         ereport(emode,
2917                                         (errcode_for_file_access(),
2918                                          errmsg("could not read from log file %u, segment %u, offset %u: %m",
2919                                                         readId, readSeg, readOff)));
2920                         goto next_record_is_invalid;
2921                 }
2922                 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2923                         goto next_record_is_invalid;
2924         }
2925
2926         targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2927         if (readOff != targetPageOff)
2928         {
2929                 readOff = targetPageOff;
2930                 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2931                 {
2932                         ereport(emode,
2933                                         (errcode_for_file_access(),
2934                                          errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2935                                                         readId, readSeg, readOff)));
2936                         goto next_record_is_invalid;
2937                 }
2938                 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2939                 {
2940                         ereport(emode,
2941                                         (errcode_for_file_access(),
2942                                          errmsg("could not read from log file %u, segment %u at offset %u: %m",
2943                                                         readId, readSeg, readOff)));
2944                         goto next_record_is_invalid;
2945                 }
2946                 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2947                         goto next_record_is_invalid;
2948         }
2949         pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2950         targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
2951         if (targetRecOff == 0)
2952         {
2953                 /*
2954                  * Can only get here in the continuing-from-prev-page case, because
2955                  * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
2956                  * to skip over the new page's header.
2957                  */
2958                 tmpRecPtr.xrecoff += pageHeaderSize;
2959                 targetRecOff = pageHeaderSize;
2960         }
2961         else if (targetRecOff < pageHeaderSize)
2962         {
2963                 ereport(emode,
2964                                 (errmsg("invalid record offset at %X/%X",
2965                                                 RecPtr->xlogid, RecPtr->xrecoff)));
2966                 goto next_record_is_invalid;
2967         }
2968         if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
2969                 targetRecOff == pageHeaderSize)
2970         {
2971                 ereport(emode,
2972                                 (errmsg("contrecord is requested by %X/%X",
2973                                                 RecPtr->xlogid, RecPtr->xrecoff)));
2974                 goto next_record_is_invalid;
2975         }
2976         record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
2977
2978 got_record:;
2979
2980         /*
2981          * xl_len == 0 is bad data for everything except XLOG SWITCH, where
2982          * it is required.
2983          */
2984         if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
2985         {
2986                 if (record->xl_len != 0)
2987                 {
2988                         ereport(emode,
2989                                         (errmsg("invalid xlog switch record at %X/%X",
2990                                                         RecPtr->xlogid, RecPtr->xrecoff)));
2991                         goto next_record_is_invalid;
2992                 }
2993         }
2994         else if (record->xl_len == 0)
2995         {
2996                 ereport(emode,
2997                                 (errmsg("record with zero length at %X/%X",
2998                                                 RecPtr->xlogid, RecPtr->xrecoff)));
2999                 goto next_record_is_invalid;
3000         }
3001         if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3002                 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3003                 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3004         {
3005                 ereport(emode,
3006                                 (errmsg("invalid record length at %X/%X",
3007                                                 RecPtr->xlogid, RecPtr->xrecoff)));
3008                 goto next_record_is_invalid;
3009         }
3010         if (record->xl_rmid > RM_MAX_ID)
3011         {
3012                 ereport(emode,
3013                                 (errmsg("invalid resource manager ID %u at %X/%X",
3014                                                 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3015                 goto next_record_is_invalid;
3016         }
3017         if (randAccess)
3018         {
3019                 /*
3020                  * We can't exactly verify the prev-link, but surely it should be less
3021                  * than the record's own address.
3022                  */
3023                 if (!XLByteLT(record->xl_prev, *RecPtr))
3024                 {
3025                         ereport(emode,
3026                                         (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3027                                                         record->xl_prev.xlogid, record->xl_prev.xrecoff,
3028                                                         RecPtr->xlogid, RecPtr->xrecoff)));
3029                         goto next_record_is_invalid;
3030                 }
3031         }
3032         else
3033         {
3034                 /*
3035                  * Record's prev-link should exactly match our previous location. This
3036                  * check guards against torn WAL pages where a stale but valid-looking
3037                  * WAL record starts on a sector boundary.
3038                  */
3039                 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3040                 {
3041                         ereport(emode,
3042                                         (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3043                                                         record->xl_prev.xlogid, record->xl_prev.xrecoff,
3044                                                         RecPtr->xlogid, RecPtr->xrecoff)));
3045                         goto next_record_is_invalid;
3046                 }
3047         }
3048
3049         /*
3050          * Allocate or enlarge readRecordBuf as needed.  To avoid useless small
3051          * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3052          * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with.  (That is
3053          * enough for all "normal" records, but very large commit or abort records
3054          * might need more space.)
3055          */
3056         total_len = record->xl_tot_len;
3057         if (total_len > readRecordBufSize)
3058         {
3059                 uint32          newSize = total_len;
3060
3061                 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3062                 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3063                 if (readRecordBuf)
3064                         free(readRecordBuf);
3065                 readRecordBuf = (char *) malloc(newSize);
3066                 if (!readRecordBuf)
3067                 {
3068                         readRecordBufSize = 0;
3069                         /* We treat this as a "bogus data" condition */
3070                         ereport(emode,
3071                                         (errmsg("record length %u at %X/%X too long",
3072                                                         total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3073                         goto next_record_is_invalid;
3074                 }
3075                 readRecordBufSize = newSize;
3076         }
3077
3078         buffer = readRecordBuf;
3079         nextRecord = NULL;
3080         len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3081         if (total_len > len)
3082         {
3083                 /* Need to reassemble record */
3084                 XLogContRecord *contrecord;
3085                 uint32          gotlen = len;
3086
3087                 memcpy(buffer, record, len);
3088                 record = (XLogRecord *) buffer;
3089                 buffer += len;
3090                 for (;;)
3091                 {
3092                         readOff += XLOG_BLCKSZ;
3093                         if (readOff >= XLogSegSize)
3094                         {
3095                                 close(readFile);
3096                                 readFile = -1;
3097                                 NextLogSeg(readId, readSeg);
3098                                 readFile = XLogFileRead(readId, readSeg, emode);
3099                                 if (readFile < 0)
3100                                         goto next_record_is_invalid;
3101                                 readOff = 0;
3102                         }
3103                         if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3104                         {
3105                                 ereport(emode,
3106                                                 (errcode_for_file_access(),
3107                                                  errmsg("could not read from log file %u, segment %u, offset %u: %m",
3108                                                                 readId, readSeg, readOff)));
3109                                 goto next_record_is_invalid;
3110                         }
3111                         if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3112                                 goto next_record_is_invalid;
3113                         if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3114                         {
3115                                 ereport(emode,
3116                                                 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3117                                                                 readId, readSeg, readOff)));
3118                                 goto next_record_is_invalid;
3119                         }
3120                         pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3121                         contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3122                         if (contrecord->xl_rem_len == 0 ||
3123                                 total_len != (contrecord->xl_rem_len + gotlen))
3124                         {
3125                                 ereport(emode,
3126                                                 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3127                                                                 contrecord->xl_rem_len,
3128                                                                 readId, readSeg, readOff)));
3129                                 goto next_record_is_invalid;
3130                         }
3131                         len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3132                         if (contrecord->xl_rem_len > len)
3133                         {
3134                                 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3135                                 gotlen += len;
3136                                 buffer += len;
3137                                 continue;
3138                         }
3139                         memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3140                                    contrecord->xl_rem_len);
3141                         break;
3142                 }
3143                 if (!RecordIsValid(record, *RecPtr, emode))
3144                         goto next_record_is_invalid;
3145                 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3146                 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3147                         MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3148                 {
3149                         nextRecord = (XLogRecord *) ((char *) contrecord +
3150                                         MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3151                 }
3152                 EndRecPtr.xlogid = readId;
3153                 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3154                         pageHeaderSize +
3155                         MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3156                 ReadRecPtr = *RecPtr;
3157                 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3158                 return record;
3159         }
3160
3161         /* Record does not cross a page boundary */
3162         if (!RecordIsValid(record, *RecPtr, emode))
3163                 goto next_record_is_invalid;
3164         if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3165                 MAXALIGN(total_len))
3166                 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3167         EndRecPtr.xlogid = RecPtr->xlogid;
3168         EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3169         ReadRecPtr = *RecPtr;
3170         memcpy(buffer, record, total_len);
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                  * Pretend that readBuf contains the last page of the segment.
3182                  * This is just to avoid Assert failure in StartupXLOG if XLOG
3183                  * ends with this segment.
3184                  */
3185                 readOff = XLogSegSize - XLOG_BLCKSZ;
3186         }
3187         return (XLogRecord *) buffer;
3188
3189 next_record_is_invalid:;
3190         close(readFile);
3191         readFile = -1;
3192         nextRecord = NULL;
3193         return NULL;
3194 }
3195
3196 /*
3197  * Check whether the xlog header of a page just read in looks valid.
3198  *
3199  * This is just a convenience subroutine to avoid duplicated code in
3200  * ReadRecord.  It's not intended for use from anywhere else.
3201  */
3202 static bool
3203 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3204 {
3205         XLogRecPtr      recaddr;
3206
3207         if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3208         {
3209                 ereport(emode,
3210                                 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3211                                                 hdr->xlp_magic, readId, readSeg, readOff)));
3212                 return false;
3213         }
3214         if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3215         {
3216                 ereport(emode,
3217                                 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3218                                                 hdr->xlp_info, readId, readSeg, readOff)));
3219                 return false;
3220         }
3221         if (hdr->xlp_info & XLP_LONG_HEADER)
3222         {
3223                 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3224
3225                 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3226                 {
3227                         char            fhdrident_str[32];
3228                         char            sysident_str[32];
3229
3230                         /*
3231                          * Format sysids separately to keep platform-dependent format code
3232                          * out of the translatable message string.
3233                          */
3234                         snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3235                                          longhdr->xlp_sysid);
3236                         snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3237                                          ControlFile->system_identifier);
3238                         ereport(emode,
3239                                         (errmsg("WAL file is from different system"),
3240                                          errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3241                                                            fhdrident_str, sysident_str)));
3242                         return false;
3243                 }
3244                 if (longhdr->xlp_seg_size != XLogSegSize)
3245                 {
3246                         ereport(emode,
3247                                         (errmsg("WAL file is from different system"),
3248                                          errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3249                         return false;
3250                 }
3251                 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3252                 {
3253                         ereport(emode,
3254                                         (errmsg("WAL file is from different system"),
3255                                          errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3256                         return false;
3257                 }
3258         }
3259         else if (readOff == 0)
3260         {
3261                 /* hmm, first page of file doesn't have a long header? */
3262                 ereport(emode,
3263                                 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3264                                                 hdr->xlp_info, readId, readSeg, readOff)));
3265                 return false;
3266         }
3267
3268         recaddr.xlogid = readId;
3269         recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3270         if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3271         {
3272                 ereport(emode,
3273                                 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3274                                                 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3275                                                 readId, readSeg, readOff)));
3276                 return false;
3277         }
3278
3279         /*
3280          * Check page TLI is one of the expected values.
3281          */
3282         if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3283         {
3284                 ereport(emode,
3285                                 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3286                                                 hdr->xlp_tli,
3287                                                 readId, readSeg, readOff)));
3288                 return false;
3289         }
3290
3291         /*
3292          * Since child timelines are always assigned a TLI greater than their
3293          * immediate parent's TLI, we should never see TLI go backwards across
3294          * successive pages of a consistent WAL sequence.
3295          *
3296          * Of course this check should only be applied when advancing sequentially
3297          * across pages; therefore ReadRecord resets lastPageTLI to zero when
3298          * going to a random page.
3299          */
3300         if (hdr->xlp_tli < lastPageTLI)
3301         {
3302                 ereport(emode,
3303                                 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3304                                                 hdr->xlp_tli, lastPageTLI,
3305                                                 readId, readSeg, readOff)));
3306                 return false;
3307         }
3308         lastPageTLI = hdr->xlp_tli;
3309         return true;
3310 }
3311
3312 /*
3313  * Try to read a timeline's history file.
3314  *
3315  * If successful, return the list of component TLIs (the given TLI followed by
3316  * its ancestor TLIs).  If we can't find the history file, assume that the
3317  * timeline has no parents, and return a list of just the specified timeline
3318  * ID.
3319  */
3320 static List *
3321 readTimeLineHistory(TimeLineID targetTLI)
3322 {
3323         List       *result;
3324         char            path[MAXPGPATH];
3325         char            histfname[MAXFNAMELEN];
3326         char            fline[MAXPGPATH];
3327         FILE       *fd;
3328
3329         if (InArchiveRecovery)
3330         {
3331                 TLHistoryFileName(histfname, targetTLI);
3332                 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3333         }
3334         else
3335                 TLHistoryFilePath(path, targetTLI);
3336
3337         fd = AllocateFile(path, "r");
3338         if (fd == NULL)
3339         {
3340                 if (errno != ENOENT)
3341                         ereport(FATAL,
3342                                         (errcode_for_file_access(),
3343                                          errmsg("could not open file \"%s\": %m", path)));
3344                 /* Not there, so assume no parents */
3345                 return list_make1_int((int) targetTLI);
3346         }
3347
3348         result = NIL;
3349
3350         /*
3351          * Parse the file...
3352          */
3353         while (fgets(fline, MAXPGPATH, fd) != NULL)
3354         {
3355                 /* skip leading whitespace and check for # comment */
3356                 char       *ptr;
3357                 char       *endptr;
3358                 TimeLineID      tli;
3359
3360                 for (ptr = fline; *ptr; ptr++)
3361                 {
3362                         if (!isspace((unsigned char) *ptr))
3363                                 break;
3364                 }
3365                 if (*ptr == '\0' || *ptr == '#')
3366                         continue;
3367
3368                 /* expect a numeric timeline ID as first field of line */
3369                 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3370                 if (endptr == ptr)
3371                         ereport(FATAL,
3372                                         (errmsg("syntax error in history file: %s", fline),
3373                                          errhint("Expected a numeric timeline ID.")));
3374
3375                 if (result &&
3376                         tli <= (TimeLineID) linitial_int(result))
3377                         ereport(FATAL,
3378                                         (errmsg("invalid data in history file: %s", fline),
3379                                    errhint("Timeline IDs must be in increasing sequence.")));
3380
3381                 /* Build list with newest item first */
3382                 result = lcons_int((int) tli, result);
3383
3384                 /* we ignore the remainder of each line */
3385         }
3386
3387         FreeFile(fd);
3388
3389         if (result &&
3390                 targetTLI <= (TimeLineID) linitial_int(result))
3391                 ereport(FATAL,
3392                                 (errmsg("invalid data in history file \"%s\"", path),
3393                         errhint("Timeline IDs must be less than child timeline's ID.")));
3394
3395         result = lcons_int((int) targetTLI, result);
3396
3397         ereport(DEBUG3,
3398                         (errmsg_internal("history of timeline %u is %s",
3399                                                          targetTLI, nodeToString(result))));
3400
3401         return result;
3402 }
3403
3404 /*
3405  * Probe whether a timeline history file exists for the given timeline ID
3406  */
3407 static bool
3408 existsTimeLineHistory(TimeLineID probeTLI)
3409 {
3410         char            path[MAXPGPATH];
3411         char            histfname[MAXFNAMELEN];
3412         FILE       *fd;
3413
3414         if (InArchiveRecovery)
3415         {
3416                 TLHistoryFileName(histfname, probeTLI);
3417                 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3418         }
3419         else
3420                 TLHistoryFilePath(path, probeTLI);
3421
3422         fd = AllocateFile(path, "r");
3423         if (fd != NULL)
3424         {
3425                 FreeFile(fd);
3426                 return true;
3427         }
3428         else
3429         {
3430                 if (errno != ENOENT)
3431                         ereport(FATAL,
3432                                         (errcode_for_file_access(),
3433                                          errmsg("could not open file \"%s\": %m", path)));
3434                 return false;
3435         }
3436 }
3437
3438 /*
3439  * Find the newest existing timeline, assuming that startTLI exists.
3440  *
3441  * Note: while this is somewhat heuristic, it does positively guarantee
3442  * that (result + 1) is not a known timeline, and therefore it should
3443  * be safe to assign that ID to a new timeline.
3444  */
3445 static TimeLineID
3446 findNewestTimeLine(TimeLineID startTLI)
3447 {
3448         TimeLineID      newestTLI;
3449         TimeLineID      probeTLI;
3450
3451         /*
3452          * The algorithm is just to probe for the existence of timeline history
3453          * files.  XXX is it useful to allow gaps in the sequence?
3454          */
3455         newestTLI = startTLI;
3456
3457         for (probeTLI = startTLI + 1;; probeTLI++)
3458         {
3459                 if (existsTimeLineHistory(probeTLI))
3460                 {
3461                         newestTLI = probeTLI;           /* probeTLI exists */
3462                 }
3463                 else
3464                 {
3465                         /* doesn't exist, assume we're done */
3466                         break;
3467                 }
3468         }
3469
3470         return newestTLI;
3471 }
3472
3473 /*
3474  * Create a new timeline history file.
3475  *
3476  *      newTLI: ID of the new timeline
3477  *      parentTLI: ID of its immediate parent
3478  *      endTLI et al: ID of the last used WAL file, for annotation purposes
3479  *
3480  * Currently this is only used during recovery, and so there are no locking
3481  * considerations.      But we should be just as tense as XLogFileInit to avoid
3482  * emplacing a bogus file.
3483  */
3484 static void
3485 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3486                                          TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3487 {
3488         char            path[MAXPGPATH];
3489         char            tmppath[MAXPGPATH];
3490         char            histfname[MAXFNAMELEN];
3491         char            xlogfname[MAXFNAMELEN];
3492         char            buffer[BLCKSZ];
3493         int                     srcfd;
3494         int                     fd;
3495         int                     nbytes;
3496
3497         Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3498
3499         /*
3500          * Write into a temp file name.
3501          */
3502         snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3503
3504         unlink(tmppath);
3505
3506         /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3507         fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3508                                            S_IRUSR | S_IWUSR);
3509         if (fd < 0)
3510                 ereport(ERROR,
3511                                 (errcode_for_file_access(),
3512                                  errmsg("could not create file \"%s\": %m", tmppath)));
3513
3514         /*
3515          * If a history file exists for the parent, copy it verbatim
3516          */
3517         if (InArchiveRecovery)
3518         {
3519                 TLHistoryFileName(histfname, parentTLI);
3520                 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3521         }
3522         else
3523                 TLHistoryFilePath(path, parentTLI);
3524
3525         srcfd = BasicOpenFile(path, O_RDONLY, 0);
3526         if (srcfd < 0)
3527         {
3528                 if (errno != ENOENT)
3529                         ereport(ERROR,
3530                                         (errcode_for_file_access(),
3531                                          errmsg("could not open file \"%s\": %m", path)));
3532                 /* Not there, so assume parent has no parents */
3533         }
3534         else
3535         {
3536                 for (;;)
3537                 {
3538                         errno = 0;
3539                         nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3540                         if (nbytes < 0 || errno != 0)
3541                                 ereport(ERROR,
3542                                                 (errcode_for_file_access(),
3543                                                  errmsg("could not read file \"%s\": %m", path)));
3544                         if (nbytes == 0)
3545                                 break;
3546                         errno = 0;
3547                         if ((int) write(fd, buffer, nbytes) != nbytes)
3548                         {
3549                                 int                     save_errno = errno;
3550
3551                                 /*
3552                                  * If we fail to make the file, delete it to release disk
3553                                  * space
3554                                  */
3555                                 unlink(tmppath);
3556
3557                                 /*
3558                                  * if write didn't set errno, assume problem is no disk space
3559                                  */
3560                                 errno = save_errno ? save_errno : ENOSPC;
3561
3562                                 ereport(ERROR,
3563                                                 (errcode_for_file_access(),
3564                                          errmsg("could not write to file \"%s\": %m", tmppath)));
3565                         }
3566                 }
3567                 close(srcfd);
3568         }
3569
3570         /*
3571          * Append one line with the details of this timeline split.
3572          *
3573          * If we did have a parent file, insert an extra newline just in case the
3574          * parent file failed to end with one.
3575          */
3576         XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3577
3578         snprintf(buffer, sizeof(buffer),
3579                          "%s%u\t%s\t%s transaction %u at %s\n",
3580                          (srcfd < 0) ? "" : "\n",
3581                          parentTLI,
3582                          xlogfname,
3583                          recoveryStopAfter ? "after" : "before",
3584                          recoveryStopXid,
3585                          str_time(recoveryStopTime));
3586
3587         nbytes = strlen(buffer);
3588         errno = 0;
3589         if ((int) write(fd, buffer, nbytes) != nbytes)
3590         {
3591                 int                     save_errno = errno;
3592
3593                 /*
3594                  * If we fail to make the file, delete it to release disk space
3595                  */
3596                 unlink(tmppath);
3597                 /* if write didn't set errno, assume problem is no disk space */
3598                 errno = save_errno ? save_errno : ENOSPC;
3599
3600                 ereport(ERROR,
3601                                 (errcode_for_file_access(),
3602                                  errmsg("could not write to file \"%s\": %m", tmppath)));
3603         }
3604
3605         if (pg_fsync(fd) != 0)
3606                 ereport(ERROR,
3607                                 (errcode_for_file_access(),
3608                                  errmsg("could not fsync file \"%s\": %m", tmppath)));
3609
3610         if (close(fd))
3611                 ereport(ERROR,
3612                                 (errcode_for_file_access(),
3613                                  errmsg("could not close file \"%s\": %m", tmppath)));
3614
3615
3616         /*
3617          * Now move the completed history file into place with its final name.
3618          */
3619         TLHistoryFilePath(path, newTLI);
3620
3621         /*
3622          * Prefer link() to rename() here just to be really sure that we don't
3623          * overwrite an existing logfile.  However, there shouldn't be one, so
3624          * rename() is an acceptable substitute except for the truly paranoid.
3625          */
3626 #if HAVE_WORKING_LINK
3627         if (link(tmppath, path) < 0)
3628                 ereport(ERROR,
3629                                 (errcode_for_file_access(),
3630                                  errmsg("could not link file \"%s\" to \"%s\": %m",
3631                                                 tmppath, path)));
3632         unlink(tmppath);
3633 #else
3634         if (rename(tmppath, path) < 0)
3635                 ereport(ERROR,
3636                                 (errcode_for_file_access(),
3637                                  errmsg("could not rename file \"%s\" to \"%s\": %m",
3638                                                 tmppath, path)));
3639 #endif
3640
3641         /* The history file can be archived immediately. */
3642         TLHistoryFileName(histfname, newTLI);
3643         XLogArchiveNotify(histfname);
3644 }
3645
3646 /*
3647  * I/O routines for pg_control
3648  *
3649  * *ControlFile is a buffer in shared memory that holds an image of the
3650  * contents of pg_control.      WriteControlFile() initializes pg_control
3651  * given a preloaded buffer, ReadControlFile() loads the buffer from
3652  * the pg_control file (during postmaster or standalone-backend startup),
3653  * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3654  *
3655  * For simplicity, WriteControlFile() initializes the fields of pg_control
3656  * that are related to checking backend/database compatibility, and
3657  * ReadControlFile() verifies they are correct.  We could split out the
3658  * I/O and compatibility-check functions, but there seems no need currently.
3659  */
3660 static void
3661 WriteControlFile(void)
3662 {
3663         int                     fd;
3664         char            buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3665         char       *localeptr;
3666
3667         /*
3668          * Initialize version and compatibility-check fields
3669          */
3670         ControlFile->pg_control_version = PG_CONTROL_VERSION;
3671         ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3672
3673         ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3674         ControlFile->floatFormat = FLOATFORMAT_VALUE;
3675
3676         ControlFile->blcksz = BLCKSZ;
3677         ControlFile->relseg_size = RELSEG_SIZE;
3678         ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3679         ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3680
3681         ControlFile->nameDataLen = NAMEDATALEN;
3682         ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3683
3684 #ifdef HAVE_INT64_TIMESTAMP
3685         ControlFile->enableIntTimes = TRUE;
3686 #else
3687         ControlFile->enableIntTimes = FALSE;
3688 #endif
3689
3690         ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3691         localeptr = setlocale(LC_COLLATE, NULL);
3692         if (!localeptr)
3693                 ereport(PANIC,
3694                                 (errmsg("invalid LC_COLLATE setting")));
3695         StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3696         localeptr = setlocale(LC_CTYPE, NULL);
3697         if (!localeptr)
3698                 ereport(PANIC,
3699                                 (errmsg("invalid LC_CTYPE setting")));
3700         StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3701
3702         /* Contents are protected with a CRC */
3703         INIT_CRC32(ControlFile->crc);
3704         COMP_CRC32(ControlFile->crc,
3705                            (char *) ControlFile,
3706                            offsetof(ControlFileData, crc));
3707         FIN_CRC32(ControlFile->crc);
3708
3709         /*
3710          * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3711          * excess over sizeof(ControlFileData).  This reduces the odds of
3712          * premature-EOF errors when reading pg_control.  We'll still fail when we
3713          * check the contents of the file, but hopefully with a more specific
3714          * error than "couldn't read pg_control".
3715          */
3716         if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3717                 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3718
3719         memset(buffer, 0, PG_CONTROL_SIZE);
3720         memcpy(buffer, ControlFile, sizeof(ControlFileData));
3721
3722         fd = BasicOpenFile(XLOG_CONTROL_FILE,
3723                                            O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3724                                            S_IRUSR | S_IWUSR);
3725         if (fd < 0)
3726                 ereport(PANIC,
3727                                 (errcode_for_file_access(),
3728                                  errmsg("could not create control file \"%s\": %m",
3729                                                 XLOG_CONTROL_FILE)));
3730
3731         errno = 0;
3732         if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3733         {
3734                 /* if write didn't set errno, assume problem is no disk space */
3735                 if (errno == 0)
3736                         errno = ENOSPC;
3737                 ereport(PANIC,
3738                                 (errcode_for_file_access(),
3739                                  errmsg("could not write to control file: %m")));
3740         }
3741
3742         if (pg_fsync(fd) != 0)
3743                 ereport(PANIC,
3744                                 (errcode_for_file_access(),
3745                                  errmsg("could not fsync control file: %m")));
3746
3747         if (close(fd))
3748                 ereport(PANIC,
3749                                 (errcode_for_file_access(),
3750                                  errmsg("could not close control file: %m")));
3751 }
3752
3753 static void
3754 ReadControlFile(void)
3755 {
3756         pg_crc32        crc;
3757         int                     fd;
3758
3759         /*
3760          * Read data...
3761          */
3762         fd = BasicOpenFile(XLOG_CONTROL_FILE,
3763                                            O_RDWR | PG_BINARY,
3764                                            S_IRUSR | S_IWUSR);
3765         if (fd < 0)
3766                 ereport(PANIC,
3767                                 (errcode_for_file_access(),
3768                                  errmsg("could not open control file \"%s\": %m",
3769                                                 XLOG_CONTROL_FILE)));
3770
3771         if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3772                 ereport(PANIC,
3773                                 (errcode_for_file_access(),
3774                                  errmsg("could not read from control file: %m")));
3775
3776         close(fd);
3777
3778         /*
3779          * Check for expected pg_control format version.  If this is wrong, the
3780          * CRC check will likely fail because we'll be checking the wrong number
3781          * of bytes.  Complaining about wrong version will probably be more
3782          * enlightening than complaining about wrong CRC.
3783          */
3784         if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3785                 ereport(FATAL,
3786                                 (errmsg("database files are incompatible with server"),
3787                                  errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3788                                   " but the server was compiled with PG_CONTROL_VERSION %d.",
3789                                                 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3790                                  errhint("It looks like you need to initdb.")));
3791         /* Now check the CRC. */
3792         INIT_CRC32(crc);
3793         COMP_CRC32(crc,
3794                            (char *) ControlFile,
3795                            offsetof(ControlFileData, crc));
3796         FIN_CRC32(crc);
3797
3798         if (!EQ_CRC32(crc, ControlFile->crc))
3799                 ereport(FATAL,
3800                                 (errmsg("incorrect checksum in control file")));
3801
3802         /*
3803          * Do compatibility checking immediately.  We do this here for 2 reasons:
3804          *
3805          * (1) if the database isn't compatible with the backend executable, we
3806          * want to abort before we can possibly do any damage;
3807          *
3808          * (2) this code is executed in the postmaster, so the setlocale() will
3809          * propagate to forked backends, which aren't going to read this file for
3810          * themselves.  (These locale settings are considered critical
3811          * compatibility items because they can affect sort order of indexes.)
3812          */
3813         if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3814                 ereport(FATAL,
3815                                 (errmsg("database files are incompatible with server"),
3816                                  errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3817                                   " but the server was compiled with CATALOG_VERSION_NO %d.",
3818                                                 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3819                                  errhint("It looks like you need to initdb.")));
3820         if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3821                 ereport(FATAL,
3822                                 (errmsg("database files are incompatible with server"),
3823                    errdetail("The database cluster was initialized with MAXALIGN %d,"
3824                                          " but the server was compiled with MAXALIGN %d.",
3825                                          ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3826                                  errhint("It looks like you need to initdb.")));
3827         if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3828                 ereport(FATAL,
3829                                 (errmsg("database files are incompatible with server"),
3830                                  errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3831                                  errhint("It looks like you need to initdb.")));
3832         if (ControlFile->blcksz != BLCKSZ)
3833                 ereport(FATAL,
3834                                 (errmsg("database files are incompatible with server"),
3835                          errdetail("The database cluster was initialized with BLCKSZ %d,"
3836                                            " but the server was compiled with BLCKSZ %d.",
3837                                            ControlFile->blcksz, BLCKSZ),
3838                                  errhint("It looks like you need to recompile or initdb.")));
3839         if (ControlFile->relseg_size != RELSEG_SIZE)
3840                 ereport(FATAL,
3841                                 (errmsg("database files are incompatible with server"),
3842                 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3843                                   " but the server was compiled with RELSEG_SIZE %d.",
3844                                   ControlFile->relseg_size, RELSEG_SIZE),
3845                                  errhint("It looks like you need to recompile or initdb.")));
3846         if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3847                 ereport(FATAL,
3848                                 (errmsg("database files are incompatible with server"),
3849                          errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3850                                            " but the server was compiled with XLOG_BLCKSZ %d.",
3851                                            ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3852                                  errhint("It looks like you need to recompile or initdb.")));
3853         if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3854                 ereport(FATAL,
3855                                 (errmsg("database files are incompatible with server"),
3856                                  errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3857                                            " but the server was compiled with XLOG_SEG_SIZE %d.",
3858                                                    ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3859                                  errhint("It looks like you need to recompile or initdb.")));
3860         if (ControlFile->nameDataLen != NAMEDATALEN)
3861                 ereport(FATAL,
3862                                 (errmsg("database files are incompatible with server"),
3863                 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3864                                   " but the server was compiled with NAMEDATALEN %d.",
3865                                   ControlFile->nameDataLen, NAMEDATALEN),
3866                                  errhint("It looks like you need to recompile or initdb.")));
3867         if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3868                 ereport(FATAL,
3869                                 (errmsg("database files are incompatible with server"),
3870                                  errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3871                                           " but the server was compiled with INDEX_MAX_KEYS %d.",
3872                                                    ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3873                                  errhint("It looks like you need to recompile or initdb.")));
3874
3875 #ifdef HAVE_INT64_TIMESTAMP
3876         if (ControlFile->enableIntTimes != TRUE)
3877                 ereport(FATAL,
3878                                 (errmsg("database files are incompatible with server"),
3879                                  errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3880                                   " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3881                                  errhint("It looks like you need to recompile or initdb.")));
3882 #else
3883         if (ControlFile->enableIntTimes != FALSE)
3884                 ereport(FATAL,
3885                                 (errmsg("database files are incompatible with server"),
3886                                  errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3887                            " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3888                                  errhint("It looks like you need to recompile or initdb.")));
3889 #endif
3890
3891         if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3892                 ereport(FATAL,
3893                                 (errmsg("database files are incompatible with server"),
3894                                  errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3895                                   " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3896                                                    ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3897                                  errhint("It looks like you need to recompile or initdb.")));
3898         if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3899                 ereport(FATAL,
3900                         (errmsg("database files are incompatible with operating system"),
3901                          errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3902                                            " which is not recognized by setlocale().",
3903                                            ControlFile->lc_collate),
3904                          errhint("It looks like you need to initdb or install locale support.")));
3905         if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3906                 ereport(FATAL,
3907                         (errmsg("database files are incompatible with operating system"),
3908                 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3909                                   " which is not recognized by setlocale().",
3910                                   ControlFile->lc_ctype),
3911                          errhint("It looks like you need to initdb or install locale support.")));
3912
3913         /* Make the fixed locale settings visible as GUC variables, too */
3914         SetConfigOption("lc_collate", ControlFile->lc_collate,
3915                                         PGC_INTERNAL, PGC_S_OVERRIDE);
3916         SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3917                                         PGC_INTERNAL, PGC_S_OVERRIDE);
3918 }
3919
3920 void
3921 UpdateControlFile(void)
3922 {
3923         int                     fd;
3924
3925         INIT_CRC32(ControlFile->crc);
3926         COMP_CRC32(ControlFile->crc,
3927                            (char *) ControlFile,
3928                            offsetof(ControlFileData, crc));
3929         FIN_CRC32(ControlFile->crc);
3930
3931         fd = BasicOpenFile(XLOG_CONTROL_FILE,
3932                                            O_RDWR | PG_BINARY,
3933                                            S_IRUSR | S_IWUSR);
3934         if (fd < 0)
3935                 ereport(PANIC,
3936                                 (errcode_for_file_access(),
3937                                  errmsg("could not open control file \"%s\": %m",
3938                                                 XLOG_CONTROL_FILE)));
3939
3940         errno = 0;
3941         if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3942         {
3943                 /* if write didn't set errno, assume problem is no disk space */
3944                 if (errno == 0)
3945                         errno = ENOSPC;
3946                 ereport(PANIC,
3947                                 (errcode_for_file_access(),
3948                                  errmsg("could not write to control file: %m")));
3949         }
3950
3951         if (pg_fsync(fd) != 0)
3952                 ereport(PANIC,
3953                                 (errcode_for_file_access(),
3954                                  errmsg("could not fsync control file: %m")));
3955
3956         if (close(fd))
3957                 ereport(PANIC,
3958                                 (errcode_for_file_access(),
3959                                  errmsg("could not close control file: %m")));
3960 }
3961
3962 /*
3963  * Initialization of shared memory for XLOG
3964  */
3965 Size
3966 XLOGShmemSize(void)
3967 {
3968         Size            size;
3969
3970         /* XLogCtl */
3971         size = sizeof(XLogCtlData);
3972         /* xlblocks array */
3973         size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
3974         /* extra alignment padding for XLOG I/O buffers */
3975         size = add_size(size, ALIGNOF_XLOG_BUFFER);
3976         /* and the buffers themselves */
3977         size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
3978
3979         /*
3980          * Note: we don't count ControlFileData, it comes out of the "slop factor"
3981          * added by CreateSharedMemoryAndSemaphores.  This lets us use this
3982          * routine again below to compute the actual allocation size.
3983          */
3984
3985         return size;
3986 }
3987
3988 void
3989 XLOGShmemInit(void)
3990 {
3991         bool            foundCFile,
3992                                 foundXLog;
3993         char       *allocptr;
3994
3995         ControlFile = (ControlFileData *)
3996                 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
3997         XLogCtl = (XLogCtlData *)
3998                 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
3999
4000         if (foundCFile || foundXLog)
4001         {
4002                 /* both should be present or neither */
4003                 Assert(foundCFile && foundXLog);
4004                 return;
4005         }
4006
4007         memset(XLogCtl, 0, sizeof(XLogCtlData));
4008
4009         /*
4010          * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4011          * multiple of the alignment for same, so no extra alignment padding is
4012          * needed here.
4013          */
4014         allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4015         XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4016         memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4017         allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4018
4019         /*
4020          * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4021          */
4022         allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4023         XLogCtl->pages = allocptr;
4024         memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4025
4026         /*
4027          * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4028          * in additional info.)
4029          */
4030         XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ * XLOGbuffers;
4031
4032         XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4033         XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4034         SpinLockInit(&XLogCtl->info_lck);
4035
4036         /*
4037          * If we are not in bootstrap mode, pg_control should already exist. Read
4038          * and validate it immediately (see comments in ReadControlFile() for the
4039          * reasons why).
4040          */
4041         if (!IsBootstrapProcessingMode())
4042                 ReadControlFile();
4043 }
4044
4045 /*
4046  * This func must be called ONCE on system install.  It creates pg_control
4047  * and the initial XLOG segment.
4048  */
4049 void
4050 BootStrapXLOG(void)
4051 {
4052         CheckPoint      checkPoint;
4053         char       *buffer;
4054         XLogPageHeader page;
4055         XLogLongPageHeader longpage;
4056         XLogRecord *record;
4057         bool            use_existent;
4058         uint64          sysidentifier;
4059         struct timeval tv;
4060         pg_crc32        crc;
4061
4062         /*
4063          * Select a hopefully-unique system identifier code for this installation.
4064          * We use the result of gettimeofday(), including the fractional seconds
4065          * field, as being about as unique as we can easily get.  (Think not to
4066          * use random(), since it hasn't been seeded and there's no portable way
4067          * to seed it other than the system clock value...)  The upper half of the
4068          * uint64 value is just the tv_sec part, while the lower half is the XOR
4069          * of tv_sec and tv_usec.  This is to ensure that we don't lose uniqueness
4070          * unnecessarily if "uint64" is really only 32 bits wide.  A person
4071          * knowing this encoding can determine the initialization time of the
4072          * installation, which could perhaps be useful sometimes.
4073          */
4074         gettimeofday(&tv, NULL);
4075         sysidentifier = ((uint64) tv.tv_sec) << 32;
4076         sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4077
4078         /* First timeline ID is always 1 */
4079         ThisTimeLineID = 1;
4080
4081         /* page buffer must be aligned suitably for O_DIRECT */
4082         buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4083         page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4084         memset(page, 0, XLOG_BLCKSZ);
4085
4086         /* Set up information for the initial checkpoint record */
4087         checkPoint.redo.xlogid = 0;
4088         checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4089         checkPoint.undo = checkPoint.redo;
4090         checkPoint.ThisTimeLineID = ThisTimeLineID;
4091         checkPoint.nextXidEpoch = 0;
4092         checkPoint.nextXid = FirstNormalTransactionId;
4093         checkPoint.nextOid = FirstBootstrapObjectId;
4094         checkPoint.nextMulti = FirstMultiXactId;
4095         checkPoint.nextMultiOffset = 0;
4096         checkPoint.time = time(NULL);
4097
4098         ShmemVariableCache->nextXid = checkPoint.nextXid;
4099         ShmemVariableCache->nextOid = checkPoint.nextOid;
4100         ShmemVariableCache->oidCount = 0;
4101         MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4102
4103         /* Set up the XLOG page header */
4104         page->xlp_magic = XLOG_PAGE_MAGIC;
4105         page->xlp_info = XLP_LONG_HEADER;
4106         page->xlp_tli = ThisTimeLineID;
4107         page->xlp_pageaddr.xlogid = 0;
4108         page->xlp_pageaddr.xrecoff = 0;
4109         longpage = (XLogLongPageHeader) page;
4110         longpage->xlp_sysid = sysidentifier;
4111         longpage->xlp_seg_size = XLogSegSize;
4112         longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4113
4114         /* Insert the initial checkpoint record */
4115         record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4116         record->xl_prev.xlogid = 0;
4117         record->xl_prev.xrecoff = 0;
4118         record->xl_xid = InvalidTransactionId;
4119         record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4120         record->xl_len = sizeof(checkPoint);
4121         record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4122         record->xl_rmid = RM_XLOG_ID;
4123         memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4124
4125         INIT_CRC32(crc);
4126         COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4127         COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4128                            SizeOfXLogRecord - sizeof(pg_crc32));
4129         FIN_CRC32(crc);
4130         record->xl_crc = crc;
4131
4132         /* Create first XLOG segment file */
4133         use_existent = false;
4134         openLogFile = XLogFileInit(0, 0, &use_existent, false);
4135
4136         /* Write the first page with the initial record */
4137         errno = 0;
4138         if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4139         {
4140                 /* if write didn't set errno, assume problem is no disk space */
4141                 if (errno == 0)
4142                         errno = ENOSPC;
4143                 ereport(PANIC,
4144                                 (errcode_for_file_access(),
4145                           errmsg("could not write bootstrap transaction log file: %m")));
4146         }
4147
4148         if (pg_fsync(openLogFile) != 0)
4149                 ereport(PANIC,
4150                                 (errcode_for_file_access(),
4151                           errmsg("could not fsync bootstrap transaction log file: %m")));
4152
4153         if (close(openLogFile))
4154                 ereport(PANIC,
4155                                 (errcode_for_file_access(),
4156                           errmsg("could not close bootstrap transaction log file: %m")));
4157
4158         openLogFile = -1;
4159
4160         /* Now create pg_control */
4161
4162         memset(ControlFile, 0, sizeof(ControlFileData));
4163         /* Initialize pg_control status fields */
4164         ControlFile->system_identifier = sysidentifier;
4165         ControlFile->state = DB_SHUTDOWNED;
4166         ControlFile->time = checkPoint.time;
4167         ControlFile->logId = 0;
4168         ControlFile->logSeg = 1;
4169         ControlFile->checkPoint = checkPoint.redo;
4170         ControlFile->checkPointCopy = checkPoint;
4171         /* some additional ControlFile fields are set in WriteControlFile() */
4172
4173         WriteControlFile();
4174
4175         /* Bootstrap the commit log, too */
4176         BootStrapCLOG();
4177         BootStrapSUBTRANS();
4178         BootStrapMultiXact();
4179
4180         pfree(buffer);
4181 }
4182
4183 static char *
4184 str_time(time_t tnow)
4185 {
4186         static char buf[128];
4187
4188         strftime(buf, sizeof(buf),
4189                          "%Y-%m-%d %H:%M:%S %Z",
4190                          localtime(&tnow));
4191
4192         return buf;
4193 }
4194
4195 /*
4196  * See if there is a recovery command file (recovery.conf), and if so
4197  * read in parameters for archive recovery.
4198  *
4199  * XXX longer term intention is to expand this to
4200  * cater for additional parameters and controls
4201  * possibly use a flex lexer similar to the GUC one
4202  */
4203 static void
4204 readRecoveryCommandFile(void)
4205 {
4206         FILE       *fd;
4207         char            cmdline[MAXPGPATH];
4208         TimeLineID      rtli = 0;
4209         bool            rtliGiven = false;
4210         bool            syntaxError = false;
4211
4212         fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4213         if (fd == NULL)
4214         {
4215                 if (errno == ENOENT)
4216                         return;                         /* not there, so no archive recovery */
4217                 ereport(FATAL,
4218                                 (errcode_for_file_access(),
4219                                  errmsg("could not open recovery command file \"%s\": %m",
4220                                                 RECOVERY_COMMAND_FILE)));
4221         }
4222
4223         ereport(LOG,
4224                         (errmsg("starting archive recovery")));
4225
4226         /*
4227          * Parse the file...
4228          */
4229         while (fgets(cmdline, MAXPGPATH, fd) != NULL)
4230         {
4231                 /* skip leading whitespace and check for # comment */
4232                 char       *ptr;
4233                 char       *tok1;
4234                 char       *tok2;
4235
4236                 for (ptr = cmdline; *ptr; ptr++)
4237                 {
4238                         if (!isspace((unsigned char) *ptr))
4239                                 break;
4240                 }
4241                 if (*ptr == '\0' || *ptr == '#')
4242                         continue;
4243
4244                 /* identify the quoted parameter value */
4245                 tok1 = strtok(ptr, "'");
4246                 if (!tok1)
4247                 {
4248                         syntaxError = true;
4249                         break;
4250                 }
4251                 tok2 = strtok(NULL, "'");
4252                 if (!tok2)
4253                 {
4254                         syntaxError = true;
4255                         break;
4256                 }
4257                 /* reparse to get just the parameter name */
4258                 tok1 = strtok(ptr, " \t=");
4259                 if (!tok1)
4260                 {
4261                         syntaxError = true;
4262                         break;
4263                 }
4264
4265                 if (strcmp(tok1, "restore_command") == 0)
4266                 {
4267                         recoveryRestoreCommand = pstrdup(tok2);
4268                         ereport(LOG,
4269                                         (errmsg("restore_command = \"%s\"",
4270                                                         recoveryRestoreCommand)));
4271                 }
4272                 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4273                 {
4274                         rtliGiven = true;
4275                         if (strcmp(tok2, "latest") == 0)
4276                                 rtli = 0;
4277                         else
4278                         {
4279                                 errno = 0;
4280                                 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4281                                 if (errno == EINVAL || errno == ERANGE)
4282                                         ereport(FATAL,
4283                                                         (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4284                                                                         tok2)));
4285                         }
4286                         if (rtli)
4287                                 ereport(LOG,
4288                                                 (errmsg("recovery_target_timeline = %u", rtli)));
4289                         else
4290                                 ereport(LOG,
4291                                                 (errmsg("recovery_target_timeline = latest")));
4292                 }
4293                 else if (strcmp(tok1, "recovery_target_xid") == 0)
4294                 {
4295                         errno = 0;
4296                         recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4297                         if (errno == EINVAL || errno == ERANGE)
4298                                 ereport(FATAL,
4299                                  (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4300                                                  tok2)));
4301                         ereport(LOG,
4302                                         (errmsg("recovery_target_xid = %u",
4303                                                         recoveryTargetXid)));
4304                         recoveryTarget = true;
4305                         recoveryTargetExact = true;
4306                 }
4307                 else if (strcmp(tok1, "recovery_target_time") == 0)
4308                 {
4309                         /*
4310                          * if recovery_target_xid specified, then this overrides
4311                          * recovery_target_time
4312                          */
4313                         if (recoveryTargetExact)
4314                                 continue;
4315                         recoveryTarget = true;
4316                         recoveryTargetExact = false;
4317
4318                         /*
4319                          * Convert the time string given by the user to the time_t format.
4320                          * We use type abstime's input converter because we know abstime
4321                          * has the same representation as time_t.
4322                          */
4323                         recoveryTargetTime = (time_t)
4324                                 DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
4325                                                                                                          CStringGetDatum(tok2)));
4326                         ereport(LOG,
4327                                         (errmsg("recovery_target_time = %s",
4328                                                         DatumGetCString(DirectFunctionCall1(abstimeout,
4329                                 AbsoluteTimeGetDatum((AbsoluteTime) recoveryTargetTime))))));
4330                 }
4331                 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4332                 {
4333                         /*
4334                          * does nothing if a recovery_target is not also set
4335                          */
4336                         if (strcmp(tok2, "true") == 0)
4337                                 recoveryTargetInclusive = true;
4338                         else
4339                         {
4340                                 recoveryTargetInclusive = false;
4341                                 tok2 = "false";
4342                         }
4343                         ereport(LOG,
4344                                         (errmsg("recovery_target_inclusive = %s", tok2)));
4345                 }
4346                 else
4347                         ereport(FATAL,
4348                                         (errmsg("unrecognized recovery parameter \"%s\"",
4349                                                         tok1)));
4350         }
4351
4352         FreeFile(fd);
4353
4354         if (syntaxError)
4355                 ereport(FATAL,
4356                                 (errmsg("syntax error in recovery command file: %s",
4357                                                 cmdline),
4358                           errhint("Lines should have the format parameter = 'value'.")));
4359
4360         /* Check that required parameters were supplied */
4361         if (recoveryRestoreCommand == NULL)
4362                 ereport(FATAL,
4363                                 (errmsg("recovery command file \"%s\" did not specify restore_command",
4364                                                 RECOVERY_COMMAND_FILE)));
4365
4366         /* Enable fetching from archive recovery area */
4367         InArchiveRecovery = true;
4368
4369         /*
4370          * If user specified recovery_target_timeline, validate it or compute the
4371          * "latest" value.      We can't do this until after we've gotten the restore
4372          * command and set InArchiveRecovery, because we need to fetch timeline
4373          * history files from the archive.
4374          */
4375         if (rtliGiven)
4376         {
4377                 if (rtli)
4378                 {
4379                         /* Timeline 1 does not have a history file, all else should */
4380                         if (rtli != 1 && !existsTimeLineHistory(rtli))
4381                                 ereport(FATAL,
4382                                                 (errmsg("recovery_target_timeline %u does not exist",
4383                                                                 rtli)));
4384                         recoveryTargetTLI = rtli;
4385                 }
4386                 else
4387                 {
4388                         /* We start the "latest" search from pg_control's timeline */
4389                         recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4390                 }
4391         }
4392 }
4393
4394 /*
4395  * Exit archive-recovery state
4396  */
4397 static void
4398 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4399 {
4400         char            recoveryPath[MAXPGPATH];
4401         char            xlogpath[MAXPGPATH];
4402
4403         /*
4404          * We are no longer in archive recovery state.
4405          */
4406         InArchiveRecovery = false;
4407
4408         /*
4409          * We should have the ending log segment currently open.  Verify, and then
4410          * close it (to avoid problems on Windows with trying to rename or delete
4411          * an open file).
4412          */
4413         Assert(readFile >= 0);
4414         Assert(readId == endLogId);
4415         Assert(readSeg == endLogSeg);
4416
4417         close(readFile);
4418         readFile = -1;
4419
4420         /*
4421          * If the segment was fetched from archival storage, we want to replace
4422          * the existing xlog segment (if any) with the archival version.  This is
4423          * because whatever is in XLOGDIR is very possibly older than what we have
4424          * from the archives, since it could have come from restoring a PGDATA
4425          * backup.      In any case, the archival version certainly is more
4426          * descriptive of what our current database state is, because that is what
4427          * we replayed from.
4428          *
4429          * Note that if we are establishing a new timeline, ThisTimeLineID is
4430          * already set to the new value, and so we will create a new file instead
4431          * of overwriting any existing file.
4432          */
4433         snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4434         XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4435
4436         if (restoredFromArchive)
4437         {
4438                 ereport(DEBUG3,
4439                                 (errmsg_internal("moving last restored xlog to \"%s\"",
4440                                                                  xlogpath)));
4441                 unlink(xlogpath);               /* might or might not exist */
4442                 if (rename(recoveryPath, xlogpath) != 0)
4443                         ereport(FATAL,
4444                                         (errcode_for_file_access(),
4445                                          errmsg("could not rename file \"%s\" to \"%s\": %m",
4446                                                         recoveryPath, xlogpath)));
4447                 /* XXX might we need to fix permissions on the file? */
4448         }
4449         else
4450         {
4451                 /*
4452                  * If the latest segment is not archival, but there's still a
4453                  * RECOVERYXLOG laying about, get rid of it.
4454                  */
4455                 unlink(recoveryPath);   /* ignore any error */
4456
4457                 /*
4458                  * If we are establishing a new timeline, we have to copy data from
4459                  * the last WAL segment of the old timeline to create a starting WAL
4460                  * segment for the new timeline.
4461                  */
4462                 if (endTLI != ThisTimeLineID)
4463                         XLogFileCopy(endLogId, endLogSeg,
4464                                                  endTLI, endLogId, endLogSeg);
4465         }
4466
4467         /*
4468          * Let's just make real sure there are not .ready or .done flags posted
4469          * for the new segment.
4470          */
4471         XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4472         XLogArchiveCleanup(xlogpath);
4473
4474         /* Get rid of any remaining recovered timeline-history file, too */
4475         snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4476         unlink(recoveryPath);           /* ignore any error */
4477
4478         /*
4479          * Rename the config file out of the way, so that we don't accidentally
4480          * re-enter archive recovery mode in a subsequent crash.
4481          */
4482         unlink(RECOVERY_COMMAND_DONE);
4483         if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4484                 ereport(FATAL,
4485                                 (errcode_for_file_access(),
4486                                  errmsg("could not rename file \"%s\" to \"%s\": %m",
4487                                                 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4488
4489         ereport(LOG,
4490                         (errmsg("archive recovery complete")));
4491 }
4492
4493 /*
4494  * For point-in-time recovery, this function decides whether we want to
4495  * stop applying the XLOG at or after the current record.
4496  *
4497  * Returns TRUE if we are stopping, FALSE otherwise.  On TRUE return,
4498  * *includeThis is set TRUE if we should apply this record before stopping.
4499  * Also, some information is saved in recoveryStopXid et al for use in
4500  * annotating the new timeline's history file.
4501  */
4502 static bool
4503 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4504 {
4505         bool            stopsHere;
4506         uint8           record_info;
4507         time_t          recordXtime;
4508
4509         /* Do we have a PITR target at all? */
4510         if (!recoveryTarget)
4511                 return false;
4512
4513         /* We only consider stopping at COMMIT or ABORT records */
4514         if (record->xl_rmid != RM_XACT_ID)
4515                 return false;
4516         record_info = record->xl_info & ~XLR_INFO_MASK;
4517         if (record_info == XLOG_XACT_COMMIT)
4518         {
4519                 xl_xact_commit *recordXactCommitData;
4520
4521                 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4522                 recordXtime = recordXactCommitData->xtime;
4523         }
4524         else if (record_info == XLOG_XACT_ABORT)
4525         {
4526                 xl_xact_abort *recordXactAbortData;
4527
4528                 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4529                 recordXtime = recordXactAbortData->xtime;
4530         }
4531         else
4532                 return false;
4533
4534         if (recoveryTargetExact)
4535         {
4536                 /*
4537                  * there can be only one transaction end record with this exact
4538                  * transactionid
4539                  *
4540                  * when testing for an xid, we MUST test for equality only, since
4541                  * transactions are numbered in the order they start, not the order
4542                  * they complete. A higher numbered xid will complete before you about
4543                  * 50% of the time...
4544                  */
4545                 stopsHere = (record->xl_xid == recoveryTargetXid);
4546                 if (stopsHere)
4547                         *includeThis = recoveryTargetInclusive;
4548         }
4549         else
4550         {
4551                 /*
4552                  * there can be many transactions that share the same commit time, so
4553                  * we stop after the last one, if we are inclusive, or stop at the
4554                  * first one if we are exclusive
4555                  */
4556                 if (recoveryTargetInclusive)
4557                         stopsHere = (recordXtime > recoveryTargetTime);
4558                 else
4559                         stopsHere = (recordXtime >= recoveryTargetTime);
4560                 if (stopsHere)
4561                         *includeThis = false;
4562         }
4563
4564         if (stopsHere)
4565         {
4566                 recoveryStopXid = record->xl_xid;
4567                 recoveryStopTime = recordXtime;
4568                 recoveryStopAfter = *includeThis;
4569
4570                 if (record_info == XLOG_XACT_COMMIT)
4571                 {
4572                         if (recoveryStopAfter)
4573                                 ereport(LOG,
4574                                                 (errmsg("recovery stopping after commit of transaction %u, time %s",
4575                                                           recoveryStopXid, str_time(recoveryStopTime))));
4576                         else
4577                                 ereport(LOG,
4578                                                 (errmsg("recovery stopping before commit of transaction %u, time %s",
4579                                                           recoveryStopXid, str_time(recoveryStopTime))));
4580                 }
4581                 else
4582                 {
4583                         if (recoveryStopAfter)
4584                                 ereport(LOG,
4585                                                 (errmsg("recovery stopping after abort of transaction %u, time %s",
4586                                                           recoveryStopXid, str_time(recoveryStopTime))));
4587                         else
4588                                 ereport(LOG,
4589                                                 (errmsg("recovery stopping before abort of transaction %u, time %s",
4590                                                           recoveryStopXid, str_time(recoveryStopTime))));
4591                 }
4592         }
4593
4594         return stopsHere;
4595 }
4596
4597 /*
4598  * This must be called ONCE during postmaster or standalone-backend startup
4599  */
4600 void
4601 StartupXLOG(void)
4602 {
4603         XLogCtlInsert *Insert;
4604         CheckPoint      checkPoint;
4605         bool            wasShutdown;
4606         bool            needNewTimeLine = false;
4607         bool            haveBackupLabel = false;
4608         XLogRecPtr      RecPtr,
4609                                 LastRec,
4610                                 checkPointLoc,
4611                                 minRecoveryLoc,
4612                                 EndOfLog;
4613         uint32          endLogId;
4614         uint32          endLogSeg;
4615         XLogRecord *record;
4616         uint32          freespace;
4617         TransactionId oldestActiveXID;
4618
4619         CritSectionCount++;
4620
4621         /*
4622          * Read control file and check XLOG status looks valid.
4623          *
4624          * Note: in most control paths, *ControlFile is already valid and we need
4625          * not do ReadControlFile() here, but might as well do it to be sure.
4626          */
4627         ReadControlFile();
4628
4629         if (ControlFile->logSeg == 0 ||
4630                 ControlFile->state < DB_SHUTDOWNED ||
4631                 ControlFile->state > DB_IN_PRODUCTION ||
4632                 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4633                 ereport(FATAL,
4634                                 (errmsg("control file contains invalid data")));
4635
4636         if (ControlFile->state == DB_SHUTDOWNED)
4637                 ereport(LOG,
4638                                 (errmsg("database system was shut down at %s",
4639                                                 str_time(ControlFile->time))));
4640         else if (ControlFile->state == DB_SHUTDOWNING)
4641                 ereport(LOG,
4642                                 (errmsg("database system shutdown was interrupted at %s",
4643                                                 str_time(ControlFile->time))));
4644         else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4645                 ereport(LOG,
4646                    (errmsg("database system was interrupted while in recovery at %s",
4647                                    str_time(ControlFile->time)),
4648                         errhint("This probably means that some data is corrupted and"
4649                                         " you will have to use the last backup for recovery.")));
4650         else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4651                 ereport(LOG,
4652                    (errmsg("database system was interrupted while in recovery at log time %s",
4653                                    str_time(ControlFile->checkPointCopy.time)),
4654                         errhint("If this has occurred more than once some data may be corrupted"
4655                                         " and you may need to choose an earlier recovery target.")));
4656         else if (ControlFile->state == DB_IN_PRODUCTION)
4657                 ereport(LOG,
4658                                 (errmsg("database system was interrupted at %s",
4659                                                 str_time(ControlFile->time))));
4660
4661         /* This is just to allow attaching to startup process with a debugger */
4662 #ifdef XLOG_REPLAY_DELAY
4663         if (ControlFile->state != DB_SHUTDOWNED)
4664                 pg_usleep(60000000L);
4665 #endif
4666
4667         /*
4668          * Initialize on the assumption we want to recover to the same timeline
4669          * that's active according to pg_control.
4670          */
4671         recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4672
4673         /*
4674          * Check for recovery control file, and if so set up state for offline
4675          * recovery
4676          */
4677         readRecoveryCommandFile();
4678
4679         /* Now we can determine the list of expected TLIs */
4680         expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4681
4682         /*
4683          * If pg_control's timeline is not in expectedTLIs, then we cannot
4684          * proceed: the backup is not part of the history of the requested
4685          * timeline.
4686          */
4687         if (!list_member_int(expectedTLIs,
4688                                                  (int) ControlFile->checkPointCopy.ThisTimeLineID))
4689                 ereport(FATAL,
4690                                 (errmsg("requested timeline %u is not a child of database system timeline %u",
4691                                                 recoveryTargetTLI,
4692                                                 ControlFile->checkPointCopy.ThisTimeLineID)));
4693
4694         if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4695         {
4696                 /*
4697                  * When a backup_label file is present, we want to roll forward from
4698                  * the checkpoint it identifies, rather than using pg_control.
4699                  */
4700                 record = ReadCheckpointRecord(checkPointLoc, 0);
4701                 if (record != NULL)
4702                 {
4703                         ereport(LOG,
4704                                         (errmsg("checkpoint record is at %X/%X",
4705                                                         checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4706                         InRecovery = true;      /* force recovery even if SHUTDOWNED */
4707                 }
4708                 else
4709                 {
4710                         ereport(PANIC,
4711                                         (errmsg("could not locate required checkpoint record"),
4712                                          errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4713                 }
4714                 /* set flag to delete it later */
4715                 haveBackupLabel = true;
4716         }
4717         else
4718         {
4719                 /*
4720                  * Get the last valid checkpoint record.  If the latest one according
4721                  * to pg_control is broken, try the next-to-last one.
4722                  */
4723                 checkPointLoc = ControlFile->checkPoint;
4724                 record = ReadCheckpointRecord(checkPointLoc, 1);
4725                 if (record != NULL)
4726                 {
4727                         ereport(LOG,
4728                                         (errmsg("checkpoint record is at %X/%X",
4729                                                         checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4730                 }
4731                 else
4732                 {
4733                         checkPointLoc = ControlFile->prevCheckPoint;
4734                         record = ReadCheckpointRecord(checkPointLoc, 2);
4735                         if (record != NULL)
4736                         {
4737                                 ereport(LOG,
4738                                                 (errmsg("using previous checkpoint record at %X/%X",
4739                                                           checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4740                                 InRecovery = true;              /* force recovery even if SHUTDOWNED */
4741                         }
4742                         else
4743                                 ereport(PANIC,
4744                                          (errmsg("could not locate a valid checkpoint record")));
4745                 }
4746         }
4747
4748         LastRec = RecPtr = checkPointLoc;
4749         memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4750         wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4751
4752         ereport(LOG,
4753          (errmsg("redo record is at %X/%X; undo record is at %X/%X; shutdown %s",
4754                          checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4755                          checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
4756                          wasShutdown ? "TRUE" : "FALSE")));
4757         ereport(LOG,
4758                         (errmsg("next transaction ID: %u/%u; next OID: %u",
4759                                         checkPoint.nextXidEpoch, checkPoint.nextXid,
4760                                         checkPoint.nextOid)));
4761         ereport(LOG,
4762                         (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4763                                         checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4764         if (!TransactionIdIsNormal(checkPoint.nextXid))
4765                 ereport(PANIC,
4766                                 (errmsg("invalid next transaction ID")));
4767
4768         ShmemVariableCache->nextXid = checkPoint.nextXid;
4769         ShmemVariableCache->nextOid = checkPoint.nextOid;
4770         ShmemVariableCache->oidCount = 0;
4771         MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4772
4773         /*
4774          * We must replay WAL entries using the same TimeLineID they were created
4775          * under, so temporarily adopt the TLI indicated by the checkpoint (see
4776          * also xlog_redo()).
4777          */
4778         ThisTimeLineID = checkPoint.ThisTimeLineID;
4779
4780         RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4781
4782         if (XLByteLT(RecPtr, checkPoint.redo))
4783                 ereport(PANIC,
4784                                 (errmsg("invalid redo in checkpoint record")));
4785         if (checkPoint.undo.xrecoff == 0)
4786                 checkPoint.undo = RecPtr;
4787
4788         /*
4789          * Check whether we need to force recovery from WAL.  If it appears to
4790          * have been a clean shutdown and we did not have a recovery.conf file,
4791          * then assume no recovery needed.
4792          */
4793         if (XLByteLT(checkPoint.undo, RecPtr) ||
4794                 XLByteLT(checkPoint.redo, RecPtr))
4795         {
4796                 if (wasShutdown)
4797                         ereport(PANIC,
4798                                 (errmsg("invalid redo/undo record in shutdown checkpoint")));
4799                 InRecovery = true;
4800         }
4801         else if (ControlFile->state != DB_SHUTDOWNED)
4802                 InRecovery = true;
4803         else if (InArchiveRecovery)
4804         {
4805                 /* force recovery due to presence of recovery.conf */
4806                 InRecovery = true;
4807         }
4808
4809         /* REDO */
4810         if (InRecovery)
4811         {
4812                 int                     rmid;
4813
4814                 /*
4815                  * Update pg_control to show that we are recovering and to show
4816                  * the selected checkpoint as the place we are starting from.
4817                  * We also mark pg_control with any minimum recovery stop point
4818                  * obtained from a backup history file.
4819                  */
4820                 if (InArchiveRecovery)
4821                 {
4822                         ereport(LOG,
4823                                         (errmsg("automatic recovery in progress")));
4824                         ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4825                 }
4826                 else
4827                 {
4828                         ereport(LOG,
4829                                         (errmsg("database system was not properly shut down; "
4830                                                         "automatic recovery in progress")));
4831                         ControlFile->state = DB_IN_CRASH_RECOVERY;
4832                 }
4833                 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4834                 ControlFile->checkPoint = checkPointLoc;
4835                 ControlFile->checkPointCopy = checkPoint;
4836                 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4837                         ControlFile->minRecoveryPoint = minRecoveryLoc;
4838                 ControlFile->time = time(NULL);
4839                 UpdateControlFile();
4840
4841                 /*
4842                  * If there was a backup label file, it's done its job and the
4843                  * info has now been propagated into pg_control.  We must get rid of
4844                  * the label file so that if we crash during recovery, we'll pick up
4845                  * at the latest recovery restartpoint instead of going all the way
4846                  * back to the backup start point.  It seems prudent though to just
4847                  * rename the file out of the way rather than delete it completely.
4848                  */
4849                 if (haveBackupLabel)
4850                 {
4851                         unlink(BACKUP_LABEL_OLD);
4852                         if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4853                                 ereport(FATAL,
4854                                                 (errcode_for_file_access(),
4855                                                  errmsg("could not rename file \"%s\" to \"%s\": %m",
4856                                                                 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4857                 }
4858
4859                 /* Start up the recovery environment */
4860                 XLogInitRelationCache();
4861
4862                 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4863                 {
4864                         if (RmgrTable[rmid].rm_startup != NULL)
4865                                 RmgrTable[rmid].rm_startup();
4866                 }
4867
4868                 /*
4869                  * Find the first record that logically follows the checkpoint --- it
4870                  * might physically precede it, though.
4871                  */
4872                 if (XLByteLT(checkPoint.redo, RecPtr))
4873                 {
4874                         /* back up to find the record */
4875                         record = ReadRecord(&(checkPoint.redo), PANIC);
4876                 }
4877                 else
4878                 {
4879                         /* just have to read next record after CheckPoint */
4880                         record = ReadRecord(NULL, LOG);
4881                 }
4882
4883                 if (record != NULL)
4884                 {
4885                         bool            recoveryContinue = true;
4886                         bool            recoveryApply = true;
4887                         ErrorContextCallback    errcontext;
4888
4889                         InRedo = true;
4890                         ereport(LOG,
4891                                         (errmsg("redo starts at %X/%X",
4892                                                         ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4893
4894                         /*
4895                          * main redo apply loop
4896                          */
4897                         do
4898                         {
4899 #ifdef WAL_DEBUG
4900                                 if (XLOG_DEBUG)
4901                                 {
4902                                         StringInfoData  buf;
4903
4904                                         initStringInfo(&buf);
4905                                         appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4906                                                         ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4907                                                         EndRecPtr.xlogid, EndRecPtr.xrecoff);
4908                                         xlog_outrec(&buf, record);
4909                                         appendStringInfo(&buf, " - ");
4910                                         RmgrTable[record->xl_rmid].rm_desc(&buf,
4911                                                                                                            record->xl_info,
4912                                                                                                            XLogRecGetData(record));
4913                                         elog(LOG, "%s", buf.data);
4914                                         pfree(buf.data);
4915                                 }
4916 #endif
4917
4918                                 /*
4919                                  * Have we reached our recovery target?
4920                                  */
4921                                 if (recoveryStopsHere(record, &recoveryApply))
4922                                 {
4923                                         needNewTimeLine = true;         /* see below */
4924                                         recoveryContinue = false;
4925                                         if (!recoveryApply)
4926                                                 break;
4927                                 }
4928
4929                                 /* Setup error traceback support for ereport() */
4930                                 errcontext.callback = rm_redo_error_callback;
4931                                 errcontext.arg = (void *) record;
4932                                 errcontext.previous = error_context_stack;
4933                                 error_context_stack = &errcontext;
4934
4935                                 /* nextXid must be beyond record's xid */
4936                                 if (TransactionIdFollowsOrEquals(record->xl_xid,
4937                                                                                                  ShmemVariableCache->nextXid))
4938                                 {
4939                                         ShmemVariableCache->nextXid = record->xl_xid;
4940                                         TransactionIdAdvance(ShmemVariableCache->nextXid);
4941                                 }
4942
4943                                 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4944                                         RestoreBkpBlocks(record, EndRecPtr);
4945
4946                                 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4947
4948                                 /* Pop the error context stack */
4949                                 error_context_stack = errcontext.previous;
4950
4951                                 LastRec = ReadRecPtr;
4952
4953                                 record = ReadRecord(NULL, LOG);
4954                         } while (record != NULL && recoveryContinue);
4955
4956                         /*
4957                          * end of main redo apply loop
4958                          */
4959
4960                         ereport(LOG,
4961                                         (errmsg("redo done at %X/%X",
4962                                                         ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4963                         InRedo = false;
4964                 }
4965                 else
4966                 {
4967                         /* there are no WAL records following the checkpoint */
4968                         ereport(LOG,
4969                                         (errmsg("redo is not required")));
4970                 }
4971         }
4972
4973         /*
4974          * Re-fetch the last valid or last applied record, so we can identify the
4975          * exact endpoint of what we consider the valid portion of WAL.
4976          */
4977         record = ReadRecord(&LastRec, PANIC);
4978         EndOfLog = EndRecPtr;
4979         XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4980
4981         /*
4982          * Complain if we did not roll forward far enough to render the backup
4983          * dump consistent.
4984          */
4985         if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
4986         {
4987                 if (needNewTimeLine)    /* stopped because of stop request */
4988                         ereport(FATAL,
4989                                         (errmsg("requested recovery stop point is before end time of backup dump")));
4990                 else
4991                         /* ran off end of WAL */
4992                         ereport(FATAL,
4993                                         (errmsg("WAL ends before end time of backup dump")));
4994         }
4995
4996         /*
4997          * Consider whether we need to assign a new timeline ID.
4998          *
4999          * If we stopped short of the end of WAL during recovery, then we are
5000          * generating a new timeline and must assign it a unique new ID.
5001          * Otherwise, we can just extend the timeline we were in when we ran out
5002          * of WAL.
5003          */
5004         if (needNewTimeLine)
5005         {
5006                 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5007                 ereport(LOG,
5008                                 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5009                 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5010                                                          curFileTLI, endLogId, endLogSeg);
5011         }
5012
5013         /* Save the selected TimeLineID in shared memory, too */
5014         XLogCtl->ThisTimeLineID = ThisTimeLineID;
5015
5016         /*
5017          * We are now done reading the old WAL.  Turn off archive fetching if it
5018          * was active, and make a writable copy of the last WAL segment. (Note
5019          * that we also have a copy of the last block of the old WAL in readBuf;
5020          * we will use that below.)
5021          */
5022         if (InArchiveRecovery)
5023                 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5024
5025         /*
5026          * Prepare to write WAL starting at EndOfLog position, and init xlog
5027          * buffer cache using the block containing the last record from the
5028          * previous incarnation.
5029          */
5030         openLogId = endLogId;
5031         openLogSeg = endLogSeg;
5032         openLogFile = XLogFileOpen(openLogId, openLogSeg);
5033         openLogOff = 0;
5034         ControlFile->logId = openLogId;
5035         ControlFile->logSeg = openLogSeg + 1;
5036         Insert = &XLogCtl->Insert;
5037         Insert->PrevRecord = LastRec;
5038         XLogCtl->xlblocks[0].xlogid = openLogId;
5039         XLogCtl->xlblocks[0].xrecoff =
5040                 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5041
5042         /*
5043          * Tricky point here: readBuf contains the *last* block that the LastRec
5044          * record spans, not the one it starts in.      The last block is indeed the
5045          * one we want to use.
5046          */
5047         Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5048         memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5049         Insert->currpos = (char *) Insert->currpage +
5050                 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5051
5052         LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5053
5054         XLogCtl->Write.LogwrtResult = LogwrtResult;
5055         Insert->LogwrtResult = LogwrtResult;
5056         XLogCtl->LogwrtResult = LogwrtResult;
5057
5058         XLogCtl->LogwrtRqst.Write = EndOfLog;
5059         XLogCtl->LogwrtRqst.Flush = EndOfLog;
5060
5061         freespace = INSERT_FREESPACE(Insert);
5062         if (freespace > 0)
5063         {
5064                 /* Make sure rest of page is zero */
5065                 MemSet(Insert->currpos, 0, freespace);
5066                 XLogCtl->Write.curridx = 0;
5067         }
5068         else
5069         {
5070                 /*
5071                  * Whenever Write.LogwrtResult points to exactly the end of a page,
5072                  * Write.curridx must point to the *next* page (see XLogWrite()).
5073                  *
5074                  * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5075                  * this is sufficient.  The first actual attempt to insert a log
5076                  * record will advance the insert state.
5077                  */
5078                 XLogCtl->Write.curridx = NextBufIdx(0);
5079         }
5080
5081         /* Pre-scan prepared transactions to find out the range of XIDs present */
5082         oldestActiveXID = PrescanPreparedTransactions();
5083
5084         if (InRecovery)
5085         {
5086                 int                     rmid;
5087
5088                 /*
5089                  * Allow resource managers to do any required cleanup.
5090                  */
5091                 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5092                 {
5093                         if (RmgrTable[rmid].rm_cleanup != NULL)
5094                                 RmgrTable[rmid].rm_cleanup();
5095                 }
5096
5097                 /*
5098                  * Check to see if the XLOG sequence contained any unresolved
5099                  * references to uninitialized pages.
5100                  */
5101                 XLogCheckInvalidPages();
5102
5103                 /*
5104                  * Reset pgstat data, because it may be invalid after recovery.
5105                  */
5106                 pgstat_reset_all();
5107
5108                 /*
5109                  * Perform a checkpoint to update all our recovery activity to disk.
5110                  *
5111                  * Note that we write a shutdown checkpoint rather than an on-line
5112                  * one. This is not particularly critical, but since we may be
5113                  * assigning a new TLI, using a shutdown checkpoint allows us to have
5114                  * the rule that TLI only changes in shutdown checkpoints, which
5115                  * allows some extra error checking in xlog_redo.
5116                  */
5117                 CreateCheckPoint(true, true);
5118
5119                 /*
5120                  * Close down recovery environment
5121                  */
5122                 XLogCloseRelationCache();
5123         }
5124
5125         /*
5126          * Preallocate additional log files, if wanted.
5127          */
5128         (void) PreallocXlogFiles(EndOfLog);
5129
5130         /*
5131          * Okay, we're officially UP.
5132          */
5133         InRecovery = false;
5134
5135         ControlFile->state = DB_IN_PRODUCTION;
5136         ControlFile->time = time(NULL);
5137         UpdateControlFile();
5138
5139         /* start the archive_timeout timer running */
5140         XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5141
5142         /* initialize shared-memory copy of latest checkpoint XID/epoch */
5143         XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5144         XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5145
5146         /* Start up the commit log and related stuff, too */
5147         StartupCLOG();
5148         StartupSUBTRANS(oldestActiveXID);
5149         StartupMultiXact();
5150
5151         /* Reload shared-memory state for prepared transactions */
5152         RecoverPreparedTransactions();
5153
5154         ereport(LOG,
5155                         (errmsg("database system is ready")));
5156         CritSectionCount--;
5157
5158         /* Shut down readFile facility, free space */
5159         if (readFile >= 0)
5160         {
5161                 close(readFile);
5162                 readFile = -1;
5163         }
5164         if (readBuf)
5165         {
5166                 free(readBuf);
5167                 readBuf = NULL;
5168         }
5169         if (readRecordBuf)
5170         {
5171                 free(readRecordBuf);
5172                 readRecordBuf = NULL;
5173                 readRecordBufSize = 0;
5174         }
5175 }
5176
5177 /*
5178  * Subroutine to try to fetch and validate a prior checkpoint record.
5179  *
5180  * whichChkpt identifies the checkpoint (merely for reporting purposes).
5181  * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5182  */
5183 static XLogRecord *
5184 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5185 {
5186         XLogRecord *record;
5187
5188         if (!XRecOffIsValid(RecPtr.xrecoff))
5189         {
5190                 switch (whichChkpt)
5191                 {
5192                         case 1:
5193                                 ereport(LOG,
5194                                 (errmsg("invalid primary checkpoint link in control file")));
5195                                 break;
5196                         case 2:
5197                                 ereport(LOG,
5198                                                 (errmsg("invalid secondary checkpoint link in control file")));
5199                                 break;
5200                         default:
5201                                 ereport(LOG,
5202                                    (errmsg("invalid checkpoint link in backup_label file")));
5203                                 break;
5204                 }
5205                 return NULL;
5206         }
5207
5208         record = ReadRecord(&RecPtr, LOG);
5209
5210         if (record == NULL)
5211         {
5212                 switch (whichChkpt)
5213                 {
5214                         case 1:
5215                                 ereport(LOG,
5216                                                 (errmsg("invalid primary checkpoint record")));
5217                                 break;
5218                         case 2:
5219                                 ereport(LOG,
5220                                                 (errmsg("invalid secondary checkpoint record")));
5221                                 break;
5222                         default:
5223                                 ereport(LOG,
5224                                                 (errmsg("invalid checkpoint record")));
5225                                 break;
5226                 }
5227                 return NULL;
5228         }
5229         if (record->xl_rmid != RM_XLOG_ID)
5230         {
5231                 switch (whichChkpt)
5232                 {
5233                         case 1:
5234                                 ereport(LOG,
5235                                                 (errmsg("invalid resource manager ID in primary checkpoint record")));
5236                                 break;
5237                         case 2:
5238                                 ereport(LOG,
5239                                                 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5240                                 break;
5241                         default:
5242                                 ereport(LOG,
5243                                 (errmsg("invalid resource manager ID in checkpoint record")));
5244                                 break;
5245                 }
5246                 return NULL;
5247         }
5248         if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5249                 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5250         {
5251                 switch (whichChkpt)
5252                 {
5253                         case 1:
5254                                 ereport(LOG,
5255                                    (errmsg("invalid xl_info in primary checkpoint record")));
5256                                 break;
5257                         case 2:
5258                                 ereport(LOG,
5259                                  (errmsg("invalid xl_info in secondary checkpoint record")));
5260                                 break;
5261                         default:
5262                                 ereport(LOG,
5263                                                 (errmsg("invalid xl_info in checkpoint record")));
5264                                 break;
5265                 }
5266                 return NULL;
5267         }
5268         if (record->xl_len != sizeof(CheckPoint) ||
5269                 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5270         {
5271                 switch (whichChkpt)
5272                 {
5273                         case 1:
5274                                 ereport(LOG,
5275                                         (errmsg("invalid length of primary checkpoint record")));
5276                                 break;
5277                         case 2:
5278                                 ereport(LOG,
5279                                   (errmsg("invalid length of secondary checkpoint record")));
5280                                 break;
5281                         default:
5282                                 ereport(LOG,
5283                                                 (errmsg("invalid length of checkpoint record")));
5284                                 break;
5285                 }
5286                 return NULL;
5287         }
5288         return record;
5289 }
5290
5291 /*
5292  * This must be called during startup of a backend process, except that
5293  * it need not be called in a standalone backend (which does StartupXLOG
5294  * instead).  We need to initialize the local copies of ThisTimeLineID and
5295  * RedoRecPtr.
5296  *
5297  * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5298  * process's copies of ThisTimeLineID and RedoRecPtr valid too.  This was
5299  * unnecessary however, since the postmaster itself never touches XLOG anyway.
5300  */
5301 void
5302 InitXLOGAccess(void)
5303 {
5304         /* ThisTimeLineID doesn't change so we need no lock to copy it */
5305         ThisTimeLineID = XLogCtl->ThisTimeLineID;
5306         /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5307         (void) GetRedoRecPtr();
5308 }
5309
5310 /*
5311  * Once spawned, a backend may update its local RedoRecPtr from
5312  * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5313  * to do so.  This is done in XLogInsert() or GetRedoRecPtr().
5314  */
5315 XLogRecPtr
5316 GetRedoRecPtr(void)
5317 {
5318         /* use volatile pointer to prevent code rearrangement */
5319         volatile XLogCtlData *xlogctl = XLogCtl;
5320
5321         SpinLockAcquire(&xlogctl->info_lck);
5322         Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5323         RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5324         SpinLockRelease(&xlogctl->info_lck);
5325
5326         return RedoRecPtr;
5327 }
5328
5329 /*
5330  * Get the time of the last xlog segment switch
5331  */
5332 time_t
5333 GetLastSegSwitchTime(void)
5334 {
5335         time_t          result;
5336
5337         /* Need WALWriteLock, but shared lock is sufficient */
5338         LWLockAcquire(WALWriteLock, LW_SHARED);
5339         result = XLogCtl->Write.lastSegSwitchTime;
5340         LWLockRelease(WALWriteLock);
5341
5342         return result;
5343 }
5344
5345 /*
5346  * GetRecentNextXid - get the nextXid value saved by the most recent checkpoint
5347  *
5348  * This is currently used only by the autovacuum daemon.  To check for
5349  * impending XID wraparound, autovac needs an approximate idea of the current
5350  * XID counter, and it needs it before choosing which DB to attach to, hence
5351  * before it sets up a PGPROC, hence before it can take any LWLocks.  But it
5352  * has attached to shared memory, and so we can let it reach into the shared
5353  * ControlFile structure and pull out the last checkpoint nextXID.
5354  *
5355  * Since we don't take any sort of lock, we have to assume that reading a
5356  * TransactionId is atomic ... but that assumption is made elsewhere, too,
5357  * and in any case the worst possible consequence of a bogus result is that
5358  * autovac issues an unnecessary database-wide VACUUM.
5359  *
5360  * Note: we could also choose to read ShmemVariableCache->nextXid in an
5361  * unlocked fashion, thus getting a more up-to-date result; but since that
5362  * changes far more frequently than the controlfile checkpoint copy, it would
5363  * pose a far higher risk of bogus result if we did have a nonatomic-read
5364  * problem.
5365  *
5366  * A (theoretically) completely safe answer is to read the actual pg_control
5367  * file into local process memory, but that certainly seems like overkill.
5368  */
5369 TransactionId
5370 GetRecentNextXid(void)
5371 {
5372         return ControlFile->checkPointCopy.nextXid;
5373 }
5374
5375 /*
5376  * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5377  *
5378  * This is exported for use by code that would like to have 64-bit XIDs.
5379  * We don't really support such things, but all XIDs within the system
5380  * can be presumed "close to" the result, and thus the epoch associated
5381  * with them can be determined.
5382  */
5383 void
5384 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5385 {
5386         uint32                  ckptXidEpoch;
5387         TransactionId   ckptXid;
5388         TransactionId   nextXid;
5389
5390         /* Must read checkpoint info first, else have race condition */
5391         {
5392                 /* use volatile pointer to prevent code rearrangement */
5393                 volatile XLogCtlData *xlogctl = XLogCtl;
5394
5395                 SpinLockAcquire(&xlogctl->info_lck);
5396                 ckptXidEpoch = xlogctl->ckptXidEpoch;
5397                 ckptXid = xlogctl->ckptXid;
5398                 SpinLockRelease(&xlogctl->info_lck);
5399         }
5400
5401         /* Now fetch current nextXid */
5402         nextXid = ReadNewTransactionId();
5403
5404         /*
5405          * nextXid is certainly logically later than ckptXid.  So if it's
5406          * numerically less, it must have wrapped into the next epoch.
5407          */
5408         if (nextXid < ckptXid)
5409                 ckptXidEpoch++;
5410
5411         *xid = nextXid;
5412         *epoch = ckptXidEpoch;
5413 }
5414
5415 /*
5416  * This must be called ONCE during postmaster or standalone-backend shutdown
5417  */
5418 void
5419 ShutdownXLOG(int code, Datum arg)
5420 {
5421         ereport(LOG,
5422                         (errmsg("shutting down")));
5423
5424         CritSectionCount++;
5425         CreateCheckPoint(true, true);
5426         ShutdownCLOG();
5427         ShutdownSUBTRANS();
5428         ShutdownMultiXact();
5429         CritSectionCount--;
5430
5431         ereport(LOG,
5432                         (errmsg("database system is shut down")));
5433 }
5434
5435 /*
5436  * Perform a checkpoint --- either during shutdown, or on-the-fly
5437  *
5438  * If force is true, we force a checkpoint regardless of whether any XLOG
5439  * activity has occurred since the last one.
5440  */
5441 void
5442 CreateCheckPoint(bool shutdown, bool force)
5443 {
5444         CheckPoint      checkPoint;
5445         XLogRecPtr      recptr;
5446         XLogCtlInsert *Insert = &XLogCtl->Insert;
5447         XLogRecData rdata;
5448         uint32          freespace;
5449         uint32          _logId;
5450         uint32          _logSeg;
5451         int                     nsegsadded = 0;
5452         int                     nsegsremoved = 0;
5453         int                     nsegsrecycled = 0;
5454
5455         /*
5456          * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5457          * (This is just pro forma, since in the present system structure there is
5458          * only one process that is allowed to issue checkpoints at any given
5459          * time.)
5460          */
5461         LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5462
5463         /*
5464          * Use a critical section to force system panic if we have trouble.
5465          */
5466         START_CRIT_SECTION();
5467
5468         if (shutdown)
5469         {
5470                 ControlFile->state = DB_SHUTDOWNING;
5471                 ControlFile->time = time(NULL);
5472                 UpdateControlFile();
5473         }
5474
5475         MemSet(&checkPoint, 0, sizeof(checkPoint));
5476         checkPoint.ThisTimeLineID = ThisTimeLineID;
5477         checkPoint.time = time(NULL);
5478
5479         /*
5480          * We must hold CheckpointStartLock while determining the checkpoint REDO
5481          * pointer.  This ensures that any concurrent transaction commits will be
5482          * either not yet logged, or logged and recorded in pg_clog. See notes in
5483          * RecordTransactionCommit().
5484          */
5485         LWLockAcquire(CheckpointStartLock, LW_EXCLUSIVE);
5486
5487         /* And we need WALInsertLock too */
5488         LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5489
5490         /*
5491          * If this isn't a shutdown or forced checkpoint, and we have not inserted
5492          * any XLOG records since the start of the last checkpoint, skip the
5493          * checkpoint.  The idea here is to avoid inserting duplicate checkpoints
5494          * when the system is idle. That wastes log space, and more importantly it
5495          * exposes us to possible loss of both current and previous checkpoint
5496          * records if the machine crashes just as we're writing the update.
5497          * (Perhaps it'd make even more sense to checkpoint only when the previous
5498          * checkpoint record is in a different xlog page?)
5499          *
5500          * We have to make two tests to determine that nothing has happened since
5501          * the start of the last checkpoint: current insertion point must match
5502          * the end of the last checkpoint record, and its redo pointer must point
5503          * to itself.
5504          */
5505         if (!shutdown && !force)
5506         {
5507                 XLogRecPtr      curInsert;
5508
5509                 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5510                 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5511                         curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5512                         MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5513                         ControlFile->checkPoint.xlogid ==
5514                         ControlFile->checkPointCopy.redo.xlogid &&
5515                         ControlFile->checkPoint.xrecoff ==
5516                         ControlFile->checkPointCopy.redo.xrecoff)
5517                 {
5518                         LWLockRelease(WALInsertLock);
5519                         LWLockRelease(CheckpointStartLock);
5520                         LWLockRelease(CheckpointLock);
5521                         END_CRIT_SECTION();
5522                         return;
5523                 }
5524         }
5525
5526         /*
5527          * Compute new REDO record ptr = location of next XLOG record.
5528          *
5529          * NB: this is NOT necessarily where the checkpoint record itself will be,
5530          * since other backends may insert more XLOG records while we're off doing
5531          * the buffer flush work.  Those XLOG records are logically after the
5532          * checkpoint, even though physically before it.  Got that?
5533          */
5534         freespace = INSERT_FREESPACE(Insert);
5535         if (freespace < SizeOfXLogRecord)
5536         {
5537                 (void) AdvanceXLInsertBuffer(false);
5538                 /* OK to ignore update return flag, since we will do flush anyway */
5539                 freespace = INSERT_FREESPACE(Insert);
5540         }
5541         INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5542
5543         /*
5544          * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5545          * must be done while holding the insert lock AND the info_lck.
5546          *
5547          * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5548          * pointing past where it really needs to point.  This is okay; the only
5549          * consequence is that XLogInsert might back up whole buffers that it
5550          * didn't really need to.  We can't postpone advancing RedoRecPtr because
5551          * XLogInserts that happen while we are dumping buffers must assume that
5552          * their buffer changes are not included in the checkpoint.
5553          */
5554         {
5555                 /* use volatile pointer to prevent code rearrangement */
5556                 volatile XLogCtlData *xlogctl = XLogCtl;
5557
5558                 SpinLockAcquire(&xlogctl->info_lck);
5559                 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5560                 SpinLockRelease(&xlogctl->info_lck);
5561         }
5562
5563         /*
5564          * Now we can release insert lock and checkpoint start lock, allowing
5565          * other xacts to proceed even while we are flushing disk buffers.
5566          */
5567         LWLockRelease(WALInsertLock);
5568
5569         LWLockRelease(CheckpointStartLock);
5570
5571         if (!shutdown)
5572                 ereport(DEBUG2,
5573                                 (errmsg("checkpoint starting")));
5574
5575         /*
5576          * Get the other info we need for the checkpoint record.
5577          */
5578         LWLockAcquire(XidGenLock, LW_SHARED);
5579         checkPoint.nextXid = ShmemVariableCache->nextXid;
5580         LWLockRelease(XidGenLock);
5581
5582         /* Increase XID epoch if we've wrapped around since last checkpoint */
5583         checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5584         if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5585                 checkPoint.nextXidEpoch++;
5586
5587         LWLockAcquire(OidGenLock, LW_SHARED);
5588         checkPoint.nextOid = ShmemVariableCache->nextOid;
5589         if (!shutdown)
5590                 checkPoint.nextOid += ShmemVariableCache->oidCount;
5591         LWLockRelease(OidGenLock);
5592
5593         MultiXactGetCheckptMulti(shutdown,
5594                                                          &checkPoint.nextMulti,
5595                                                          &checkPoint.nextMultiOffset);
5596
5597         /*
5598          * Having constructed the checkpoint record, ensure all shmem disk buffers
5599          * and commit-log buffers are flushed to disk.
5600          *
5601          * This I/O could fail for various reasons.  If so, we will fail to
5602          * complete the checkpoint, but there is no reason to force a system
5603          * panic. Accordingly, exit critical section while doing it.  (If we are
5604          * doing a shutdown checkpoint, we probably *should* panic --- but that
5605          * will happen anyway because we'll still be inside the critical section
5606          * established by ShutdownXLOG.)
5607          */
5608         END_CRIT_SECTION();
5609
5610         CheckPointGuts(checkPoint.redo);
5611
5612         START_CRIT_SECTION();
5613
5614         /*
5615          * Now insert the checkpoint record into XLOG.
5616          */
5617         rdata.data = (char *) (&checkPoint);
5618         rdata.len = sizeof(checkPoint);
5619         rdata.buffer = InvalidBuffer;
5620         rdata.next = NULL;
5621
5622         recptr = XLogInsert(RM_XLOG_ID,
5623                                                 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5624                                                 XLOG_CHECKPOINT_ONLINE,
5625                                                 &rdata);
5626
5627         XLogFlush(recptr);
5628
5629         /*
5630          * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5631          * = end of actual checkpoint record.
5632          */
5633         if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5634                 ereport(PANIC,
5635                                 (errmsg("concurrent transaction log activity while database system is shutting down")));
5636
5637         /*
5638          * Select point at which we can truncate the log, which we base on the
5639          * prior checkpoint's earliest info.
5640          */
5641         XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5642
5643         /*
5644          * Update the control file.
5645          */
5646         LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5647         if (shutdown)
5648                 ControlFile->state = DB_SHUTDOWNED;
5649         ControlFile->prevCheckPoint = ControlFile->checkPoint;
5650         ControlFile->checkPoint = ProcLastRecPtr;
5651         ControlFile->checkPointCopy = checkPoint;
5652         ControlFile->time = time(NULL);
5653         UpdateControlFile();
5654         LWLockRelease(ControlFileLock);
5655
5656         /* Update shared-memory copy of checkpoint XID/epoch */
5657         {
5658                 /* use volatile pointer to prevent code rearrangement */
5659                 volatile XLogCtlData *xlogctl = XLogCtl;
5660
5661                 SpinLockAcquire(&xlogctl->info_lck);
5662                 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5663                 xlogctl->ckptXid = checkPoint.nextXid;
5664                 SpinLockRelease(&xlogctl->info_lck);
5665         }
5666
5667         /*
5668          * We are now done with critical updates; no need for system panic if we
5669          * have trouble while fooling with offline log segments.
5670          */
5671         END_CRIT_SECTION();
5672
5673         /*
5674          * Delete offline log files (those no longer needed even for previous
5675          * checkpoint).
5676          */
5677         if (_logId || _logSeg)
5678         {
5679                 PrevLogSeg(_logId, _logSeg);
5680                 MoveOfflineLogs(_logId, _logSeg, recptr,
5681                                                 &nsegsremoved, &nsegsrecycled);
5682         }
5683
5684         /*
5685          * Make more log segments if needed.  (Do this after deleting offline log
5686          * segments, to avoid having peak disk space usage higher than necessary.)
5687          */
5688         if (!shutdown)
5689                 nsegsadded = PreallocXlogFiles(recptr);
5690
5691         /*
5692          * Truncate pg_subtrans if possible.  We can throw away all data before
5693          * the oldest XMIN of any running transaction.  No future transaction will
5694          * attempt to reference any pg_subtrans entry older than that (see Asserts
5695          * in subtrans.c).      During recovery, though, we mustn't do this because
5696          * StartupSUBTRANS hasn't been called yet.
5697          */
5698         if (!InRecovery)
5699                 TruncateSUBTRANS(GetOldestXmin(true, false));
5700
5701         if (!shutdown)
5702                 ereport(DEBUG2,
5703                                 (errmsg("checkpoint complete; %d transaction log file(s) added, %d removed, %d recycled",
5704                                                 nsegsadded, nsegsremoved, nsegsrecycled)));
5705
5706         LWLockRelease(CheckpointLock);
5707 }
5708
5709 /*
5710  * Flush all data in shared memory to disk, and fsync
5711  *
5712  * This is the common code shared between regular checkpoints and
5713  * recovery restartpoints.
5714  */
5715 static void
5716 CheckPointGuts(XLogRecPtr checkPointRedo)
5717 {
5718         CheckPointCLOG();
5719         CheckPointSUBTRANS();
5720         CheckPointMultiXact();
5721         FlushBufferPool();     /* performs all required fsyncs */
5722         /* We deliberately delay 2PC checkpointing as long as possible */
5723         CheckPointTwoPhase(checkPointRedo);
5724 }
5725
5726 /*
5727  * Set a recovery restart point if appropriate
5728  *
5729  * This is similar to CreateCheckpoint, but is used during WAL recovery
5730  * to establish a point from which recovery can roll forward without
5731  * replaying the entire recovery log.  This function is called each time
5732  * a checkpoint record is read from XLOG; it must determine whether a
5733  * restartpoint is needed or not.
5734  */
5735 static void
5736 RecoveryRestartPoint(const CheckPoint *checkPoint)
5737 {
5738         int             elapsed_secs;
5739         int     rmid;
5740
5741         /*
5742          * Do nothing if the elapsed time since the last restartpoint is less
5743          * than half of checkpoint_timeout.  (We use a value less than
5744          * checkpoint_timeout so that variations in the timing of checkpoints on
5745          * the master, or speed of transmission of WAL segments to a slave, won't
5746          * make the slave skip a restartpoint once it's synced with the master.)
5747          * Checking true elapsed time keeps us from doing restartpoints too often
5748          * while rapidly scanning large amounts of WAL.
5749          */
5750         elapsed_secs = time(NULL) - ControlFile->time;
5751         if (elapsed_secs < CheckPointTimeout / 2)
5752                 return;
5753
5754         /*
5755          * Is it safe to checkpoint?  We must ask each of the resource managers
5756          * whether they have any partial state information that might prevent a
5757          * correct restart from this point.  If so, we skip this opportunity, but
5758          * return at the next checkpoint record for another try.
5759          */
5760         for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5761         {
5762                 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5763                         if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5764                                 return;
5765         }
5766
5767         /*
5768          * OK, force data out to disk
5769          */
5770         CheckPointGuts(checkPoint->redo);
5771
5772         /*
5773          * Update pg_control so that any subsequent crash will restart from
5774          * this checkpoint.  Note: ReadRecPtr gives the XLOG address of the
5775          * checkpoint record itself.
5776          */
5777         ControlFile->prevCheckPoint = ControlFile->checkPoint;
5778         ControlFile->checkPoint = ReadRecPtr;
5779         ControlFile->checkPointCopy = *checkPoint;
5780         ControlFile->time = time(NULL);
5781         UpdateControlFile();
5782
5783         ereport(DEBUG2,
5784                         (errmsg("recovery restart point at %X/%X",
5785                                         checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5786 }
5787
5788 /*
5789  * Write a NEXTOID log record
5790  */
5791 void
5792 XLogPutNextOid(Oid nextOid)
5793 {
5794         XLogRecData rdata;
5795
5796         rdata.data = (char *) (&nextOid);
5797         rdata.len = sizeof(Oid);
5798         rdata.buffer = InvalidBuffer;
5799         rdata.next = NULL;
5800         (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5801
5802         /*
5803          * We need not flush the NEXTOID record immediately, because any of the
5804          * just-allocated OIDs could only reach disk as part of a tuple insert or
5805          * update that would have its own XLOG record that must follow the NEXTOID
5806          * record.      Therefore, the standard buffer LSN interlock applied to those
5807          * records will ensure no such OID reaches disk before the NEXTOID record
5808          * does.
5809          */
5810 }
5811
5812 /*
5813  * Write an XLOG SWITCH record.
5814  *
5815  * Here we just blindly issue an XLogInsert request for the record.
5816  * All the magic happens inside XLogInsert.
5817  *
5818  * The return value is either the end+1 address of the switch record,
5819  * or the end+1 address of the prior segment if we did not need to
5820  * write a switch record because we are already at segment start.
5821  */
5822 XLogRecPtr
5823 RequestXLogSwitch(void)
5824 {
5825         XLogRecPtr      RecPtr;
5826         XLogRecData rdata;
5827
5828         /* XLOG SWITCH, alone among xlog record types, has no data */
5829         rdata.buffer = InvalidBuffer;
5830         rdata.data = NULL;
5831         rdata.len = 0;
5832         rdata.next = NULL;
5833
5834         RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5835
5836         return RecPtr;
5837 }
5838
5839 /*
5840  * XLOG resource manager's routines
5841  */
5842 void
5843 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5844 {
5845         uint8           info = record->xl_info & ~XLR_INFO_MASK;
5846
5847         if (info == XLOG_NEXTOID)
5848         {
5849                 Oid                     nextOid;
5850
5851                 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5852                 if (ShmemVariableCache->nextOid < nextOid)
5853                 {
5854                         ShmemVariableCache->nextOid = nextOid;
5855                         ShmemVariableCache->oidCount = 0;
5856                 }
5857         }
5858         else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5859         {
5860                 CheckPoint      checkPoint;
5861
5862                 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5863                 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5864                 ShmemVariableCache->nextXid = checkPoint.nextXid;
5865                 ShmemVariableCache->nextOid = checkPoint.nextOid;
5866                 ShmemVariableCache->oidCount = 0;
5867                 MultiXactSetNextMXact(checkPoint.nextMulti,
5868                                                           checkPoint.nextMultiOffset);
5869
5870                 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5871                 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5872                 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5873
5874                 /*
5875                  * TLI may change in a shutdown checkpoint, but it shouldn't decrease
5876                  */
5877                 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5878                 {
5879                         if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5880                                 !list_member_int(expectedTLIs,
5881                                                                  (int) checkPoint.ThisTimeLineID))
5882                                 ereport(PANIC,
5883                                                 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5884                                                                 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5885                         /* Following WAL records should be run with new TLI */
5886                         ThisTimeLineID = checkPoint.ThisTimeLineID;
5887                 }
5888
5889                 RecoveryRestartPoint(&checkPoint);
5890         }
5891         else if (info == XLOG_CHECKPOINT_ONLINE)
5892         {
5893                 CheckPoint      checkPoint;
5894
5895                 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5896                 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5897                 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5898                                                                   checkPoint.nextXid))
5899                         ShmemVariableCache->nextXid = checkPoint.nextXid;
5900                 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5901                 {
5902                         ShmemVariableCache->nextOid = checkPoint.nextOid;
5903                         ShmemVariableCache->oidCount = 0;
5904                 }
5905                 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
5906                                                                   checkPoint.nextMultiOffset);
5907
5908                 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5909                 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5910                 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5911
5912                 /* TLI should not change in an on-line checkpoint */
5913                 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5914                         ereport(PANIC,
5915                                         (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5916                                                         checkPoint.ThisTimeLineID, ThisTimeLineID)));
5917
5918                 RecoveryRestartPoint(&checkPoint);
5919         }
5920         else if (info == XLOG_SWITCH)
5921         {
5922                 /* nothing to do here */
5923         }
5924 }
5925
5926 void
5927 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
5928 {
5929         uint8                   info = xl_info & ~XLR_INFO_MASK;
5930
5931         if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5932                 info == XLOG_CHECKPOINT_ONLINE)
5933         {
5934                 CheckPoint *checkpoint = (CheckPoint *) rec;
5935
5936                 appendStringInfo(buf, "checkpoint: redo %X/%X; undo %X/%X; "
5937                                 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
5938                                 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5939                                 checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
5940                                 checkpoint->ThisTimeLineID,
5941                                 checkpoint->nextXidEpoch, checkpoint->nextXid,
5942                                 checkpoint->nextOid,
5943                                 checkpoint->nextMulti,
5944                                 checkpoint->nextMultiOffset,
5945                                 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
5946         }
5947         else if (info == XLOG_NEXTOID)
5948         {
5949                 Oid                     nextOid;
5950
5951                 memcpy(&nextOid, rec, sizeof(Oid));
5952                 appendStringInfo(buf, "nextOid: %u", nextOid);
5953         }
5954         else if (info == XLOG_SWITCH)
5955         {
5956                 appendStringInfo(buf, "xlog switch");
5957         }
5958         else
5959                 appendStringInfo(buf, "UNKNOWN");
5960 }
5961
5962 #ifdef WAL_DEBUG
5963
5964 static void
5965 xlog_outrec(StringInfo buf, XLogRecord *record)
5966 {
5967         int                     i;
5968
5969         appendStringInfo(buf, "prev %X/%X; xid %u",
5970                                          record->xl_prev.xlogid, record->xl_prev.xrecoff,
5971                                          record->xl_xid);
5972
5973         for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
5974         {
5975                 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
5976                         appendStringInfo(buf, "; bkpb%d", i+1);
5977         }
5978
5979         appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
5980 }
5981 #endif   /* WAL_DEBUG */
5982
5983
5984 /*
5985  * GUC support
5986  */
5987 const char *
5988 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
5989 {
5990         int                     new_sync_method;
5991         int                     new_sync_bit;
5992
5993         if (pg_strcasecmp(method, "fsync") == 0)
5994         {
5995                 new_sync_method = SYNC_METHOD_FSYNC;
5996                 new_sync_bit = 0;
5997         }
5998 #ifdef HAVE_FSYNC_WRITETHROUGH
5999         else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
6000         {
6001                 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
6002                 new_sync_bit = 0;
6003         }
6004 #endif
6005 #ifdef HAVE_FDATASYNC
6006         else if (pg_strcasecmp(method, "fdatasync") == 0)
6007         {
6008                 new_sync_method = SYNC_METHOD_FDATASYNC;
6009                 new_sync_bit = 0;
6010         }
6011 #endif
6012 #ifdef OPEN_SYNC_FLAG
6013         else if (pg_strcasecmp(method, "open_sync") == 0)
6014         {
6015                 new_sync_method = SYNC_METHOD_OPEN;
6016                 new_sync_bit = OPEN_SYNC_FLAG;
6017         }
6018 #endif
6019 #ifdef OPEN_DATASYNC_FLAG
6020         else if (pg_strcasecmp(method, "open_datasync") == 0)
6021         {
6022                 new_sync_method = SYNC_METHOD_OPEN;
6023                 new_sync_bit = OPEN_DATASYNC_FLAG;
6024         }
6025 #endif
6026         else
6027                 return NULL;
6028
6029         if (!doit)
6030                 return method;
6031
6032         if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
6033         {
6034                 /*
6035                  * To ensure that no blocks escape unsynced, force an fsync on the
6036                  * currently open log segment (if any).  Also, if the open flag is
6037                  * changing, close the log file so it will be reopened (with new flag
6038                  * bit) at next use.
6039                  */
6040                 if (openLogFile >= 0)
6041                 {
6042                         if (pg_fsync(openLogFile) != 0)
6043                                 ereport(PANIC,
6044                                                 (errcode_for_file_access(),
6045                                                  errmsg("could not fsync log file %u, segment %u: %m",
6046                                                                 openLogId, openLogSeg)));
6047                         if (open_sync_bit != new_sync_bit)
6048                                 XLogFileClose();
6049                 }
6050                 sync_method = new_sync_method;
6051                 open_sync_bit = new_sync_bit;
6052         }
6053
6054         return method;
6055 }
6056
6057
6058 /*
6059  * Issue appropriate kind of fsync (if any) on the current XLOG output file
6060  */
6061 static void
6062 issue_xlog_fsync(void)
6063 {
6064         switch (sync_method)
6065         {
6066                 case SYNC_METHOD_FSYNC:
6067                         if (pg_fsync_no_writethrough(openLogFile) != 0)
6068                                 ereport(PANIC,
6069                                                 (errcode_for_file_access(),
6070                                                  errmsg("could not fsync log file %u, segment %u: %m",
6071                                                                 openLogId, openLogSeg)));
6072                         break;
6073 #ifdef HAVE_FSYNC_WRITETHROUGH
6074                 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6075                         if (pg_fsync_writethrough(openLogFile) != 0)
6076                                 ereport(PANIC,
6077                                                 (errcode_for_file_access(),
6078                                                  errmsg("could not fsync write-through log file %u, segment %u: %m",
6079                                                                 openLogId, openLogSeg)));
6080                         break;
6081 #endif
6082 #ifdef HAVE_FDATASYNC
6083                 case SYNC_METHOD_FDATASYNC:
6084                         if (pg_fdatasync(openLogFile) != 0)
6085                                 ereport(PANIC,
6086                                                 (errcode_for_file_access(),
6087                                         errmsg("could not fdatasync log file %u, segment %u: %m",
6088                                                    openLogId, openLogSeg)));
6089                         break;
6090 #endif
6091                 case SYNC_METHOD_OPEN:
6092                         /* write synced it already */
6093                         break;
6094                 default:
6095                         elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6096                         break;
6097         }
6098 }
6099
6100
6101 /*
6102  * pg_start_backup: set up for taking an on-line backup dump
6103  *
6104  * Essentially what this does is to create a backup label file in $PGDATA,
6105  * where it will be archived as part of the backup dump.  The label file
6106  * contains the user-supplied label string (typically this would be used
6107  * to tell where the backup dump will be stored) and the starting time and
6108  * starting WAL location for the dump.
6109  */
6110 Datum
6111 pg_start_backup(PG_FUNCTION_ARGS)
6112 {
6113         text       *backupid = PG_GETARG_TEXT_P(0);
6114         text       *result;
6115         char       *backupidstr;
6116         XLogRecPtr      checkpointloc;
6117         XLogRecPtr      startpoint;
6118         time_t          stamp_time;
6119         char            strfbuf[128];
6120         char            xlogfilename[MAXFNAMELEN];
6121         uint32          _logId;
6122         uint32          _logSeg;
6123         struct stat stat_buf;
6124         FILE       *fp;
6125
6126         if (!superuser())
6127                 ereport(ERROR,
6128                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6129                                  (errmsg("must be superuser to run a backup"))));
6130
6131         if (!XLogArchivingActive())
6132                 ereport(ERROR,
6133                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6134                                  (errmsg("WAL archiving is not active"),
6135                                   (errhint("archive_command must be defined before "
6136                                                    "online backups can be made safely.")))));
6137
6138         backupidstr = DatumGetCString(DirectFunctionCall1(textout,
6139                                                                                                  PointerGetDatum(backupid)));
6140
6141         /*
6142          * Mark backup active in shared memory.  We must do full-page WAL writes
6143          * during an on-line backup even if not doing so at other times, because
6144          * it's quite possible for the backup dump to obtain a "torn" (partially
6145          * written) copy of a database page if it reads the page concurrently
6146          * with our write to the same page.  This can be fixed as long as the
6147          * first write to the page in the WAL sequence is a full-page write.
6148          * Hence, we turn on forcePageWrites and then force a CHECKPOINT, to
6149          * ensure there are no dirty pages in shared memory that might get
6150          * dumped while the backup is in progress without having a corresponding
6151          * WAL record.  (Once the backup is complete, we need not force full-page
6152          * writes anymore, since we expect that any pages not modified during
6153          * the backup interval must have been correctly captured by the backup.)
6154          *
6155          * We must hold WALInsertLock to change the value of forcePageWrites,
6156          * to ensure adequate interlocking against XLogInsert().
6157          */
6158         LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6159         if (XLogCtl->Insert.forcePageWrites)
6160         {
6161                 LWLockRelease(WALInsertLock);
6162                 ereport(ERROR,
6163                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6164                                  errmsg("a backup is already in progress"),
6165                                  errhint("Run pg_stop_backup() and try again.")));
6166         }
6167         XLogCtl->Insert.forcePageWrites = true;
6168         LWLockRelease(WALInsertLock);
6169
6170         /* Use a TRY block to ensure we release forcePageWrites if fail below */
6171         PG_TRY();
6172         {
6173                 /*
6174                  * Force a CHECKPOINT.  Aside from being necessary to prevent torn
6175                  * page problems, this guarantees that two successive backup runs will
6176                  * have different checkpoint positions and hence different history
6177                  * file names, even if nothing happened in between.
6178                  */
6179                 RequestCheckpoint(true, false);
6180
6181                 /*
6182                  * Now we need to fetch the checkpoint record location, and also its
6183                  * REDO pointer.  The oldest point in WAL that would be needed to
6184                  * restore starting from the checkpoint is precisely the REDO pointer.
6185                  */
6186                 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6187                 checkpointloc = ControlFile->checkPoint;
6188                 startpoint = ControlFile->checkPointCopy.redo;
6189                 LWLockRelease(ControlFileLock);
6190
6191                 XLByteToSeg(startpoint, _logId, _logSeg);
6192                 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6193
6194                 /*
6195                  * We deliberately use strftime/localtime not the src/timezone
6196                  * functions, so that backup labels will consistently be recorded in
6197                  * the same timezone regardless of TimeZone setting.  This matches
6198                  * elog.c's practice.
6199                  */
6200                 stamp_time = time(NULL);
6201                 strftime(strfbuf, sizeof(strfbuf),
6202                                  "%Y-%m-%d %H:%M:%S %Z",
6203                                  localtime(&stamp_time));
6204
6205                 /*
6206                  * Check for existing backup label --- implies a backup is already
6207                  * running.  (XXX given that we checked forcePageWrites above, maybe
6208                  * it would be OK to just unlink any such label file?)
6209                  */
6210                 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6211                 {
6212                         if (errno != ENOENT)
6213                                 ereport(ERROR,
6214                                                 (errcode_for_file_access(),
6215                                                  errmsg("could not stat file \"%s\": %m",
6216                                                                 BACKUP_LABEL_FILE)));
6217                 }
6218                 else
6219                         ereport(ERROR,
6220                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6221                                          errmsg("a backup is already in progress"),
6222                                          errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6223                                                          BACKUP_LABEL_FILE)));
6224
6225                 /*
6226                  * Okay, write the file
6227                  */
6228                 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6229                 if (!fp)
6230                         ereport(ERROR,
6231                                         (errcode_for_file_access(),
6232                                          errmsg("could not create file \"%s\": %m",
6233                                                         BACKUP_LABEL_FILE)));
6234                 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6235                                 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6236                 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6237                                 checkpointloc.xlogid, checkpointloc.xrecoff);
6238                 fprintf(fp, "START TIME: %s\n", strfbuf);
6239                 fprintf(fp, "LABEL: %s\n", backupidstr);
6240                 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6241                         ereport(ERROR,
6242                                         (errcode_for_file_access(),
6243                                          errmsg("could not write file \"%s\": %m",
6244                                                         BACKUP_LABEL_FILE)));
6245         }
6246         PG_CATCH();
6247         {
6248                 /* Turn off forcePageWrites on failure */
6249                 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6250                 XLogCtl->Insert.forcePageWrites = false;
6251                 LWLockRelease(WALInsertLock);
6252
6253                 PG_RE_THROW();
6254         }
6255         PG_END_TRY();
6256
6257         /*
6258          * We're done.  As a convenience, return the starting WAL location.
6259          */
6260         snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6261                          startpoint.xlogid, startpoint.xrecoff);
6262         result = DatumGetTextP(DirectFunctionCall1(textin,
6263                                                                                          CStringGetDatum(xlogfilename)));
6264         PG_RETURN_TEXT_P(result);
6265 }
6266
6267 /*
6268  * pg_stop_backup: finish taking an on-line backup dump
6269  *
6270  * We remove the backup label file created by pg_start_backup, and instead
6271  * create a backup history file in pg_xlog (whence it will immediately be
6272  * archived).  The backup history file contains the same info found in
6273  * the label file, plus the backup-end time and WAL location.
6274  */
6275 Datum
6276 pg_stop_backup(PG_FUNCTION_ARGS)
6277 {
6278         text       *result;
6279         XLogRecPtr      startpoint;
6280         XLogRecPtr      stoppoint;
6281         time_t          stamp_time;
6282         char            strfbuf[128];
6283         char            histfilepath[MAXPGPATH];
6284         char            startxlogfilename[MAXFNAMELEN];
6285         char            stopxlogfilename[MAXFNAMELEN];
6286         uint32          _logId;
6287         uint32          _logSeg;
6288         FILE       *lfp;
6289         FILE       *fp;
6290         char            ch;
6291         int                     ich;
6292
6293         if (!superuser())
6294                 ereport(ERROR,
6295                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6296                                  (errmsg("must be superuser to run a backup"))));
6297
6298         /*
6299          * OK to clear forcePageWrites
6300          */
6301         LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6302         XLogCtl->Insert.forcePageWrites = false;
6303         LWLockRelease(WALInsertLock);
6304
6305         /*
6306          * Force a switch to a new xlog segment file, so that the backup
6307          * is valid as soon as archiver moves out the current segment file.
6308          * We'll report the end address of the XLOG SWITCH record as the backup
6309          * 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,
6396          * this will post a .ready file for the newly created history file,
6397          * notifying 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
6540          * this 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 }