OSDN Git Service

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