OSDN Git Service

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