OSDN Git Service

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