OSDN Git Service

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