OSDN Git Service

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