1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/access/transam/xlog.c,v 1.245 2006/07/30 02:07:18 alvherre Exp $
12 *-------------------------------------------------------------------------
25 #include "access/clog.h"
26 #include "access/multixact.h"
27 #include "access/subtrans.h"
28 #include "access/transam.h"
29 #include "access/twophase.h"
30 #include "access/xact.h"
31 #include "access/xlog_internal.h"
32 #include "access/xlogutils.h"
33 #include "catalog/catversion.h"
34 #include "catalog/pg_control.h"
35 #include "miscadmin.h"
37 #include "postmaster/bgwriter.h"
38 #include "storage/bufpage.h"
39 #include "storage/fd.h"
40 #include "storage/pmsignal.h"
41 #include "storage/procarray.h"
42 #include "storage/spin.h"
43 #include "utils/builtins.h"
44 #include "utils/nabstime.h"
45 #include "utils/pg_locale.h"
49 * Because O_DIRECT bypasses the kernel buffers, and because we never
50 * read those buffers except during crash recovery, it is a win to use
51 * it in all cases where we sync on each write(). We could allow O_DIRECT
52 * with fsync(), but because skipping the kernel buffer forces writes out
53 * quickly, it seems best just to use it for O_SYNC. It is hard to imagine
54 * how fsync() could be a win for O_DIRECT compared to O_SYNC and O_DIRECT.
55 * Also, O_DIRECT is never enough to force data to the drives, it merely
56 * tries to bypass the kernel cache, so we still need O_SYNC or fsync().
59 #define PG_O_DIRECT O_DIRECT
65 * This chunk of hackery attempts to determine which file sync methods
66 * are available on the current platform, and to choose an appropriate
67 * default method. We assume that fsync() is always available, and that
68 * configure determined whether fdatasync() is.
71 #define BARE_OPEN_SYNC_FLAG O_SYNC
72 #elif defined(O_FSYNC)
73 #define BARE_OPEN_SYNC_FLAG O_FSYNC
75 #ifdef BARE_OPEN_SYNC_FLAG
76 #define OPEN_SYNC_FLAG (BARE_OPEN_SYNC_FLAG | PG_O_DIRECT)
80 #if defined(OPEN_SYNC_FLAG)
81 /* O_DSYNC is distinct? */
82 #if O_DSYNC != BARE_OPEN_SYNC_FLAG
83 #define OPEN_DATASYNC_FLAG (O_DSYNC | PG_O_DIRECT)
85 #else /* !defined(OPEN_SYNC_FLAG) */
86 /* Win32 only has O_DSYNC */
87 #define OPEN_DATASYNC_FLAG (O_DSYNC | PG_O_DIRECT)
91 #if defined(OPEN_DATASYNC_FLAG)
92 #define DEFAULT_SYNC_METHOD_STR "open_datasync"
93 #define DEFAULT_SYNC_METHOD SYNC_METHOD_OPEN
94 #define DEFAULT_SYNC_FLAGBIT OPEN_DATASYNC_FLAG
95 #elif defined(HAVE_FDATASYNC)
96 #define DEFAULT_SYNC_METHOD_STR "fdatasync"
97 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FDATASYNC
98 #define DEFAULT_SYNC_FLAGBIT 0
99 #elif defined(HAVE_FSYNC_WRITETHROUGH_ONLY)
100 #define DEFAULT_SYNC_METHOD_STR "fsync_writethrough"
101 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FSYNC_WRITETHROUGH
102 #define DEFAULT_SYNC_FLAGBIT 0
104 #define DEFAULT_SYNC_METHOD_STR "fsync"
105 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FSYNC
106 #define DEFAULT_SYNC_FLAGBIT 0
111 * Limitation of buffer-alignment for direct IO depends on OS and filesystem,
112 * but XLOG_BLCKSZ is assumed to be enough for it.
115 #define ALIGNOF_XLOG_BUFFER XLOG_BLCKSZ
117 #define ALIGNOF_XLOG_BUFFER ALIGNOF_BUFFER
121 /* File path names (all relative to $PGDATA) */
122 #define BACKUP_LABEL_FILE "backup_label"
123 #define RECOVERY_COMMAND_FILE "recovery.conf"
124 #define RECOVERY_COMMAND_DONE "recovery.done"
127 /* User-settable parameters */
128 int CheckPointSegments = 3;
130 char *XLogArchiveCommand = NULL;
131 char *XLOG_sync_method = NULL;
132 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
133 bool fullPageWrites = true;
136 bool XLOG_DEBUG = false;
140 * XLOGfileslop is used in the code as the allowed "fuzz" in the number of
141 * preallocated XLOG segments --- we try to have at least XLOGfiles advance
142 * segments but no more than XLOGfileslop segments. This could
143 * be made a separate GUC variable, but at present I think it's sufficient
144 * to hardwire it as 2*CheckPointSegments+1. Under normal conditions, a
145 * checkpoint will free no more than 2*CheckPointSegments log segments, and
146 * we want to recycle all of them; the +1 allows boundary cases to happen
147 * without wasting a delete/create-segment cycle.
150 #define XLOGfileslop (2*CheckPointSegments + 1)
153 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
154 int sync_method = DEFAULT_SYNC_METHOD;
155 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
157 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
161 * ThisTimeLineID will be same in all backends --- it identifies current
162 * WAL timeline for the database system.
164 TimeLineID ThisTimeLineID = 0;
166 /* Are we doing recovery from XLOG? */
167 bool InRecovery = false;
169 /* Are we recovering using offline XLOG archives? */
170 static bool InArchiveRecovery = false;
172 /* Was the last xlog file restored from archive, or local? */
173 static bool restoredFromArchive = false;
175 /* options taken from recovery.conf */
176 static char *recoveryRestoreCommand = NULL;
177 static bool recoveryTarget = false;
178 static bool recoveryTargetExact = false;
179 static bool recoveryTargetInclusive = true;
180 static TransactionId recoveryTargetXid;
181 static time_t recoveryTargetTime;
183 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
184 static TransactionId recoveryStopXid;
185 static time_t recoveryStopTime;
186 static bool recoveryStopAfter;
188 /* constraint set by read_backup_label */
189 static XLogRecPtr recoveryMinXlogOffset = {0, 0};
192 * During normal operation, the only timeline we care about is ThisTimeLineID.
193 * During recovery, however, things are more complicated. To simplify life
194 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
195 * scan through the WAL history (that is, it is the line that was active when
196 * the currently-scanned WAL record was generated). We also need these
199 * recoveryTargetTLI: the desired timeline that we want to end in.
201 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
202 * its known parents, newest first (so recoveryTargetTLI is always the
203 * first list member). Only these TLIs are expected to be seen in the WAL
204 * segments we read, and indeed only these TLIs will be considered as
205 * candidate WAL files to open at all.
207 * curFileTLI: the TLI appearing in the name of the current input WAL file.
208 * (This is not necessarily the same as ThisTimeLineID, because we could
209 * be scanning data that was copied from an ancestor timeline when the current
210 * file was created.) During a sequential scan we do not allow this value
213 static TimeLineID recoveryTargetTLI;
214 static List *expectedTLIs;
215 static TimeLineID curFileTLI;
218 * MyLastRecPtr points to the start of the last XLOG record inserted by the
219 * current transaction. If MyLastRecPtr.xrecoff == 0, then the current
220 * xact hasn't yet inserted any transaction-controlled XLOG records.
222 * Note that XLOG records inserted outside transaction control are not
223 * reflected into MyLastRecPtr. They do, however, cause MyXactMadeXLogEntry
224 * to be set true. The latter can be used to test whether the current xact
225 * made any loggable changes (including out-of-xact changes, such as
228 * When we insert/update/delete a tuple in a temporary relation, we do not
229 * make any XLOG record, since we don't care about recovering the state of
230 * the temp rel after a crash. However, we will still need to remember
231 * whether our transaction committed or aborted in that case. So, we must
232 * set MyXactMadeTempRelUpdate true to indicate that the XID will be of
235 XLogRecPtr MyLastRecPtr = {0, 0};
237 bool MyXactMadeXLogEntry = false;
239 bool MyXactMadeTempRelUpdate = false;
242 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
243 * current backend. It is updated for all inserts, transaction-controlled
244 * or not. ProcLastRecEnd is similar but points to end+1 of last record.
246 static XLogRecPtr ProcLastRecPtr = {0, 0};
248 XLogRecPtr ProcLastRecEnd = {0, 0};
251 * RedoRecPtr is this backend's local copy of the REDO record pointer
252 * (which is almost but not quite the same as a pointer to the most recent
253 * CHECKPOINT record). We update this from the shared-memory copy,
254 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
255 * hold the Insert lock). See XLogInsert for details. We are also allowed
256 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
257 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
260 static XLogRecPtr RedoRecPtr;
263 * Shared-memory data structures for XLOG control
265 * LogwrtRqst indicates a byte position that we need to write and/or fsync
266 * the log up to (all records before that point must be written or fsynced).
267 * LogwrtResult indicates the byte positions we have already written/fsynced.
268 * These structs are identical but are declared separately to indicate their
269 * slightly different functions.
271 * We do a lot of pushups to minimize the amount of access to lockable
272 * shared memory values. There are actually three shared-memory copies of
273 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
274 * XLogCtl->LogwrtResult is protected by info_lck
275 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
276 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
277 * One must hold the associated lock to read or write any of these, but
278 * of course no lock is needed to read/write the unshared LogwrtResult.
280 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
281 * right", since both are updated by a write or flush operation before
282 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
283 * is that it can be examined/modified by code that already holds WALWriteLock
284 * without needing to grab info_lck as well.
286 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
287 * but is updated when convenient. Again, it exists for the convenience of
288 * code that is already holding WALInsertLock but not the other locks.
290 * The unshared LogwrtResult may lag behind any or all of these, and again
291 * is updated when convenient.
293 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
294 * (protected by info_lck), but we don't need to cache any copies of it.
296 * Note that this all works because the request and result positions can only
297 * advance forward, never back up, and so we can easily determine which of two
298 * values is "more up to date".
300 * info_lck is only held long enough to read/update the protected variables,
301 * so it's a plain spinlock. The other locks are held longer (potentially
302 * over I/O operations), so we use LWLocks for them. These locks are:
304 * WALInsertLock: must be held to insert a record into the WAL buffers.
306 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
309 * ControlFileLock: must be held to read/update control file or create
312 * CheckpointLock: must be held to do a checkpoint (ensures only one
313 * checkpointer at a time; even though the postmaster won't launch
314 * parallel checkpoint processes, we need this because manual checkpoints
315 * could be launched simultaneously).
320 typedef struct XLogwrtRqst
322 XLogRecPtr Write; /* last byte + 1 to write out */
323 XLogRecPtr Flush; /* last byte + 1 to flush */
326 typedef struct XLogwrtResult
328 XLogRecPtr Write; /* last byte + 1 written out */
329 XLogRecPtr Flush; /* last byte + 1 flushed */
333 * Shared state data for XLogInsert.
335 typedef struct XLogCtlInsert
337 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
338 XLogRecPtr PrevRecord; /* start of previously-inserted record */
339 int curridx; /* current block index in cache */
340 XLogPageHeader currpage; /* points to header of block in cache */
341 char *currpos; /* current insertion point in cache */
342 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
343 bool forcePageWrites; /* forcing full-page writes for PITR? */
347 * Shared state data for XLogWrite/XLogFlush.
349 typedef struct XLogCtlWrite
351 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
352 int curridx; /* cache index of next block to write */
356 * Total shared-memory state for XLOG.
358 typedef struct XLogCtlData
360 /* Protected by WALInsertLock: */
361 XLogCtlInsert Insert;
362 /* Protected by info_lck: */
363 XLogwrtRqst LogwrtRqst;
364 XLogwrtResult LogwrtResult;
365 /* Protected by WALWriteLock: */
369 * These values do not change after startup, although the pointed-to pages
370 * and xlblocks values certainly do. Permission to read/write the pages
371 * and xlblocks values depends on WALInsertLock and WALWriteLock.
373 char *pages; /* buffers for unwritten XLOG pages */
374 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
375 Size XLogCacheByte; /* # bytes in xlog buffers */
376 int XLogCacheBlck; /* highest allocated xlog buffer index */
377 TimeLineID ThisTimeLineID;
379 slock_t info_lck; /* locks shared LogwrtRqst/LogwrtResult */
382 static XLogCtlData *XLogCtl = NULL;
385 * We maintain an image of pg_control in shared memory.
387 static ControlFileData *ControlFile = NULL;
390 * Macros for managing XLogInsert state. In most cases, the calling routine
391 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
392 * so these are passed as parameters instead of being fetched via XLogCtl.
395 /* Free space remaining in the current xlog page buffer */
396 #define INSERT_FREESPACE(Insert) \
397 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
399 /* Construct XLogRecPtr value for current insertion point */
400 #define INSERT_RECPTR(recptr,Insert,curridx) \
402 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
404 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
407 #define PrevBufIdx(idx) \
408 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
410 #define NextBufIdx(idx) \
411 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
414 * Private, possibly out-of-date copy of shared LogwrtResult.
415 * See discussion above.
417 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
420 * openLogFile is -1 or a kernel FD for an open log file segment.
421 * When it's open, openLogOff is the current seek offset in the file.
422 * openLogId/openLogSeg identify the segment. These variables are only
423 * used to write the XLOG, and so will normally refer to the active segment.
425 static int openLogFile = -1;
426 static uint32 openLogId = 0;
427 static uint32 openLogSeg = 0;
428 static uint32 openLogOff = 0;
431 * These variables are used similarly to the ones above, but for reading
432 * the XLOG. Note, however, that readOff generally represents the offset
433 * of the page just read, not the seek position of the FD itself, which
434 * will be just past that page.
436 static int readFile = -1;
437 static uint32 readId = 0;
438 static uint32 readSeg = 0;
439 static uint32 readOff = 0;
441 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
442 static char *readBuf = NULL;
444 /* Buffer for current ReadRecord result (expandable) */
445 static char *readRecordBuf = NULL;
446 static uint32 readRecordBufSize = 0;
448 /* State information for XLOG reading */
449 static XLogRecPtr ReadRecPtr; /* start of last record read */
450 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
451 static XLogRecord *nextRecord = NULL;
452 static TimeLineID lastPageTLI = 0;
454 static bool InRedo = false;
457 static void XLogArchiveNotify(const char *xlog);
458 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
459 static bool XLogArchiveCheckDone(const char *xlog);
460 static void XLogArchiveCleanup(const char *xlog);
461 static void readRecoveryCommandFile(void);
462 static void exitArchiveRecovery(TimeLineID endTLI,
463 uint32 endLogId, uint32 endLogSeg);
464 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
466 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
467 XLogRecPtr *lsn, BkpBlock *bkpb);
468 static bool AdvanceXLInsertBuffer(void);
469 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible);
470 static int XLogFileInit(uint32 log, uint32 seg,
471 bool *use_existent, bool use_lock);
472 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
473 bool find_free, int *max_advance,
475 static int XLogFileOpen(uint32 log, uint32 seg);
476 static int XLogFileRead(uint32 log, uint32 seg, int emode);
477 static void XLogFileClose(void);
478 static bool RestoreArchivedFile(char *path, const char *xlogfname,
479 const char *recovername, off_t expectedSize);
480 static int PreallocXlogFiles(XLogRecPtr endptr);
481 static void MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
482 int *nsegsremoved, int *nsegsrecycled);
483 static void CleanupBackupHistory(void);
484 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
485 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
486 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
487 static List *readTimeLineHistory(TimeLineID targetTLI);
488 static bool existsTimeLineHistory(TimeLineID probeTLI);
489 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
490 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
492 uint32 endLogId, uint32 endLogSeg);
493 static void WriteControlFile(void);
494 static void ReadControlFile(void);
495 static char *str_time(time_t tnow);
496 static void issue_xlog_fsync(void);
499 static void xlog_outrec(StringInfo buf, XLogRecord *record);
501 static bool read_backup_label(XLogRecPtr *checkPointLoc);
502 static void remove_backup_label(void);
503 static void rm_redo_error_callback(void *arg);
507 * Insert an XLOG record having the specified RMID and info bytes,
508 * with the body of the record being the data chunk(s) described by
509 * the rdata chain (see xlog.h for notes about rdata).
511 * Returns XLOG pointer to end of record (beginning of next record).
512 * This can be used as LSN for data pages affected by the logged action.
513 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
514 * before the data page can be written out. This implements the basic
515 * WAL rule "write the log before the data".)
517 * NB: this routine feels free to scribble on the XLogRecData structs,
518 * though not on the data they reference. This is OK since the XLogRecData
519 * structs are always just temporaries in the calling code.
522 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
524 XLogCtlInsert *Insert = &XLogCtl->Insert;
526 XLogContRecord *contrecord;
528 XLogRecPtr WriteRqst;
532 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
533 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
534 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
535 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
536 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
537 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
538 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
543 XLogwrtRqst LogwrtRqst;
546 bool no_tran = (rmid == RM_XLOG_ID) ? true : false;
548 if (info & XLR_INFO_MASK)
550 if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
551 elog(PANIC, "invalid xlog info mask %02X", (info & XLR_INFO_MASK));
553 info &= ~XLR_INFO_MASK;
557 * In bootstrap mode, we don't actually log anything but XLOG resources;
558 * return a phony record pointer.
560 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
563 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
568 * Here we scan the rdata chain, determine which buffers must be backed
569 * up, and compute the CRC values for the data. Note that the record
570 * header isn't added into the CRC initially since we don't know the final
571 * length or info bits quite yet. Thus, the CRC will represent the CRC of
572 * the whole record in the order "rdata, then backup blocks, then record
575 * We may have to loop back to here if a race condition is detected below.
576 * We could prevent the race by doing all this work while holding the
577 * insert lock, but it seems better to avoid doing CRC calculations while
578 * holding the lock. This means we have to be careful about modifying the
579 * rdata chain until we know we aren't going to loop back again. The only
580 * change we allow ourselves to make earlier is to set rdt->data = NULL in
581 * chain items we have decided we will have to back up the whole buffer
582 * for. This is OK because we will certainly decide the same thing again
583 * for those items if we do it over; doing it here saves an extra pass
584 * over the chain later.
587 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
589 dtbuf[i] = InvalidBuffer;
590 dtbuf_bkp[i] = false;
594 * Decide if we need to do full-page writes in this XLOG record: true if
595 * full_page_writes is on or we have a PITR request for it. Since we
596 * don't yet have the insert lock, forcePageWrites could change under us,
597 * but we'll recheck it once we have the lock.
599 doPageWrites = fullPageWrites || Insert->forcePageWrites;
601 INIT_CRC32(rdata_crc);
605 if (rdt->buffer == InvalidBuffer)
607 /* Simple data, just include it */
609 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
613 /* Find info for buffer */
614 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
616 if (rdt->buffer == dtbuf[i])
618 /* Buffer already referenced by earlier chain item */
624 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
628 if (dtbuf[i] == InvalidBuffer)
630 /* OK, put it in this slot */
631 dtbuf[i] = rdt->buffer;
632 if (XLogCheckBuffer(rdt, doPageWrites,
633 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
641 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
646 if (i >= XLR_MAX_BKP_BLOCKS)
647 elog(PANIC, "can backup at most %d blocks per xlog record",
650 /* Break out of loop when rdt points to last chain item */
651 if (rdt->next == NULL)
657 * Now add the backup block headers and data into the CRC
659 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
663 BkpBlock *bkpb = &(dtbuf_xlg[i]);
666 COMP_CRC32(rdata_crc,
669 page = (char *) BufferGetBlock(dtbuf[i]);
670 if (bkpb->hole_length == 0)
672 COMP_CRC32(rdata_crc,
678 /* must skip the hole */
679 COMP_CRC32(rdata_crc,
682 COMP_CRC32(rdata_crc,
683 page + (bkpb->hole_offset + bkpb->hole_length),
684 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
690 * NOTE: the test for len == 0 here is somewhat fishy, since in theory all
691 * of the rmgr data might have been suppressed in favor of backup blocks.
692 * Currently, all callers of XLogInsert provide at least some
693 * not-in-a-buffer data and so len == 0 should never happen, but that may
694 * not be true forever. If you need to remove the len == 0 check, also
695 * remove the check for xl_len == 0 in ReadRecord, below.
698 elog(PANIC, "invalid xlog record length %u", len);
700 START_CRIT_SECTION();
702 /* update LogwrtResult before doing cache fill check */
704 /* use volatile pointer to prevent code rearrangement */
705 volatile XLogCtlData *xlogctl = XLogCtl;
707 SpinLockAcquire(&xlogctl->info_lck);
708 LogwrtRqst = xlogctl->LogwrtRqst;
709 LogwrtResult = xlogctl->LogwrtResult;
710 SpinLockRelease(&xlogctl->info_lck);
714 * If cache is half filled then try to acquire write lock and do
715 * XLogWrite. Ignore any fractional blocks in performing this check.
717 LogwrtRqst.Write.xrecoff -= LogwrtRqst.Write.xrecoff % XLOG_BLCKSZ;
718 if (LogwrtRqst.Write.xlogid != LogwrtResult.Write.xlogid ||
719 (LogwrtRqst.Write.xrecoff >= LogwrtResult.Write.xrecoff +
720 XLogCtl->XLogCacheByte / 2))
722 if (LWLockConditionalAcquire(WALWriteLock, LW_EXCLUSIVE))
725 * Since the amount of data we write here is completely optional
726 * anyway, tell XLogWrite it can be "flexible" and stop at a
727 * convenient boundary. This allows writes triggered by this
728 * mechanism to synchronize with the cache boundaries, so that in
729 * a long transaction we'll basically dump alternating halves of
732 LogwrtResult = XLogCtl->Write.LogwrtResult;
733 if (XLByteLT(LogwrtResult.Write, LogwrtRqst.Write))
734 XLogWrite(LogwrtRqst, true);
735 LWLockRelease(WALWriteLock);
739 /* Now wait to get insert lock */
740 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
743 * Check to see if my RedoRecPtr is out of date. If so, may have to go
744 * back and recompute everything. This can only happen just after a
745 * checkpoint, so it's better to be slow in this case and fast otherwise.
747 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
748 * affect the contents of the XLOG record, so we'll update our local
749 * copy but not force a recomputation.
751 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
753 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
754 RedoRecPtr = Insert->RedoRecPtr;
758 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
760 if (dtbuf[i] == InvalidBuffer)
762 if (dtbuf_bkp[i] == false &&
763 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
766 * Oops, this buffer now needs to be backed up, but we
767 * didn't think so above. Start over.
769 LWLockRelease(WALInsertLock);
778 * Also check to see if forcePageWrites was just turned on; if we
779 * weren't already doing full-page writes then go back and recompute.
780 * (If it was just turned off, we could recompute the record without
781 * full pages, but we choose not to bother.)
783 if (Insert->forcePageWrites && !doPageWrites)
785 /* Oops, must redo it with full-page data */
786 LWLockRelease(WALInsertLock);
792 * Make additional rdata chain entries for the backup blocks, so that we
793 * don't need to special-case them in the write loop. Note that we have
794 * now irrevocably changed the input rdata chain. At the exit of this
795 * loop, write_len includes the backup block data.
797 * Also set the appropriate info bits to show which buffers were backed
798 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
799 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
802 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
810 info |= XLR_SET_BKP_BLOCK(i);
812 bkpb = &(dtbuf_xlg[i]);
813 page = (char *) BufferGetBlock(dtbuf[i]);
815 rdt->next = &(dtbuf_rdt1[i]);
818 rdt->data = (char *) bkpb;
819 rdt->len = sizeof(BkpBlock);
820 write_len += sizeof(BkpBlock);
822 rdt->next = &(dtbuf_rdt2[i]);
825 if (bkpb->hole_length == 0)
834 /* must skip the hole */
836 rdt->len = bkpb->hole_offset;
837 write_len += bkpb->hole_offset;
839 rdt->next = &(dtbuf_rdt3[i]);
842 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
843 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
844 write_len += rdt->len;
850 * If there isn't enough space on the current XLOG page for a record
851 * header, advance to the next page (leaving the unused space as zeroes).
854 freespace = INSERT_FREESPACE(Insert);
855 if (freespace < SizeOfXLogRecord)
857 updrqst = AdvanceXLInsertBuffer();
858 freespace = INSERT_FREESPACE(Insert);
861 curridx = Insert->curridx;
862 record = (XLogRecord *) Insert->currpos;
864 /* Insert record header */
866 record->xl_prev = Insert->PrevRecord;
867 record->xl_xid = GetCurrentTransactionIdIfAny();
868 record->xl_tot_len = SizeOfXLogRecord + write_len;
869 record->xl_len = len; /* doesn't include backup blocks */
870 record->xl_info = info;
871 record->xl_rmid = rmid;
873 /* Now we can finish computing the record's CRC */
874 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
875 SizeOfXLogRecord - sizeof(pg_crc32));
876 FIN_CRC32(rdata_crc);
877 record->xl_crc = rdata_crc;
879 /* Compute record's XLOG location */
880 INSERT_RECPTR(RecPtr, Insert, curridx);
887 initStringInfo(&buf);
888 appendStringInfo(&buf, "INSERT @ %X/%X: ",
889 RecPtr.xlogid, RecPtr.xrecoff);
890 xlog_outrec(&buf, record);
891 if (rdata->data != NULL)
893 appendStringInfo(&buf, " - ");
894 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
896 elog(LOG, "%s", buf.data);
901 /* Record begin of record in appropriate places */
903 MyLastRecPtr = RecPtr;
904 ProcLastRecPtr = RecPtr;
905 Insert->PrevRecord = RecPtr;
906 MyXactMadeXLogEntry = true;
908 Insert->currpos += SizeOfXLogRecord;
909 freespace -= SizeOfXLogRecord;
912 * Append the data, including backup blocks if any
916 while (rdata->data == NULL)
921 if (rdata->len > freespace)
923 memcpy(Insert->currpos, rdata->data, freespace);
924 rdata->data += freespace;
925 rdata->len -= freespace;
926 write_len -= freespace;
930 memcpy(Insert->currpos, rdata->data, rdata->len);
931 freespace -= rdata->len;
932 write_len -= rdata->len;
933 Insert->currpos += rdata->len;
939 /* Use next buffer */
940 updrqst = AdvanceXLInsertBuffer();
941 curridx = Insert->curridx;
942 /* Insert cont-record header */
943 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
944 contrecord = (XLogContRecord *) Insert->currpos;
945 contrecord->xl_rem_len = write_len;
946 Insert->currpos += SizeOfXLogContRecord;
947 freespace = INSERT_FREESPACE(Insert);
950 /* Ensure next record will be properly aligned */
951 Insert->currpos = (char *) Insert->currpage +
952 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
953 freespace = INSERT_FREESPACE(Insert);
956 * The recptr I return is the beginning of the *next* record. This will be
957 * stored as LSN for changed data pages...
959 INSERT_RECPTR(RecPtr, Insert, curridx);
961 /* Need to update shared LogwrtRqst if some block was filled up */
962 if (freespace < SizeOfXLogRecord)
963 updrqst = true; /* curridx is filled and available for writing
966 curridx = PrevBufIdx(curridx);
967 WriteRqst = XLogCtl->xlblocks[curridx];
969 LWLockRelease(WALInsertLock);
973 /* use volatile pointer to prevent code rearrangement */
974 volatile XLogCtlData *xlogctl = XLogCtl;
976 SpinLockAcquire(&xlogctl->info_lck);
977 /* advance global request to include new block(s) */
978 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
979 xlogctl->LogwrtRqst.Write = WriteRqst;
980 /* update local result copy while I have the chance */
981 LogwrtResult = xlogctl->LogwrtResult;
982 SpinLockRelease(&xlogctl->info_lck);
985 ProcLastRecEnd = RecPtr;
993 * Determine whether the buffer referenced by an XLogRecData item has to
994 * be backed up, and if so fill a BkpBlock struct for it. In any case
995 * save the buffer's LSN at *lsn.
998 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
999 XLogRecPtr *lsn, BkpBlock *bkpb)
1003 page = (PageHeader) BufferGetBlock(rdata->buffer);
1006 * XXX We assume page LSN is first data on *every* page that can be passed
1007 * to XLogInsert, whether it otherwise has the standard page layout or
1010 *lsn = page->pd_lsn;
1013 XLByteLE(page->pd_lsn, RedoRecPtr))
1016 * The page needs to be backed up, so set up *bkpb
1018 bkpb->node = BufferGetFileNode(rdata->buffer);
1019 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1021 if (rdata->buffer_std)
1023 /* Assume we can omit data between pd_lower and pd_upper */
1024 uint16 lower = page->pd_lower;
1025 uint16 upper = page->pd_upper;
1027 if (lower >= SizeOfPageHeaderData &&
1031 bkpb->hole_offset = lower;
1032 bkpb->hole_length = upper - lower;
1036 /* No "hole" to compress out */
1037 bkpb->hole_offset = 0;
1038 bkpb->hole_length = 0;
1043 /* Not a standard page header, don't try to eliminate "hole" */
1044 bkpb->hole_offset = 0;
1045 bkpb->hole_length = 0;
1048 return true; /* buffer requires backup */
1051 return false; /* buffer does not need to be backed up */
1057 * Create an archive notification file
1059 * The name of the notification file is the message that will be picked up
1060 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1061 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1062 * then when complete, rename it to 0000000100000001000000C6.done
1065 XLogArchiveNotify(const char *xlog)
1067 char archiveStatusPath[MAXPGPATH];
1070 /* insert an otherwise empty file called <XLOG>.ready */
1071 StatusFilePath(archiveStatusPath, xlog, ".ready");
1072 fd = AllocateFile(archiveStatusPath, "w");
1076 (errcode_for_file_access(),
1077 errmsg("could not create archive status file \"%s\": %m",
1078 archiveStatusPath)));
1084 (errcode_for_file_access(),
1085 errmsg("could not write archive status file \"%s\": %m",
1086 archiveStatusPath)));
1090 /* Notify archiver that it's got something to do */
1091 if (IsUnderPostmaster)
1092 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1096 * Convenience routine to notify using log/seg representation of filename
1099 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1101 char xlog[MAXFNAMELEN];
1103 XLogFileName(xlog, ThisTimeLineID, log, seg);
1104 XLogArchiveNotify(xlog);
1108 * XLogArchiveCheckDone
1110 * This is called when we are ready to delete or recycle an old XLOG segment
1111 * file or backup history file. If it is okay to delete it then return true.
1112 * If it is not time to delete it, make sure a .ready file exists, and return
1115 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1116 * then return false; else create <XLOG>.ready and return false.
1118 * The reason we do things this way is so that if the original attempt to
1119 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1122 XLogArchiveCheckDone(const char *xlog)
1124 char archiveStatusPath[MAXPGPATH];
1125 struct stat stat_buf;
1127 /* Always deletable if archiving is off */
1128 if (!XLogArchivingActive())
1131 /* First check for .done --- this means archiver is done with it */
1132 StatusFilePath(archiveStatusPath, xlog, ".done");
1133 if (stat(archiveStatusPath, &stat_buf) == 0)
1136 /* check for .ready --- this means archiver is still busy with it */
1137 StatusFilePath(archiveStatusPath, xlog, ".ready");
1138 if (stat(archiveStatusPath, &stat_buf) == 0)
1141 /* Race condition --- maybe archiver just finished, so recheck */
1142 StatusFilePath(archiveStatusPath, xlog, ".done");
1143 if (stat(archiveStatusPath, &stat_buf) == 0)
1146 /* Retry creation of the .ready file */
1147 XLogArchiveNotify(xlog);
1152 * XLogArchiveCleanup
1154 * Cleanup archive notification file(s) for a particular xlog segment
1157 XLogArchiveCleanup(const char *xlog)
1159 char archiveStatusPath[MAXPGPATH];
1161 /* Remove the .done file */
1162 StatusFilePath(archiveStatusPath, xlog, ".done");
1163 unlink(archiveStatusPath);
1164 /* should we complain about failure? */
1166 /* Remove the .ready file if present --- normally it shouldn't be */
1167 StatusFilePath(archiveStatusPath, xlog, ".ready");
1168 unlink(archiveStatusPath);
1169 /* should we complain about failure? */
1173 * Advance the Insert state to the next buffer page, writing out the next
1174 * buffer if it still contains unwritten data.
1176 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1177 * just-filled page. If we can do this for free (without an extra lock),
1178 * we do so here. Otherwise the caller must do it. We return TRUE if the
1179 * request update still needs to be done, FALSE if we did it internally.
1181 * Must be called with WALInsertLock held.
1184 AdvanceXLInsertBuffer(void)
1186 XLogCtlInsert *Insert = &XLogCtl->Insert;
1187 XLogCtlWrite *Write = &XLogCtl->Write;
1188 int nextidx = NextBufIdx(Insert->curridx);
1189 bool update_needed = true;
1190 XLogRecPtr OldPageRqstPtr;
1191 XLogwrtRqst WriteRqst;
1192 XLogRecPtr NewPageEndPtr;
1193 XLogPageHeader NewPage;
1195 /* Use Insert->LogwrtResult copy if it's more fresh */
1196 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1197 LogwrtResult = Insert->LogwrtResult;
1200 * Get ending-offset of the buffer page we need to replace (this may be
1201 * zero if the buffer hasn't been used yet). Fall through if it's already
1204 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1205 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1207 /* nope, got work to do... */
1208 XLogRecPtr FinishedPageRqstPtr;
1210 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1212 /* Before waiting, get info_lck and update LogwrtResult */
1214 /* use volatile pointer to prevent code rearrangement */
1215 volatile XLogCtlData *xlogctl = XLogCtl;
1217 SpinLockAcquire(&xlogctl->info_lck);
1218 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1219 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1220 LogwrtResult = xlogctl->LogwrtResult;
1221 SpinLockRelease(&xlogctl->info_lck);
1224 update_needed = false; /* Did the shared-request update */
1226 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1228 /* OK, someone wrote it already */
1229 Insert->LogwrtResult = LogwrtResult;
1233 /* Must acquire write lock */
1234 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1235 LogwrtResult = Write->LogwrtResult;
1236 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1238 /* OK, someone wrote it already */
1239 LWLockRelease(WALWriteLock);
1240 Insert->LogwrtResult = LogwrtResult;
1245 * Have to write buffers while holding insert lock. This is
1246 * not good, so only write as much as we absolutely must.
1248 WriteRqst.Write = OldPageRqstPtr;
1249 WriteRqst.Flush.xlogid = 0;
1250 WriteRqst.Flush.xrecoff = 0;
1251 XLogWrite(WriteRqst, false);
1252 LWLockRelease(WALWriteLock);
1253 Insert->LogwrtResult = LogwrtResult;
1259 * Now the next buffer slot is free and we can set it up to be the next
1262 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1263 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1265 /* crossing a logid boundary */
1266 NewPageEndPtr.xlogid += 1;
1267 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1270 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1271 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1272 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1274 Insert->curridx = nextidx;
1275 Insert->currpage = NewPage;
1277 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1280 * Be sure to re-zero the buffer so that bytes beyond what we've written
1281 * will look like zeroes and not valid XLOG records...
1283 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1286 * Fill the new page's header
1288 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1290 /* NewPage->xlp_info = 0; */ /* done by memset */
1291 NewPage ->xlp_tli = ThisTimeLineID;
1292 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1293 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1296 * If first page of an XLOG segment file, make it a long header.
1298 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1300 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1302 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1303 NewLongPage->xlp_seg_size = XLogSegSize;
1304 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1305 NewPage ->xlp_info |= XLP_LONG_HEADER;
1307 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1310 return update_needed;
1314 * Write and/or fsync the log at least as far as WriteRqst indicates.
1316 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1317 * may stop at any convenient boundary (such as a cache or logfile boundary).
1318 * This option allows us to avoid uselessly issuing multiple writes when a
1319 * single one would do.
1321 * Must be called with WALWriteLock held.
1324 XLogWrite(XLogwrtRqst WriteRqst, bool flexible)
1326 XLogCtlWrite *Write = &XLogCtl->Write;
1335 /* We should always be inside a critical section here */
1336 Assert(CritSectionCount > 0);
1339 * Update local LogwrtResult (caller probably did this already, but...)
1341 LogwrtResult = Write->LogwrtResult;
1344 * Since successive pages in the xlog cache are consecutively allocated,
1345 * we can usually gather multiple pages together and issue just one
1346 * write() call. npages is the number of pages we have determined can be
1347 * written together; startidx is the cache block index of the first one,
1348 * and startoffset is the file offset at which it should go. The latter
1349 * two variables are only valid when npages > 0, but we must initialize
1350 * all of them to keep the compiler quiet.
1357 * Within the loop, curridx is the cache block index of the page to
1358 * consider writing. We advance Write->curridx only after successfully
1359 * writing pages. (Right now, this refinement is useless since we are
1360 * going to PANIC if any error occurs anyway; but someday it may come in
1363 curridx = Write->curridx;
1365 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1368 * Make sure we're not ahead of the insert process. This could happen
1369 * if we're passed a bogus WriteRqst.Write that is past the end of the
1370 * last page that's been initialized by AdvanceXLInsertBuffer.
1372 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1373 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1374 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1375 XLogCtl->xlblocks[curridx].xlogid,
1376 XLogCtl->xlblocks[curridx].xrecoff);
1378 /* Advance LogwrtResult.Write to end of current buffer page */
1379 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1380 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1382 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1385 * Switch to new logfile segment. We cannot have any pending
1386 * pages here (since we dump what we have at segment end).
1388 Assert(npages == 0);
1389 if (openLogFile >= 0)
1391 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1393 /* create/use new log file */
1394 use_existent = true;
1395 openLogFile = XLogFileInit(openLogId, openLogSeg,
1396 &use_existent, true);
1399 /* update pg_control, unless someone else already did */
1400 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1401 if (ControlFile->logId < openLogId ||
1402 (ControlFile->logId == openLogId &&
1403 ControlFile->logSeg < openLogSeg + 1))
1405 ControlFile->logId = openLogId;
1406 ControlFile->logSeg = openLogSeg + 1;
1407 ControlFile->time = time(NULL);
1408 UpdateControlFile();
1411 * Signal bgwriter to start a checkpoint if it's been too long
1412 * since the last one. (We look at local copy of RedoRecPtr
1413 * which might be a little out of date, but should be close
1414 * enough for this purpose.)
1416 * A straight computation of segment number could overflow 32
1417 * bits. Rather than assuming we have working 64-bit
1418 * arithmetic, we compare the highest-order bits separately,
1419 * and force a checkpoint immediately when they change.
1421 if (IsUnderPostmaster)
1425 uint32 old_highbits,
1428 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1429 (RedoRecPtr.xrecoff / XLogSegSize);
1430 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1431 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile +
1433 new_highbits = openLogId / XLogSegSize;
1434 if (new_highbits != old_highbits ||
1435 new_segno >= old_segno + (uint32) CheckPointSegments)
1439 elog(LOG, "time for a checkpoint, signaling bgwriter");
1441 RequestCheckpoint(false, true);
1445 LWLockRelease(ControlFileLock);
1448 /* Make sure we have the current logfile open */
1449 if (openLogFile < 0)
1451 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1452 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1456 /* Add current page to the set of pending pages-to-dump */
1459 /* first of group */
1461 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1466 * Dump the set if this will be the last loop iteration, or if we are
1467 * at the last page of the cache area (since the next page won't be
1468 * contiguous in memory), or if we are at the end of the logfile
1471 finishing_seg = !ispartialpage &&
1472 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1474 if (!XLByteLT(LogwrtResult.Write, WriteRqst.Write) ||
1475 curridx == XLogCtl->XLogCacheBlck ||
1481 /* Need to seek in the file? */
1482 if (openLogOff != startoffset)
1484 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1486 (errcode_for_file_access(),
1487 errmsg("could not seek in log file %u, "
1488 "segment %u to offset %u: %m",
1489 openLogId, openLogSeg, startoffset)));
1490 openLogOff = startoffset;
1493 /* OK to write the page(s) */
1494 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1495 nbytes = npages * (Size) XLOG_BLCKSZ;
1497 if (write(openLogFile, from, nbytes) != nbytes)
1499 /* if write didn't set errno, assume no disk space */
1503 (errcode_for_file_access(),
1504 errmsg("could not write to log file %u, segment %u "
1505 "at offset %u, length %lu: %m",
1506 openLogId, openLogSeg,
1507 openLogOff, (unsigned long) nbytes)));
1510 /* Update state for write */
1511 openLogOff += nbytes;
1512 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1516 * If we just wrote the whole last page of a logfile segment,
1517 * fsync the segment immediately. This avoids having to go back
1518 * and re-open prior segments when an fsync request comes along
1519 * later. Doing it here ensures that one and only one backend will
1520 * perform this fsync.
1522 * This is also the right place to notify the Archiver that the
1523 * segment is ready to copy to archival storage.
1528 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1530 if (XLogArchivingActive())
1531 XLogArchiveNotifySeg(openLogId, openLogSeg);
1537 /* Only asked to write a partial page */
1538 LogwrtResult.Write = WriteRqst.Write;
1541 curridx = NextBufIdx(curridx);
1543 /* If flexible, break out of loop as soon as we wrote something */
1544 if (flexible && npages == 0)
1548 Assert(npages == 0);
1549 Assert(curridx == Write->curridx);
1552 * If asked to flush, do so
1554 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1555 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1558 * Could get here without iterating above loop, in which case we might
1559 * have no open file or the wrong one. However, we do not need to
1560 * fsync more than one file.
1562 if (sync_method != SYNC_METHOD_OPEN)
1564 if (openLogFile >= 0 &&
1565 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1567 if (openLogFile < 0)
1569 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1570 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1575 LogwrtResult.Flush = LogwrtResult.Write;
1579 * Update shared-memory status
1581 * We make sure that the shared 'request' values do not fall behind the
1582 * 'result' values. This is not absolutely essential, but it saves some
1583 * code in a couple of places.
1586 /* use volatile pointer to prevent code rearrangement */
1587 volatile XLogCtlData *xlogctl = XLogCtl;
1589 SpinLockAcquire(&xlogctl->info_lck);
1590 xlogctl->LogwrtResult = LogwrtResult;
1591 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1592 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1593 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1594 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1595 SpinLockRelease(&xlogctl->info_lck);
1598 Write->LogwrtResult = LogwrtResult;
1602 * Ensure that all XLOG data through the given position is flushed to disk.
1604 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1605 * already held, and we try to avoid acquiring it if possible.
1608 XLogFlush(XLogRecPtr record)
1610 XLogRecPtr WriteRqstPtr;
1611 XLogwrtRqst WriteRqst;
1613 /* Disabled during REDO */
1617 /* Quick exit if already known flushed */
1618 if (XLByteLE(record, LogwrtResult.Flush))
1623 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1624 record.xlogid, record.xrecoff,
1625 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1626 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1629 START_CRIT_SECTION();
1632 * Since fsync is usually a horribly expensive operation, we try to
1633 * piggyback as much data as we can on each fsync: if we see any more data
1634 * entered into the xlog buffer, we'll write and fsync that too, so that
1635 * the final value of LogwrtResult.Flush is as large as possible. This
1636 * gives us some chance of avoiding another fsync immediately after.
1639 /* initialize to given target; may increase below */
1640 WriteRqstPtr = record;
1642 /* read LogwrtResult and update local state */
1644 /* use volatile pointer to prevent code rearrangement */
1645 volatile XLogCtlData *xlogctl = XLogCtl;
1647 SpinLockAcquire(&xlogctl->info_lck);
1648 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1649 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1650 LogwrtResult = xlogctl->LogwrtResult;
1651 SpinLockRelease(&xlogctl->info_lck);
1655 if (!XLByteLE(record, LogwrtResult.Flush))
1657 /* now wait for the write lock */
1658 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1659 LogwrtResult = XLogCtl->Write.LogwrtResult;
1660 if (!XLByteLE(record, LogwrtResult.Flush))
1662 /* try to write/flush later additions to XLOG as well */
1663 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1665 XLogCtlInsert *Insert = &XLogCtl->Insert;
1666 uint32 freespace = INSERT_FREESPACE(Insert);
1668 if (freespace < SizeOfXLogRecord) /* buffer is full */
1669 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1672 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1673 WriteRqstPtr.xrecoff -= freespace;
1675 LWLockRelease(WALInsertLock);
1676 WriteRqst.Write = WriteRqstPtr;
1677 WriteRqst.Flush = WriteRqstPtr;
1681 WriteRqst.Write = WriteRqstPtr;
1682 WriteRqst.Flush = record;
1684 XLogWrite(WriteRqst, false);
1686 LWLockRelease(WALWriteLock);
1692 * If we still haven't flushed to the request point then we have a
1693 * problem; most likely, the requested flush point is past end of XLOG.
1694 * This has been seen to occur when a disk page has a corrupted LSN.
1696 * Formerly we treated this as a PANIC condition, but that hurts the
1697 * system's robustness rather than helping it: we do not want to take down
1698 * the whole system due to corruption on one data page. In particular, if
1699 * the bad page is encountered again during recovery then we would be
1700 * unable to restart the database at all! (This scenario has actually
1701 * happened in the field several times with 7.1 releases. Note that we
1702 * cannot get here while InRedo is true, but if the bad page is brought in
1703 * and marked dirty during recovery then CreateCheckPoint will try to
1704 * flush it at the end of recovery.)
1706 * The current approach is to ERROR under normal conditions, but only
1707 * WARNING during recovery, so that the system can be brought up even if
1708 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1709 * be promoted to PANIC since xact.c calls this routine inside a critical
1710 * section. However, calls from bufmgr.c are not within critical sections
1711 * and so we will not force a restart for a bad LSN on a data page.
1713 if (XLByteLT(LogwrtResult.Flush, record))
1714 elog(InRecovery ? WARNING : ERROR,
1715 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1716 record.xlogid, record.xrecoff,
1717 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1721 * Create a new XLOG file segment, or open a pre-existing one.
1723 * log, seg: identify segment to be created/opened.
1725 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1726 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1729 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1730 * place. This should be TRUE except during bootstrap log creation. The
1731 * caller must *not* hold the lock at call.
1733 * Returns FD of opened file.
1735 * Note: errors here are ERROR not PANIC because we might or might not be
1736 * inside a critical section (eg, during checkpoint there is no reason to
1737 * take down the system on failure). They will promote to PANIC if we are
1738 * in a critical section.
1741 XLogFileInit(uint32 log, uint32 seg,
1742 bool *use_existent, bool use_lock)
1744 char path[MAXPGPATH];
1745 char tmppath[MAXPGPATH];
1746 char zbuffer[XLOG_BLCKSZ];
1747 uint32 installed_log;
1748 uint32 installed_seg;
1753 XLogFilePath(path, ThisTimeLineID, log, seg);
1756 * Try to use existent file (checkpoint maker may have created it already)
1760 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1764 if (errno != ENOENT)
1766 (errcode_for_file_access(),
1767 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1775 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
1776 * another process is doing the same thing. If so, we will end up
1777 * pre-creating an extra log segment. That seems OK, and better than
1778 * holding the lock throughout this lengthy process.
1780 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1784 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1785 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1789 (errcode_for_file_access(),
1790 errmsg("could not create file \"%s\": %m", tmppath)));
1793 * Zero-fill the file. We have to do this the hard way to ensure that all
1794 * the file space has really been allocated --- on platforms that allow
1795 * "holes" in files, just seeking to the end doesn't allocate intermediate
1796 * space. This way, we know that we have all the space and (after the
1797 * fsync below) that all the indirect blocks are down on disk. Therefore,
1798 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
1801 MemSet(zbuffer, 0, sizeof(zbuffer));
1802 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(zbuffer))
1805 if ((int) write(fd, zbuffer, sizeof(zbuffer)) != (int) sizeof(zbuffer))
1807 int save_errno = errno;
1810 * If we fail to make the file, delete it to release disk space
1813 /* if write didn't set errno, assume problem is no disk space */
1814 errno = save_errno ? save_errno : ENOSPC;
1817 (errcode_for_file_access(),
1818 errmsg("could not write to file \"%s\": %m", tmppath)));
1822 if (pg_fsync(fd) != 0)
1824 (errcode_for_file_access(),
1825 errmsg("could not fsync file \"%s\": %m", tmppath)));
1829 (errcode_for_file_access(),
1830 errmsg("could not close file \"%s\": %m", tmppath)));
1833 * Now move the segment into place with its final name.
1835 * If caller didn't want to use a pre-existing file, get rid of any
1836 * pre-existing file. Otherwise, cope with possibility that someone else
1837 * has created the file while we were filling ours: if so, use ours to
1838 * pre-create a future log segment.
1840 installed_log = log;
1841 installed_seg = seg;
1842 max_advance = XLOGfileslop;
1843 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
1844 *use_existent, &max_advance,
1847 /* No need for any more future segments... */
1851 /* Set flag to tell caller there was no existent file */
1852 *use_existent = false;
1854 /* Now open original target segment (might not be file I just made) */
1855 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1859 (errcode_for_file_access(),
1860 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1867 * Create a new XLOG file segment by copying a pre-existing one.
1869 * log, seg: identify segment to be created.
1871 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
1872 * a different timeline)
1874 * Currently this is only used during recovery, and so there are no locking
1875 * considerations. But we should be just as tense as XLogFileInit to avoid
1876 * emplacing a bogus file.
1879 XLogFileCopy(uint32 log, uint32 seg,
1880 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
1882 char path[MAXPGPATH];
1883 char tmppath[MAXPGPATH];
1884 char buffer[XLOG_BLCKSZ];
1890 * Open the source file
1892 XLogFilePath(path, srcTLI, srclog, srcseg);
1893 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1896 (errcode_for_file_access(),
1897 errmsg("could not open file \"%s\": %m", path)));
1900 * Copy into a temp file name.
1902 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1906 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1907 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1911 (errcode_for_file_access(),
1912 errmsg("could not create file \"%s\": %m", tmppath)));
1915 * Do the data copying.
1917 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
1920 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
1924 (errcode_for_file_access(),
1925 errmsg("could not read file \"%s\": %m", path)));
1928 (errmsg("not enough data in file \"%s\"", path)));
1931 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
1933 int save_errno = errno;
1936 * If we fail to make the file, delete it to release disk space
1939 /* if write didn't set errno, assume problem is no disk space */
1940 errno = save_errno ? save_errno : ENOSPC;
1943 (errcode_for_file_access(),
1944 errmsg("could not write to file \"%s\": %m", tmppath)));
1948 if (pg_fsync(fd) != 0)
1950 (errcode_for_file_access(),
1951 errmsg("could not fsync file \"%s\": %m", tmppath)));
1955 (errcode_for_file_access(),
1956 errmsg("could not close file \"%s\": %m", tmppath)));
1961 * Now move the segment into place with its final name.
1963 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
1964 elog(ERROR, "InstallXLogFileSegment should not have failed");
1968 * Install a new XLOG segment file as a current or future log segment.
1970 * This is used both to install a newly-created segment (which has a temp
1971 * filename while it's being created) and to recycle an old segment.
1973 * *log, *seg: identify segment to install as (or first possible target).
1974 * When find_free is TRUE, these are modified on return to indicate the
1975 * actual installation location or last segment searched.
1977 * tmppath: initial name of file to install. It will be renamed into place.
1979 * find_free: if TRUE, install the new segment at the first empty log/seg
1980 * number at or after the passed numbers. If FALSE, install the new segment
1981 * exactly where specified, deleting any existing segment file there.
1983 * *max_advance: maximum number of log/seg slots to advance past the starting
1984 * point. Fail if no free slot is found in this range. On return, reduced
1985 * by the number of slots skipped over. (Irrelevant, and may be NULL,
1986 * when find_free is FALSE.)
1988 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1989 * place. This should be TRUE except during bootstrap log creation. The
1990 * caller must *not* hold the lock at call.
1992 * Returns TRUE if file installed, FALSE if not installed because of
1993 * exceeding max_advance limit. (Any other kind of failure causes ereport().)
1996 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
1997 bool find_free, int *max_advance,
2000 char path[MAXPGPATH];
2001 struct stat stat_buf;
2003 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2006 * We want to be sure that only one process does this at a time.
2009 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2013 /* Force installation: get rid of any pre-existing segment file */
2018 /* Find a free slot to put it in */
2019 while (stat(path, &stat_buf) == 0)
2021 if (*max_advance <= 0)
2023 /* Failed to find a free slot within specified range */
2025 LWLockRelease(ControlFileLock);
2028 NextLogSeg(*log, *seg);
2030 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2035 * Prefer link() to rename() here just to be really sure that we don't
2036 * overwrite an existing logfile. However, there shouldn't be one, so
2037 * rename() is an acceptable substitute except for the truly paranoid.
2039 #if HAVE_WORKING_LINK
2040 if (link(tmppath, path) < 0)
2042 (errcode_for_file_access(),
2043 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2044 tmppath, path, *log, *seg)));
2047 if (rename(tmppath, path) < 0)
2049 (errcode_for_file_access(),
2050 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2051 tmppath, path, *log, *seg)));
2055 LWLockRelease(ControlFileLock);
2061 * Open a pre-existing logfile segment for writing.
2064 XLogFileOpen(uint32 log, uint32 seg)
2066 char path[MAXPGPATH];
2069 XLogFilePath(path, ThisTimeLineID, log, seg);
2071 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2075 (errcode_for_file_access(),
2076 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2083 * Open a logfile segment for reading (during recovery).
2086 XLogFileRead(uint32 log, uint32 seg, int emode)
2088 char path[MAXPGPATH];
2089 char xlogfname[MAXFNAMELEN];
2094 * Loop looking for a suitable timeline ID: we might need to read any of
2095 * the timelines listed in expectedTLIs.
2097 * We expect curFileTLI on entry to be the TLI of the preceding file in
2098 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2099 * to go backwards; this prevents us from picking up the wrong file when a
2100 * parent timeline extends to higher segment numbers than the child we
2103 foreach(cell, expectedTLIs)
2105 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2107 if (tli < curFileTLI)
2108 break; /* don't bother looking at too-old TLIs */
2110 if (InArchiveRecovery)
2112 XLogFileName(xlogfname, tli, log, seg);
2113 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2118 XLogFilePath(path, tli, log, seg);
2120 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2127 if (errno != ENOENT) /* unexpected failure? */
2129 (errcode_for_file_access(),
2130 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2134 /* Couldn't find it. For simplicity, complain about front timeline */
2135 XLogFilePath(path, recoveryTargetTLI, log, seg);
2138 (errcode_for_file_access(),
2139 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2145 * Close the current logfile segment for writing.
2150 Assert(openLogFile >= 0);
2153 * posix_fadvise is problematic on many platforms: on older x86 Linux
2154 * it just dumps core, and there are reports of problems on PPC platforms
2155 * as well. The following is therefore disabled for the time being.
2156 * We could consider some kind of configure test to see if it's safe to
2157 * use, but since we lack hard evidence that there's any useful performance
2158 * gain to be had, spending time on that seems unprofitable for now.
2163 * WAL segment files will not be re-read in normal operation, so we advise
2164 * OS to release any cached pages. But do not do so if WAL archiving is
2165 * active, because archiver process could use the cache to read the WAL
2168 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync()
2169 * and O_SYNC, and some platforms only have posix_fadvise().
2171 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2172 if (!XLogArchivingActive())
2173 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2176 #endif /* NOT_USED */
2178 if (close(openLogFile))
2180 (errcode_for_file_access(),
2181 errmsg("could not close log file %u, segment %u: %m",
2182 openLogId, openLogSeg)));
2187 * Attempt to retrieve the specified file from off-line archival storage.
2188 * If successful, fill "path" with its complete path (note that this will be
2189 * a temp file name that doesn't follow the normal naming convention), and
2192 * If not successful, fill "path" with the name of the normal on-line file
2193 * (which may or may not actually exist, but we'll try to use it), and return
2196 * For fixed-size files, the caller may pass the expected size as an
2197 * additional crosscheck on successful recovery. If the file size is not
2198 * known, set expectedSize = 0.
2201 RestoreArchivedFile(char *path, const char *xlogfname,
2202 const char *recovername, off_t expectedSize)
2204 char xlogpath[MAXPGPATH];
2205 char xlogRestoreCmd[MAXPGPATH];
2210 struct stat stat_buf;
2213 * When doing archive recovery, we always prefer an archived log file even
2214 * if a file of the same name exists in XLOGDIR. The reason is that the
2215 * file in XLOGDIR could be an old, un-filled or partly-filled version
2216 * that was copied and restored as part of backing up $PGDATA.
2218 * We could try to optimize this slightly by checking the local copy
2219 * lastchange timestamp against the archived copy, but we have no API to
2220 * do this, nor can we guarantee that the lastchange timestamp was
2221 * preserved correctly when we copied to archive. Our aim is robustness,
2222 * so we elect not to do this.
2224 * If we cannot obtain the log file from the archive, however, we will try
2225 * to use the XLOGDIR file if it exists. This is so that we can make use
2226 * of log segments that weren't yet transferred to the archive.
2228 * Notice that we don't actually overwrite any files when we copy back
2229 * from archive because the recoveryRestoreCommand may inadvertently
2230 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2231 * fallback to the segments remaining in current XLOGDIR later. The
2232 * copy-from-archive filename is always the same, ensuring that we don't
2233 * run out of disk space on long recoveries.
2235 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2238 * Make sure there is no existing file named recovername.
2240 if (stat(xlogpath, &stat_buf) != 0)
2242 if (errno != ENOENT)
2244 (errcode_for_file_access(),
2245 errmsg("could not stat file \"%s\": %m",
2250 if (unlink(xlogpath) != 0)
2252 (errcode_for_file_access(),
2253 errmsg("could not remove file \"%s\": %m",
2258 * construct the command to be executed
2260 dp = xlogRestoreCmd;
2261 endp = xlogRestoreCmd + MAXPGPATH - 1;
2264 for (sp = recoveryRestoreCommand; *sp; sp++)
2271 /* %p: full path of target file */
2273 StrNCpy(dp, xlogpath, endp - dp);
2274 make_native_path(dp);
2278 /* %f: filename of desired file */
2280 StrNCpy(dp, xlogfname, endp - dp);
2284 /* convert %% to a single % */
2290 /* otherwise treat the % as not special */
2305 (errmsg_internal("executing restore command \"%s\"",
2309 * Copy xlog from archival storage to XLOGDIR
2311 rc = system(xlogRestoreCmd);
2315 * command apparently succeeded, but let's make sure the file is
2316 * really there now and has the correct size.
2318 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2319 * it, but is that too strong? We could try to plow ahead with a
2320 * local copy of the file ... but the problem is that there probably
2321 * isn't one, and we'd incorrectly conclude we've reached the end of
2322 * WAL and we're done recovering ...
2324 if (stat(xlogpath, &stat_buf) == 0)
2326 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2328 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2330 (unsigned long) stat_buf.st_size,
2331 (unsigned long) expectedSize)));
2335 (errmsg("restored log file \"%s\" from archive",
2337 strcpy(path, xlogpath);
2344 if (errno != ENOENT)
2346 (errcode_for_file_access(),
2347 errmsg("could not stat file \"%s\": %m",
2353 * remember, we rollforward UNTIL the restore fails so failure here is
2354 * just part of the process... that makes it difficult to determine
2355 * whether the restore failed because there isn't an archive to restore,
2356 * or because the administrator has specified the restore program
2357 * incorrectly. We have to assume the former.
2360 (errmsg("could not restore file \"%s\" from archive: return code %d",
2364 * if an archived file is not available, there might still be a version of
2365 * this file in XLOGDIR, so return that as the filename to open.
2367 * In many recovery scenarios we expect this to fail also, but if so that
2368 * just means we've reached the end of WAL.
2370 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2375 * Preallocate log files beyond the specified log endpoint, according to
2376 * the XLOGfile user parameter.
2379 PreallocXlogFiles(XLogRecPtr endptr)
2387 XLByteToPrevSeg(endptr, _logId, _logSeg);
2388 if ((endptr.xrecoff - 1) % XLogSegSize >=
2389 (uint32) (0.75 * XLogSegSize))
2391 NextLogSeg(_logId, _logSeg);
2392 use_existent = true;
2393 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2402 * Remove or move offline all log files older or equal to passed log/seg#
2404 * endptr is current (or recent) end of xlog; this is used to determine
2405 * whether we want to recycle rather than delete no-longer-wanted log files.
2408 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
2409 int *nsegsremoved, int *nsegsrecycled)
2415 struct dirent *xlde;
2416 char lastoff[MAXFNAMELEN];
2417 char path[MAXPGPATH];
2423 * Initialize info about where to try to recycle to. We allow recycling
2424 * segments up to XLOGfileslop segments beyond the current XLOG location.
2426 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2427 max_advance = XLOGfileslop;
2429 xldir = AllocateDir(XLOGDIR);
2432 (errcode_for_file_access(),
2433 errmsg("could not open transaction log directory \"%s\": %m",
2436 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2438 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2441 * We ignore the timeline part of the XLOG segment identifiers in
2442 * deciding whether a segment is still needed. This ensures that we
2443 * won't prematurely remove a segment from a parent timeline. We could
2444 * probably be a little more proactive about removing segments of
2445 * non-parent timelines, but that would be a whole lot more
2448 * We use the alphanumeric sorting property of the filenames to decide
2449 * which ones are earlier than the lastoff segment.
2451 if (strlen(xlde->d_name) == 24 &&
2452 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2453 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2455 if (XLogArchiveCheckDone(xlde->d_name))
2457 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2460 * Before deleting the file, see if it can be recycled as a
2461 * future log segment.
2463 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2468 (errmsg("recycled transaction log file \"%s\"",
2471 /* Needn't recheck that slot on future iterations */
2472 if (max_advance > 0)
2474 NextLogSeg(endlogId, endlogSeg);
2480 /* No need for any more future segments... */
2482 (errmsg("removing transaction log file \"%s\"",
2488 XLogArchiveCleanup(xlde->d_name);
2497 * Remove previous backup history files. This also retries creation of
2498 * .ready files for any backup history files for which XLogArchiveNotify
2502 CleanupBackupHistory(void)
2505 struct dirent *xlde;
2506 char path[MAXPGPATH];
2508 xldir = AllocateDir(XLOGDIR);
2511 (errcode_for_file_access(),
2512 errmsg("could not open transaction log directory \"%s\": %m",
2515 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2517 if (strlen(xlde->d_name) > 24 &&
2518 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2519 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2522 if (XLogArchiveCheckDone(xlde->d_name))
2525 (errmsg("removing transaction log backup history file \"%s\"",
2527 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2529 XLogArchiveCleanup(xlde->d_name);
2538 * Restore the backup blocks present in an XLOG record, if any.
2540 * We assume all of the record has been read into memory at *record.
2542 * Note: when a backup block is available in XLOG, we restore it
2543 * unconditionally, even if the page in the database appears newer.
2544 * This is to protect ourselves against database pages that were partially
2545 * or incorrectly written during a crash. We assume that the XLOG data
2546 * must be good because it has passed a CRC check, while the database
2547 * page might not be. This will force us to replay all subsequent
2548 * modifications of the page that appear in XLOG, rather than possibly
2549 * ignoring them as already applied, but that's not a huge drawback.
2552 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2561 blk = (char *) XLogRecGetData(record) + record->xl_len;
2562 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2564 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2567 memcpy(&bkpb, blk, sizeof(BkpBlock));
2568 blk += sizeof(BkpBlock);
2570 reln = XLogOpenRelation(bkpb.node);
2571 buffer = XLogReadBuffer(reln, bkpb.block, true);
2572 Assert(BufferIsValid(buffer));
2573 page = (Page) BufferGetPage(buffer);
2575 if (bkpb.hole_length == 0)
2577 memcpy((char *) page, blk, BLCKSZ);
2581 /* must zero-fill the hole */
2582 MemSet((char *) page, 0, BLCKSZ);
2583 memcpy((char *) page, blk, bkpb.hole_offset);
2584 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2585 blk + bkpb.hole_offset,
2586 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2589 PageSetLSN(page, lsn);
2590 PageSetTLI(page, ThisTimeLineID);
2591 MarkBufferDirty(buffer);
2592 UnlockReleaseBuffer(buffer);
2594 blk += BLCKSZ - bkpb.hole_length;
2599 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2600 * record (other than to the minimal extent of computing the amount of
2601 * data to read in) until we've checked the CRCs.
2603 * We assume all of the record has been read into memory at *record.
2606 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2610 uint32 len = record->xl_len;
2614 /* First the rmgr data */
2616 COMP_CRC32(crc, XLogRecGetData(record), len);
2618 /* Add in the backup blocks, if any */
2619 blk = (char *) XLogRecGetData(record) + len;
2620 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2624 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2627 memcpy(&bkpb, blk, sizeof(BkpBlock));
2628 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2631 (errmsg("incorrect hole size in record at %X/%X",
2632 recptr.xlogid, recptr.xrecoff)));
2635 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2636 COMP_CRC32(crc, blk, blen);
2640 /* Check that xl_tot_len agrees with our calculation */
2641 if (blk != (char *) record + record->xl_tot_len)
2644 (errmsg("incorrect total length in record at %X/%X",
2645 recptr.xlogid, recptr.xrecoff)));
2649 /* Finally include the record header */
2650 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2651 SizeOfXLogRecord - sizeof(pg_crc32));
2654 if (!EQ_CRC32(record->xl_crc, crc))
2657 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2658 recptr.xlogid, recptr.xrecoff)));
2666 * Attempt to read an XLOG record.
2668 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2669 * try to read a record just after the last one previously read.
2671 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2672 * (emode must be either PANIC or LOG.)
2674 * The record is copied into readRecordBuf, so that on successful return,
2675 * the returned record pointer always points there.
2678 ReadRecord(XLogRecPtr *RecPtr, int emode)
2682 XLogRecPtr tmpRecPtr = EndRecPtr;
2683 bool randAccess = false;
2686 uint32 targetPageOff;
2687 uint32 targetRecOff;
2688 uint32 pageHeaderSize;
2690 if (readBuf == NULL)
2693 * First time through, permanently allocate readBuf. We do it this
2694 * way, rather than just making a static array, for two reasons: (1)
2695 * no need to waste the storage in most instantiations of the backend;
2696 * (2) a static char array isn't guaranteed to have any particular
2697 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2699 readBuf = (char *) malloc(XLOG_BLCKSZ);
2700 Assert(readBuf != NULL);
2705 RecPtr = &tmpRecPtr;
2706 /* fast case if next record is on same page */
2707 if (nextRecord != NULL)
2709 record = nextRecord;
2712 /* align old recptr to next page */
2713 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2714 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2715 if (tmpRecPtr.xrecoff >= XLogFileSize)
2717 (tmpRecPtr.xlogid)++;
2718 tmpRecPtr.xrecoff = 0;
2720 /* We will account for page header size below */
2724 if (!XRecOffIsValid(RecPtr->xrecoff))
2726 (errmsg("invalid record offset at %X/%X",
2727 RecPtr->xlogid, RecPtr->xrecoff)));
2730 * Since we are going to a random position in WAL, forget any prior
2731 * state about what timeline we were in, and allow it to be any
2732 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
2733 * to go backwards (but we can't reset that variable right here, since
2734 * we might not change files at all).
2736 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2737 randAccess = true; /* allow curFileTLI to go backwards too */
2740 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2745 XLByteToSeg(*RecPtr, readId, readSeg);
2748 /* Now it's okay to reset curFileTLI if random fetch */
2752 readFile = XLogFileRead(readId, readSeg, emode);
2754 goto next_record_is_invalid;
2757 * Whenever switching to a new WAL segment, we read the first page of
2758 * the file and validate its header, even if that's not where the
2759 * target record is. This is so that we can check the additional
2760 * identification info that is present in the first page's "long"
2764 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2767 (errcode_for_file_access(),
2768 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2769 readId, readSeg, readOff)));
2770 goto next_record_is_invalid;
2772 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2773 goto next_record_is_invalid;
2776 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2777 if (readOff != targetPageOff)
2779 readOff = targetPageOff;
2780 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2783 (errcode_for_file_access(),
2784 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2785 readId, readSeg, readOff)));
2786 goto next_record_is_invalid;
2788 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2791 (errcode_for_file_access(),
2792 errmsg("could not read from log file %u, segment %u at offset %u: %m",
2793 readId, readSeg, readOff)));
2794 goto next_record_is_invalid;
2796 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2797 goto next_record_is_invalid;
2799 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2800 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
2801 if (targetRecOff == 0)
2804 * Can only get here in the continuing-from-prev-page case, because
2805 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
2806 * to skip over the new page's header.
2808 tmpRecPtr.xrecoff += pageHeaderSize;
2809 targetRecOff = pageHeaderSize;
2811 else if (targetRecOff < pageHeaderSize)
2814 (errmsg("invalid record offset at %X/%X",
2815 RecPtr->xlogid, RecPtr->xrecoff)));
2816 goto next_record_is_invalid;
2818 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
2819 targetRecOff == pageHeaderSize)
2822 (errmsg("contrecord is requested by %X/%X",
2823 RecPtr->xlogid, RecPtr->xrecoff)));
2824 goto next_record_is_invalid;
2826 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
2831 * Currently, xl_len == 0 must be bad data, but that might not be true
2832 * forever. See note in XLogInsert.
2834 if (record->xl_len == 0)
2837 (errmsg("record with zero length at %X/%X",
2838 RecPtr->xlogid, RecPtr->xrecoff)));
2839 goto next_record_is_invalid;
2841 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
2842 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
2843 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
2846 (errmsg("invalid record length at %X/%X",
2847 RecPtr->xlogid, RecPtr->xrecoff)));
2848 goto next_record_is_invalid;
2850 if (record->xl_rmid > RM_MAX_ID)
2853 (errmsg("invalid resource manager ID %u at %X/%X",
2854 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
2855 goto next_record_is_invalid;
2860 * We can't exactly verify the prev-link, but surely it should be less
2861 * than the record's own address.
2863 if (!XLByteLT(record->xl_prev, *RecPtr))
2866 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
2867 record->xl_prev.xlogid, record->xl_prev.xrecoff,
2868 RecPtr->xlogid, RecPtr->xrecoff)));
2869 goto next_record_is_invalid;
2875 * Record's prev-link should exactly match our previous location. This
2876 * check guards against torn WAL pages where a stale but valid-looking
2877 * WAL record starts on a sector boundary.
2879 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
2882 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
2883 record->xl_prev.xlogid, record->xl_prev.xrecoff,
2884 RecPtr->xlogid, RecPtr->xrecoff)));
2885 goto next_record_is_invalid;
2890 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
2891 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
2892 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
2893 * enough for all "normal" records, but very large commit or abort records
2894 * might need more space.)
2896 total_len = record->xl_tot_len;
2897 if (total_len > readRecordBufSize)
2899 uint32 newSize = total_len;
2901 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
2902 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
2904 free(readRecordBuf);
2905 readRecordBuf = (char *) malloc(newSize);
2908 readRecordBufSize = 0;
2909 /* We treat this as a "bogus data" condition */
2911 (errmsg("record length %u at %X/%X too long",
2912 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
2913 goto next_record_is_invalid;
2915 readRecordBufSize = newSize;
2918 buffer = readRecordBuf;
2920 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
2921 if (total_len > len)
2923 /* Need to reassemble record */
2924 XLogContRecord *contrecord;
2925 uint32 gotlen = len;
2927 memcpy(buffer, record, len);
2928 record = (XLogRecord *) buffer;
2932 readOff += XLOG_BLCKSZ;
2933 if (readOff >= XLogSegSize)
2937 NextLogSeg(readId, readSeg);
2938 readFile = XLogFileRead(readId, readSeg, emode);
2940 goto next_record_is_invalid;
2943 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2946 (errcode_for_file_access(),
2947 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2948 readId, readSeg, readOff)));
2949 goto next_record_is_invalid;
2951 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2952 goto next_record_is_invalid;
2953 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
2956 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
2957 readId, readSeg, readOff)));
2958 goto next_record_is_invalid;
2960 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2961 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
2962 if (contrecord->xl_rem_len == 0 ||
2963 total_len != (contrecord->xl_rem_len + gotlen))
2966 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
2967 contrecord->xl_rem_len,
2968 readId, readSeg, readOff)));
2969 goto next_record_is_invalid;
2971 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
2972 if (contrecord->xl_rem_len > len)
2974 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
2979 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
2980 contrecord->xl_rem_len);
2983 if (!RecordIsValid(record, *RecPtr, emode))
2984 goto next_record_is_invalid;
2985 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2986 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
2987 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
2989 nextRecord = (XLogRecord *) ((char *) contrecord +
2990 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
2992 EndRecPtr.xlogid = readId;
2993 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
2995 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
2996 ReadRecPtr = *RecPtr;
3000 /* Record does not cross a page boundary */
3001 if (!RecordIsValid(record, *RecPtr, emode))
3002 goto next_record_is_invalid;
3003 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3004 MAXALIGN(total_len))
3005 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3006 EndRecPtr.xlogid = RecPtr->xlogid;
3007 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3008 ReadRecPtr = *RecPtr;
3009 memcpy(buffer, record, total_len);
3010 return (XLogRecord *) buffer;
3012 next_record_is_invalid:;
3020 * Check whether the xlog header of a page just read in looks valid.
3022 * This is just a convenience subroutine to avoid duplicated code in
3023 * ReadRecord. It's not intended for use from anywhere else.
3026 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3030 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3033 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3034 hdr->xlp_magic, readId, readSeg, readOff)));
3037 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3040 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3041 hdr->xlp_info, readId, readSeg, readOff)));
3044 if (hdr->xlp_info & XLP_LONG_HEADER)
3046 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3048 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3050 char fhdrident_str[32];
3051 char sysident_str[32];
3054 * Format sysids separately to keep platform-dependent format code
3055 * out of the translatable message string.
3057 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3058 longhdr->xlp_sysid);
3059 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3060 ControlFile->system_identifier);
3062 (errmsg("WAL file is from different system"),
3063 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3064 fhdrident_str, sysident_str)));
3067 if (longhdr->xlp_seg_size != XLogSegSize)
3070 (errmsg("WAL file is from different system"),
3071 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3074 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3077 (errmsg("WAL file is from different system"),
3078 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3082 else if (readOff == 0)
3084 /* hmm, first page of file doesn't have a long header? */
3086 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3087 hdr->xlp_info, readId, readSeg, readOff)));
3091 recaddr.xlogid = readId;
3092 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3093 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3096 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3097 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3098 readId, readSeg, readOff)));
3103 * Check page TLI is one of the expected values.
3105 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3108 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3110 readId, readSeg, readOff)));
3115 * Since child timelines are always assigned a TLI greater than their
3116 * immediate parent's TLI, we should never see TLI go backwards across
3117 * successive pages of a consistent WAL sequence.
3119 * Of course this check should only be applied when advancing sequentially
3120 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3121 * going to a random page.
3123 if (hdr->xlp_tli < lastPageTLI)
3126 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3127 hdr->xlp_tli, lastPageTLI,
3128 readId, readSeg, readOff)));
3131 lastPageTLI = hdr->xlp_tli;
3136 * Try to read a timeline's history file.
3138 * If successful, return the list of component TLIs (the given TLI followed by
3139 * its ancestor TLIs). If we can't find the history file, assume that the
3140 * timeline has no parents, and return a list of just the specified timeline
3144 readTimeLineHistory(TimeLineID targetTLI)
3147 char path[MAXPGPATH];
3148 char histfname[MAXFNAMELEN];
3149 char fline[MAXPGPATH];
3152 if (InArchiveRecovery)
3154 TLHistoryFileName(histfname, targetTLI);
3155 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3158 TLHistoryFilePath(path, targetTLI);
3160 fd = AllocateFile(path, "r");
3163 if (errno != ENOENT)
3165 (errcode_for_file_access(),
3166 errmsg("could not open file \"%s\": %m", path)));
3167 /* Not there, so assume no parents */
3168 return list_make1_int((int) targetTLI);
3176 while (fgets(fline, MAXPGPATH, fd) != NULL)
3178 /* skip leading whitespace and check for # comment */
3183 for (ptr = fline; *ptr; ptr++)
3185 if (!isspace((unsigned char) *ptr))
3188 if (*ptr == '\0' || *ptr == '#')
3191 /* expect a numeric timeline ID as first field of line */
3192 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3195 (errmsg("syntax error in history file: %s", fline),
3196 errhint("Expected a numeric timeline ID.")));
3199 tli <= (TimeLineID) linitial_int(result))
3201 (errmsg("invalid data in history file: %s", fline),
3202 errhint("Timeline IDs must be in increasing sequence.")));
3204 /* Build list with newest item first */
3205 result = lcons_int((int) tli, result);
3207 /* we ignore the remainder of each line */
3213 targetTLI <= (TimeLineID) linitial_int(result))
3215 (errmsg("invalid data in history file \"%s\"", path),
3216 errhint("Timeline IDs must be less than child timeline's ID.")));
3218 result = lcons_int((int) targetTLI, result);
3221 (errmsg_internal("history of timeline %u is %s",
3222 targetTLI, nodeToString(result))));
3228 * Probe whether a timeline history file exists for the given timeline ID
3231 existsTimeLineHistory(TimeLineID probeTLI)
3233 char path[MAXPGPATH];
3234 char histfname[MAXFNAMELEN];
3237 if (InArchiveRecovery)
3239 TLHistoryFileName(histfname, probeTLI);
3240 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3243 TLHistoryFilePath(path, probeTLI);
3245 fd = AllocateFile(path, "r");
3253 if (errno != ENOENT)
3255 (errcode_for_file_access(),
3256 errmsg("could not open file \"%s\": %m", path)));
3262 * Find the newest existing timeline, assuming that startTLI exists.
3264 * Note: while this is somewhat heuristic, it does positively guarantee
3265 * that (result + 1) is not a known timeline, and therefore it should
3266 * be safe to assign that ID to a new timeline.
3269 findNewestTimeLine(TimeLineID startTLI)
3271 TimeLineID newestTLI;
3272 TimeLineID probeTLI;
3275 * The algorithm is just to probe for the existence of timeline history
3276 * files. XXX is it useful to allow gaps in the sequence?
3278 newestTLI = startTLI;
3280 for (probeTLI = startTLI + 1;; probeTLI++)
3282 if (existsTimeLineHistory(probeTLI))
3284 newestTLI = probeTLI; /* probeTLI exists */
3288 /* doesn't exist, assume we're done */
3297 * Create a new timeline history file.
3299 * newTLI: ID of the new timeline
3300 * parentTLI: ID of its immediate parent
3301 * endTLI et al: ID of the last used WAL file, for annotation purposes
3303 * Currently this is only used during recovery, and so there are no locking
3304 * considerations. But we should be just as tense as XLogFileInit to avoid
3305 * emplacing a bogus file.
3308 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3309 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3311 char path[MAXPGPATH];
3312 char tmppath[MAXPGPATH];
3313 char histfname[MAXFNAMELEN];
3314 char xlogfname[MAXFNAMELEN];
3315 char buffer[BLCKSZ];
3320 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3323 * Write into a temp file name.
3325 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3329 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3330 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3334 (errcode_for_file_access(),
3335 errmsg("could not create file \"%s\": %m", tmppath)));
3338 * If a history file exists for the parent, copy it verbatim
3340 if (InArchiveRecovery)
3342 TLHistoryFileName(histfname, parentTLI);
3343 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3346 TLHistoryFilePath(path, parentTLI);
3348 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3351 if (errno != ENOENT)
3353 (errcode_for_file_access(),
3354 errmsg("could not open file \"%s\": %m", path)));
3355 /* Not there, so assume parent has no parents */
3362 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3363 if (nbytes < 0 || errno != 0)
3365 (errcode_for_file_access(),
3366 errmsg("could not read file \"%s\": %m", path)));
3370 if ((int) write(fd, buffer, nbytes) != nbytes)
3372 int save_errno = errno;
3375 * If we fail to make the file, delete it to release disk
3381 * if write didn't set errno, assume problem is no disk space
3383 errno = save_errno ? save_errno : ENOSPC;
3386 (errcode_for_file_access(),
3387 errmsg("could not write to file \"%s\": %m", tmppath)));
3394 * Append one line with the details of this timeline split.
3396 * If we did have a parent file, insert an extra newline just in case the
3397 * parent file failed to end with one.
3399 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3401 snprintf(buffer, sizeof(buffer),
3402 "%s%u\t%s\t%s transaction %u at %s\n",
3403 (srcfd < 0) ? "" : "\n",
3406 recoveryStopAfter ? "after" : "before",
3408 str_time(recoveryStopTime));
3410 nbytes = strlen(buffer);
3412 if ((int) write(fd, buffer, nbytes) != nbytes)
3414 int save_errno = errno;
3417 * If we fail to make the file, delete it to release disk space
3420 /* if write didn't set errno, assume problem is no disk space */
3421 errno = save_errno ? save_errno : ENOSPC;
3424 (errcode_for_file_access(),
3425 errmsg("could not write to file \"%s\": %m", tmppath)));
3428 if (pg_fsync(fd) != 0)
3430 (errcode_for_file_access(),
3431 errmsg("could not fsync file \"%s\": %m", tmppath)));
3435 (errcode_for_file_access(),
3436 errmsg("could not close file \"%s\": %m", tmppath)));
3440 * Now move the completed history file into place with its final name.
3442 TLHistoryFilePath(path, newTLI);
3445 * Prefer link() to rename() here just to be really sure that we don't
3446 * overwrite an existing logfile. However, there shouldn't be one, so
3447 * rename() is an acceptable substitute except for the truly paranoid.
3449 #if HAVE_WORKING_LINK
3450 if (link(tmppath, path) < 0)
3452 (errcode_for_file_access(),
3453 errmsg("could not link file \"%s\" to \"%s\": %m",
3457 if (rename(tmppath, path) < 0)
3459 (errcode_for_file_access(),
3460 errmsg("could not rename file \"%s\" to \"%s\": %m",
3464 /* The history file can be archived immediately. */
3465 TLHistoryFileName(histfname, newTLI);
3466 XLogArchiveNotify(histfname);
3470 * I/O routines for pg_control
3472 * *ControlFile is a buffer in shared memory that holds an image of the
3473 * contents of pg_control. WriteControlFile() initializes pg_control
3474 * given a preloaded buffer, ReadControlFile() loads the buffer from
3475 * the pg_control file (during postmaster or standalone-backend startup),
3476 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3478 * For simplicity, WriteControlFile() initializes the fields of pg_control
3479 * that are related to checking backend/database compatibility, and
3480 * ReadControlFile() verifies they are correct. We could split out the
3481 * I/O and compatibility-check functions, but there seems no need currently.
3484 WriteControlFile(void)
3487 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3491 * Initialize version and compatibility-check fields
3493 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3494 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3496 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3497 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3499 ControlFile->blcksz = BLCKSZ;
3500 ControlFile->relseg_size = RELSEG_SIZE;
3501 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3502 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3504 ControlFile->nameDataLen = NAMEDATALEN;
3505 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3507 #ifdef HAVE_INT64_TIMESTAMP
3508 ControlFile->enableIntTimes = TRUE;
3510 ControlFile->enableIntTimes = FALSE;
3513 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3514 localeptr = setlocale(LC_COLLATE, NULL);
3517 (errmsg("invalid LC_COLLATE setting")));
3518 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3519 localeptr = setlocale(LC_CTYPE, NULL);
3522 (errmsg("invalid LC_CTYPE setting")));
3523 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3525 /* Contents are protected with a CRC */
3526 INIT_CRC32(ControlFile->crc);
3527 COMP_CRC32(ControlFile->crc,
3528 (char *) ControlFile,
3529 offsetof(ControlFileData, crc));
3530 FIN_CRC32(ControlFile->crc);
3533 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3534 * excess over sizeof(ControlFileData). This reduces the odds of
3535 * premature-EOF errors when reading pg_control. We'll still fail when we
3536 * check the contents of the file, but hopefully with a more specific
3537 * error than "couldn't read pg_control".
3539 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3540 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3542 memset(buffer, 0, PG_CONTROL_SIZE);
3543 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3545 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3546 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3550 (errcode_for_file_access(),
3551 errmsg("could not create control file \"%s\": %m",
3552 XLOG_CONTROL_FILE)));
3555 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3557 /* if write didn't set errno, assume problem is no disk space */
3561 (errcode_for_file_access(),
3562 errmsg("could not write to control file: %m")));
3565 if (pg_fsync(fd) != 0)
3567 (errcode_for_file_access(),
3568 errmsg("could not fsync control file: %m")));
3572 (errcode_for_file_access(),
3573 errmsg("could not close control file: %m")));
3577 ReadControlFile(void)
3585 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3590 (errcode_for_file_access(),
3591 errmsg("could not open control file \"%s\": %m",
3592 XLOG_CONTROL_FILE)));
3594 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3596 (errcode_for_file_access(),
3597 errmsg("could not read from control file: %m")));
3602 * Check for expected pg_control format version. If this is wrong, the
3603 * CRC check will likely fail because we'll be checking the wrong number
3604 * of bytes. Complaining about wrong version will probably be more
3605 * enlightening than complaining about wrong CRC.
3607 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3609 (errmsg("database files are incompatible with server"),
3610 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3611 " but the server was compiled with PG_CONTROL_VERSION %d.",
3612 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3613 errhint("It looks like you need to initdb.")));
3614 /* Now check the CRC. */
3617 (char *) ControlFile,
3618 offsetof(ControlFileData, crc));
3621 if (!EQ_CRC32(crc, ControlFile->crc))
3623 (errmsg("incorrect checksum in control file")));
3626 * Do compatibility checking immediately. We do this here for 2 reasons:
3628 * (1) if the database isn't compatible with the backend executable, we
3629 * want to abort before we can possibly do any damage;
3631 * (2) this code is executed in the postmaster, so the setlocale() will
3632 * propagate to forked backends, which aren't going to read this file for
3633 * themselves. (These locale settings are considered critical
3634 * compatibility items because they can affect sort order of indexes.)
3636 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3638 (errmsg("database files are incompatible with server"),
3639 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3640 " but the server was compiled with CATALOG_VERSION_NO %d.",
3641 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3642 errhint("It looks like you need to initdb.")));
3643 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3645 (errmsg("database files are incompatible with server"),
3646 errdetail("The database cluster was initialized with MAXALIGN %d,"
3647 " but the server was compiled with MAXALIGN %d.",
3648 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3649 errhint("It looks like you need to initdb.")));
3650 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3652 (errmsg("database files are incompatible with server"),
3653 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3654 errhint("It looks like you need to initdb.")));
3655 if (ControlFile->blcksz != BLCKSZ)
3657 (errmsg("database files are incompatible with server"),
3658 errdetail("The database cluster was initialized with BLCKSZ %d,"
3659 " but the server was compiled with BLCKSZ %d.",
3660 ControlFile->blcksz, BLCKSZ),
3661 errhint("It looks like you need to recompile or initdb.")));
3662 if (ControlFile->relseg_size != RELSEG_SIZE)
3664 (errmsg("database files are incompatible with server"),
3665 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3666 " but the server was compiled with RELSEG_SIZE %d.",
3667 ControlFile->relseg_size, RELSEG_SIZE),
3668 errhint("It looks like you need to recompile or initdb.")));
3669 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3671 (errmsg("database files are incompatible with server"),
3672 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3673 " but the server was compiled with XLOG_BLCKSZ %d.",
3674 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3675 errhint("It looks like you need to recompile or initdb.")));
3676 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3678 (errmsg("database files are incompatible with server"),
3679 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3680 " but the server was compiled with XLOG_SEG_SIZE %d.",
3681 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3682 errhint("It looks like you need to recompile or initdb.")));
3683 if (ControlFile->nameDataLen != NAMEDATALEN)
3685 (errmsg("database files are incompatible with server"),
3686 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3687 " but the server was compiled with NAMEDATALEN %d.",
3688 ControlFile->nameDataLen, NAMEDATALEN),
3689 errhint("It looks like you need to recompile or initdb.")));
3690 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3692 (errmsg("database files are incompatible with server"),
3693 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3694 " but the server was compiled with INDEX_MAX_KEYS %d.",
3695 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3696 errhint("It looks like you need to recompile or initdb.")));
3698 #ifdef HAVE_INT64_TIMESTAMP
3699 if (ControlFile->enableIntTimes != TRUE)
3701 (errmsg("database files are incompatible with server"),
3702 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3703 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3704 errhint("It looks like you need to recompile or initdb.")));
3706 if (ControlFile->enableIntTimes != FALSE)
3708 (errmsg("database files are incompatible with server"),
3709 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3710 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3711 errhint("It looks like you need to recompile or initdb.")));
3714 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3716 (errmsg("database files are incompatible with server"),
3717 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3718 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3719 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3720 errhint("It looks like you need to recompile or initdb.")));
3721 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3723 (errmsg("database files are incompatible with operating system"),
3724 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3725 " which is not recognized by setlocale().",
3726 ControlFile->lc_collate),
3727 errhint("It looks like you need to initdb or install locale support.")));
3728 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3730 (errmsg("database files are incompatible with operating system"),
3731 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3732 " which is not recognized by setlocale().",
3733 ControlFile->lc_ctype),
3734 errhint("It looks like you need to initdb or install locale support.")));
3736 /* Make the fixed locale settings visible as GUC variables, too */
3737 SetConfigOption("lc_collate", ControlFile->lc_collate,
3738 PGC_INTERNAL, PGC_S_OVERRIDE);
3739 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3740 PGC_INTERNAL, PGC_S_OVERRIDE);
3744 UpdateControlFile(void)
3748 INIT_CRC32(ControlFile->crc);
3749 COMP_CRC32(ControlFile->crc,
3750 (char *) ControlFile,
3751 offsetof(ControlFileData, crc));
3752 FIN_CRC32(ControlFile->crc);
3754 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3759 (errcode_for_file_access(),
3760 errmsg("could not open control file \"%s\": %m",
3761 XLOG_CONTROL_FILE)));
3764 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3766 /* if write didn't set errno, assume problem is no disk space */
3770 (errcode_for_file_access(),
3771 errmsg("could not write to control file: %m")));
3774 if (pg_fsync(fd) != 0)
3776 (errcode_for_file_access(),
3777 errmsg("could not fsync control file: %m")));
3781 (errcode_for_file_access(),
3782 errmsg("could not close control file: %m")));
3786 * Initialization of shared memory for XLOG
3794 size = sizeof(XLogCtlData);
3795 /* xlblocks array */
3796 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
3797 /* extra alignment padding for XLOG I/O buffers */
3798 size = add_size(size, ALIGNOF_XLOG_BUFFER);
3799 /* and the buffers themselves */
3800 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
3803 * Note: we don't count ControlFileData, it comes out of the "slop factor"
3804 * added by CreateSharedMemoryAndSemaphores. This lets us use this
3805 * routine again below to compute the actual allocation size.
3818 ControlFile = (ControlFileData *)
3819 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
3820 XLogCtl = (XLogCtlData *)
3821 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
3823 if (foundCFile || foundXLog)
3825 /* both should be present or neither */
3826 Assert(foundCFile && foundXLog);
3830 memset(XLogCtl, 0, sizeof(XLogCtlData));
3833 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
3834 * multiple of the alignment for same, so no extra alignment padding is
3837 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
3838 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
3839 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
3840 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
3843 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
3845 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
3846 XLogCtl->pages = allocptr;
3847 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
3850 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
3851 * in additional info.)
3853 XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ * XLOGbuffers;
3855 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
3856 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
3857 SpinLockInit(&XLogCtl->info_lck);
3860 * If we are not in bootstrap mode, pg_control should already exist. Read
3861 * and validate it immediately (see comments in ReadControlFile() for the
3864 if (!IsBootstrapProcessingMode())
3869 * This func must be called ONCE on system install. It creates pg_control
3870 * and the initial XLOG segment.
3875 CheckPoint checkPoint;
3877 XLogPageHeader page;
3878 XLogLongPageHeader longpage;
3881 uint64 sysidentifier;
3886 * Select a hopefully-unique system identifier code for this installation.
3887 * We use the result of gettimeofday(), including the fractional seconds
3888 * field, as being about as unique as we can easily get. (Think not to
3889 * use random(), since it hasn't been seeded and there's no portable way
3890 * to seed it other than the system clock value...) The upper half of the
3891 * uint64 value is just the tv_sec part, while the lower half is the XOR
3892 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
3893 * unnecessarily if "uint64" is really only 32 bits wide. A person
3894 * knowing this encoding can determine the initialization time of the
3895 * installation, which could perhaps be useful sometimes.
3897 gettimeofday(&tv, NULL);
3898 sysidentifier = ((uint64) tv.tv_sec) << 32;
3899 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
3901 /* First timeline ID is always 1 */
3904 /* page buffer must be aligned suitably for O_DIRECT */
3905 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
3906 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
3907 memset(page, 0, XLOG_BLCKSZ);
3909 /* Set up information for the initial checkpoint record */
3910 checkPoint.redo.xlogid = 0;
3911 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
3912 checkPoint.undo = checkPoint.redo;
3913 checkPoint.ThisTimeLineID = ThisTimeLineID;
3914 checkPoint.nextXid = FirstNormalTransactionId;
3915 checkPoint.nextOid = FirstBootstrapObjectId;
3916 checkPoint.nextMulti = FirstMultiXactId;
3917 checkPoint.nextMultiOffset = 0;
3918 checkPoint.time = time(NULL);
3920 ShmemVariableCache->nextXid = checkPoint.nextXid;
3921 ShmemVariableCache->nextOid = checkPoint.nextOid;
3922 ShmemVariableCache->oidCount = 0;
3923 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
3925 /* Set up the XLOG page header */
3926 page->xlp_magic = XLOG_PAGE_MAGIC;
3927 page->xlp_info = XLP_LONG_HEADER;
3928 page->xlp_tli = ThisTimeLineID;
3929 page->xlp_pageaddr.xlogid = 0;
3930 page->xlp_pageaddr.xrecoff = 0;
3931 longpage = (XLogLongPageHeader) page;
3932 longpage->xlp_sysid = sysidentifier;
3933 longpage->xlp_seg_size = XLogSegSize;
3934 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
3936 /* Insert the initial checkpoint record */
3937 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
3938 record->xl_prev.xlogid = 0;
3939 record->xl_prev.xrecoff = 0;
3940 record->xl_xid = InvalidTransactionId;
3941 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
3942 record->xl_len = sizeof(checkPoint);
3943 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
3944 record->xl_rmid = RM_XLOG_ID;
3945 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
3948 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
3949 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
3950 SizeOfXLogRecord - sizeof(pg_crc32));
3952 record->xl_crc = crc;
3954 /* Create first XLOG segment file */
3955 use_existent = false;
3956 openLogFile = XLogFileInit(0, 0, &use_existent, false);
3958 /* Write the first page with the initial record */
3960 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3962 /* if write didn't set errno, assume problem is no disk space */
3966 (errcode_for_file_access(),
3967 errmsg("could not write bootstrap transaction log file: %m")));
3970 if (pg_fsync(openLogFile) != 0)
3972 (errcode_for_file_access(),
3973 errmsg("could not fsync bootstrap transaction log file: %m")));
3975 if (close(openLogFile))
3977 (errcode_for_file_access(),
3978 errmsg("could not close bootstrap transaction log file: %m")));
3982 /* Now create pg_control */
3984 memset(ControlFile, 0, sizeof(ControlFileData));
3985 /* Initialize pg_control status fields */
3986 ControlFile->system_identifier = sysidentifier;
3987 ControlFile->state = DB_SHUTDOWNED;
3988 ControlFile->time = checkPoint.time;
3989 ControlFile->logId = 0;
3990 ControlFile->logSeg = 1;
3991 ControlFile->checkPoint = checkPoint.redo;
3992 ControlFile->checkPointCopy = checkPoint;
3993 /* some additional ControlFile fields are set in WriteControlFile() */
3997 /* Bootstrap the commit log, too */
3999 BootStrapSUBTRANS();
4000 BootStrapMultiXact();
4006 str_time(time_t tnow)
4008 static char buf[128];
4010 strftime(buf, sizeof(buf),
4011 "%Y-%m-%d %H:%M:%S %Z",
4018 * See if there is a recovery command file (recovery.conf), and if so
4019 * read in parameters for archive recovery.
4021 * XXX longer term intention is to expand this to
4022 * cater for additional parameters and controls
4023 * possibly use a flex lexer similar to the GUC one
4026 readRecoveryCommandFile(void)
4029 char cmdline[MAXPGPATH];
4030 TimeLineID rtli = 0;
4031 bool rtliGiven = false;
4032 bool syntaxError = false;
4034 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4037 if (errno == ENOENT)
4038 return; /* not there, so no archive recovery */
4040 (errcode_for_file_access(),
4041 errmsg("could not open recovery command file \"%s\": %m",
4042 RECOVERY_COMMAND_FILE)));
4046 (errmsg("starting archive recovery")));
4051 while (fgets(cmdline, MAXPGPATH, fd) != NULL)
4053 /* skip leading whitespace and check for # comment */
4058 for (ptr = cmdline; *ptr; ptr++)
4060 if (!isspace((unsigned char) *ptr))
4063 if (*ptr == '\0' || *ptr == '#')
4066 /* identify the quoted parameter value */
4067 tok1 = strtok(ptr, "'");
4073 tok2 = strtok(NULL, "'");
4079 /* reparse to get just the parameter name */
4080 tok1 = strtok(ptr, " \t=");
4087 if (strcmp(tok1, "restore_command") == 0)
4089 recoveryRestoreCommand = pstrdup(tok2);
4091 (errmsg("restore_command = \"%s\"",
4092 recoveryRestoreCommand)));
4094 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4097 if (strcmp(tok2, "latest") == 0)
4102 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4103 if (errno == EINVAL || errno == ERANGE)
4105 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4110 (errmsg("recovery_target_timeline = %u", rtli)));
4113 (errmsg("recovery_target_timeline = latest")));
4115 else if (strcmp(tok1, "recovery_target_xid") == 0)
4118 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4119 if (errno == EINVAL || errno == ERANGE)
4121 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4124 (errmsg("recovery_target_xid = %u",
4125 recoveryTargetXid)));
4126 recoveryTarget = true;
4127 recoveryTargetExact = true;
4129 else if (strcmp(tok1, "recovery_target_time") == 0)
4132 * if recovery_target_xid specified, then this overrides
4133 * recovery_target_time
4135 if (recoveryTargetExact)
4137 recoveryTarget = true;
4138 recoveryTargetExact = false;
4141 * Convert the time string given by the user to the time_t format.
4142 * We use type abstime's input converter because we know abstime
4143 * has the same representation as time_t.
4145 recoveryTargetTime = (time_t)
4146 DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
4147 CStringGetDatum(tok2)));
4149 (errmsg("recovery_target_time = %s",
4150 DatumGetCString(DirectFunctionCall1(abstimeout,
4151 AbsoluteTimeGetDatum((AbsoluteTime) recoveryTargetTime))))));
4153 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4156 * does nothing if a recovery_target is not also set
4158 if (strcmp(tok2, "true") == 0)
4159 recoveryTargetInclusive = true;
4162 recoveryTargetInclusive = false;
4166 (errmsg("recovery_target_inclusive = %s", tok2)));
4170 (errmsg("unrecognized recovery parameter \"%s\"",
4178 (errmsg("syntax error in recovery command file: %s",
4180 errhint("Lines should have the format parameter = 'value'.")));
4182 /* Check that required parameters were supplied */
4183 if (recoveryRestoreCommand == NULL)
4185 (errmsg("recovery command file \"%s\" did not specify restore_command",
4186 RECOVERY_COMMAND_FILE)));
4188 /* Enable fetching from archive recovery area */
4189 InArchiveRecovery = true;
4192 * If user specified recovery_target_timeline, validate it or compute the
4193 * "latest" value. We can't do this until after we've gotten the restore
4194 * command and set InArchiveRecovery, because we need to fetch timeline
4195 * history files from the archive.
4201 /* Timeline 1 does not have a history file, all else should */
4202 if (rtli != 1 && !existsTimeLineHistory(rtli))
4204 (errmsg("recovery_target_timeline %u does not exist",
4206 recoveryTargetTLI = rtli;
4210 /* We start the "latest" search from pg_control's timeline */
4211 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4217 * Exit archive-recovery state
4220 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4222 char recoveryPath[MAXPGPATH];
4223 char xlogpath[MAXPGPATH];
4226 * We are no longer in archive recovery state.
4228 InArchiveRecovery = false;
4231 * We should have the ending log segment currently open. Verify, and then
4232 * close it (to avoid problems on Windows with trying to rename or delete
4235 Assert(readFile >= 0);
4236 Assert(readId == endLogId);
4237 Assert(readSeg == endLogSeg);
4243 * If the segment was fetched from archival storage, we want to replace
4244 * the existing xlog segment (if any) with the archival version. This is
4245 * because whatever is in XLOGDIR is very possibly older than what we have
4246 * from the archives, since it could have come from restoring a PGDATA
4247 * backup. In any case, the archival version certainly is more
4248 * descriptive of what our current database state is, because that is what
4251 * Note that if we are establishing a new timeline, ThisTimeLineID is
4252 * already set to the new value, and so we will create a new file instead
4253 * of overwriting any existing file.
4255 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4256 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4258 if (restoredFromArchive)
4261 (errmsg_internal("moving last restored xlog to \"%s\"",
4263 unlink(xlogpath); /* might or might not exist */
4264 if (rename(recoveryPath, xlogpath) != 0)
4266 (errcode_for_file_access(),
4267 errmsg("could not rename file \"%s\" to \"%s\": %m",
4268 recoveryPath, xlogpath)));
4269 /* XXX might we need to fix permissions on the file? */
4274 * If the latest segment is not archival, but there's still a
4275 * RECOVERYXLOG laying about, get rid of it.
4277 unlink(recoveryPath); /* ignore any error */
4280 * If we are establishing a new timeline, we have to copy data from
4281 * the last WAL segment of the old timeline to create a starting WAL
4282 * segment for the new timeline.
4284 if (endTLI != ThisTimeLineID)
4285 XLogFileCopy(endLogId, endLogSeg,
4286 endTLI, endLogId, endLogSeg);
4290 * Let's just make real sure there are not .ready or .done flags posted
4291 * for the new segment.
4293 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4294 XLogArchiveCleanup(xlogpath);
4296 /* Get rid of any remaining recovered timeline-history file, too */
4297 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4298 unlink(recoveryPath); /* ignore any error */
4301 * Rename the config file out of the way, so that we don't accidentally
4302 * re-enter archive recovery mode in a subsequent crash.
4304 unlink(RECOVERY_COMMAND_DONE);
4305 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4307 (errcode_for_file_access(),
4308 errmsg("could not rename file \"%s\" to \"%s\": %m",
4309 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4312 (errmsg("archive recovery complete")));
4316 * For point-in-time recovery, this function decides whether we want to
4317 * stop applying the XLOG at or after the current record.
4319 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4320 * *includeThis is set TRUE if we should apply this record before stopping.
4321 * Also, some information is saved in recoveryStopXid et al for use in
4322 * annotating the new timeline's history file.
4325 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4331 /* Do we have a PITR target at all? */
4332 if (!recoveryTarget)
4335 /* We only consider stopping at COMMIT or ABORT records */
4336 if (record->xl_rmid != RM_XACT_ID)
4338 record_info = record->xl_info & ~XLR_INFO_MASK;
4339 if (record_info == XLOG_XACT_COMMIT)
4341 xl_xact_commit *recordXactCommitData;
4343 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4344 recordXtime = recordXactCommitData->xtime;
4346 else if (record_info == XLOG_XACT_ABORT)
4348 xl_xact_abort *recordXactAbortData;
4350 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4351 recordXtime = recordXactAbortData->xtime;
4356 if (recoveryTargetExact)
4359 * there can be only one transaction end record with this exact
4362 * when testing for an xid, we MUST test for equality only, since
4363 * transactions are numbered in the order they start, not the order
4364 * they complete. A higher numbered xid will complete before you about
4365 * 50% of the time...
4367 stopsHere = (record->xl_xid == recoveryTargetXid);
4369 *includeThis = recoveryTargetInclusive;
4374 * there can be many transactions that share the same commit time, so
4375 * we stop after the last one, if we are inclusive, or stop at the
4376 * first one if we are exclusive
4378 if (recoveryTargetInclusive)
4379 stopsHere = (recordXtime > recoveryTargetTime);
4381 stopsHere = (recordXtime >= recoveryTargetTime);
4383 *includeThis = false;
4388 recoveryStopXid = record->xl_xid;
4389 recoveryStopTime = recordXtime;
4390 recoveryStopAfter = *includeThis;
4392 if (record_info == XLOG_XACT_COMMIT)
4394 if (recoveryStopAfter)
4396 (errmsg("recovery stopping after commit of transaction %u, time %s",
4397 recoveryStopXid, str_time(recoveryStopTime))));
4400 (errmsg("recovery stopping before commit of transaction %u, time %s",
4401 recoveryStopXid, str_time(recoveryStopTime))));
4405 if (recoveryStopAfter)
4407 (errmsg("recovery stopping after abort of transaction %u, time %s",
4408 recoveryStopXid, str_time(recoveryStopTime))));
4411 (errmsg("recovery stopping before abort of transaction %u, time %s",
4412 recoveryStopXid, str_time(recoveryStopTime))));
4420 * This must be called ONCE during postmaster or standalone-backend startup
4425 XLogCtlInsert *Insert;
4426 CheckPoint checkPoint;
4428 bool needNewTimeLine = false;
4437 TransactionId oldestActiveXID;
4442 * Read control file and check XLOG status looks valid.
4444 * Note: in most control paths, *ControlFile is already valid and we need
4445 * not do ReadControlFile() here, but might as well do it to be sure.
4449 if (ControlFile->logSeg == 0 ||
4450 ControlFile->state < DB_SHUTDOWNED ||
4451 ControlFile->state > DB_IN_PRODUCTION ||
4452 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4454 (errmsg("control file contains invalid data")));
4456 if (ControlFile->state == DB_SHUTDOWNED)
4458 (errmsg("database system was shut down at %s",
4459 str_time(ControlFile->time))));
4460 else if (ControlFile->state == DB_SHUTDOWNING)
4462 (errmsg("database system shutdown was interrupted at %s",
4463 str_time(ControlFile->time))));
4464 else if (ControlFile->state == DB_IN_RECOVERY)
4466 (errmsg("database system was interrupted while in recovery at %s",
4467 str_time(ControlFile->time)),
4468 errhint("This probably means that some data is corrupted and"
4469 " you will have to use the last backup for recovery.")));
4470 else if (ControlFile->state == DB_IN_PRODUCTION)
4472 (errmsg("database system was interrupted at %s",
4473 str_time(ControlFile->time))));
4475 /* This is just to allow attaching to startup process with a debugger */
4476 #ifdef XLOG_REPLAY_DELAY
4477 if (ControlFile->state != DB_SHUTDOWNED)
4478 pg_usleep(60000000L);
4482 * Initialize on the assumption we want to recover to the same timeline
4483 * that's active according to pg_control.
4485 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4488 * Check for recovery control file, and if so set up state for offline
4491 readRecoveryCommandFile();
4493 /* Now we can determine the list of expected TLIs */
4494 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4497 * If pg_control's timeline is not in expectedTLIs, then we cannot
4498 * proceed: the backup is not part of the history of the requested
4501 if (!list_member_int(expectedTLIs,
4502 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4504 (errmsg("requested timeline %u is not a child of database system timeline %u",
4506 ControlFile->checkPointCopy.ThisTimeLineID)));
4508 if (read_backup_label(&checkPointLoc))
4511 * When a backup_label file is present, we want to roll forward from
4512 * the checkpoint it identifies, rather than using pg_control.
4514 record = ReadCheckpointRecord(checkPointLoc, 0);
4518 (errmsg("checkpoint record is at %X/%X",
4519 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4520 InRecovery = true; /* force recovery even if SHUTDOWNED */
4525 (errmsg("could not locate required checkpoint record"),
4526 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4532 * Get the last valid checkpoint record. If the latest one according
4533 * to pg_control is broken, try the next-to-last one.
4535 checkPointLoc = ControlFile->checkPoint;
4536 record = ReadCheckpointRecord(checkPointLoc, 1);
4540 (errmsg("checkpoint record is at %X/%X",
4541 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4545 checkPointLoc = ControlFile->prevCheckPoint;
4546 record = ReadCheckpointRecord(checkPointLoc, 2);
4550 (errmsg("using previous checkpoint record at %X/%X",
4551 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4552 InRecovery = true; /* force recovery even if SHUTDOWNED */
4556 (errmsg("could not locate a valid checkpoint record")));
4560 LastRec = RecPtr = checkPointLoc;
4561 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4562 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4565 (errmsg("redo record is at %X/%X; undo record is at %X/%X; shutdown %s",
4566 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4567 checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
4568 wasShutdown ? "TRUE" : "FALSE")));
4570 (errmsg("next transaction ID: %u; next OID: %u",
4571 checkPoint.nextXid, checkPoint.nextOid)));
4573 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4574 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4575 if (!TransactionIdIsNormal(checkPoint.nextXid))
4577 (errmsg("invalid next transaction ID")));
4579 ShmemVariableCache->nextXid = checkPoint.nextXid;
4580 ShmemVariableCache->nextOid = checkPoint.nextOid;
4581 ShmemVariableCache->oidCount = 0;
4582 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4585 * We must replay WAL entries using the same TimeLineID they were created
4586 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4587 * also xlog_redo()).
4589 ThisTimeLineID = checkPoint.ThisTimeLineID;
4591 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4593 if (XLByteLT(RecPtr, checkPoint.redo))
4595 (errmsg("invalid redo in checkpoint record")));
4596 if (checkPoint.undo.xrecoff == 0)
4597 checkPoint.undo = RecPtr;
4600 * Check whether we need to force recovery from WAL. If it appears to
4601 * have been a clean shutdown and we did not have a recovery.conf file,
4602 * then assume no recovery needed.
4604 if (XLByteLT(checkPoint.undo, RecPtr) ||
4605 XLByteLT(checkPoint.redo, RecPtr))
4609 (errmsg("invalid redo/undo record in shutdown checkpoint")));
4612 else if (ControlFile->state != DB_SHUTDOWNED)
4614 else if (InArchiveRecovery)
4616 /* force recovery due to presence of recovery.conf */
4625 if (InArchiveRecovery)
4627 (errmsg("automatic recovery in progress")));
4630 (errmsg("database system was not properly shut down; "
4631 "automatic recovery in progress")));
4632 ControlFile->state = DB_IN_RECOVERY;
4633 ControlFile->time = time(NULL);
4634 UpdateControlFile();
4636 /* Start up the recovery environment */
4637 XLogInitRelationCache();
4639 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4641 if (RmgrTable[rmid].rm_startup != NULL)
4642 RmgrTable[rmid].rm_startup();
4646 * Find the first record that logically follows the checkpoint --- it
4647 * might physically precede it, though.
4649 if (XLByteLT(checkPoint.redo, RecPtr))
4651 /* back up to find the record */
4652 record = ReadRecord(&(checkPoint.redo), PANIC);
4656 /* just have to read next record after CheckPoint */
4657 record = ReadRecord(NULL, LOG);
4662 bool recoveryContinue = true;
4663 bool recoveryApply = true;
4664 ErrorContextCallback errcontext;
4668 (errmsg("redo starts at %X/%X",
4669 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4672 * main redo apply loop
4681 initStringInfo(&buf);
4682 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4683 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4684 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4685 xlog_outrec(&buf, record);
4686 appendStringInfo(&buf, " - ");
4687 RmgrTable[record->xl_rmid].rm_desc(&buf,
4689 XLogRecGetData(record));
4690 elog(LOG, "%s", buf.data);
4696 * Have we reached our recovery target?
4698 if (recoveryStopsHere(record, &recoveryApply))
4700 needNewTimeLine = true; /* see below */
4701 recoveryContinue = false;
4706 /* Setup error traceback support for ereport() */
4707 errcontext.callback = rm_redo_error_callback;
4708 errcontext.arg = (void *) record;
4709 errcontext.previous = error_context_stack;
4710 error_context_stack = &errcontext;
4712 /* nextXid must be beyond record's xid */
4713 if (TransactionIdFollowsOrEquals(record->xl_xid,
4714 ShmemVariableCache->nextXid))
4716 ShmemVariableCache->nextXid = record->xl_xid;
4717 TransactionIdAdvance(ShmemVariableCache->nextXid);
4720 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4721 RestoreBkpBlocks(record, EndRecPtr);
4723 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4725 /* Pop the error context stack */
4726 error_context_stack = errcontext.previous;
4728 LastRec = ReadRecPtr;
4730 record = ReadRecord(NULL, LOG);
4731 } while (record != NULL && recoveryContinue);
4734 * end of main redo apply loop
4738 (errmsg("redo done at %X/%X",
4739 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4744 /* there are no WAL records following the checkpoint */
4746 (errmsg("redo is not required")));
4751 * Re-fetch the last valid or last applied record, so we can identify the
4752 * exact endpoint of what we consider the valid portion of WAL.
4754 record = ReadRecord(&LastRec, PANIC);
4755 EndOfLog = EndRecPtr;
4756 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4759 * Complain if we did not roll forward far enough to render the backup
4762 if (XLByteLT(EndOfLog, recoveryMinXlogOffset))
4764 if (needNewTimeLine) /* stopped because of stop request */
4766 (errmsg("requested recovery stop point is before end time of backup dump")));
4768 /* ran off end of WAL */
4770 (errmsg("WAL ends before end time of backup dump")));
4774 * Consider whether we need to assign a new timeline ID.
4776 * If we stopped short of the end of WAL during recovery, then we are
4777 * generating a new timeline and must assign it a unique new ID.
4778 * Otherwise, we can just extend the timeline we were in when we ran out
4781 if (needNewTimeLine)
4783 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
4785 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
4786 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
4787 curFileTLI, endLogId, endLogSeg);
4790 /* Save the selected TimeLineID in shared memory, too */
4791 XLogCtl->ThisTimeLineID = ThisTimeLineID;
4794 * We are now done reading the old WAL. Turn off archive fetching if it
4795 * was active, and make a writable copy of the last WAL segment. (Note
4796 * that we also have a copy of the last block of the old WAL in readBuf;
4797 * we will use that below.)
4799 if (InArchiveRecovery)
4800 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
4803 * Prepare to write WAL starting at EndOfLog position, and init xlog
4804 * buffer cache using the block containing the last record from the
4805 * previous incarnation.
4807 openLogId = endLogId;
4808 openLogSeg = endLogSeg;
4809 openLogFile = XLogFileOpen(openLogId, openLogSeg);
4811 ControlFile->logId = openLogId;
4812 ControlFile->logSeg = openLogSeg + 1;
4813 Insert = &XLogCtl->Insert;
4814 Insert->PrevRecord = LastRec;
4815 XLogCtl->xlblocks[0].xlogid = openLogId;
4816 XLogCtl->xlblocks[0].xrecoff =
4817 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
4820 * Tricky point here: readBuf contains the *last* block that the LastRec
4821 * record spans, not the one it starts in. The last block is indeed the
4822 * one we want to use.
4824 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
4825 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
4826 Insert->currpos = (char *) Insert->currpage +
4827 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
4829 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
4831 XLogCtl->Write.LogwrtResult = LogwrtResult;
4832 Insert->LogwrtResult = LogwrtResult;
4833 XLogCtl->LogwrtResult = LogwrtResult;
4835 XLogCtl->LogwrtRqst.Write = EndOfLog;
4836 XLogCtl->LogwrtRqst.Flush = EndOfLog;
4838 freespace = INSERT_FREESPACE(Insert);
4841 /* Make sure rest of page is zero */
4842 MemSet(Insert->currpos, 0, freespace);
4843 XLogCtl->Write.curridx = 0;
4848 * Whenever Write.LogwrtResult points to exactly the end of a page,
4849 * Write.curridx must point to the *next* page (see XLogWrite()).
4851 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
4852 * this is sufficient. The first actual attempt to insert a log
4853 * record will advance the insert state.
4855 XLogCtl->Write.curridx = NextBufIdx(0);
4858 /* Pre-scan prepared transactions to find out the range of XIDs present */
4859 oldestActiveXID = PrescanPreparedTransactions();
4866 * Allow resource managers to do any required cleanup.
4868 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4870 if (RmgrTable[rmid].rm_cleanup != NULL)
4871 RmgrTable[rmid].rm_cleanup();
4875 * Check to see if the XLOG sequence contained any unresolved
4876 * references to uninitialized pages.
4878 XLogCheckInvalidPages();
4881 * Reset pgstat data, because it may be invalid after recovery.
4886 * Perform a new checkpoint to update our recovery activity to disk.
4888 * Note that we write a shutdown checkpoint rather than an on-line
4889 * one. This is not particularly critical, but since we may be
4890 * assigning a new TLI, using a shutdown checkpoint allows us to have
4891 * the rule that TLI only changes in shutdown checkpoints, which
4892 * allows some extra error checking in xlog_redo.
4894 * In case we had to use the secondary checkpoint, make sure that it
4895 * will still be shown as the secondary checkpoint after this
4896 * CreateCheckPoint operation; we don't want the broken primary
4897 * checkpoint to become prevCheckPoint...
4899 if (XLByteEQ(checkPointLoc, ControlFile->prevCheckPoint))
4900 ControlFile->checkPoint = checkPointLoc;
4902 CreateCheckPoint(true, true);
4905 * Close down recovery environment
4907 XLogCloseRelationCache();
4910 * Now that we've checkpointed the recovery, it's safe to flush old
4911 * backup_label, if present.
4913 remove_backup_label();
4917 * Preallocate additional log files, if wanted.
4919 (void) PreallocXlogFiles(EndOfLog);
4922 * Okay, we're officially UP.
4926 ControlFile->state = DB_IN_PRODUCTION;
4927 ControlFile->time = time(NULL);
4928 UpdateControlFile();
4930 /* Start up the commit log and related stuff, too */
4932 StartupSUBTRANS(oldestActiveXID);
4935 /* Reload shared-memory state for prepared transactions */
4936 RecoverPreparedTransactions();
4939 (errmsg("database system is ready")));
4942 /* Shut down readFile facility, free space */
4955 free(readRecordBuf);
4956 readRecordBuf = NULL;
4957 readRecordBufSize = 0;
4962 * Subroutine to try to fetch and validate a prior checkpoint record.
4964 * whichChkpt identifies the checkpoint (merely for reporting purposes).
4965 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
4968 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
4972 if (!XRecOffIsValid(RecPtr.xrecoff))
4978 (errmsg("invalid primary checkpoint link in control file")));
4982 (errmsg("invalid secondary checkpoint link in control file")));
4986 (errmsg("invalid checkpoint link in backup_label file")));
4992 record = ReadRecord(&RecPtr, LOG);
5000 (errmsg("invalid primary checkpoint record")));
5004 (errmsg("invalid secondary checkpoint record")));
5008 (errmsg("invalid checkpoint record")));
5013 if (record->xl_rmid != RM_XLOG_ID)
5019 (errmsg("invalid resource manager ID in primary checkpoint record")));
5023 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5027 (errmsg("invalid resource manager ID in checkpoint record")));
5032 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5033 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5039 (errmsg("invalid xl_info in primary checkpoint record")));
5043 (errmsg("invalid xl_info in secondary checkpoint record")));
5047 (errmsg("invalid xl_info in checkpoint record")));
5052 if (record->xl_len != sizeof(CheckPoint) ||
5053 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5059 (errmsg("invalid length of primary checkpoint record")));
5063 (errmsg("invalid length of secondary checkpoint record")));
5067 (errmsg("invalid length of checkpoint record")));
5076 * This must be called during startup of a backend process, except that
5077 * it need not be called in a standalone backend (which does StartupXLOG
5078 * instead). We need to initialize the local copies of ThisTimeLineID and
5081 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5082 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5083 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5086 InitXLOGAccess(void)
5088 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5089 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5090 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5091 (void) GetRedoRecPtr();
5095 * Once spawned, a backend may update its local RedoRecPtr from
5096 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5097 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5102 /* use volatile pointer to prevent code rearrangement */
5103 volatile XLogCtlData *xlogctl = XLogCtl;
5105 SpinLockAcquire(&xlogctl->info_lck);
5106 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5107 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5108 SpinLockRelease(&xlogctl->info_lck);
5114 * GetRecentNextXid - get the nextXid value saved by the most recent checkpoint
5116 * This is currently used only by the autovacuum daemon. To check for
5117 * impending XID wraparound, autovac needs an approximate idea of the current
5118 * XID counter, and it needs it before choosing which DB to attach to, hence
5119 * before it sets up a PGPROC, hence before it can take any LWLocks. But it
5120 * has attached to shared memory, and so we can let it reach into the shared
5121 * ControlFile structure and pull out the last checkpoint nextXID.
5123 * Since we don't take any sort of lock, we have to assume that reading a
5124 * TransactionId is atomic ... but that assumption is made elsewhere, too,
5125 * and in any case the worst possible consequence of a bogus result is that
5126 * autovac issues an unnecessary database-wide VACUUM.
5128 * Note: we could also choose to read ShmemVariableCache->nextXid in an
5129 * unlocked fashion, thus getting a more up-to-date result; but since that
5130 * changes far more frequently than the controlfile checkpoint copy, it would
5131 * pose a far higher risk of bogus result if we did have a nonatomic-read
5134 * A (theoretically) completely safe answer is to read the actual pg_control
5135 * file into local process memory, but that certainly seems like overkill.
5138 GetRecentNextXid(void)
5140 return ControlFile->checkPointCopy.nextXid;
5144 * This must be called ONCE during postmaster or standalone-backend shutdown
5147 ShutdownXLOG(int code, Datum arg)
5150 (errmsg("shutting down")));
5153 CreateCheckPoint(true, true);
5156 ShutdownMultiXact();
5160 (errmsg("database system is shut down")));
5164 * Perform a checkpoint --- either during shutdown, or on-the-fly
5166 * If force is true, we force a checkpoint regardless of whether any XLOG
5167 * activity has occurred since the last one.
5170 CreateCheckPoint(bool shutdown, bool force)
5172 CheckPoint checkPoint;
5174 XLogCtlInsert *Insert = &XLogCtl->Insert;
5180 int nsegsremoved = 0;
5181 int nsegsrecycled = 0;
5184 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5185 * (This is just pro forma, since in the present system structure there is
5186 * only one process that is allowed to issue checkpoints at any given
5189 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5192 * Use a critical section to force system panic if we have trouble.
5194 START_CRIT_SECTION();
5198 ControlFile->state = DB_SHUTDOWNING;
5199 ControlFile->time = time(NULL);
5200 UpdateControlFile();
5203 MemSet(&checkPoint, 0, sizeof(checkPoint));
5204 checkPoint.ThisTimeLineID = ThisTimeLineID;
5205 checkPoint.time = time(NULL);
5208 * We must hold CheckpointStartLock while determining the checkpoint REDO
5209 * pointer. This ensures that any concurrent transaction commits will be
5210 * either not yet logged, or logged and recorded in pg_clog. See notes in
5211 * RecordTransactionCommit().
5213 LWLockAcquire(CheckpointStartLock, LW_EXCLUSIVE);
5215 /* And we need WALInsertLock too */
5216 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5219 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5220 * any XLOG records since the start of the last checkpoint, skip the
5221 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5222 * when the system is idle. That wastes log space, and more importantly it
5223 * exposes us to possible loss of both current and previous checkpoint
5224 * records if the machine crashes just as we're writing the update.
5225 * (Perhaps it'd make even more sense to checkpoint only when the previous
5226 * checkpoint record is in a different xlog page?)
5228 * We have to make two tests to determine that nothing has happened since
5229 * the start of the last checkpoint: current insertion point must match
5230 * the end of the last checkpoint record, and its redo pointer must point
5233 if (!shutdown && !force)
5235 XLogRecPtr curInsert;
5237 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5238 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5239 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5240 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5241 ControlFile->checkPoint.xlogid ==
5242 ControlFile->checkPointCopy.redo.xlogid &&
5243 ControlFile->checkPoint.xrecoff ==
5244 ControlFile->checkPointCopy.redo.xrecoff)
5246 LWLockRelease(WALInsertLock);
5247 LWLockRelease(CheckpointStartLock);
5248 LWLockRelease(CheckpointLock);
5255 * Compute new REDO record ptr = location of next XLOG record.
5257 * NB: this is NOT necessarily where the checkpoint record itself will be,
5258 * since other backends may insert more XLOG records while we're off doing
5259 * the buffer flush work. Those XLOG records are logically after the
5260 * checkpoint, even though physically before it. Got that?
5262 freespace = INSERT_FREESPACE(Insert);
5263 if (freespace < SizeOfXLogRecord)
5265 (void) AdvanceXLInsertBuffer();
5266 /* OK to ignore update return flag, since we will do flush anyway */
5267 freespace = INSERT_FREESPACE(Insert);
5269 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5272 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5273 * must be done while holding the insert lock AND the info_lck.
5275 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5276 * pointing past where it really needs to point. This is okay; the only
5277 * consequence is that XLogInsert might back up whole buffers that it
5278 * didn't really need to. We can't postpone advancing RedoRecPtr because
5279 * XLogInserts that happen while we are dumping buffers must assume that
5280 * their buffer changes are not included in the checkpoint.
5283 /* use volatile pointer to prevent code rearrangement */
5284 volatile XLogCtlData *xlogctl = XLogCtl;
5286 SpinLockAcquire(&xlogctl->info_lck);
5287 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5288 SpinLockRelease(&xlogctl->info_lck);
5292 * Now we can release insert lock and checkpoint start lock, allowing
5293 * other xacts to proceed even while we are flushing disk buffers.
5295 LWLockRelease(WALInsertLock);
5297 LWLockRelease(CheckpointStartLock);
5300 * Get the other info we need for the checkpoint record.
5302 LWLockAcquire(XidGenLock, LW_SHARED);
5303 checkPoint.nextXid = ShmemVariableCache->nextXid;
5304 LWLockRelease(XidGenLock);
5306 LWLockAcquire(OidGenLock, LW_SHARED);
5307 checkPoint.nextOid = ShmemVariableCache->nextOid;
5309 checkPoint.nextOid += ShmemVariableCache->oidCount;
5310 LWLockRelease(OidGenLock);
5312 MultiXactGetCheckptMulti(shutdown,
5313 &checkPoint.nextMulti,
5314 &checkPoint.nextMultiOffset);
5317 * Having constructed the checkpoint record, ensure all shmem disk buffers
5318 * and commit-log buffers are flushed to disk.
5320 * This I/O could fail for various reasons. If so, we will fail to
5321 * complete the checkpoint, but there is no reason to force a system
5322 * panic. Accordingly, exit critical section while doing it. (If we are
5323 * doing a shutdown checkpoint, we probably *should* panic --- but that
5324 * will happen anyway because we'll still be inside the critical section
5325 * established by ShutdownXLOG.)
5331 (errmsg("checkpoint starting")));
5334 CheckPointSUBTRANS();
5335 CheckPointMultiXact();
5337 /* We deliberately delay 2PC checkpointing as long as possible */
5338 CheckPointTwoPhase(checkPoint.redo);
5340 START_CRIT_SECTION();
5343 * Now insert the checkpoint record into XLOG.
5345 rdata.data = (char *) (&checkPoint);
5346 rdata.len = sizeof(checkPoint);
5347 rdata.buffer = InvalidBuffer;
5350 recptr = XLogInsert(RM_XLOG_ID,
5351 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5352 XLOG_CHECKPOINT_ONLINE,
5358 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5359 * = end of actual checkpoint record.
5361 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5363 (errmsg("concurrent transaction log activity while database system is shutting down")));
5366 * Select point at which we can truncate the log, which we base on the
5367 * prior checkpoint's earliest info.
5369 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5372 * Update the control file.
5374 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5376 ControlFile->state = DB_SHUTDOWNED;
5377 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5378 ControlFile->checkPoint = ProcLastRecPtr;
5379 ControlFile->checkPointCopy = checkPoint;
5380 ControlFile->time = time(NULL);
5381 UpdateControlFile();
5382 LWLockRelease(ControlFileLock);
5385 * We are now done with critical updates; no need for system panic if we
5386 * have trouble while fooling with offline log segments.
5391 * Delete offline log files (those no longer needed even for previous
5394 if (_logId || _logSeg)
5396 PrevLogSeg(_logId, _logSeg);
5397 MoveOfflineLogs(_logId, _logSeg, recptr,
5398 &nsegsremoved, &nsegsrecycled);
5402 * Make more log segments if needed. (Do this after deleting offline log
5403 * segments, to avoid having peak disk space usage higher than necessary.)
5406 nsegsadded = PreallocXlogFiles(recptr);
5409 * Truncate pg_subtrans if possible. We can throw away all data before
5410 * the oldest XMIN of any running transaction. No future transaction will
5411 * attempt to reference any pg_subtrans entry older than that (see Asserts
5412 * in subtrans.c). During recovery, though, we mustn't do this because
5413 * StartupSUBTRANS hasn't been called yet.
5416 TruncateSUBTRANS(GetOldestXmin(true, false));
5420 (errmsg("checkpoint complete; %d transaction log file(s) added, %d removed, %d recycled",
5421 nsegsadded, nsegsremoved, nsegsrecycled)));
5423 LWLockRelease(CheckpointLock);
5427 * Write a NEXTOID log record
5430 XLogPutNextOid(Oid nextOid)
5434 rdata.data = (char *) (&nextOid);
5435 rdata.len = sizeof(Oid);
5436 rdata.buffer = InvalidBuffer;
5438 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5441 * We need not flush the NEXTOID record immediately, because any of the
5442 * just-allocated OIDs could only reach disk as part of a tuple insert or
5443 * update that would have its own XLOG record that must follow the NEXTOID
5444 * record. Therefore, the standard buffer LSN interlock applied to those
5445 * records will ensure no such OID reaches disk before the NEXTOID record
5451 * XLOG resource manager's routines
5454 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5456 uint8 info = record->xl_info & ~XLR_INFO_MASK;
5458 if (info == XLOG_NEXTOID)
5462 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5463 if (ShmemVariableCache->nextOid < nextOid)
5465 ShmemVariableCache->nextOid = nextOid;
5466 ShmemVariableCache->oidCount = 0;
5469 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5471 CheckPoint checkPoint;
5473 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5474 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5475 ShmemVariableCache->nextXid = checkPoint.nextXid;
5476 ShmemVariableCache->nextOid = checkPoint.nextOid;
5477 ShmemVariableCache->oidCount = 0;
5478 MultiXactSetNextMXact(checkPoint.nextMulti,
5479 checkPoint.nextMultiOffset);
5482 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
5484 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5486 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5487 !list_member_int(expectedTLIs,
5488 (int) checkPoint.ThisTimeLineID))
5490 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5491 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5492 /* Following WAL records should be run with new TLI */
5493 ThisTimeLineID = checkPoint.ThisTimeLineID;
5496 else if (info == XLOG_CHECKPOINT_ONLINE)
5498 CheckPoint checkPoint;
5500 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5501 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5502 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5503 checkPoint.nextXid))
5504 ShmemVariableCache->nextXid = checkPoint.nextXid;
5505 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5507 ShmemVariableCache->nextOid = checkPoint.nextOid;
5508 ShmemVariableCache->oidCount = 0;
5510 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
5511 checkPoint.nextMultiOffset);
5512 /* TLI should not change in an on-line checkpoint */
5513 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5515 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5516 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5521 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
5523 uint8 info = xl_info & ~XLR_INFO_MASK;
5525 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5526 info == XLOG_CHECKPOINT_ONLINE)
5528 CheckPoint *checkpoint = (CheckPoint *) rec;
5530 appendStringInfo(buf, "checkpoint: redo %X/%X; undo %X/%X; "
5531 "tli %u; xid %u; oid %u; multi %u; offset %u; %s",
5532 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5533 checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
5534 checkpoint->ThisTimeLineID, checkpoint->nextXid,
5535 checkpoint->nextOid,
5536 checkpoint->nextMulti,
5537 checkpoint->nextMultiOffset,
5538 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
5540 else if (info == XLOG_NEXTOID)
5544 memcpy(&nextOid, rec, sizeof(Oid));
5545 appendStringInfo(buf, "nextOid: %u", nextOid);
5548 appendStringInfo(buf, "UNKNOWN");
5554 xlog_outrec(StringInfo buf, XLogRecord *record)
5558 appendStringInfo(buf, "prev %X/%X; xid %u",
5559 record->xl_prev.xlogid, record->xl_prev.xrecoff,
5562 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
5564 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
5565 appendStringInfo(buf, "; bkpb%d", i+1);
5568 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
5570 #endif /* WAL_DEBUG */
5577 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
5579 int new_sync_method;
5582 if (pg_strcasecmp(method, "fsync") == 0)
5584 new_sync_method = SYNC_METHOD_FSYNC;
5587 #ifdef HAVE_FSYNC_WRITETHROUGH
5588 else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
5590 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
5594 #ifdef HAVE_FDATASYNC
5595 else if (pg_strcasecmp(method, "fdatasync") == 0)
5597 new_sync_method = SYNC_METHOD_FDATASYNC;
5601 #ifdef OPEN_SYNC_FLAG
5602 else if (pg_strcasecmp(method, "open_sync") == 0)
5604 new_sync_method = SYNC_METHOD_OPEN;
5605 new_sync_bit = OPEN_SYNC_FLAG;
5608 #ifdef OPEN_DATASYNC_FLAG
5609 else if (pg_strcasecmp(method, "open_datasync") == 0)
5611 new_sync_method = SYNC_METHOD_OPEN;
5612 new_sync_bit = OPEN_DATASYNC_FLAG;
5621 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
5624 * To ensure that no blocks escape unsynced, force an fsync on the
5625 * currently open log segment (if any). Also, if the open flag is
5626 * changing, close the log file so it will be reopened (with new flag
5629 if (openLogFile >= 0)
5631 if (pg_fsync(openLogFile) != 0)
5633 (errcode_for_file_access(),
5634 errmsg("could not fsync log file %u, segment %u: %m",
5635 openLogId, openLogSeg)));
5636 if (open_sync_bit != new_sync_bit)
5639 sync_method = new_sync_method;
5640 open_sync_bit = new_sync_bit;
5648 * Issue appropriate kind of fsync (if any) on the current XLOG output file
5651 issue_xlog_fsync(void)
5653 switch (sync_method)
5655 case SYNC_METHOD_FSYNC:
5656 if (pg_fsync_no_writethrough(openLogFile) != 0)
5658 (errcode_for_file_access(),
5659 errmsg("could not fsync log file %u, segment %u: %m",
5660 openLogId, openLogSeg)));
5662 #ifdef HAVE_FSYNC_WRITETHROUGH
5663 case SYNC_METHOD_FSYNC_WRITETHROUGH:
5664 if (pg_fsync_writethrough(openLogFile) != 0)
5666 (errcode_for_file_access(),
5667 errmsg("could not fsync write-through log file %u, segment %u: %m",
5668 openLogId, openLogSeg)));
5671 #ifdef HAVE_FDATASYNC
5672 case SYNC_METHOD_FDATASYNC:
5673 if (pg_fdatasync(openLogFile) != 0)
5675 (errcode_for_file_access(),
5676 errmsg("could not fdatasync log file %u, segment %u: %m",
5677 openLogId, openLogSeg)));
5680 case SYNC_METHOD_OPEN:
5681 /* write synced it already */
5684 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
5691 * pg_start_backup: set up for taking an on-line backup dump
5693 * Essentially what this does is to create a backup label file in $PGDATA,
5694 * where it will be archived as part of the backup dump. The label file
5695 * contains the user-supplied label string (typically this would be used
5696 * to tell where the backup dump will be stored) and the starting time and
5697 * starting WAL offset for the dump.
5700 pg_start_backup(PG_FUNCTION_ARGS)
5702 text *backupid = PG_GETARG_TEXT_P(0);
5705 XLogRecPtr checkpointloc;
5706 XLogRecPtr startpoint;
5709 char xlogfilename[MAXFNAMELEN];
5712 struct stat stat_buf;
5717 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5718 (errmsg("must be superuser to run a backup"))));
5720 if (!XLogArchivingActive())
5722 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5723 (errmsg("WAL archiving is not active"),
5724 (errhint("archive_command must be defined before "
5725 "online backups can be made safely.")))));
5727 backupidstr = DatumGetCString(DirectFunctionCall1(textout,
5728 PointerGetDatum(backupid)));
5731 * Mark backup active in shared memory. We must do full-page WAL writes
5732 * during an on-line backup even if not doing so at other times, because
5733 * it's quite possible for the backup dump to obtain a "torn" (partially
5734 * written) copy of a database page if it reads the page concurrently
5735 * with our write to the same page. This can be fixed as long as the
5736 * first write to the page in the WAL sequence is a full-page write.
5737 * Hence, we turn on forcePageWrites and then force a CHECKPOINT, to
5738 * ensure there are no dirty pages in shared memory that might get
5739 * dumped while the backup is in progress without having a corresponding
5740 * WAL record. (Once the backup is complete, we need not force full-page
5741 * writes anymore, since we expect that any pages not modified during
5742 * the backup interval must have been correctly captured by the backup.)
5744 * We must hold WALInsertLock to change the value of forcePageWrites,
5745 * to ensure adequate interlocking against XLogInsert().
5747 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5748 if (XLogCtl->Insert.forcePageWrites)
5750 LWLockRelease(WALInsertLock);
5752 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5753 errmsg("a backup is already in progress"),
5754 errhint("Run pg_stop_backup() and try again.")));
5756 XLogCtl->Insert.forcePageWrites = true;
5757 LWLockRelease(WALInsertLock);
5759 /* Use a TRY block to ensure we release forcePageWrites if fail below */
5763 * Force a CHECKPOINT. Aside from being necessary to prevent torn
5764 * page problems, this guarantees that two successive backup runs will
5765 * have different checkpoint positions and hence different history
5766 * file names, even if nothing happened in between.
5768 RequestCheckpoint(true, false);
5771 * Now we need to fetch the checkpoint record location, and also its
5772 * REDO pointer. The oldest point in WAL that would be needed to
5773 * restore starting from the checkpoint is precisely the REDO pointer.
5775 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5776 checkpointloc = ControlFile->checkPoint;
5777 startpoint = ControlFile->checkPointCopy.redo;
5778 LWLockRelease(ControlFileLock);
5780 XLByteToSeg(startpoint, _logId, _logSeg);
5781 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
5784 * We deliberately use strftime/localtime not the src/timezone
5785 * functions, so that backup labels will consistently be recorded in
5786 * the same timezone regardless of TimeZone setting. This matches
5787 * elog.c's practice.
5789 stamp_time = time(NULL);
5790 strftime(strfbuf, sizeof(strfbuf),
5791 "%Y-%m-%d %H:%M:%S %Z",
5792 localtime(&stamp_time));
5795 * Check for existing backup label --- implies a backup is already
5796 * running. (XXX given that we checked forcePageWrites above, maybe
5797 * it would be OK to just unlink any such label file?)
5799 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
5801 if (errno != ENOENT)
5803 (errcode_for_file_access(),
5804 errmsg("could not stat file \"%s\": %m",
5805 BACKUP_LABEL_FILE)));
5809 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5810 errmsg("a backup is already in progress"),
5811 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
5812 BACKUP_LABEL_FILE)));
5815 * Okay, write the file
5817 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
5820 (errcode_for_file_access(),
5821 errmsg("could not create file \"%s\": %m",
5822 BACKUP_LABEL_FILE)));
5823 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
5824 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
5825 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
5826 checkpointloc.xlogid, checkpointloc.xrecoff);
5827 fprintf(fp, "START TIME: %s\n", strfbuf);
5828 fprintf(fp, "LABEL: %s\n", backupidstr);
5829 if (fflush(fp) || ferror(fp) || FreeFile(fp))
5831 (errcode_for_file_access(),
5832 errmsg("could not write file \"%s\": %m",
5833 BACKUP_LABEL_FILE)));
5837 /* Turn off forcePageWrites on failure */
5838 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5839 XLogCtl->Insert.forcePageWrites = false;
5840 LWLockRelease(WALInsertLock);
5847 * We're done. As a convenience, return the starting WAL offset.
5849 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
5850 startpoint.xlogid, startpoint.xrecoff);
5851 result = DatumGetTextP(DirectFunctionCall1(textin,
5852 CStringGetDatum(xlogfilename)));
5853 PG_RETURN_TEXT_P(result);
5857 * pg_stop_backup: finish taking an on-line backup dump
5859 * We remove the backup label file created by pg_start_backup, and instead
5860 * create a backup history file in pg_xlog (whence it will immediately be
5861 * archived). The backup history file contains the same info found in
5862 * the label file, plus the backup-end time and WAL offset.
5865 pg_stop_backup(PG_FUNCTION_ARGS)
5868 XLogCtlInsert *Insert = &XLogCtl->Insert;
5869 XLogRecPtr startpoint;
5870 XLogRecPtr stoppoint;
5873 char histfilepath[MAXPGPATH];
5874 char startxlogfilename[MAXFNAMELEN];
5875 char stopxlogfilename[MAXFNAMELEN];
5885 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5886 (errmsg("must be superuser to run a backup"))));
5889 * Get the current end-of-WAL position; it will be unsafe to use this dump
5890 * to restore to a point in advance of this time. We can also clear
5891 * forcePageWrites here.
5893 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5894 INSERT_RECPTR(stoppoint, Insert, Insert->curridx);
5895 XLogCtl->Insert.forcePageWrites = false;
5896 LWLockRelease(WALInsertLock);
5898 XLByteToSeg(stoppoint, _logId, _logSeg);
5899 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
5902 * We deliberately use strftime/localtime not the src/timezone functions,
5903 * so that backup labels will consistently be recorded in the same
5904 * timezone regardless of TimeZone setting. This matches elog.c's
5907 stamp_time = time(NULL);
5908 strftime(strfbuf, sizeof(strfbuf),
5909 "%Y-%m-%d %H:%M:%S %Z",
5910 localtime(&stamp_time));
5913 * Open the existing label file
5915 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
5918 if (errno != ENOENT)
5920 (errcode_for_file_access(),
5921 errmsg("could not read file \"%s\": %m",
5922 BACKUP_LABEL_FILE)));
5924 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5925 errmsg("a backup is not in progress")));
5929 * Read and parse the START WAL LOCATION line (this code is pretty crude,
5930 * but we are not expecting any variability in the file format).
5932 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
5933 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
5934 &ch) != 4 || ch != '\n')
5936 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5937 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
5940 * Write the backup history file
5942 XLByteToSeg(startpoint, _logId, _logSeg);
5943 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
5944 startpoint.xrecoff % XLogSegSize);
5945 fp = AllocateFile(histfilepath, "w");
5948 (errcode_for_file_access(),
5949 errmsg("could not create file \"%s\": %m",
5951 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
5952 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
5953 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
5954 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
5955 /* transfer remaining lines from label to history file */
5956 while ((ich = fgetc(lfp)) != EOF)
5958 fprintf(fp, "STOP TIME: %s\n", strfbuf);
5959 if (fflush(fp) || ferror(fp) || FreeFile(fp))
5961 (errcode_for_file_access(),
5962 errmsg("could not write file \"%s\": %m",
5966 * Close and remove the backup label file
5968 if (ferror(lfp) || FreeFile(lfp))
5970 (errcode_for_file_access(),
5971 errmsg("could not read file \"%s\": %m",
5972 BACKUP_LABEL_FILE)));
5973 if (unlink(BACKUP_LABEL_FILE) != 0)
5975 (errcode_for_file_access(),
5976 errmsg("could not remove file \"%s\": %m",
5977 BACKUP_LABEL_FILE)));
5980 * Clean out any no-longer-needed history files. As a side effect,
5981 * this will post a .ready file for the newly created history file,
5982 * notifying the archiver that history file may be archived immediately.
5984 CleanupBackupHistory();
5987 * We're done. As a convenience, return the ending WAL offset.
5989 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
5990 stoppoint.xlogid, stoppoint.xrecoff);
5991 result = DatumGetTextP(DirectFunctionCall1(textin,
5992 CStringGetDatum(stopxlogfilename)));
5993 PG_RETURN_TEXT_P(result);
5997 * read_backup_label: check to see if a backup_label file is present
5999 * If we see a backup_label during recovery, we assume that we are recovering
6000 * from a backup dump file, and we therefore roll forward from the checkpoint
6001 * identified by the label file, NOT what pg_control says. This avoids the
6002 * problem that pg_control might have been archived one or more checkpoints
6003 * later than the start of the dump, and so if we rely on it as the start
6004 * point, we will fail to restore a consistent database state.
6006 * We also attempt to retrieve the corresponding backup history file.
6007 * If successful, set recoveryMinXlogOffset to constrain valid PITR stopping
6010 * Returns TRUE if a backup_label was found (and fills the checkpoint
6011 * location into *checkPointLoc); returns FALSE if not.
6014 read_backup_label(XLogRecPtr *checkPointLoc)
6016 XLogRecPtr startpoint;
6017 XLogRecPtr stoppoint;
6018 char histfilename[MAXFNAMELEN];
6019 char histfilepath[MAXPGPATH];
6020 char startxlogfilename[MAXFNAMELEN];
6021 char stopxlogfilename[MAXFNAMELEN];
6030 * See if label file is present
6032 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6035 if (errno != ENOENT)
6037 (errcode_for_file_access(),
6038 errmsg("could not read file \"%s\": %m",
6039 BACKUP_LABEL_FILE)));
6040 return false; /* it's not there, all is fine */
6044 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
6045 * is pretty crude, but we are not expecting any variability in the file
6048 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
6049 &startpoint.xlogid, &startpoint.xrecoff, &tli,
6050 startxlogfilename, &ch) != 5 || ch != '\n')
6052 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6053 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6054 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
6055 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
6056 &ch) != 3 || ch != '\n')
6058 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6059 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6060 if (ferror(lfp) || FreeFile(lfp))
6062 (errcode_for_file_access(),
6063 errmsg("could not read file \"%s\": %m",
6064 BACKUP_LABEL_FILE)));
6067 * Try to retrieve the backup history file (no error if we can't)
6069 XLByteToSeg(startpoint, _logId, _logSeg);
6070 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
6071 startpoint.xrecoff % XLogSegSize);
6073 if (InArchiveRecovery)
6074 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
6076 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
6077 startpoint.xrecoff % XLogSegSize);
6079 fp = AllocateFile(histfilepath, "r");
6083 * Parse history file to identify stop point.
6085 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
6086 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6087 &ch) != 4 || ch != '\n')
6089 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6090 errmsg("invalid data in file \"%s\"", histfilename)));
6091 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
6092 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6093 &ch) != 4 || ch != '\n')
6095 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6096 errmsg("invalid data in file \"%s\"", histfilename)));
6097 recoveryMinXlogOffset = stoppoint;
6098 if (ferror(fp) || FreeFile(fp))
6100 (errcode_for_file_access(),
6101 errmsg("could not read file \"%s\": %m",
6109 * remove_backup_label: remove any extant backup_label after successful
6110 * recovery. Once we have completed the end-of-recovery checkpoint there
6111 * is no reason to have to replay from the start point indicated by the
6112 * label (and indeed we'll probably have removed/recycled the needed WAL
6113 * segments), so remove the label to prevent trouble in later crash recoveries.
6116 remove_backup_label(void)
6118 if (unlink(BACKUP_LABEL_FILE) != 0)
6119 if (errno != ENOENT)
6121 (errcode_for_file_access(),
6122 errmsg("could not remove file \"%s\": %m",
6123 BACKUP_LABEL_FILE)));
6127 * Error context callback for errors occurring during rm_redo().
6130 rm_redo_error_callback(void *arg)
6132 XLogRecord *record = (XLogRecord *) arg;
6135 initStringInfo(&buf);
6136 RmgrTable[record->xl_rmid].rm_desc(&buf,
6138 XLogRecGetData(record));
6140 /* don't bother emitting empty description */
6142 errcontext("xlog redo %s", buf.data);