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