OSDN Git Service

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