OSDN Git Service

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