OSDN Git Service

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