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