OSDN Git Service

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