1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2007, 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.268 2007/04/30 21:01:52 tgl Exp $
12 *-------------------------------------------------------------------------
26 #include "access/clog.h"
27 #include "access/heapam.h"
28 #include "access/multixact.h"
29 #include "access/subtrans.h"
30 #include "access/transam.h"
31 #include "access/tuptoaster.h"
32 #include "access/twophase.h"
33 #include "access/xact.h"
34 #include "access/xlog_internal.h"
35 #include "access/xlogdefs.h"
36 #include "access/xlogutils.h"
37 #include "catalog/catversion.h"
38 #include "catalog/pg_control.h"
39 #include "catalog/pg_type.h"
41 #include "miscadmin.h"
43 #include "postmaster/bgwriter.h"
44 #include "storage/bufpage.h"
45 #include "storage/fd.h"
46 #include "storage/pmsignal.h"
47 #include "storage/procarray.h"
48 #include "storage/spin.h"
49 #include "utils/builtins.h"
50 #include "utils/pg_locale.h"
54 /* File path names (all relative to $PGDATA) */
55 #define BACKUP_LABEL_FILE "backup_label"
56 #define BACKUP_LABEL_OLD "backup_label.old"
57 #define RECOVERY_COMMAND_FILE "recovery.conf"
58 #define RECOVERY_COMMAND_DONE "recovery.done"
61 /* User-settable parameters */
62 int CheckPointSegments = 3;
64 int XLogArchiveTimeout = 0;
65 char *XLogArchiveCommand = NULL;
66 char *XLOG_sync_method = NULL;
67 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
68 bool fullPageWrites = true;
71 bool XLOG_DEBUG = false;
75 * XLOGfileslop is used in the code as the allowed "fuzz" in the number of
76 * preallocated XLOG segments --- we try to have at least XLOGfiles advance
77 * segments but no more than XLOGfileslop segments. This could
78 * be made a separate GUC variable, but at present I think it's sufficient
79 * to hardwire it as 2*CheckPointSegments+1. Under normal conditions, a
80 * checkpoint will free no more than 2*CheckPointSegments log segments, and
81 * we want to recycle all of them; the +1 allows boundary cases to happen
82 * without wasting a delete/create-segment cycle.
85 #define XLOGfileslop (2*CheckPointSegments + 1)
88 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
89 int sync_method = DEFAULT_SYNC_METHOD;
90 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
92 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
96 * ThisTimeLineID will be same in all backends --- it identifies current
97 * WAL timeline for the database system.
99 TimeLineID ThisTimeLineID = 0;
101 /* Are we doing recovery from XLOG? */
102 bool InRecovery = false;
104 /* Are we recovering using offline XLOG archives? */
105 static bool InArchiveRecovery = false;
107 /* Was the last xlog file restored from archive, or local? */
108 static bool restoredFromArchive = false;
110 /* options taken from recovery.conf */
111 static char *recoveryRestoreCommand = NULL;
112 static bool recoveryTarget = false;
113 static bool recoveryTargetExact = false;
114 static bool recoveryTargetInclusive = true;
115 static TransactionId recoveryTargetXid;
116 static TimestampTz recoveryTargetTime;
118 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
119 static TransactionId recoveryStopXid;
120 static TimestampTz recoveryStopTime;
121 static bool recoveryStopAfter;
124 * During normal operation, the only timeline we care about is ThisTimeLineID.
125 * During recovery, however, things are more complicated. To simplify life
126 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
127 * scan through the WAL history (that is, it is the line that was active when
128 * the currently-scanned WAL record was generated). We also need these
131 * recoveryTargetTLI: the desired timeline that we want to end in.
133 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
134 * its known parents, newest first (so recoveryTargetTLI is always the
135 * first list member). Only these TLIs are expected to be seen in the WAL
136 * segments we read, and indeed only these TLIs will be considered as
137 * candidate WAL files to open at all.
139 * curFileTLI: the TLI appearing in the name of the current input WAL file.
140 * (This is not necessarily the same as ThisTimeLineID, because we could
141 * be scanning data that was copied from an ancestor timeline when the current
142 * file was created.) During a sequential scan we do not allow this value
145 static TimeLineID recoveryTargetTLI;
146 static List *expectedTLIs;
147 static TimeLineID curFileTLI;
150 * MyLastRecPtr points to the start of the last XLOG record inserted by the
151 * current transaction. If MyLastRecPtr.xrecoff == 0, then the current
152 * xact hasn't yet inserted any transaction-controlled XLOG records.
154 * Note that XLOG records inserted outside transaction control are not
155 * reflected into MyLastRecPtr. They do, however, cause MyXactMadeXLogEntry
156 * to be set true. The latter can be used to test whether the current xact
157 * made any loggable changes (including out-of-xact changes, such as
160 * When we insert/update/delete a tuple in a temporary relation, we do not
161 * make any XLOG record, since we don't care about recovering the state of
162 * the temp rel after a crash. However, we will still need to remember
163 * whether our transaction committed or aborted in that case. So, we must
164 * set MyXactMadeTempRelUpdate true to indicate that the XID will be of
167 XLogRecPtr MyLastRecPtr = {0, 0};
169 bool MyXactMadeXLogEntry = false;
171 bool MyXactMadeTempRelUpdate = false;
174 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
175 * current backend. It is updated for all inserts, transaction-controlled
176 * or not. ProcLastRecEnd is similar but points to end+1 of last record.
178 static XLogRecPtr ProcLastRecPtr = {0, 0};
180 XLogRecPtr ProcLastRecEnd = {0, 0};
183 * RedoRecPtr is this backend's local copy of the REDO record pointer
184 * (which is almost but not quite the same as a pointer to the most recent
185 * CHECKPOINT record). We update this from the shared-memory copy,
186 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
187 * hold the Insert lock). See XLogInsert for details. We are also allowed
188 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
189 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
192 static XLogRecPtr RedoRecPtr;
195 * Shared-memory data structures for XLOG control
197 * LogwrtRqst indicates a byte position that we need to write and/or fsync
198 * the log up to (all records before that point must be written or fsynced).
199 * LogwrtResult indicates the byte positions we have already written/fsynced.
200 * These structs are identical but are declared separately to indicate their
201 * slightly different functions.
203 * We do a lot of pushups to minimize the amount of access to lockable
204 * shared memory values. There are actually three shared-memory copies of
205 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
206 * XLogCtl->LogwrtResult is protected by info_lck
207 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
208 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
209 * One must hold the associated lock to read or write any of these, but
210 * of course no lock is needed to read/write the unshared LogwrtResult.
212 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
213 * right", since both are updated by a write or flush operation before
214 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
215 * is that it can be examined/modified by code that already holds WALWriteLock
216 * without needing to grab info_lck as well.
218 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
219 * but is updated when convenient. Again, it exists for the convenience of
220 * code that is already holding WALInsertLock but not the other locks.
222 * The unshared LogwrtResult may lag behind any or all of these, and again
223 * is updated when convenient.
225 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
226 * (protected by info_lck), but we don't need to cache any copies of it.
228 * Note that this all works because the request and result positions can only
229 * advance forward, never back up, and so we can easily determine which of two
230 * values is "more up to date".
232 * info_lck is only held long enough to read/update the protected variables,
233 * so it's a plain spinlock. The other locks are held longer (potentially
234 * over I/O operations), so we use LWLocks for them. These locks are:
236 * WALInsertLock: must be held to insert a record into the WAL buffers.
238 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
241 * ControlFileLock: must be held to read/update control file or create
244 * CheckpointLock: must be held to do a checkpoint (ensures only one
245 * checkpointer at a time; currently, with all checkpoints done by the
246 * bgwriter, this is just pro forma).
251 typedef struct XLogwrtRqst
253 XLogRecPtr Write; /* last byte + 1 to write out */
254 XLogRecPtr Flush; /* last byte + 1 to flush */
257 typedef struct XLogwrtResult
259 XLogRecPtr Write; /* last byte + 1 written out */
260 XLogRecPtr Flush; /* last byte + 1 flushed */
264 * Shared state data for XLogInsert.
266 typedef struct XLogCtlInsert
268 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
269 XLogRecPtr PrevRecord; /* start of previously-inserted record */
270 int curridx; /* current block index in cache */
271 XLogPageHeader currpage; /* points to header of block in cache */
272 char *currpos; /* current insertion point in cache */
273 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
274 bool forcePageWrites; /* forcing full-page writes for PITR? */
278 * Shared state data for XLogWrite/XLogFlush.
280 typedef struct XLogCtlWrite
282 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
283 int curridx; /* cache index of next block to write */
284 time_t lastSegSwitchTime; /* time of last xlog segment switch */
288 * Total shared-memory state for XLOG.
290 typedef struct XLogCtlData
292 /* Protected by WALInsertLock: */
293 XLogCtlInsert Insert;
295 /* Protected by info_lck: */
296 XLogwrtRqst LogwrtRqst;
297 XLogwrtResult LogwrtResult;
298 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
299 TransactionId ckptXid;
301 /* Protected by WALWriteLock: */
305 * These values do not change after startup, although the pointed-to pages
306 * and xlblocks values certainly do. Permission to read/write the pages
307 * and xlblocks values depends on WALInsertLock and WALWriteLock.
309 char *pages; /* buffers for unwritten XLOG pages */
310 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
311 Size XLogCacheByte; /* # bytes in xlog buffers */
312 int XLogCacheBlck; /* highest allocated xlog buffer index */
313 TimeLineID ThisTimeLineID;
315 slock_t info_lck; /* locks shared variables shown above */
318 static XLogCtlData *XLogCtl = NULL;
321 * We maintain an image of pg_control in shared memory.
323 static ControlFileData *ControlFile = NULL;
326 * Macros for managing XLogInsert state. In most cases, the calling routine
327 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
328 * so these are passed as parameters instead of being fetched via XLogCtl.
331 /* Free space remaining in the current xlog page buffer */
332 #define INSERT_FREESPACE(Insert) \
333 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
335 /* Construct XLogRecPtr value for current insertion point */
336 #define INSERT_RECPTR(recptr,Insert,curridx) \
338 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
340 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
343 #define PrevBufIdx(idx) \
344 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
346 #define NextBufIdx(idx) \
347 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
350 * Private, possibly out-of-date copy of shared LogwrtResult.
351 * See discussion above.
353 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
356 * openLogFile is -1 or a kernel FD for an open log file segment.
357 * When it's open, openLogOff is the current seek offset in the file.
358 * openLogId/openLogSeg identify the segment. These variables are only
359 * used to write the XLOG, and so will normally refer to the active segment.
361 static int openLogFile = -1;
362 static uint32 openLogId = 0;
363 static uint32 openLogSeg = 0;
364 static uint32 openLogOff = 0;
367 * These variables are used similarly to the ones above, but for reading
368 * the XLOG. Note, however, that readOff generally represents the offset
369 * of the page just read, not the seek position of the FD itself, which
370 * will be just past that page.
372 static int readFile = -1;
373 static uint32 readId = 0;
374 static uint32 readSeg = 0;
375 static uint32 readOff = 0;
377 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
378 static char *readBuf = NULL;
380 /* Buffer for current ReadRecord result (expandable) */
381 static char *readRecordBuf = NULL;
382 static uint32 readRecordBufSize = 0;
384 /* State information for XLOG reading */
385 static XLogRecPtr ReadRecPtr; /* start of last record read */
386 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
387 static XLogRecord *nextRecord = NULL;
388 static TimeLineID lastPageTLI = 0;
390 static bool InRedo = false;
393 static void XLogArchiveNotify(const char *xlog);
394 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
395 static bool XLogArchiveCheckDone(const char *xlog);
396 static void XLogArchiveCleanup(const char *xlog);
397 static void readRecoveryCommandFile(void);
398 static void exitArchiveRecovery(TimeLineID endTLI,
399 uint32 endLogId, uint32 endLogSeg);
400 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
401 static void CheckPointGuts(XLogRecPtr checkPointRedo);
403 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
404 XLogRecPtr *lsn, BkpBlock *bkpb);
405 static bool AdvanceXLInsertBuffer(bool new_segment);
406 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
407 static int XLogFileInit(uint32 log, uint32 seg,
408 bool *use_existent, bool use_lock);
409 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
410 bool find_free, int *max_advance,
412 static int XLogFileOpen(uint32 log, uint32 seg);
413 static int XLogFileRead(uint32 log, uint32 seg, int emode);
414 static void XLogFileClose(void);
415 static bool RestoreArchivedFile(char *path, const char *xlogfname,
416 const char *recovername, off_t expectedSize);
417 static int PreallocXlogFiles(XLogRecPtr endptr);
418 static void MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
419 int *nsegsremoved, int *nsegsrecycled);
420 static void CleanupBackupHistory(void);
421 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
422 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
423 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
424 static List *readTimeLineHistory(TimeLineID targetTLI);
425 static bool existsTimeLineHistory(TimeLineID probeTLI);
426 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
427 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
429 uint32 endLogId, uint32 endLogSeg);
430 static void WriteControlFile(void);
431 static void ReadControlFile(void);
432 static char *str_time(time_t tnow);
433 static void issue_xlog_fsync(void);
436 static void xlog_outrec(StringInfo buf, XLogRecord *record);
438 static bool read_backup_label(XLogRecPtr *checkPointLoc,
439 XLogRecPtr *minRecoveryLoc);
440 static void rm_redo_error_callback(void *arg);
444 * Insert an XLOG record having the specified RMID and info bytes,
445 * with the body of the record being the data chunk(s) described by
446 * the rdata chain (see xlog.h for notes about rdata).
448 * Returns XLOG pointer to end of record (beginning of next record).
449 * This can be used as LSN for data pages affected by the logged action.
450 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
451 * before the data page can be written out. This implements the basic
452 * WAL rule "write the log before the data".)
454 * NB: this routine feels free to scribble on the XLogRecData structs,
455 * though not on the data they reference. This is OK since the XLogRecData
456 * structs are always just temporaries in the calling code.
459 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
461 XLogCtlInsert *Insert = &XLogCtl->Insert;
463 XLogContRecord *contrecord;
465 XLogRecPtr WriteRqst;
469 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
470 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
471 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
472 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
473 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
474 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
475 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
480 XLogwrtRqst LogwrtRqst;
483 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
484 bool no_tran = (rmid == RM_XLOG_ID);
486 if (info & XLR_INFO_MASK)
488 if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
489 elog(PANIC, "invalid xlog info mask %02X", (info & XLR_INFO_MASK));
491 info &= ~XLR_INFO_MASK;
495 * In bootstrap mode, we don't actually log anything but XLOG resources;
496 * return a phony record pointer.
498 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
501 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
506 * Here we scan the rdata chain, determine which buffers must be backed
507 * up, and compute the CRC values for the data. Note that the record
508 * header isn't added into the CRC initially since we don't know the final
509 * length or info bits quite yet. Thus, the CRC will represent the CRC of
510 * the whole record in the order "rdata, then backup blocks, then record
513 * We may have to loop back to here if a race condition is detected below.
514 * We could prevent the race by doing all this work while holding the
515 * insert lock, but it seems better to avoid doing CRC calculations while
516 * holding the lock. This means we have to be careful about modifying the
517 * rdata chain until we know we aren't going to loop back again. The only
518 * change we allow ourselves to make earlier is to set rdt->data = NULL in
519 * chain items we have decided we will have to back up the whole buffer
520 * for. This is OK because we will certainly decide the same thing again
521 * for those items if we do it over; doing it here saves an extra pass
522 * over the chain later.
525 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
527 dtbuf[i] = InvalidBuffer;
528 dtbuf_bkp[i] = false;
532 * Decide if we need to do full-page writes in this XLOG record: true if
533 * full_page_writes is on or we have a PITR request for it. Since we
534 * don't yet have the insert lock, forcePageWrites could change under us,
535 * but we'll recheck it once we have the lock.
537 doPageWrites = fullPageWrites || Insert->forcePageWrites;
539 INIT_CRC32(rdata_crc);
543 if (rdt->buffer == InvalidBuffer)
545 /* Simple data, just include it */
547 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
551 /* Find info for buffer */
552 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
554 if (rdt->buffer == dtbuf[i])
556 /* Buffer already referenced by earlier chain item */
562 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
566 if (dtbuf[i] == InvalidBuffer)
568 /* OK, put it in this slot */
569 dtbuf[i] = rdt->buffer;
570 if (XLogCheckBuffer(rdt, doPageWrites,
571 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
579 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
584 if (i >= XLR_MAX_BKP_BLOCKS)
585 elog(PANIC, "can backup at most %d blocks per xlog record",
588 /* Break out of loop when rdt points to last chain item */
589 if (rdt->next == NULL)
595 * Now add the backup block headers and data into the CRC
597 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
601 BkpBlock *bkpb = &(dtbuf_xlg[i]);
604 COMP_CRC32(rdata_crc,
607 page = (char *) BufferGetBlock(dtbuf[i]);
608 if (bkpb->hole_length == 0)
610 COMP_CRC32(rdata_crc,
616 /* must skip the hole */
617 COMP_CRC32(rdata_crc,
620 COMP_CRC32(rdata_crc,
621 page + (bkpb->hole_offset + bkpb->hole_length),
622 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
628 * NOTE: We disallow len == 0 because it provides a useful bit of extra
629 * error checking in ReadRecord. This means that all callers of
630 * XLogInsert must supply at least some not-in-a-buffer data. However, we
631 * make an exception for XLOG SWITCH records because we don't want them to
632 * ever cross a segment boundary.
634 if (len == 0 && !isLogSwitch)
635 elog(PANIC, "invalid xlog record length %u", len);
637 START_CRIT_SECTION();
639 /* update LogwrtResult before doing cache fill check */
641 /* use volatile pointer to prevent code rearrangement */
642 volatile XLogCtlData *xlogctl = XLogCtl;
644 SpinLockAcquire(&xlogctl->info_lck);
645 LogwrtRqst = xlogctl->LogwrtRqst;
646 LogwrtResult = xlogctl->LogwrtResult;
647 SpinLockRelease(&xlogctl->info_lck);
651 * If cache is half filled then try to acquire write lock and do
652 * XLogWrite. Ignore any fractional blocks in performing this check.
654 LogwrtRqst.Write.xrecoff -= LogwrtRqst.Write.xrecoff % XLOG_BLCKSZ;
655 if (LogwrtRqst.Write.xlogid != LogwrtResult.Write.xlogid ||
656 (LogwrtRqst.Write.xrecoff >= LogwrtResult.Write.xrecoff +
657 XLogCtl->XLogCacheByte / 2))
659 if (LWLockConditionalAcquire(WALWriteLock, LW_EXCLUSIVE))
662 * Since the amount of data we write here is completely optional
663 * anyway, tell XLogWrite it can be "flexible" and stop at a
664 * convenient boundary. This allows writes triggered by this
665 * mechanism to synchronize with the cache boundaries, so that in
666 * a long transaction we'll basically dump alternating halves of
669 LogwrtResult = XLogCtl->Write.LogwrtResult;
670 if (XLByteLT(LogwrtResult.Write, LogwrtRqst.Write))
671 XLogWrite(LogwrtRqst, true, false);
672 LWLockRelease(WALWriteLock);
676 /* Now wait to get insert lock */
677 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
680 * Check to see if my RedoRecPtr is out of date. If so, may have to go
681 * back and recompute everything. This can only happen just after a
682 * checkpoint, so it's better to be slow in this case and fast otherwise.
684 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
685 * affect the contents of the XLOG record, so we'll update our local copy
686 * but not force a recomputation.
688 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
690 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
691 RedoRecPtr = Insert->RedoRecPtr;
695 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
697 if (dtbuf[i] == InvalidBuffer)
699 if (dtbuf_bkp[i] == false &&
700 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
703 * Oops, this buffer now needs to be backed up, but we
704 * didn't think so above. Start over.
706 LWLockRelease(WALInsertLock);
715 * Also check to see if forcePageWrites was just turned on; if we weren't
716 * already doing full-page writes then go back and recompute. (If it was
717 * just turned off, we could recompute the record without full pages, but
718 * we choose not to bother.)
720 if (Insert->forcePageWrites && !doPageWrites)
722 /* Oops, must redo it with full-page data */
723 LWLockRelease(WALInsertLock);
729 * Make additional rdata chain entries for the backup blocks, so that we
730 * don't need to special-case them in the write loop. Note that we have
731 * now irrevocably changed the input rdata chain. At the exit of this
732 * loop, write_len includes the backup block data.
734 * Also set the appropriate info bits to show which buffers were backed
735 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
736 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
739 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
747 info |= XLR_SET_BKP_BLOCK(i);
749 bkpb = &(dtbuf_xlg[i]);
750 page = (char *) BufferGetBlock(dtbuf[i]);
752 rdt->next = &(dtbuf_rdt1[i]);
755 rdt->data = (char *) bkpb;
756 rdt->len = sizeof(BkpBlock);
757 write_len += sizeof(BkpBlock);
759 rdt->next = &(dtbuf_rdt2[i]);
762 if (bkpb->hole_length == 0)
771 /* must skip the hole */
773 rdt->len = bkpb->hole_offset;
774 write_len += bkpb->hole_offset;
776 rdt->next = &(dtbuf_rdt3[i]);
779 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
780 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
781 write_len += rdt->len;
787 * If there isn't enough space on the current XLOG page for a record
788 * header, advance to the next page (leaving the unused space as zeroes).
791 freespace = INSERT_FREESPACE(Insert);
792 if (freespace < SizeOfXLogRecord)
794 updrqst = AdvanceXLInsertBuffer(false);
795 freespace = INSERT_FREESPACE(Insert);
798 /* Compute record's XLOG location */
799 curridx = Insert->curridx;
800 INSERT_RECPTR(RecPtr, Insert, curridx);
803 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
804 * segment, we need not insert it (and don't want to because we'd like
805 * consecutive switch requests to be no-ops). Instead, make sure
806 * everything is written and flushed through the end of the prior segment,
807 * and return the prior segment's end address.
810 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
812 /* We can release insert lock immediately */
813 LWLockRelease(WALInsertLock);
815 RecPtr.xrecoff -= SizeOfXLogLongPHD;
816 if (RecPtr.xrecoff == 0)
818 /* crossing a logid boundary */
820 RecPtr.xrecoff = XLogFileSize;
823 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
824 LogwrtResult = XLogCtl->Write.LogwrtResult;
825 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
827 XLogwrtRqst FlushRqst;
829 FlushRqst.Write = RecPtr;
830 FlushRqst.Flush = RecPtr;
831 XLogWrite(FlushRqst, false, false);
833 LWLockRelease(WALWriteLock);
840 /* Insert record header */
842 record = (XLogRecord *) Insert->currpos;
843 record->xl_prev = Insert->PrevRecord;
844 record->xl_xid = GetCurrentTransactionIdIfAny();
845 record->xl_tot_len = SizeOfXLogRecord + write_len;
846 record->xl_len = len; /* doesn't include backup blocks */
847 record->xl_info = info;
848 record->xl_rmid = rmid;
850 /* Now we can finish computing the record's CRC */
851 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
852 SizeOfXLogRecord - sizeof(pg_crc32));
853 FIN_CRC32(rdata_crc);
854 record->xl_crc = rdata_crc;
861 initStringInfo(&buf);
862 appendStringInfo(&buf, "INSERT @ %X/%X: ",
863 RecPtr.xlogid, RecPtr.xrecoff);
864 xlog_outrec(&buf, record);
865 if (rdata->data != NULL)
867 appendStringInfo(&buf, " - ");
868 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
870 elog(LOG, "%s", buf.data);
875 /* Record begin of record in appropriate places */
877 MyLastRecPtr = RecPtr;
878 ProcLastRecPtr = RecPtr;
879 Insert->PrevRecord = RecPtr;
880 MyXactMadeXLogEntry = true;
882 Insert->currpos += SizeOfXLogRecord;
883 freespace -= SizeOfXLogRecord;
886 * Append the data, including backup blocks if any
890 while (rdata->data == NULL)
895 if (rdata->len > freespace)
897 memcpy(Insert->currpos, rdata->data, freespace);
898 rdata->data += freespace;
899 rdata->len -= freespace;
900 write_len -= freespace;
904 memcpy(Insert->currpos, rdata->data, rdata->len);
905 freespace -= rdata->len;
906 write_len -= rdata->len;
907 Insert->currpos += rdata->len;
913 /* Use next buffer */
914 updrqst = AdvanceXLInsertBuffer(false);
915 curridx = Insert->curridx;
916 /* Insert cont-record header */
917 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
918 contrecord = (XLogContRecord *) Insert->currpos;
919 contrecord->xl_rem_len = write_len;
920 Insert->currpos += SizeOfXLogContRecord;
921 freespace = INSERT_FREESPACE(Insert);
924 /* Ensure next record will be properly aligned */
925 Insert->currpos = (char *) Insert->currpage +
926 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
927 freespace = INSERT_FREESPACE(Insert);
930 * The recptr I return is the beginning of the *next* record. This will be
931 * stored as LSN for changed data pages...
933 INSERT_RECPTR(RecPtr, Insert, curridx);
936 * If the record is an XLOG_SWITCH, we must now write and flush all the
937 * existing data, and then forcibly advance to the start of the next
938 * segment. It's not good to do this I/O while holding the insert lock,
939 * but there seems too much risk of confusion if we try to release the
940 * lock sooner. Fortunately xlog switch needn't be a high-performance
941 * operation anyway...
945 XLogCtlWrite *Write = &XLogCtl->Write;
946 XLogwrtRqst FlushRqst;
947 XLogRecPtr OldSegEnd;
949 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
952 * Flush through the end of the page containing XLOG_SWITCH, and
953 * perform end-of-segment actions (eg, notifying archiver).
955 WriteRqst = XLogCtl->xlblocks[curridx];
956 FlushRqst.Write = WriteRqst;
957 FlushRqst.Flush = WriteRqst;
958 XLogWrite(FlushRqst, false, true);
960 /* Set up the next buffer as first page of next segment */
961 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
962 (void) AdvanceXLInsertBuffer(true);
964 /* There should be no unwritten data */
965 curridx = Insert->curridx;
966 Assert(curridx == Write->curridx);
968 /* Compute end address of old segment */
969 OldSegEnd = XLogCtl->xlblocks[curridx];
970 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
971 if (OldSegEnd.xrecoff == 0)
973 /* crossing a logid boundary */
974 OldSegEnd.xlogid -= 1;
975 OldSegEnd.xrecoff = XLogFileSize;
978 /* Make it look like we've written and synced all of old segment */
979 LogwrtResult.Write = OldSegEnd;
980 LogwrtResult.Flush = OldSegEnd;
983 * Update shared-memory status --- this code should match XLogWrite
986 /* use volatile pointer to prevent code rearrangement */
987 volatile XLogCtlData *xlogctl = XLogCtl;
989 SpinLockAcquire(&xlogctl->info_lck);
990 xlogctl->LogwrtResult = LogwrtResult;
991 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
992 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
993 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
994 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
995 SpinLockRelease(&xlogctl->info_lck);
998 Write->LogwrtResult = LogwrtResult;
1000 LWLockRelease(WALWriteLock);
1002 updrqst = false; /* done already */
1006 /* normal case, ie not xlog switch */
1008 /* Need to update shared LogwrtRqst if some block was filled up */
1009 if (freespace < SizeOfXLogRecord)
1011 /* curridx is filled and available for writing out */
1016 /* if updrqst already set, write through end of previous buf */
1017 curridx = PrevBufIdx(curridx);
1019 WriteRqst = XLogCtl->xlblocks[curridx];
1022 LWLockRelease(WALInsertLock);
1026 /* use volatile pointer to prevent code rearrangement */
1027 volatile XLogCtlData *xlogctl = XLogCtl;
1029 SpinLockAcquire(&xlogctl->info_lck);
1030 /* advance global request to include new block(s) */
1031 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
1032 xlogctl->LogwrtRqst.Write = WriteRqst;
1033 /* update local result copy while I have the chance */
1034 LogwrtResult = xlogctl->LogwrtResult;
1035 SpinLockRelease(&xlogctl->info_lck);
1038 ProcLastRecEnd = RecPtr;
1046 * Determine whether the buffer referenced by an XLogRecData item has to
1047 * be backed up, and if so fill a BkpBlock struct for it. In any case
1048 * save the buffer's LSN at *lsn.
1051 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1052 XLogRecPtr *lsn, BkpBlock *bkpb)
1056 page = (PageHeader) BufferGetBlock(rdata->buffer);
1059 * XXX We assume page LSN is first data on *every* page that can be passed
1060 * to XLogInsert, whether it otherwise has the standard page layout or
1063 *lsn = page->pd_lsn;
1066 XLByteLE(page->pd_lsn, RedoRecPtr))
1069 * The page needs to be backed up, so set up *bkpb
1071 bkpb->node = BufferGetFileNode(rdata->buffer);
1072 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1074 if (rdata->buffer_std)
1076 /* Assume we can omit data between pd_lower and pd_upper */
1077 uint16 lower = page->pd_lower;
1078 uint16 upper = page->pd_upper;
1080 if (lower >= SizeOfPageHeaderData &&
1084 bkpb->hole_offset = lower;
1085 bkpb->hole_length = upper - lower;
1089 /* No "hole" to compress out */
1090 bkpb->hole_offset = 0;
1091 bkpb->hole_length = 0;
1096 /* Not a standard page header, don't try to eliminate "hole" */
1097 bkpb->hole_offset = 0;
1098 bkpb->hole_length = 0;
1101 return true; /* buffer requires backup */
1104 return false; /* buffer does not need to be backed up */
1110 * Create an archive notification file
1112 * The name of the notification file is the message that will be picked up
1113 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1114 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1115 * then when complete, rename it to 0000000100000001000000C6.done
1118 XLogArchiveNotify(const char *xlog)
1120 char archiveStatusPath[MAXPGPATH];
1123 /* insert an otherwise empty file called <XLOG>.ready */
1124 StatusFilePath(archiveStatusPath, xlog, ".ready");
1125 fd = AllocateFile(archiveStatusPath, "w");
1129 (errcode_for_file_access(),
1130 errmsg("could not create archive status file \"%s\": %m",
1131 archiveStatusPath)));
1137 (errcode_for_file_access(),
1138 errmsg("could not write archive status file \"%s\": %m",
1139 archiveStatusPath)));
1143 /* Notify archiver that it's got something to do */
1144 if (IsUnderPostmaster)
1145 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1149 * Convenience routine to notify using log/seg representation of filename
1152 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1154 char xlog[MAXFNAMELEN];
1156 XLogFileName(xlog, ThisTimeLineID, log, seg);
1157 XLogArchiveNotify(xlog);
1161 * XLogArchiveCheckDone
1163 * This is called when we are ready to delete or recycle an old XLOG segment
1164 * file or backup history file. If it is okay to delete it then return true.
1165 * If it is not time to delete it, make sure a .ready file exists, and return
1168 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1169 * then return false; else create <XLOG>.ready and return false.
1171 * The reason we do things this way is so that if the original attempt to
1172 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1175 XLogArchiveCheckDone(const char *xlog)
1177 char archiveStatusPath[MAXPGPATH];
1178 struct stat stat_buf;
1180 /* Always deletable if archiving is off */
1181 if (!XLogArchivingActive())
1184 /* First check for .done --- this means archiver is done with it */
1185 StatusFilePath(archiveStatusPath, xlog, ".done");
1186 if (stat(archiveStatusPath, &stat_buf) == 0)
1189 /* check for .ready --- this means archiver is still busy with it */
1190 StatusFilePath(archiveStatusPath, xlog, ".ready");
1191 if (stat(archiveStatusPath, &stat_buf) == 0)
1194 /* Race condition --- maybe archiver just finished, so recheck */
1195 StatusFilePath(archiveStatusPath, xlog, ".done");
1196 if (stat(archiveStatusPath, &stat_buf) == 0)
1199 /* Retry creation of the .ready file */
1200 XLogArchiveNotify(xlog);
1205 * XLogArchiveCleanup
1207 * Cleanup archive notification file(s) for a particular xlog segment
1210 XLogArchiveCleanup(const char *xlog)
1212 char archiveStatusPath[MAXPGPATH];
1214 /* Remove the .done file */
1215 StatusFilePath(archiveStatusPath, xlog, ".done");
1216 unlink(archiveStatusPath);
1217 /* should we complain about failure? */
1219 /* Remove the .ready file if present --- normally it shouldn't be */
1220 StatusFilePath(archiveStatusPath, xlog, ".ready");
1221 unlink(archiveStatusPath);
1222 /* should we complain about failure? */
1226 * Advance the Insert state to the next buffer page, writing out the next
1227 * buffer if it still contains unwritten data.
1229 * If new_segment is TRUE then we set up the next buffer page as the first
1230 * page of the next xlog segment file, possibly but not usually the next
1231 * consecutive file page.
1233 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1234 * just-filled page. If we can do this for free (without an extra lock),
1235 * we do so here. Otherwise the caller must do it. We return TRUE if the
1236 * request update still needs to be done, FALSE if we did it internally.
1238 * Must be called with WALInsertLock held.
1241 AdvanceXLInsertBuffer(bool new_segment)
1243 XLogCtlInsert *Insert = &XLogCtl->Insert;
1244 XLogCtlWrite *Write = &XLogCtl->Write;
1245 int nextidx = NextBufIdx(Insert->curridx);
1246 bool update_needed = true;
1247 XLogRecPtr OldPageRqstPtr;
1248 XLogwrtRqst WriteRqst;
1249 XLogRecPtr NewPageEndPtr;
1250 XLogPageHeader NewPage;
1252 /* Use Insert->LogwrtResult copy if it's more fresh */
1253 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1254 LogwrtResult = Insert->LogwrtResult;
1257 * Get ending-offset of the buffer page we need to replace (this may be
1258 * zero if the buffer hasn't been used yet). Fall through if it's already
1261 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1262 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1264 /* nope, got work to do... */
1265 XLogRecPtr FinishedPageRqstPtr;
1267 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1269 /* Before waiting, get info_lck and update LogwrtResult */
1271 /* use volatile pointer to prevent code rearrangement */
1272 volatile XLogCtlData *xlogctl = XLogCtl;
1274 SpinLockAcquire(&xlogctl->info_lck);
1275 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1276 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1277 LogwrtResult = xlogctl->LogwrtResult;
1278 SpinLockRelease(&xlogctl->info_lck);
1281 update_needed = false; /* Did the shared-request update */
1283 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1285 /* OK, someone wrote it already */
1286 Insert->LogwrtResult = LogwrtResult;
1290 /* Must acquire write lock */
1291 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1292 LogwrtResult = Write->LogwrtResult;
1293 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1295 /* OK, someone wrote it already */
1296 LWLockRelease(WALWriteLock);
1297 Insert->LogwrtResult = LogwrtResult;
1302 * Have to write buffers while holding insert lock. This is
1303 * not good, so only write as much as we absolutely must.
1305 WriteRqst.Write = OldPageRqstPtr;
1306 WriteRqst.Flush.xlogid = 0;
1307 WriteRqst.Flush.xrecoff = 0;
1308 XLogWrite(WriteRqst, false, false);
1309 LWLockRelease(WALWriteLock);
1310 Insert->LogwrtResult = LogwrtResult;
1316 * Now the next buffer slot is free and we can set it up to be the next
1319 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1323 /* force it to a segment start point */
1324 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1325 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1328 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1330 /* crossing a logid boundary */
1331 NewPageEndPtr.xlogid += 1;
1332 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1335 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1336 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1337 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1339 Insert->curridx = nextidx;
1340 Insert->currpage = NewPage;
1342 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1345 * Be sure to re-zero the buffer so that bytes beyond what we've written
1346 * will look like zeroes and not valid XLOG records...
1348 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1351 * Fill the new page's header
1353 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1355 /* NewPage->xlp_info = 0; */ /* done by memset */
1356 NewPage ->xlp_tli = ThisTimeLineID;
1357 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1358 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1361 * If first page of an XLOG segment file, make it a long header.
1363 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1365 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1367 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1368 NewLongPage->xlp_seg_size = XLogSegSize;
1369 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1370 NewPage ->xlp_info |= XLP_LONG_HEADER;
1372 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1375 return update_needed;
1379 * Write and/or fsync the log at least as far as WriteRqst indicates.
1381 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1382 * may stop at any convenient boundary (such as a cache or logfile boundary).
1383 * This option allows us to avoid uselessly issuing multiple writes when a
1384 * single one would do.
1386 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1387 * perform end-of-segment actions after writing the last page, even if
1388 * it's not physically the end of its segment. (NB: this will work properly
1389 * only if caller specifies WriteRqst == page-end and flexible == false,
1390 * and there is some data to write.)
1392 * Must be called with WALWriteLock held.
1395 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1397 XLogCtlWrite *Write = &XLogCtl->Write;
1399 bool last_iteration;
1407 /* We should always be inside a critical section here */
1408 Assert(CritSectionCount > 0);
1411 * Update local LogwrtResult (caller probably did this already, but...)
1413 LogwrtResult = Write->LogwrtResult;
1416 * Since successive pages in the xlog cache are consecutively allocated,
1417 * we can usually gather multiple pages together and issue just one
1418 * write() call. npages is the number of pages we have determined can be
1419 * written together; startidx is the cache block index of the first one,
1420 * and startoffset is the file offset at which it should go. The latter
1421 * two variables are only valid when npages > 0, but we must initialize
1422 * all of them to keep the compiler quiet.
1429 * Within the loop, curridx is the cache block index of the page to
1430 * consider writing. We advance Write->curridx only after successfully
1431 * writing pages. (Right now, this refinement is useless since we are
1432 * going to PANIC if any error occurs anyway; but someday it may come in
1435 curridx = Write->curridx;
1437 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1440 * Make sure we're not ahead of the insert process. This could happen
1441 * if we're passed a bogus WriteRqst.Write that is past the end of the
1442 * last page that's been initialized by AdvanceXLInsertBuffer.
1444 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1445 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1446 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1447 XLogCtl->xlblocks[curridx].xlogid,
1448 XLogCtl->xlblocks[curridx].xrecoff);
1450 /* Advance LogwrtResult.Write to end of current buffer page */
1451 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1452 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1454 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1457 * Switch to new logfile segment. We cannot have any pending
1458 * pages here (since we dump what we have at segment end).
1460 Assert(npages == 0);
1461 if (openLogFile >= 0)
1463 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1465 /* create/use new log file */
1466 use_existent = true;
1467 openLogFile = XLogFileInit(openLogId, openLogSeg,
1468 &use_existent, true);
1472 /* Make sure we have the current logfile open */
1473 if (openLogFile < 0)
1475 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1476 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1480 /* Add current page to the set of pending pages-to-dump */
1483 /* first of group */
1485 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1490 * Dump the set if this will be the last loop iteration, or if we are
1491 * at the last page of the cache area (since the next page won't be
1492 * contiguous in memory), or if we are at the end of the logfile
1495 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1497 finishing_seg = !ispartialpage &&
1498 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1500 if (last_iteration ||
1501 curridx == XLogCtl->XLogCacheBlck ||
1507 /* Need to seek in the file? */
1508 if (openLogOff != startoffset)
1510 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1512 (errcode_for_file_access(),
1513 errmsg("could not seek in log file %u, "
1514 "segment %u to offset %u: %m",
1515 openLogId, openLogSeg, startoffset)));
1516 openLogOff = startoffset;
1519 /* OK to write the page(s) */
1520 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1521 nbytes = npages * (Size) XLOG_BLCKSZ;
1523 if (write(openLogFile, from, nbytes) != nbytes)
1525 /* if write didn't set errno, assume no disk space */
1529 (errcode_for_file_access(),
1530 errmsg("could not write to log file %u, segment %u "
1531 "at offset %u, length %lu: %m",
1532 openLogId, openLogSeg,
1533 openLogOff, (unsigned long) nbytes)));
1536 /* Update state for write */
1537 openLogOff += nbytes;
1538 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1542 * If we just wrote the whole last page of a logfile segment,
1543 * fsync the segment immediately. This avoids having to go back
1544 * and re-open prior segments when an fsync request comes along
1545 * later. Doing it here ensures that one and only one backend will
1546 * perform this fsync.
1548 * We also do this if this is the last page written for an xlog
1551 * This is also the right place to notify the Archiver that the
1552 * segment is ready to copy to archival storage, and to update the
1553 * timer for archive_timeout, and to signal for a checkpoint if
1554 * too many logfile segments have been used since the last
1557 if (finishing_seg || (xlog_switch && last_iteration))
1560 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1562 if (XLogArchivingActive())
1563 XLogArchiveNotifySeg(openLogId, openLogSeg);
1565 Write->lastSegSwitchTime = time(NULL);
1568 * Signal bgwriter to start a checkpoint if it's been too long
1569 * since the last one. (We look at local copy of RedoRecPtr
1570 * which might be a little out of date, but should be close
1571 * enough for this purpose.)
1573 * A straight computation of segment number could overflow 32
1574 * bits. Rather than assuming we have working 64-bit
1575 * arithmetic, we compare the highest-order bits separately,
1576 * and force a checkpoint immediately when they change.
1578 if (IsUnderPostmaster)
1582 uint32 old_highbits,
1585 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1586 (RedoRecPtr.xrecoff / XLogSegSize);
1587 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1588 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile +
1590 new_highbits = openLogId / XLogSegSize;
1591 if (new_highbits != old_highbits ||
1592 new_segno >= old_segno + (uint32) (CheckPointSegments-1))
1596 elog(LOG, "time for a checkpoint, signaling bgwriter");
1598 RequestCheckpoint(false, true);
1606 /* Only asked to write a partial page */
1607 LogwrtResult.Write = WriteRqst.Write;
1610 curridx = NextBufIdx(curridx);
1612 /* If flexible, break out of loop as soon as we wrote something */
1613 if (flexible && npages == 0)
1617 Assert(npages == 0);
1618 Assert(curridx == Write->curridx);
1621 * If asked to flush, do so
1623 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1624 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1627 * Could get here without iterating above loop, in which case we might
1628 * have no open file or the wrong one. However, we do not need to
1629 * fsync more than one file.
1631 if (sync_method != SYNC_METHOD_OPEN)
1633 if (openLogFile >= 0 &&
1634 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1636 if (openLogFile < 0)
1638 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1639 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1644 LogwrtResult.Flush = LogwrtResult.Write;
1648 * Update shared-memory status
1650 * We make sure that the shared 'request' values do not fall behind the
1651 * 'result' values. This is not absolutely essential, but it saves some
1652 * code in a couple of places.
1655 /* use volatile pointer to prevent code rearrangement */
1656 volatile XLogCtlData *xlogctl = XLogCtl;
1658 SpinLockAcquire(&xlogctl->info_lck);
1659 xlogctl->LogwrtResult = LogwrtResult;
1660 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1661 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1662 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1663 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1664 SpinLockRelease(&xlogctl->info_lck);
1667 Write->LogwrtResult = LogwrtResult;
1671 * Ensure that all XLOG data through the given position is flushed to disk.
1673 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1674 * already held, and we try to avoid acquiring it if possible.
1677 XLogFlush(XLogRecPtr record)
1679 XLogRecPtr WriteRqstPtr;
1680 XLogwrtRqst WriteRqst;
1682 /* Disabled during REDO */
1686 /* Quick exit if already known flushed */
1687 if (XLByteLE(record, LogwrtResult.Flush))
1692 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1693 record.xlogid, record.xrecoff,
1694 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1695 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1698 START_CRIT_SECTION();
1701 * Since fsync is usually a horribly expensive operation, we try to
1702 * piggyback as much data as we can on each fsync: if we see any more data
1703 * entered into the xlog buffer, we'll write and fsync that too, so that
1704 * the final value of LogwrtResult.Flush is as large as possible. This
1705 * gives us some chance of avoiding another fsync immediately after.
1708 /* initialize to given target; may increase below */
1709 WriteRqstPtr = record;
1711 /* read LogwrtResult and update local state */
1713 /* use volatile pointer to prevent code rearrangement */
1714 volatile XLogCtlData *xlogctl = XLogCtl;
1716 SpinLockAcquire(&xlogctl->info_lck);
1717 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1718 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1719 LogwrtResult = xlogctl->LogwrtResult;
1720 SpinLockRelease(&xlogctl->info_lck);
1724 if (!XLByteLE(record, LogwrtResult.Flush))
1726 /* now wait for the write lock */
1727 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1728 LogwrtResult = XLogCtl->Write.LogwrtResult;
1729 if (!XLByteLE(record, LogwrtResult.Flush))
1731 /* try to write/flush later additions to XLOG as well */
1732 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1734 XLogCtlInsert *Insert = &XLogCtl->Insert;
1735 uint32 freespace = INSERT_FREESPACE(Insert);
1737 if (freespace < SizeOfXLogRecord) /* buffer is full */
1738 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1741 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1742 WriteRqstPtr.xrecoff -= freespace;
1744 LWLockRelease(WALInsertLock);
1745 WriteRqst.Write = WriteRqstPtr;
1746 WriteRqst.Flush = WriteRqstPtr;
1750 WriteRqst.Write = WriteRqstPtr;
1751 WriteRqst.Flush = record;
1753 XLogWrite(WriteRqst, false, false);
1755 LWLockRelease(WALWriteLock);
1761 * If we still haven't flushed to the request point then we have a
1762 * problem; most likely, the requested flush point is past end of XLOG.
1763 * This has been seen to occur when a disk page has a corrupted LSN.
1765 * Formerly we treated this as a PANIC condition, but that hurts the
1766 * system's robustness rather than helping it: we do not want to take down
1767 * the whole system due to corruption on one data page. In particular, if
1768 * the bad page is encountered again during recovery then we would be
1769 * unable to restart the database at all! (This scenario has actually
1770 * happened in the field several times with 7.1 releases. Note that we
1771 * cannot get here while InRedo is true, but if the bad page is brought in
1772 * and marked dirty during recovery then CreateCheckPoint will try to
1773 * flush it at the end of recovery.)
1775 * The current approach is to ERROR under normal conditions, but only
1776 * WARNING during recovery, so that the system can be brought up even if
1777 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1778 * be promoted to PANIC since xact.c calls this routine inside a critical
1779 * section. However, calls from bufmgr.c are not within critical sections
1780 * and so we will not force a restart for a bad LSN on a data page.
1782 if (XLByteLT(LogwrtResult.Flush, record))
1783 elog(InRecovery ? WARNING : ERROR,
1784 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1785 record.xlogid, record.xrecoff,
1786 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1790 * Create a new XLOG file segment, or open a pre-existing one.
1792 * log, seg: identify segment to be created/opened.
1794 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1795 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1798 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1799 * place. This should be TRUE except during bootstrap log creation. The
1800 * caller must *not* hold the lock at call.
1802 * Returns FD of opened file.
1804 * Note: errors here are ERROR not PANIC because we might or might not be
1805 * inside a critical section (eg, during checkpoint there is no reason to
1806 * take down the system on failure). They will promote to PANIC if we are
1807 * in a critical section.
1810 XLogFileInit(uint32 log, uint32 seg,
1811 bool *use_existent, bool use_lock)
1813 char path[MAXPGPATH];
1814 char tmppath[MAXPGPATH];
1815 char zbuffer[XLOG_BLCKSZ];
1816 uint32 installed_log;
1817 uint32 installed_seg;
1822 XLogFilePath(path, ThisTimeLineID, log, seg);
1825 * Try to use existent file (checkpoint maker may have created it already)
1829 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1833 if (errno != ENOENT)
1835 (errcode_for_file_access(),
1836 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1844 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
1845 * another process is doing the same thing. If so, we will end up
1846 * pre-creating an extra log segment. That seems OK, and better than
1847 * holding the lock throughout this lengthy process.
1849 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1853 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1854 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1858 (errcode_for_file_access(),
1859 errmsg("could not create file \"%s\": %m", tmppath)));
1862 * Zero-fill the file. We have to do this the hard way to ensure that all
1863 * the file space has really been allocated --- on platforms that allow
1864 * "holes" in files, just seeking to the end doesn't allocate intermediate
1865 * space. This way, we know that we have all the space and (after the
1866 * fsync below) that all the indirect blocks are down on disk. Therefore,
1867 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
1870 MemSet(zbuffer, 0, sizeof(zbuffer));
1871 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(zbuffer))
1874 if ((int) write(fd, zbuffer, sizeof(zbuffer)) != (int) sizeof(zbuffer))
1876 int save_errno = errno;
1879 * If we fail to make the file, delete it to release disk space
1882 /* if write didn't set errno, assume problem is no disk space */
1883 errno = save_errno ? save_errno : ENOSPC;
1886 (errcode_for_file_access(),
1887 errmsg("could not write to file \"%s\": %m", tmppath)));
1891 if (pg_fsync(fd) != 0)
1893 (errcode_for_file_access(),
1894 errmsg("could not fsync file \"%s\": %m", tmppath)));
1898 (errcode_for_file_access(),
1899 errmsg("could not close file \"%s\": %m", tmppath)));
1902 * Now move the segment into place with its final name.
1904 * If caller didn't want to use a pre-existing file, get rid of any
1905 * pre-existing file. Otherwise, cope with possibility that someone else
1906 * has created the file while we were filling ours: if so, use ours to
1907 * pre-create a future log segment.
1909 installed_log = log;
1910 installed_seg = seg;
1911 max_advance = XLOGfileslop;
1912 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
1913 *use_existent, &max_advance,
1916 /* No need for any more future segments... */
1920 /* Set flag to tell caller there was no existent file */
1921 *use_existent = false;
1923 /* Now open original target segment (might not be file I just made) */
1924 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1928 (errcode_for_file_access(),
1929 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1936 * Create a new XLOG file segment by copying a pre-existing one.
1938 * log, seg: identify segment to be created.
1940 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
1941 * a different timeline)
1943 * Currently this is only used during recovery, and so there are no locking
1944 * considerations. But we should be just as tense as XLogFileInit to avoid
1945 * emplacing a bogus file.
1948 XLogFileCopy(uint32 log, uint32 seg,
1949 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
1951 char path[MAXPGPATH];
1952 char tmppath[MAXPGPATH];
1953 char buffer[XLOG_BLCKSZ];
1959 * Open the source file
1961 XLogFilePath(path, srcTLI, srclog, srcseg);
1962 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1965 (errcode_for_file_access(),
1966 errmsg("could not open file \"%s\": %m", path)));
1969 * Copy into a temp file name.
1971 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1975 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1976 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1980 (errcode_for_file_access(),
1981 errmsg("could not create file \"%s\": %m", tmppath)));
1984 * Do the data copying.
1986 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
1989 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
1993 (errcode_for_file_access(),
1994 errmsg("could not read file \"%s\": %m", path)));
1997 (errmsg("not enough data in file \"%s\"", path)));
2000 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2002 int save_errno = errno;
2005 * If we fail to make the file, delete it to release disk space
2008 /* if write didn't set errno, assume problem is no disk space */
2009 errno = save_errno ? save_errno : ENOSPC;
2012 (errcode_for_file_access(),
2013 errmsg("could not write to file \"%s\": %m", tmppath)));
2017 if (pg_fsync(fd) != 0)
2019 (errcode_for_file_access(),
2020 errmsg("could not fsync file \"%s\": %m", tmppath)));
2024 (errcode_for_file_access(),
2025 errmsg("could not close file \"%s\": %m", tmppath)));
2030 * Now move the segment into place with its final name.
2032 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2033 elog(ERROR, "InstallXLogFileSegment should not have failed");
2037 * Install a new XLOG segment file as a current or future log segment.
2039 * This is used both to install a newly-created segment (which has a temp
2040 * filename while it's being created) and to recycle an old segment.
2042 * *log, *seg: identify segment to install as (or first possible target).
2043 * When find_free is TRUE, these are modified on return to indicate the
2044 * actual installation location or last segment searched.
2046 * tmppath: initial name of file to install. It will be renamed into place.
2048 * find_free: if TRUE, install the new segment at the first empty log/seg
2049 * number at or after the passed numbers. If FALSE, install the new segment
2050 * exactly where specified, deleting any existing segment file there.
2052 * *max_advance: maximum number of log/seg slots to advance past the starting
2053 * point. Fail if no free slot is found in this range. On return, reduced
2054 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2055 * when find_free is FALSE.)
2057 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2058 * place. This should be TRUE except during bootstrap log creation. The
2059 * caller must *not* hold the lock at call.
2061 * Returns TRUE if file installed, FALSE if not installed because of
2062 * exceeding max_advance limit. On Windows, we also return FALSE if we
2063 * can't rename the file into place because someone's got it open.
2064 * (Any other kind of failure causes ereport().)
2067 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2068 bool find_free, int *max_advance,
2071 char path[MAXPGPATH];
2072 struct stat stat_buf;
2074 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2077 * We want to be sure that only one process does this at a time.
2080 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2084 /* Force installation: get rid of any pre-existing segment file */
2089 /* Find a free slot to put it in */
2090 while (stat(path, &stat_buf) == 0)
2092 if (*max_advance <= 0)
2094 /* Failed to find a free slot within specified range */
2096 LWLockRelease(ControlFileLock);
2099 NextLogSeg(*log, *seg);
2101 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2106 * Prefer link() to rename() here just to be really sure that we don't
2107 * overwrite an existing logfile. However, there shouldn't be one, so
2108 * rename() is an acceptable substitute except for the truly paranoid.
2110 #if HAVE_WORKING_LINK
2111 if (link(tmppath, path) < 0)
2113 (errcode_for_file_access(),
2114 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2115 tmppath, path, *log, *seg)));
2118 if (rename(tmppath, path) < 0)
2121 #if !defined(__CYGWIN__)
2122 if (GetLastError() == ERROR_ACCESS_DENIED)
2124 if (errno == EACCES)
2128 LWLockRelease(ControlFileLock);
2134 (errcode_for_file_access(),
2135 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2136 tmppath, path, *log, *seg)));
2141 LWLockRelease(ControlFileLock);
2147 * Open a pre-existing logfile segment for writing.
2150 XLogFileOpen(uint32 log, uint32 seg)
2152 char path[MAXPGPATH];
2155 XLogFilePath(path, ThisTimeLineID, log, seg);
2157 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2161 (errcode_for_file_access(),
2162 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2169 * Open a logfile segment for reading (during recovery).
2172 XLogFileRead(uint32 log, uint32 seg, int emode)
2174 char path[MAXPGPATH];
2175 char xlogfname[MAXFNAMELEN];
2180 * Loop looking for a suitable timeline ID: we might need to read any of
2181 * the timelines listed in expectedTLIs.
2183 * We expect curFileTLI on entry to be the TLI of the preceding file in
2184 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2185 * to go backwards; this prevents us from picking up the wrong file when a
2186 * parent timeline extends to higher segment numbers than the child we
2189 foreach(cell, expectedTLIs)
2191 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2193 if (tli < curFileTLI)
2194 break; /* don't bother looking at too-old TLIs */
2196 if (InArchiveRecovery)
2198 XLogFileName(xlogfname, tli, log, seg);
2199 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2204 XLogFilePath(path, tli, log, seg);
2206 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2213 if (errno != ENOENT) /* unexpected failure? */
2215 (errcode_for_file_access(),
2216 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2220 /* Couldn't find it. For simplicity, complain about front timeline */
2221 XLogFilePath(path, recoveryTargetTLI, log, seg);
2224 (errcode_for_file_access(),
2225 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2231 * Close the current logfile segment for writing.
2236 Assert(openLogFile >= 0);
2239 * posix_fadvise is problematic on many platforms: on older x86 Linux it
2240 * just dumps core, and there are reports of problems on PPC platforms as
2241 * well. The following is therefore disabled for the time being. We could
2242 * consider some kind of configure test to see if it's safe to use, but
2243 * since we lack hard evidence that there's any useful performance gain to
2244 * be had, spending time on that seems unprofitable for now.
2249 * WAL segment files will not be re-read in normal operation, so we advise
2250 * OS to release any cached pages. But do not do so if WAL archiving is
2251 * active, because archiver process could use the cache to read the WAL
2254 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
2255 * O_SYNC, and some platforms only have posix_fadvise().
2257 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2258 if (!XLogArchivingActive())
2259 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2261 #endif /* NOT_USED */
2263 if (close(openLogFile))
2265 (errcode_for_file_access(),
2266 errmsg("could not close log file %u, segment %u: %m",
2267 openLogId, openLogSeg)));
2272 * Attempt to retrieve the specified file from off-line archival storage.
2273 * If successful, fill "path" with its complete path (note that this will be
2274 * a temp file name that doesn't follow the normal naming convention), and
2277 * If not successful, fill "path" with the name of the normal on-line file
2278 * (which may or may not actually exist, but we'll try to use it), and return
2281 * For fixed-size files, the caller may pass the expected size as an
2282 * additional crosscheck on successful recovery. If the file size is not
2283 * known, set expectedSize = 0.
2286 RestoreArchivedFile(char *path, const char *xlogfname,
2287 const char *recovername, off_t expectedSize)
2289 char xlogpath[MAXPGPATH];
2290 char xlogRestoreCmd[MAXPGPATH];
2296 struct stat stat_buf;
2299 * When doing archive recovery, we always prefer an archived log file even
2300 * if a file of the same name exists in XLOGDIR. The reason is that the
2301 * file in XLOGDIR could be an old, un-filled or partly-filled version
2302 * that was copied and restored as part of backing up $PGDATA.
2304 * We could try to optimize this slightly by checking the local copy
2305 * lastchange timestamp against the archived copy, but we have no API to
2306 * do this, nor can we guarantee that the lastchange timestamp was
2307 * preserved correctly when we copied to archive. Our aim is robustness,
2308 * so we elect not to do this.
2310 * If we cannot obtain the log file from the archive, however, we will try
2311 * to use the XLOGDIR file if it exists. This is so that we can make use
2312 * of log segments that weren't yet transferred to the archive.
2314 * Notice that we don't actually overwrite any files when we copy back
2315 * from archive because the recoveryRestoreCommand may inadvertently
2316 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2317 * fallback to the segments remaining in current XLOGDIR later. The
2318 * copy-from-archive filename is always the same, ensuring that we don't
2319 * run out of disk space on long recoveries.
2321 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2324 * Make sure there is no existing file named recovername.
2326 if (stat(xlogpath, &stat_buf) != 0)
2328 if (errno != ENOENT)
2330 (errcode_for_file_access(),
2331 errmsg("could not stat file \"%s\": %m",
2336 if (unlink(xlogpath) != 0)
2338 (errcode_for_file_access(),
2339 errmsg("could not remove file \"%s\": %m",
2344 * construct the command to be executed
2346 dp = xlogRestoreCmd;
2347 endp = xlogRestoreCmd + MAXPGPATH - 1;
2350 for (sp = recoveryRestoreCommand; *sp; sp++)
2357 /* %p: relative path of target file */
2359 StrNCpy(dp, xlogpath, endp - dp);
2360 make_native_path(dp);
2364 /* %f: filename of desired file */
2366 StrNCpy(dp, xlogfname, endp - dp);
2370 /* convert %% to a single % */
2376 /* otherwise treat the % as not special */
2391 (errmsg_internal("executing restore command \"%s\"",
2395 * Copy xlog from archival storage to XLOGDIR
2397 rc = system(xlogRestoreCmd);
2401 * command apparently succeeded, but let's make sure the file is
2402 * really there now and has the correct size.
2404 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2405 * it, but is that too strong? We could try to plow ahead with a
2406 * local copy of the file ... but the problem is that there probably
2407 * isn't one, and we'd incorrectly conclude we've reached the end of
2408 * WAL and we're done recovering ...
2410 if (stat(xlogpath, &stat_buf) == 0)
2412 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2414 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2416 (unsigned long) stat_buf.st_size,
2417 (unsigned long) expectedSize)));
2421 (errmsg("restored log file \"%s\" from archive",
2423 strcpy(path, xlogpath);
2430 if (errno != ENOENT)
2432 (errcode_for_file_access(),
2433 errmsg("could not stat file \"%s\": %m",
2439 * Remember, we rollforward UNTIL the restore fails so failure here is
2440 * just part of the process... that makes it difficult to determine
2441 * whether the restore failed because there isn't an archive to restore,
2442 * or because the administrator has specified the restore program
2443 * incorrectly. We have to assume the former.
2445 * However, if the failure was due to any sort of signal, it's best to
2446 * punt and abort recovery. (If we "return false" here, upper levels
2447 * will assume that recovery is complete and start up the database!)
2448 * It's essential to abort on child SIGINT and SIGQUIT, because per spec
2449 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2450 * those it's a good bet we should have gotten it too. Aborting on other
2451 * signals such as SIGTERM seems a good idea as well.
2453 * Per the Single Unix Spec, shells report exit status > 128 when
2454 * a called command died on a signal. Also, 126 and 127 are used to
2455 * report problems such as an unfindable command; treat those as fatal
2458 signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;
2460 ereport(signaled ? FATAL : DEBUG2,
2461 (errmsg("could not restore file \"%s\" from archive: return code %d",
2465 * if an archived file is not available, there might still be a version of
2466 * this file in XLOGDIR, so return that as the filename to open.
2468 * In many recovery scenarios we expect this to fail also, but if so that
2469 * just means we've reached the end of WAL.
2471 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2476 * Preallocate log files beyond the specified log endpoint, according to
2477 * the XLOGfile user parameter.
2480 PreallocXlogFiles(XLogRecPtr endptr)
2488 XLByteToPrevSeg(endptr, _logId, _logSeg);
2489 if ((endptr.xrecoff - 1) % XLogSegSize >=
2490 (uint32) (0.75 * XLogSegSize))
2492 NextLogSeg(_logId, _logSeg);
2493 use_existent = true;
2494 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2503 * Remove or move offline all log files older or equal to passed log/seg#
2505 * endptr is current (or recent) end of xlog; this is used to determine
2506 * whether we want to recycle rather than delete no-longer-wanted log files.
2509 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
2510 int *nsegsremoved, int *nsegsrecycled)
2516 struct dirent *xlde;
2517 char lastoff[MAXFNAMELEN];
2518 char path[MAXPGPATH];
2524 * Initialize info about where to try to recycle to. We allow recycling
2525 * segments up to XLOGfileslop segments beyond the current XLOG location.
2527 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2528 max_advance = XLOGfileslop;
2530 xldir = AllocateDir(XLOGDIR);
2533 (errcode_for_file_access(),
2534 errmsg("could not open transaction log directory \"%s\": %m",
2537 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2539 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2542 * We ignore the timeline part of the XLOG segment identifiers in
2543 * deciding whether a segment is still needed. This ensures that we
2544 * won't prematurely remove a segment from a parent timeline. We could
2545 * probably be a little more proactive about removing segments of
2546 * non-parent timelines, but that would be a whole lot more
2549 * We use the alphanumeric sorting property of the filenames to decide
2550 * which ones are earlier than the lastoff segment.
2552 if (strlen(xlde->d_name) == 24 &&
2553 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2554 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2556 if (XLogArchiveCheckDone(xlde->d_name))
2558 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2561 * Before deleting the file, see if it can be recycled as a
2562 * future log segment.
2564 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2569 (errmsg("recycled transaction log file \"%s\"",
2572 /* Needn't recheck that slot on future iterations */
2573 if (max_advance > 0)
2575 NextLogSeg(endlogId, endlogSeg);
2581 /* No need for any more future segments... */
2583 (errmsg("removing transaction log file \"%s\"",
2589 XLogArchiveCleanup(xlde->d_name);
2598 * Remove previous backup history files. This also retries creation of
2599 * .ready files for any backup history files for which XLogArchiveNotify
2603 CleanupBackupHistory(void)
2606 struct dirent *xlde;
2607 char path[MAXPGPATH];
2609 xldir = AllocateDir(XLOGDIR);
2612 (errcode_for_file_access(),
2613 errmsg("could not open transaction log directory \"%s\": %m",
2616 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2618 if (strlen(xlde->d_name) > 24 &&
2619 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2620 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2623 if (XLogArchiveCheckDone(xlde->d_name))
2626 (errmsg("removing transaction log backup history file \"%s\"",
2628 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2630 XLogArchiveCleanup(xlde->d_name);
2639 * Restore the backup blocks present in an XLOG record, if any.
2641 * We assume all of the record has been read into memory at *record.
2643 * Note: when a backup block is available in XLOG, we restore it
2644 * unconditionally, even if the page in the database appears newer.
2645 * This is to protect ourselves against database pages that were partially
2646 * or incorrectly written during a crash. We assume that the XLOG data
2647 * must be good because it has passed a CRC check, while the database
2648 * page might not be. This will force us to replay all subsequent
2649 * modifications of the page that appear in XLOG, rather than possibly
2650 * ignoring them as already applied, but that's not a huge drawback.
2653 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2662 blk = (char *) XLogRecGetData(record) + record->xl_len;
2663 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2665 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2668 memcpy(&bkpb, blk, sizeof(BkpBlock));
2669 blk += sizeof(BkpBlock);
2671 reln = XLogOpenRelation(bkpb.node);
2672 buffer = XLogReadBuffer(reln, bkpb.block, true);
2673 Assert(BufferIsValid(buffer));
2674 page = (Page) BufferGetPage(buffer);
2676 if (bkpb.hole_length == 0)
2678 memcpy((char *) page, blk, BLCKSZ);
2682 /* must zero-fill the hole */
2683 MemSet((char *) page, 0, BLCKSZ);
2684 memcpy((char *) page, blk, bkpb.hole_offset);
2685 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2686 blk + bkpb.hole_offset,
2687 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2690 PageSetLSN(page, lsn);
2691 PageSetTLI(page, ThisTimeLineID);
2692 MarkBufferDirty(buffer);
2693 UnlockReleaseBuffer(buffer);
2695 blk += BLCKSZ - bkpb.hole_length;
2700 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2701 * record (other than to the minimal extent of computing the amount of
2702 * data to read in) until we've checked the CRCs.
2704 * We assume all of the record has been read into memory at *record.
2707 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2711 uint32 len = record->xl_len;
2715 /* First the rmgr data */
2717 COMP_CRC32(crc, XLogRecGetData(record), len);
2719 /* Add in the backup blocks, if any */
2720 blk = (char *) XLogRecGetData(record) + len;
2721 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2725 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2728 memcpy(&bkpb, blk, sizeof(BkpBlock));
2729 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2732 (errmsg("incorrect hole size in record at %X/%X",
2733 recptr.xlogid, recptr.xrecoff)));
2736 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2737 COMP_CRC32(crc, blk, blen);
2741 /* Check that xl_tot_len agrees with our calculation */
2742 if (blk != (char *) record + record->xl_tot_len)
2745 (errmsg("incorrect total length in record at %X/%X",
2746 recptr.xlogid, recptr.xrecoff)));
2750 /* Finally include the record header */
2751 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2752 SizeOfXLogRecord - sizeof(pg_crc32));
2755 if (!EQ_CRC32(record->xl_crc, crc))
2758 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2759 recptr.xlogid, recptr.xrecoff)));
2767 * Attempt to read an XLOG record.
2769 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2770 * try to read a record just after the last one previously read.
2772 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2773 * (emode must be either PANIC or LOG.)
2775 * The record is copied into readRecordBuf, so that on successful return,
2776 * the returned record pointer always points there.
2779 ReadRecord(XLogRecPtr *RecPtr, int emode)
2783 XLogRecPtr tmpRecPtr = EndRecPtr;
2784 bool randAccess = false;
2787 uint32 targetPageOff;
2788 uint32 targetRecOff;
2789 uint32 pageHeaderSize;
2791 if (readBuf == NULL)
2794 * First time through, permanently allocate readBuf. We do it this
2795 * way, rather than just making a static array, for two reasons: (1)
2796 * no need to waste the storage in most instantiations of the backend;
2797 * (2) a static char array isn't guaranteed to have any particular
2798 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2800 readBuf = (char *) malloc(XLOG_BLCKSZ);
2801 Assert(readBuf != NULL);
2806 RecPtr = &tmpRecPtr;
2807 /* fast case if next record is on same page */
2808 if (nextRecord != NULL)
2810 record = nextRecord;
2813 /* align old recptr to next page */
2814 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2815 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2816 if (tmpRecPtr.xrecoff >= XLogFileSize)
2818 (tmpRecPtr.xlogid)++;
2819 tmpRecPtr.xrecoff = 0;
2821 /* We will account for page header size below */
2825 if (!XRecOffIsValid(RecPtr->xrecoff))
2827 (errmsg("invalid record offset at %X/%X",
2828 RecPtr->xlogid, RecPtr->xrecoff)));
2831 * Since we are going to a random position in WAL, forget any prior
2832 * state about what timeline we were in, and allow it to be any
2833 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
2834 * to go backwards (but we can't reset that variable right here, since
2835 * we might not change files at all).
2837 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2838 randAccess = true; /* allow curFileTLI to go backwards too */
2841 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2846 XLByteToSeg(*RecPtr, readId, readSeg);
2849 /* Now it's okay to reset curFileTLI if random fetch */
2853 readFile = XLogFileRead(readId, readSeg, emode);
2855 goto next_record_is_invalid;
2858 * Whenever switching to a new WAL segment, we read the first page of
2859 * the file and validate its header, even if that's not where the
2860 * target record is. This is so that we can check the additional
2861 * identification info that is present in the first page's "long"
2865 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2868 (errcode_for_file_access(),
2869 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2870 readId, readSeg, readOff)));
2871 goto next_record_is_invalid;
2873 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2874 goto next_record_is_invalid;
2877 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2878 if (readOff != targetPageOff)
2880 readOff = targetPageOff;
2881 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2884 (errcode_for_file_access(),
2885 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2886 readId, readSeg, readOff)));
2887 goto next_record_is_invalid;
2889 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2892 (errcode_for_file_access(),
2893 errmsg("could not read from log file %u, segment %u at offset %u: %m",
2894 readId, readSeg, readOff)));
2895 goto next_record_is_invalid;
2897 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2898 goto next_record_is_invalid;
2900 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2901 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
2902 if (targetRecOff == 0)
2905 * Can only get here in the continuing-from-prev-page case, because
2906 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
2907 * to skip over the new page's header.
2909 tmpRecPtr.xrecoff += pageHeaderSize;
2910 targetRecOff = pageHeaderSize;
2912 else if (targetRecOff < pageHeaderSize)
2915 (errmsg("invalid record offset at %X/%X",
2916 RecPtr->xlogid, RecPtr->xrecoff)));
2917 goto next_record_is_invalid;
2919 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
2920 targetRecOff == pageHeaderSize)
2923 (errmsg("contrecord is requested by %X/%X",
2924 RecPtr->xlogid, RecPtr->xrecoff)));
2925 goto next_record_is_invalid;
2927 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
2932 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
2935 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
2937 if (record->xl_len != 0)
2940 (errmsg("invalid xlog switch record at %X/%X",
2941 RecPtr->xlogid, RecPtr->xrecoff)));
2942 goto next_record_is_invalid;
2945 else if (record->xl_len == 0)
2948 (errmsg("record with zero length at %X/%X",
2949 RecPtr->xlogid, RecPtr->xrecoff)));
2950 goto next_record_is_invalid;
2952 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
2953 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
2954 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
2957 (errmsg("invalid record length at %X/%X",
2958 RecPtr->xlogid, RecPtr->xrecoff)));
2959 goto next_record_is_invalid;
2961 if (record->xl_rmid > RM_MAX_ID)
2964 (errmsg("invalid resource manager ID %u at %X/%X",
2965 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
2966 goto next_record_is_invalid;
2971 * We can't exactly verify the prev-link, but surely it should be less
2972 * than the record's own address.
2974 if (!XLByteLT(record->xl_prev, *RecPtr))
2977 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
2978 record->xl_prev.xlogid, record->xl_prev.xrecoff,
2979 RecPtr->xlogid, RecPtr->xrecoff)));
2980 goto next_record_is_invalid;
2986 * Record's prev-link should exactly match our previous location. This
2987 * check guards against torn WAL pages where a stale but valid-looking
2988 * WAL record starts on a sector boundary.
2990 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
2993 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
2994 record->xl_prev.xlogid, record->xl_prev.xrecoff,
2995 RecPtr->xlogid, RecPtr->xrecoff)));
2996 goto next_record_is_invalid;
3001 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3002 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3003 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3004 * enough for all "normal" records, but very large commit or abort records
3005 * might need more space.)
3007 total_len = record->xl_tot_len;
3008 if (total_len > readRecordBufSize)
3010 uint32 newSize = total_len;
3012 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3013 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3015 free(readRecordBuf);
3016 readRecordBuf = (char *) malloc(newSize);
3019 readRecordBufSize = 0;
3020 /* We treat this as a "bogus data" condition */
3022 (errmsg("record length %u at %X/%X too long",
3023 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3024 goto next_record_is_invalid;
3026 readRecordBufSize = newSize;
3029 buffer = readRecordBuf;
3031 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3032 if (total_len > len)
3034 /* Need to reassemble record */
3035 XLogContRecord *contrecord;
3036 uint32 gotlen = len;
3038 memcpy(buffer, record, len);
3039 record = (XLogRecord *) buffer;
3043 readOff += XLOG_BLCKSZ;
3044 if (readOff >= XLogSegSize)
3048 NextLogSeg(readId, readSeg);
3049 readFile = XLogFileRead(readId, readSeg, emode);
3051 goto next_record_is_invalid;
3054 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3057 (errcode_for_file_access(),
3058 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3059 readId, readSeg, readOff)));
3060 goto next_record_is_invalid;
3062 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3063 goto next_record_is_invalid;
3064 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3067 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3068 readId, readSeg, readOff)));
3069 goto next_record_is_invalid;
3071 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3072 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3073 if (contrecord->xl_rem_len == 0 ||
3074 total_len != (contrecord->xl_rem_len + gotlen))
3077 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3078 contrecord->xl_rem_len,
3079 readId, readSeg, readOff)));
3080 goto next_record_is_invalid;
3082 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3083 if (contrecord->xl_rem_len > len)
3085 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3090 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3091 contrecord->xl_rem_len);
3094 if (!RecordIsValid(record, *RecPtr, emode))
3095 goto next_record_is_invalid;
3096 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3097 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3098 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3100 nextRecord = (XLogRecord *) ((char *) contrecord +
3101 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3103 EndRecPtr.xlogid = readId;
3104 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3106 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3107 ReadRecPtr = *RecPtr;
3108 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3112 /* Record does not cross a page boundary */
3113 if (!RecordIsValid(record, *RecPtr, emode))
3114 goto next_record_is_invalid;
3115 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3116 MAXALIGN(total_len))
3117 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3118 EndRecPtr.xlogid = RecPtr->xlogid;
3119 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3120 ReadRecPtr = *RecPtr;
3121 memcpy(buffer, record, total_len);
3124 * Special processing if it's an XLOG SWITCH record
3126 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3128 /* Pretend it extends to end of segment */
3129 EndRecPtr.xrecoff += XLogSegSize - 1;
3130 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3131 nextRecord = NULL; /* definitely not on same page */
3134 * Pretend that readBuf contains the last page of the segment. This is
3135 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3138 readOff = XLogSegSize - XLOG_BLCKSZ;
3140 return (XLogRecord *) buffer;
3142 next_record_is_invalid:;
3150 * Check whether the xlog header of a page just read in looks valid.
3152 * This is just a convenience subroutine to avoid duplicated code in
3153 * ReadRecord. It's not intended for use from anywhere else.
3156 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3160 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3163 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3164 hdr->xlp_magic, readId, readSeg, readOff)));
3167 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3170 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3171 hdr->xlp_info, readId, readSeg, readOff)));
3174 if (hdr->xlp_info & XLP_LONG_HEADER)
3176 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3178 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3180 char fhdrident_str[32];
3181 char sysident_str[32];
3184 * Format sysids separately to keep platform-dependent format code
3185 * out of the translatable message string.
3187 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3188 longhdr->xlp_sysid);
3189 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3190 ControlFile->system_identifier);
3192 (errmsg("WAL file is from different system"),
3193 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3194 fhdrident_str, sysident_str)));
3197 if (longhdr->xlp_seg_size != XLogSegSize)
3200 (errmsg("WAL file is from different system"),
3201 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3204 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3207 (errmsg("WAL file is from different system"),
3208 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3212 else if (readOff == 0)
3214 /* hmm, first page of file doesn't have a long header? */
3216 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3217 hdr->xlp_info, readId, readSeg, readOff)));
3221 recaddr.xlogid = readId;
3222 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3223 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3226 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3227 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3228 readId, readSeg, readOff)));
3233 * Check page TLI is one of the expected values.
3235 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3238 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3240 readId, readSeg, readOff)));
3245 * Since child timelines are always assigned a TLI greater than their
3246 * immediate parent's TLI, we should never see TLI go backwards across
3247 * successive pages of a consistent WAL sequence.
3249 * Of course this check should only be applied when advancing sequentially
3250 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3251 * going to a random page.
3253 if (hdr->xlp_tli < lastPageTLI)
3256 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3257 hdr->xlp_tli, lastPageTLI,
3258 readId, readSeg, readOff)));
3261 lastPageTLI = hdr->xlp_tli;
3266 * Try to read a timeline's history file.
3268 * If successful, return the list of component TLIs (the given TLI followed by
3269 * its ancestor TLIs). If we can't find the history file, assume that the
3270 * timeline has no parents, and return a list of just the specified timeline
3274 readTimeLineHistory(TimeLineID targetTLI)
3277 char path[MAXPGPATH];
3278 char histfname[MAXFNAMELEN];
3279 char fline[MAXPGPATH];
3282 if (InArchiveRecovery)
3284 TLHistoryFileName(histfname, targetTLI);
3285 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3288 TLHistoryFilePath(path, targetTLI);
3290 fd = AllocateFile(path, "r");
3293 if (errno != ENOENT)
3295 (errcode_for_file_access(),
3296 errmsg("could not open file \"%s\": %m", path)));
3297 /* Not there, so assume no parents */
3298 return list_make1_int((int) targetTLI);
3306 while (fgets(fline, sizeof(fline), fd) != NULL)
3308 /* skip leading whitespace and check for # comment */
3313 for (ptr = fline; *ptr; ptr++)
3315 if (!isspace((unsigned char) *ptr))
3318 if (*ptr == '\0' || *ptr == '#')
3321 /* expect a numeric timeline ID as first field of line */
3322 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3325 (errmsg("syntax error in history file: %s", fline),
3326 errhint("Expected a numeric timeline ID.")));
3329 tli <= (TimeLineID) linitial_int(result))
3331 (errmsg("invalid data in history file: %s", fline),
3332 errhint("Timeline IDs must be in increasing sequence.")));
3334 /* Build list with newest item first */
3335 result = lcons_int((int) tli, result);
3337 /* we ignore the remainder of each line */
3343 targetTLI <= (TimeLineID) linitial_int(result))
3345 (errmsg("invalid data in history file \"%s\"", path),
3346 errhint("Timeline IDs must be less than child timeline's ID.")));
3348 result = lcons_int((int) targetTLI, result);
3351 (errmsg_internal("history of timeline %u is %s",
3352 targetTLI, nodeToString(result))));
3358 * Probe whether a timeline history file exists for the given timeline ID
3361 existsTimeLineHistory(TimeLineID probeTLI)
3363 char path[MAXPGPATH];
3364 char histfname[MAXFNAMELEN];
3367 if (InArchiveRecovery)
3369 TLHistoryFileName(histfname, probeTLI);
3370 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3373 TLHistoryFilePath(path, probeTLI);
3375 fd = AllocateFile(path, "r");
3383 if (errno != ENOENT)
3385 (errcode_for_file_access(),
3386 errmsg("could not open file \"%s\": %m", path)));
3392 * Find the newest existing timeline, assuming that startTLI exists.
3394 * Note: while this is somewhat heuristic, it does positively guarantee
3395 * that (result + 1) is not a known timeline, and therefore it should
3396 * be safe to assign that ID to a new timeline.
3399 findNewestTimeLine(TimeLineID startTLI)
3401 TimeLineID newestTLI;
3402 TimeLineID probeTLI;
3405 * The algorithm is just to probe for the existence of timeline history
3406 * files. XXX is it useful to allow gaps in the sequence?
3408 newestTLI = startTLI;
3410 for (probeTLI = startTLI + 1;; probeTLI++)
3412 if (existsTimeLineHistory(probeTLI))
3414 newestTLI = probeTLI; /* probeTLI exists */
3418 /* doesn't exist, assume we're done */
3427 * Create a new timeline history file.
3429 * newTLI: ID of the new timeline
3430 * parentTLI: ID of its immediate parent
3431 * endTLI et al: ID of the last used WAL file, for annotation purposes
3433 * Currently this is only used during recovery, and so there are no locking
3434 * considerations. But we should be just as tense as XLogFileInit to avoid
3435 * emplacing a bogus file.
3438 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3439 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3441 char path[MAXPGPATH];
3442 char tmppath[MAXPGPATH];
3443 char histfname[MAXFNAMELEN];
3444 char xlogfname[MAXFNAMELEN];
3445 char buffer[BLCKSZ];
3450 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3453 * Write into a temp file name.
3455 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3459 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3460 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3464 (errcode_for_file_access(),
3465 errmsg("could not create file \"%s\": %m", tmppath)));
3468 * If a history file exists for the parent, copy it verbatim
3470 if (InArchiveRecovery)
3472 TLHistoryFileName(histfname, parentTLI);
3473 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3476 TLHistoryFilePath(path, parentTLI);
3478 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3481 if (errno != ENOENT)
3483 (errcode_for_file_access(),
3484 errmsg("could not open file \"%s\": %m", path)));
3485 /* Not there, so assume parent has no parents */
3492 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3493 if (nbytes < 0 || errno != 0)
3495 (errcode_for_file_access(),
3496 errmsg("could not read file \"%s\": %m", path)));
3500 if ((int) write(fd, buffer, nbytes) != nbytes)
3502 int save_errno = errno;
3505 * If we fail to make the file, delete it to release disk
3511 * if write didn't set errno, assume problem is no disk space
3513 errno = save_errno ? save_errno : ENOSPC;
3516 (errcode_for_file_access(),
3517 errmsg("could not write to file \"%s\": %m", tmppath)));
3524 * Append one line with the details of this timeline split.
3526 * If we did have a parent file, insert an extra newline just in case the
3527 * parent file failed to end with one.
3529 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3531 snprintf(buffer, sizeof(buffer),
3532 "%s%u\t%s\t%s transaction %u at %s\n",
3533 (srcfd < 0) ? "" : "\n",
3536 recoveryStopAfter ? "after" : "before",
3538 timestamptz_to_str(recoveryStopTime));
3540 nbytes = strlen(buffer);
3542 if ((int) write(fd, buffer, nbytes) != nbytes)
3544 int save_errno = errno;
3547 * If we fail to make the file, delete it to release disk space
3550 /* if write didn't set errno, assume problem is no disk space */
3551 errno = save_errno ? save_errno : ENOSPC;
3554 (errcode_for_file_access(),
3555 errmsg("could not write to file \"%s\": %m", tmppath)));
3558 if (pg_fsync(fd) != 0)
3560 (errcode_for_file_access(),
3561 errmsg("could not fsync file \"%s\": %m", tmppath)));
3565 (errcode_for_file_access(),
3566 errmsg("could not close file \"%s\": %m", tmppath)));
3570 * Now move the completed history file into place with its final name.
3572 TLHistoryFilePath(path, newTLI);
3575 * Prefer link() to rename() here just to be really sure that we don't
3576 * overwrite an existing logfile. However, there shouldn't be one, so
3577 * rename() is an acceptable substitute except for the truly paranoid.
3579 #if HAVE_WORKING_LINK
3580 if (link(tmppath, path) < 0)
3582 (errcode_for_file_access(),
3583 errmsg("could not link file \"%s\" to \"%s\": %m",
3587 if (rename(tmppath, path) < 0)
3589 (errcode_for_file_access(),
3590 errmsg("could not rename file \"%s\" to \"%s\": %m",
3594 /* The history file can be archived immediately. */
3595 TLHistoryFileName(histfname, newTLI);
3596 XLogArchiveNotify(histfname);
3600 * I/O routines for pg_control
3602 * *ControlFile is a buffer in shared memory that holds an image of the
3603 * contents of pg_control. WriteControlFile() initializes pg_control
3604 * given a preloaded buffer, ReadControlFile() loads the buffer from
3605 * the pg_control file (during postmaster or standalone-backend startup),
3606 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3608 * For simplicity, WriteControlFile() initializes the fields of pg_control
3609 * that are related to checking backend/database compatibility, and
3610 * ReadControlFile() verifies they are correct. We could split out the
3611 * I/O and compatibility-check functions, but there seems no need currently.
3614 WriteControlFile(void)
3617 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3621 * Initialize version and compatibility-check fields
3623 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3624 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3626 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3627 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3629 ControlFile->blcksz = BLCKSZ;
3630 ControlFile->relseg_size = RELSEG_SIZE;
3631 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3632 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3634 ControlFile->nameDataLen = NAMEDATALEN;
3635 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3637 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
3639 #ifdef HAVE_INT64_TIMESTAMP
3640 ControlFile->enableIntTimes = TRUE;
3642 ControlFile->enableIntTimes = FALSE;
3645 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3646 localeptr = setlocale(LC_COLLATE, NULL);
3649 (errmsg("invalid LC_COLLATE setting")));
3650 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3651 localeptr = setlocale(LC_CTYPE, NULL);
3654 (errmsg("invalid LC_CTYPE setting")));
3655 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3657 /* Contents are protected with a CRC */
3658 INIT_CRC32(ControlFile->crc);
3659 COMP_CRC32(ControlFile->crc,
3660 (char *) ControlFile,
3661 offsetof(ControlFileData, crc));
3662 FIN_CRC32(ControlFile->crc);
3665 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3666 * excess over sizeof(ControlFileData). This reduces the odds of
3667 * premature-EOF errors when reading pg_control. We'll still fail when we
3668 * check the contents of the file, but hopefully with a more specific
3669 * error than "couldn't read pg_control".
3671 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3672 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3674 memset(buffer, 0, PG_CONTROL_SIZE);
3675 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3677 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3678 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3682 (errcode_for_file_access(),
3683 errmsg("could not create control file \"%s\": %m",
3684 XLOG_CONTROL_FILE)));
3687 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3689 /* if write didn't set errno, assume problem is no disk space */
3693 (errcode_for_file_access(),
3694 errmsg("could not write to control file: %m")));
3697 if (pg_fsync(fd) != 0)
3699 (errcode_for_file_access(),
3700 errmsg("could not fsync control file: %m")));
3704 (errcode_for_file_access(),
3705 errmsg("could not close control file: %m")));
3709 ReadControlFile(void)
3717 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3722 (errcode_for_file_access(),
3723 errmsg("could not open control file \"%s\": %m",
3724 XLOG_CONTROL_FILE)));
3726 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3728 (errcode_for_file_access(),
3729 errmsg("could not read from control file: %m")));
3734 * Check for expected pg_control format version. If this is wrong, the
3735 * CRC check will likely fail because we'll be checking the wrong number
3736 * of bytes. Complaining about wrong version will probably be more
3737 * enlightening than complaining about wrong CRC.
3739 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3741 (errmsg("database files are incompatible with server"),
3742 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3743 " but the server was compiled with PG_CONTROL_VERSION %d.",
3744 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3745 errhint("It looks like you need to initdb.")));
3746 /* Now check the CRC. */
3749 (char *) ControlFile,
3750 offsetof(ControlFileData, crc));
3753 if (!EQ_CRC32(crc, ControlFile->crc))
3755 (errmsg("incorrect checksum in control file")));
3758 * Do compatibility checking immediately. We do this here for 2 reasons:
3760 * (1) if the database isn't compatible with the backend executable, we
3761 * want to abort before we can possibly do any damage;
3763 * (2) this code is executed in the postmaster, so the setlocale() will
3764 * propagate to forked backends, which aren't going to read this file for
3765 * themselves. (These locale settings are considered critical
3766 * compatibility items because they can affect sort order of indexes.)
3768 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3770 (errmsg("database files are incompatible with server"),
3771 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3772 " but the server was compiled with CATALOG_VERSION_NO %d.",
3773 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3774 errhint("It looks like you need to initdb.")));
3775 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3777 (errmsg("database files are incompatible with server"),
3778 errdetail("The database cluster was initialized with MAXALIGN %d,"
3779 " but the server was compiled with MAXALIGN %d.",
3780 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3781 errhint("It looks like you need to initdb.")));
3782 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3784 (errmsg("database files are incompatible with server"),
3785 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3786 errhint("It looks like you need to initdb.")));
3787 if (ControlFile->blcksz != BLCKSZ)
3789 (errmsg("database files are incompatible with server"),
3790 errdetail("The database cluster was initialized with BLCKSZ %d,"
3791 " but the server was compiled with BLCKSZ %d.",
3792 ControlFile->blcksz, BLCKSZ),
3793 errhint("It looks like you need to recompile or initdb.")));
3794 if (ControlFile->relseg_size != RELSEG_SIZE)
3796 (errmsg("database files are incompatible with server"),
3797 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3798 " but the server was compiled with RELSEG_SIZE %d.",
3799 ControlFile->relseg_size, RELSEG_SIZE),
3800 errhint("It looks like you need to recompile or initdb.")));
3801 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3803 (errmsg("database files are incompatible with server"),
3804 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3805 " but the server was compiled with XLOG_BLCKSZ %d.",
3806 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3807 errhint("It looks like you need to recompile or initdb.")));
3808 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3810 (errmsg("database files are incompatible with server"),
3811 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3812 " but the server was compiled with XLOG_SEG_SIZE %d.",
3813 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3814 errhint("It looks like you need to recompile or initdb.")));
3815 if (ControlFile->nameDataLen != NAMEDATALEN)
3817 (errmsg("database files are incompatible with server"),
3818 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3819 " but the server was compiled with NAMEDATALEN %d.",
3820 ControlFile->nameDataLen, NAMEDATALEN),
3821 errhint("It looks like you need to recompile or initdb.")));
3822 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3824 (errmsg("database files are incompatible with server"),
3825 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3826 " but the server was compiled with INDEX_MAX_KEYS %d.",
3827 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3828 errhint("It looks like you need to recompile or initdb.")));
3829 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
3831 (errmsg("database files are incompatible with server"),
3832 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
3833 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
3834 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
3835 errhint("It looks like you need to recompile or initdb.")));
3837 #ifdef HAVE_INT64_TIMESTAMP
3838 if (ControlFile->enableIntTimes != TRUE)
3840 (errmsg("database files are incompatible with server"),
3841 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3842 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3843 errhint("It looks like you need to recompile or initdb.")));
3845 if (ControlFile->enableIntTimes != FALSE)
3847 (errmsg("database files are incompatible with server"),
3848 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3849 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3850 errhint("It looks like you need to recompile or initdb.")));
3853 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3855 (errmsg("database files are incompatible with server"),
3856 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3857 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3858 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3859 errhint("It looks like you need to recompile or initdb.")));
3860 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3862 (errmsg("database files are incompatible with operating system"),
3863 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3864 " which is not recognized by setlocale().",
3865 ControlFile->lc_collate),
3866 errhint("It looks like you need to initdb or install locale support.")));
3867 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3869 (errmsg("database files are incompatible with operating system"),
3870 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3871 " which is not recognized by setlocale().",
3872 ControlFile->lc_ctype),
3873 errhint("It looks like you need to initdb or install locale support.")));
3875 /* Make the fixed locale settings visible as GUC variables, too */
3876 SetConfigOption("lc_collate", ControlFile->lc_collate,
3877 PGC_INTERNAL, PGC_S_OVERRIDE);
3878 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3879 PGC_INTERNAL, PGC_S_OVERRIDE);
3883 UpdateControlFile(void)
3887 INIT_CRC32(ControlFile->crc);
3888 COMP_CRC32(ControlFile->crc,
3889 (char *) ControlFile,
3890 offsetof(ControlFileData, crc));
3891 FIN_CRC32(ControlFile->crc);
3893 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3898 (errcode_for_file_access(),
3899 errmsg("could not open control file \"%s\": %m",
3900 XLOG_CONTROL_FILE)));
3903 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3905 /* if write didn't set errno, assume problem is no disk space */
3909 (errcode_for_file_access(),
3910 errmsg("could not write to control file: %m")));
3913 if (pg_fsync(fd) != 0)
3915 (errcode_for_file_access(),
3916 errmsg("could not fsync control file: %m")));
3920 (errcode_for_file_access(),
3921 errmsg("could not close control file: %m")));
3925 * Initialization of shared memory for XLOG
3933 size = sizeof(XLogCtlData);
3934 /* xlblocks array */
3935 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
3936 /* extra alignment padding for XLOG I/O buffers */
3937 size = add_size(size, ALIGNOF_XLOG_BUFFER);
3938 /* and the buffers themselves */
3939 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
3942 * Note: we don't count ControlFileData, it comes out of the "slop factor"
3943 * added by CreateSharedMemoryAndSemaphores. This lets us use this
3944 * routine again below to compute the actual allocation size.
3957 ControlFile = (ControlFileData *)
3958 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
3959 XLogCtl = (XLogCtlData *)
3960 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
3962 if (foundCFile || foundXLog)
3964 /* both should be present or neither */
3965 Assert(foundCFile && foundXLog);
3969 memset(XLogCtl, 0, sizeof(XLogCtlData));
3972 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
3973 * multiple of the alignment for same, so no extra alignment padding is
3976 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
3977 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
3978 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
3979 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
3982 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
3984 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
3985 XLogCtl->pages = allocptr;
3986 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
3989 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
3990 * in additional info.)
3992 XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
3994 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
3995 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
3996 SpinLockInit(&XLogCtl->info_lck);
3999 * If we are not in bootstrap mode, pg_control should already exist. Read
4000 * and validate it immediately (see comments in ReadControlFile() for the
4003 if (!IsBootstrapProcessingMode())
4008 * This func must be called ONCE on system install. It creates pg_control
4009 * and the initial XLOG segment.
4014 CheckPoint checkPoint;
4016 XLogPageHeader page;
4017 XLogLongPageHeader longpage;
4020 uint64 sysidentifier;
4025 * Select a hopefully-unique system identifier code for this installation.
4026 * We use the result of gettimeofday(), including the fractional seconds
4027 * field, as being about as unique as we can easily get. (Think not to
4028 * use random(), since it hasn't been seeded and there's no portable way
4029 * to seed it other than the system clock value...) The upper half of the
4030 * uint64 value is just the tv_sec part, while the lower half is the XOR
4031 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4032 * unnecessarily if "uint64" is really only 32 bits wide. A person
4033 * knowing this encoding can determine the initialization time of the
4034 * installation, which could perhaps be useful sometimes.
4036 gettimeofday(&tv, NULL);
4037 sysidentifier = ((uint64) tv.tv_sec) << 32;
4038 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4040 /* First timeline ID is always 1 */
4043 /* page buffer must be aligned suitably for O_DIRECT */
4044 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4045 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4046 memset(page, 0, XLOG_BLCKSZ);
4048 /* Set up information for the initial checkpoint record */
4049 checkPoint.redo.xlogid = 0;
4050 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4051 checkPoint.ThisTimeLineID = ThisTimeLineID;
4052 checkPoint.nextXidEpoch = 0;
4053 checkPoint.nextXid = FirstNormalTransactionId;
4054 checkPoint.nextOid = FirstBootstrapObjectId;
4055 checkPoint.nextMulti = FirstMultiXactId;
4056 checkPoint.nextMultiOffset = 0;
4057 checkPoint.time = time(NULL);
4059 ShmemVariableCache->nextXid = checkPoint.nextXid;
4060 ShmemVariableCache->nextOid = checkPoint.nextOid;
4061 ShmemVariableCache->oidCount = 0;
4062 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4064 /* Set up the XLOG page header */
4065 page->xlp_magic = XLOG_PAGE_MAGIC;
4066 page->xlp_info = XLP_LONG_HEADER;
4067 page->xlp_tli = ThisTimeLineID;
4068 page->xlp_pageaddr.xlogid = 0;
4069 page->xlp_pageaddr.xrecoff = 0;
4070 longpage = (XLogLongPageHeader) page;
4071 longpage->xlp_sysid = sysidentifier;
4072 longpage->xlp_seg_size = XLogSegSize;
4073 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4075 /* Insert the initial checkpoint record */
4076 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4077 record->xl_prev.xlogid = 0;
4078 record->xl_prev.xrecoff = 0;
4079 record->xl_xid = InvalidTransactionId;
4080 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4081 record->xl_len = sizeof(checkPoint);
4082 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4083 record->xl_rmid = RM_XLOG_ID;
4084 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4087 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4088 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4089 SizeOfXLogRecord - sizeof(pg_crc32));
4091 record->xl_crc = crc;
4093 /* Create first XLOG segment file */
4094 use_existent = false;
4095 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4097 /* Write the first page with the initial record */
4099 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4101 /* if write didn't set errno, assume problem is no disk space */
4105 (errcode_for_file_access(),
4106 errmsg("could not write bootstrap transaction log file: %m")));
4109 if (pg_fsync(openLogFile) != 0)
4111 (errcode_for_file_access(),
4112 errmsg("could not fsync bootstrap transaction log file: %m")));
4114 if (close(openLogFile))
4116 (errcode_for_file_access(),
4117 errmsg("could not close bootstrap transaction log file: %m")));
4121 /* Now create pg_control */
4123 memset(ControlFile, 0, sizeof(ControlFileData));
4124 /* Initialize pg_control status fields */
4125 ControlFile->system_identifier = sysidentifier;
4126 ControlFile->state = DB_SHUTDOWNED;
4127 ControlFile->time = checkPoint.time;
4128 ControlFile->checkPoint = checkPoint.redo;
4129 ControlFile->checkPointCopy = checkPoint;
4130 /* some additional ControlFile fields are set in WriteControlFile() */
4134 /* Bootstrap the commit log, too */
4136 BootStrapSUBTRANS();
4137 BootStrapMultiXact();
4143 str_time(time_t tnow)
4145 static char buf[128];
4147 strftime(buf, sizeof(buf),
4148 "%Y-%m-%d %H:%M:%S %Z",
4155 * See if there is a recovery command file (recovery.conf), and if so
4156 * read in parameters for archive recovery.
4158 * XXX longer term intention is to expand this to
4159 * cater for additional parameters and controls
4160 * possibly use a flex lexer similar to the GUC one
4163 readRecoveryCommandFile(void)
4166 char cmdline[MAXPGPATH];
4167 TimeLineID rtli = 0;
4168 bool rtliGiven = false;
4169 bool syntaxError = false;
4171 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4174 if (errno == ENOENT)
4175 return; /* not there, so no archive recovery */
4177 (errcode_for_file_access(),
4178 errmsg("could not open recovery command file \"%s\": %m",
4179 RECOVERY_COMMAND_FILE)));
4183 (errmsg("starting archive recovery")));
4188 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4190 /* skip leading whitespace and check for # comment */
4195 for (ptr = cmdline; *ptr; ptr++)
4197 if (!isspace((unsigned char) *ptr))
4200 if (*ptr == '\0' || *ptr == '#')
4203 /* identify the quoted parameter value */
4204 tok1 = strtok(ptr, "'");
4210 tok2 = strtok(NULL, "'");
4216 /* reparse to get just the parameter name */
4217 tok1 = strtok(ptr, " \t=");
4224 if (strcmp(tok1, "restore_command") == 0)
4226 recoveryRestoreCommand = pstrdup(tok2);
4228 (errmsg("restore_command = \"%s\"",
4229 recoveryRestoreCommand)));
4231 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4234 if (strcmp(tok2, "latest") == 0)
4239 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4240 if (errno == EINVAL || errno == ERANGE)
4242 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4247 (errmsg("recovery_target_timeline = %u", rtli)));
4250 (errmsg("recovery_target_timeline = latest")));
4252 else if (strcmp(tok1, "recovery_target_xid") == 0)
4255 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4256 if (errno == EINVAL || errno == ERANGE)
4258 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4261 (errmsg("recovery_target_xid = %u",
4262 recoveryTargetXid)));
4263 recoveryTarget = true;
4264 recoveryTargetExact = true;
4266 else if (strcmp(tok1, "recovery_target_time") == 0)
4269 * if recovery_target_xid specified, then this overrides
4270 * recovery_target_time
4272 if (recoveryTargetExact)
4274 recoveryTarget = true;
4275 recoveryTargetExact = false;
4278 * Convert the time string given by the user to TimestampTz form.
4280 recoveryTargetTime =
4281 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
4282 CStringGetDatum(tok2),
4283 ObjectIdGetDatum(InvalidOid),
4284 Int32GetDatum(-1)));
4286 (errmsg("recovery_target_time = %s",
4287 timestamptz_to_str(recoveryTargetTime))));
4289 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4292 * does nothing if a recovery_target is not also set
4294 if (strcmp(tok2, "true") == 0)
4295 recoveryTargetInclusive = true;
4298 recoveryTargetInclusive = false;
4302 (errmsg("recovery_target_inclusive = %s", tok2)));
4306 (errmsg("unrecognized recovery parameter \"%s\"",
4314 (errmsg("syntax error in recovery command file: %s",
4316 errhint("Lines should have the format parameter = 'value'.")));
4318 /* Check that required parameters were supplied */
4319 if (recoveryRestoreCommand == NULL)
4321 (errmsg("recovery command file \"%s\" did not specify restore_command",
4322 RECOVERY_COMMAND_FILE)));
4324 /* Enable fetching from archive recovery area */
4325 InArchiveRecovery = true;
4328 * If user specified recovery_target_timeline, validate it or compute the
4329 * "latest" value. We can't do this until after we've gotten the restore
4330 * command and set InArchiveRecovery, because we need to fetch timeline
4331 * history files from the archive.
4337 /* Timeline 1 does not have a history file, all else should */
4338 if (rtli != 1 && !existsTimeLineHistory(rtli))
4340 (errmsg("recovery_target_timeline %u does not exist",
4342 recoveryTargetTLI = rtli;
4346 /* We start the "latest" search from pg_control's timeline */
4347 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4353 * Exit archive-recovery state
4356 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4358 char recoveryPath[MAXPGPATH];
4359 char xlogpath[MAXPGPATH];
4362 * We are no longer in archive recovery state.
4364 InArchiveRecovery = false;
4367 * We should have the ending log segment currently open. Verify, and then
4368 * close it (to avoid problems on Windows with trying to rename or delete
4371 Assert(readFile >= 0);
4372 Assert(readId == endLogId);
4373 Assert(readSeg == endLogSeg);
4379 * If the segment was fetched from archival storage, we want to replace
4380 * the existing xlog segment (if any) with the archival version. This is
4381 * because whatever is in XLOGDIR is very possibly older than what we have
4382 * from the archives, since it could have come from restoring a PGDATA
4383 * backup. In any case, the archival version certainly is more
4384 * descriptive of what our current database state is, because that is what
4387 * Note that if we are establishing a new timeline, ThisTimeLineID is
4388 * already set to the new value, and so we will create a new file instead
4389 * of overwriting any existing file.
4391 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4392 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4394 if (restoredFromArchive)
4397 (errmsg_internal("moving last restored xlog to \"%s\"",
4399 unlink(xlogpath); /* might or might not exist */
4400 if (rename(recoveryPath, xlogpath) != 0)
4402 (errcode_for_file_access(),
4403 errmsg("could not rename file \"%s\" to \"%s\": %m",
4404 recoveryPath, xlogpath)));
4405 /* XXX might we need to fix permissions on the file? */
4410 * If the latest segment is not archival, but there's still a
4411 * RECOVERYXLOG laying about, get rid of it.
4413 unlink(recoveryPath); /* ignore any error */
4416 * If we are establishing a new timeline, we have to copy data from
4417 * the last WAL segment of the old timeline to create a starting WAL
4418 * segment for the new timeline.
4420 if (endTLI != ThisTimeLineID)
4421 XLogFileCopy(endLogId, endLogSeg,
4422 endTLI, endLogId, endLogSeg);
4426 * Let's just make real sure there are not .ready or .done flags posted
4427 * for the new segment.
4429 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4430 XLogArchiveCleanup(xlogpath);
4432 /* Get rid of any remaining recovered timeline-history file, too */
4433 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4434 unlink(recoveryPath); /* ignore any error */
4437 * Rename the config file out of the way, so that we don't accidentally
4438 * re-enter archive recovery mode in a subsequent crash.
4440 unlink(RECOVERY_COMMAND_DONE);
4441 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4443 (errcode_for_file_access(),
4444 errmsg("could not rename file \"%s\" to \"%s\": %m",
4445 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4448 (errmsg("archive recovery complete")));
4452 * For point-in-time recovery, this function decides whether we want to
4453 * stop applying the XLOG at or after the current record.
4455 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4456 * *includeThis is set TRUE if we should apply this record before stopping.
4457 * Also, some information is saved in recoveryStopXid et al for use in
4458 * annotating the new timeline's history file.
4461 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4465 TimestampTz recordXtime;
4467 /* Do we have a PITR target at all? */
4468 if (!recoveryTarget)
4471 /* We only consider stopping at COMMIT or ABORT records */
4472 if (record->xl_rmid != RM_XACT_ID)
4474 record_info = record->xl_info & ~XLR_INFO_MASK;
4475 if (record_info == XLOG_XACT_COMMIT)
4477 xl_xact_commit *recordXactCommitData;
4479 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4480 recordXtime = recordXactCommitData->xact_time;
4482 else if (record_info == XLOG_XACT_ABORT)
4484 xl_xact_abort *recordXactAbortData;
4486 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4487 recordXtime = recordXactAbortData->xact_time;
4492 if (recoveryTargetExact)
4495 * there can be only one transaction end record with this exact
4498 * when testing for an xid, we MUST test for equality only, since
4499 * transactions are numbered in the order they start, not the order
4500 * they complete. A higher numbered xid will complete before you about
4501 * 50% of the time...
4503 stopsHere = (record->xl_xid == recoveryTargetXid);
4505 *includeThis = recoveryTargetInclusive;
4510 * there can be many transactions that share the same commit time, so
4511 * we stop after the last one, if we are inclusive, or stop at the
4512 * first one if we are exclusive
4514 if (recoveryTargetInclusive)
4515 stopsHere = (recordXtime > recoveryTargetTime);
4517 stopsHere = (recordXtime >= recoveryTargetTime);
4519 *includeThis = false;
4524 recoveryStopXid = record->xl_xid;
4525 recoveryStopTime = recordXtime;
4526 recoveryStopAfter = *includeThis;
4528 if (record_info == XLOG_XACT_COMMIT)
4530 if (recoveryStopAfter)
4532 (errmsg("recovery stopping after commit of transaction %u, time %s",
4534 timestamptz_to_str(recoveryStopTime))));
4537 (errmsg("recovery stopping before commit of transaction %u, time %s",
4539 timestamptz_to_str(recoveryStopTime))));
4543 if (recoveryStopAfter)
4545 (errmsg("recovery stopping after abort of transaction %u, time %s",
4547 timestamptz_to_str(recoveryStopTime))));
4550 (errmsg("recovery stopping before abort of transaction %u, time %s",
4552 timestamptz_to_str(recoveryStopTime))));
4560 * This must be called ONCE during postmaster or standalone-backend startup
4565 XLogCtlInsert *Insert;
4566 CheckPoint checkPoint;
4568 bool needNewTimeLine = false;
4569 bool haveBackupLabel = false;
4579 TransactionId oldestActiveXID;
4582 * Read control file and check XLOG status looks valid.
4584 * Note: in most control paths, *ControlFile is already valid and we need
4585 * not do ReadControlFile() here, but might as well do it to be sure.
4589 if (ControlFile->state < DB_SHUTDOWNED ||
4590 ControlFile->state > DB_IN_PRODUCTION ||
4591 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4593 (errmsg("control file contains invalid data")));
4595 if (ControlFile->state == DB_SHUTDOWNED)
4597 (errmsg("database system was shut down at %s",
4598 str_time(ControlFile->time))));
4599 else if (ControlFile->state == DB_SHUTDOWNING)
4601 (errmsg("database system shutdown was interrupted; last known up at %s",
4602 str_time(ControlFile->time))));
4603 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4605 (errmsg("database system was interrupted while in recovery at %s",
4606 str_time(ControlFile->time)),
4607 errhint("This probably means that some data is corrupted and"
4608 " you will have to use the last backup for recovery.")));
4609 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4611 (errmsg("database system was interrupted while in recovery at log time %s",
4612 str_time(ControlFile->checkPointCopy.time)),
4613 errhint("If this has occurred more than once some data might be corrupted"
4614 " and you might need to choose an earlier recovery target.")));
4615 else if (ControlFile->state == DB_IN_PRODUCTION)
4617 (errmsg("database system was interrupted; last known up at %s",
4618 str_time(ControlFile->time))));
4620 /* This is just to allow attaching to startup process with a debugger */
4621 #ifdef XLOG_REPLAY_DELAY
4622 if (ControlFile->state != DB_SHUTDOWNED)
4623 pg_usleep(60000000L);
4627 * Initialize on the assumption we want to recover to the same timeline
4628 * that's active according to pg_control.
4630 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4633 * Check for recovery control file, and if so set up state for offline
4636 readRecoveryCommandFile();
4638 /* Now we can determine the list of expected TLIs */
4639 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4642 * If pg_control's timeline is not in expectedTLIs, then we cannot
4643 * proceed: the backup is not part of the history of the requested
4646 if (!list_member_int(expectedTLIs,
4647 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4649 (errmsg("requested timeline %u is not a child of database system timeline %u",
4651 ControlFile->checkPointCopy.ThisTimeLineID)));
4653 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4656 * When a backup_label file is present, we want to roll forward from
4657 * the checkpoint it identifies, rather than using pg_control.
4659 record = ReadCheckpointRecord(checkPointLoc, 0);
4663 (errmsg("checkpoint record is at %X/%X",
4664 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4665 InRecovery = true; /* force recovery even if SHUTDOWNED */
4670 (errmsg("could not locate required checkpoint record"),
4671 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4673 /* set flag to delete it later */
4674 haveBackupLabel = true;
4679 * Get the last valid checkpoint record. If the latest one according
4680 * to pg_control is broken, try the next-to-last one.
4682 checkPointLoc = ControlFile->checkPoint;
4683 record = ReadCheckpointRecord(checkPointLoc, 1);
4687 (errmsg("checkpoint record is at %X/%X",
4688 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4692 checkPointLoc = ControlFile->prevCheckPoint;
4693 record = ReadCheckpointRecord(checkPointLoc, 2);
4697 (errmsg("using previous checkpoint record at %X/%X",
4698 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4699 InRecovery = true; /* force recovery even if SHUTDOWNED */
4703 (errmsg("could not locate a valid checkpoint record")));
4707 LastRec = RecPtr = checkPointLoc;
4708 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4709 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4712 (errmsg("redo record is at %X/%X; shutdown %s",
4713 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4714 wasShutdown ? "TRUE" : "FALSE")));
4716 (errmsg("next transaction ID: %u/%u; next OID: %u",
4717 checkPoint.nextXidEpoch, checkPoint.nextXid,
4718 checkPoint.nextOid)));
4720 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4721 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4722 if (!TransactionIdIsNormal(checkPoint.nextXid))
4724 (errmsg("invalid next transaction ID")));
4726 ShmemVariableCache->nextXid = checkPoint.nextXid;
4727 ShmemVariableCache->nextOid = checkPoint.nextOid;
4728 ShmemVariableCache->oidCount = 0;
4729 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4732 * We must replay WAL entries using the same TimeLineID they were created
4733 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4734 * also xlog_redo()).
4736 ThisTimeLineID = checkPoint.ThisTimeLineID;
4738 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4740 if (XLByteLT(RecPtr, checkPoint.redo))
4742 (errmsg("invalid redo in checkpoint record")));
4745 * Check whether we need to force recovery from WAL. If it appears to
4746 * have been a clean shutdown and we did not have a recovery.conf file,
4747 * then assume no recovery needed.
4749 if (XLByteLT(checkPoint.redo, RecPtr))
4753 (errmsg("invalid redo record in shutdown checkpoint")));
4756 else if (ControlFile->state != DB_SHUTDOWNED)
4758 else if (InArchiveRecovery)
4760 /* force recovery due to presence of recovery.conf */
4770 * Update pg_control to show that we are recovering and to show the
4771 * selected checkpoint as the place we are starting from. We also mark
4772 * pg_control with any minimum recovery stop point obtained from a
4773 * backup history file.
4775 if (InArchiveRecovery)
4778 (errmsg("automatic recovery in progress")));
4779 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4784 (errmsg("database system was not properly shut down; "
4785 "automatic recovery in progress")));
4786 ControlFile->state = DB_IN_CRASH_RECOVERY;
4788 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4789 ControlFile->checkPoint = checkPointLoc;
4790 ControlFile->checkPointCopy = checkPoint;
4791 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4792 ControlFile->minRecoveryPoint = minRecoveryLoc;
4793 ControlFile->time = time(NULL);
4794 UpdateControlFile();
4797 * If there was a backup label file, it's done its job and the info
4798 * has now been propagated into pg_control. We must get rid of the
4799 * label file so that if we crash during recovery, we'll pick up at
4800 * the latest recovery restartpoint instead of going all the way back
4801 * to the backup start point. It seems prudent though to just rename
4802 * the file out of the way rather than delete it completely.
4804 if (haveBackupLabel)
4806 unlink(BACKUP_LABEL_OLD);
4807 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4809 (errcode_for_file_access(),
4810 errmsg("could not rename file \"%s\" to \"%s\": %m",
4811 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4814 /* Start up the recovery environment */
4815 XLogInitRelationCache();
4817 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4819 if (RmgrTable[rmid].rm_startup != NULL)
4820 RmgrTable[rmid].rm_startup();
4824 * Find the first record that logically follows the checkpoint --- it
4825 * might physically precede it, though.
4827 if (XLByteLT(checkPoint.redo, RecPtr))
4829 /* back up to find the record */
4830 record = ReadRecord(&(checkPoint.redo), PANIC);
4834 /* just have to read next record after CheckPoint */
4835 record = ReadRecord(NULL, LOG);
4840 bool recoveryContinue = true;
4841 bool recoveryApply = true;
4842 ErrorContextCallback errcontext;
4846 (errmsg("redo starts at %X/%X",
4847 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4850 * main redo apply loop
4859 initStringInfo(&buf);
4860 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4861 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4862 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4863 xlog_outrec(&buf, record);
4864 appendStringInfo(&buf, " - ");
4865 RmgrTable[record->xl_rmid].rm_desc(&buf,
4867 XLogRecGetData(record));
4868 elog(LOG, "%s", buf.data);
4874 * Have we reached our recovery target?
4876 if (recoveryStopsHere(record, &recoveryApply))
4878 needNewTimeLine = true; /* see below */
4879 recoveryContinue = false;
4884 /* Setup error traceback support for ereport() */
4885 errcontext.callback = rm_redo_error_callback;
4886 errcontext.arg = (void *) record;
4887 errcontext.previous = error_context_stack;
4888 error_context_stack = &errcontext;
4890 /* nextXid must be beyond record's xid */
4891 if (TransactionIdFollowsOrEquals(record->xl_xid,
4892 ShmemVariableCache->nextXid))
4894 ShmemVariableCache->nextXid = record->xl_xid;
4895 TransactionIdAdvance(ShmemVariableCache->nextXid);
4898 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4899 RestoreBkpBlocks(record, EndRecPtr);
4901 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4903 /* Pop the error context stack */
4904 error_context_stack = errcontext.previous;
4906 LastRec = ReadRecPtr;
4908 record = ReadRecord(NULL, LOG);
4909 } while (record != NULL && recoveryContinue);
4912 * end of main redo apply loop
4916 (errmsg("redo done at %X/%X",
4917 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4922 /* there are no WAL records following the checkpoint */
4924 (errmsg("redo is not required")));
4929 * Re-fetch the last valid or last applied record, so we can identify the
4930 * exact endpoint of what we consider the valid portion of WAL.
4932 record = ReadRecord(&LastRec, PANIC);
4933 EndOfLog = EndRecPtr;
4934 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4937 * Complain if we did not roll forward far enough to render the backup
4940 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
4942 if (needNewTimeLine) /* stopped because of stop request */
4944 (errmsg("requested recovery stop point is before end time of backup dump")));
4946 /* ran off end of WAL */
4948 (errmsg("WAL ends before end time of backup dump")));
4952 * Consider whether we need to assign a new timeline ID.
4954 * If we stopped short of the end of WAL during recovery, then we are
4955 * generating a new timeline and must assign it a unique new ID.
4956 * Otherwise, we can just extend the timeline we were in when we ran out
4959 if (needNewTimeLine)
4961 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
4963 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
4964 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
4965 curFileTLI, endLogId, endLogSeg);
4968 /* Save the selected TimeLineID in shared memory, too */
4969 XLogCtl->ThisTimeLineID = ThisTimeLineID;
4972 * We are now done reading the old WAL. Turn off archive fetching if it
4973 * was active, and make a writable copy of the last WAL segment. (Note
4974 * that we also have a copy of the last block of the old WAL in readBuf;
4975 * we will use that below.)
4977 if (InArchiveRecovery)
4978 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
4981 * Prepare to write WAL starting at EndOfLog position, and init xlog
4982 * buffer cache using the block containing the last record from the
4983 * previous incarnation.
4985 openLogId = endLogId;
4986 openLogSeg = endLogSeg;
4987 openLogFile = XLogFileOpen(openLogId, openLogSeg);
4989 Insert = &XLogCtl->Insert;
4990 Insert->PrevRecord = LastRec;
4991 XLogCtl->xlblocks[0].xlogid = openLogId;
4992 XLogCtl->xlblocks[0].xrecoff =
4993 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
4996 * Tricky point here: readBuf contains the *last* block that the LastRec
4997 * record spans, not the one it starts in. The last block is indeed the
4998 * one we want to use.
5000 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5001 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5002 Insert->currpos = (char *) Insert->currpage +
5003 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5005 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5007 XLogCtl->Write.LogwrtResult = LogwrtResult;
5008 Insert->LogwrtResult = LogwrtResult;
5009 XLogCtl->LogwrtResult = LogwrtResult;
5011 XLogCtl->LogwrtRqst.Write = EndOfLog;
5012 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5014 freespace = INSERT_FREESPACE(Insert);
5017 /* Make sure rest of page is zero */
5018 MemSet(Insert->currpos, 0, freespace);
5019 XLogCtl->Write.curridx = 0;
5024 * Whenever Write.LogwrtResult points to exactly the end of a page,
5025 * Write.curridx must point to the *next* page (see XLogWrite()).
5027 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5028 * this is sufficient. The first actual attempt to insert a log
5029 * record will advance the insert state.
5031 XLogCtl->Write.curridx = NextBufIdx(0);
5034 /* Pre-scan prepared transactions to find out the range of XIDs present */
5035 oldestActiveXID = PrescanPreparedTransactions();
5042 * Allow resource managers to do any required cleanup.
5044 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5046 if (RmgrTable[rmid].rm_cleanup != NULL)
5047 RmgrTable[rmid].rm_cleanup();
5051 * Check to see if the XLOG sequence contained any unresolved
5052 * references to uninitialized pages.
5054 XLogCheckInvalidPages();
5057 * Reset pgstat data, because it may be invalid after recovery.
5062 * Perform a checkpoint to update all our recovery activity to disk.
5064 * Note that we write a shutdown checkpoint rather than an on-line
5065 * one. This is not particularly critical, but since we may be
5066 * assigning a new TLI, using a shutdown checkpoint allows us to have
5067 * the rule that TLI only changes in shutdown checkpoints, which
5068 * allows some extra error checking in xlog_redo.
5070 CreateCheckPoint(true, true);
5073 * Close down recovery environment
5075 XLogCloseRelationCache();
5079 * Preallocate additional log files, if wanted.
5081 (void) PreallocXlogFiles(EndOfLog);
5084 * Okay, we're officially UP.
5088 ControlFile->state = DB_IN_PRODUCTION;
5089 ControlFile->time = time(NULL);
5090 UpdateControlFile();
5092 /* start the archive_timeout timer running */
5093 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5095 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5096 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5097 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5099 /* Start up the commit log and related stuff, too */
5101 StartupSUBTRANS(oldestActiveXID);
5104 /* Reload shared-memory state for prepared transactions */
5105 RecoverPreparedTransactions();
5107 /* Shut down readFile facility, free space */
5120 free(readRecordBuf);
5121 readRecordBuf = NULL;
5122 readRecordBufSize = 0;
5127 * Subroutine to try to fetch and validate a prior checkpoint record.
5129 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5130 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5133 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5137 if (!XRecOffIsValid(RecPtr.xrecoff))
5143 (errmsg("invalid primary checkpoint link in control file")));
5147 (errmsg("invalid secondary checkpoint link in control file")));
5151 (errmsg("invalid checkpoint link in backup_label file")));
5157 record = ReadRecord(&RecPtr, LOG);
5165 (errmsg("invalid primary checkpoint record")));
5169 (errmsg("invalid secondary checkpoint record")));
5173 (errmsg("invalid checkpoint record")));
5178 if (record->xl_rmid != RM_XLOG_ID)
5184 (errmsg("invalid resource manager ID in primary checkpoint record")));
5188 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5192 (errmsg("invalid resource manager ID in checkpoint record")));
5197 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5198 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5204 (errmsg("invalid xl_info in primary checkpoint record")));
5208 (errmsg("invalid xl_info in secondary checkpoint record")));
5212 (errmsg("invalid xl_info in checkpoint record")));
5217 if (record->xl_len != sizeof(CheckPoint) ||
5218 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5224 (errmsg("invalid length of primary checkpoint record")));
5228 (errmsg("invalid length of secondary checkpoint record")));
5232 (errmsg("invalid length of checkpoint record")));
5241 * This must be called during startup of a backend process, except that
5242 * it need not be called in a standalone backend (which does StartupXLOG
5243 * instead). We need to initialize the local copies of ThisTimeLineID and
5246 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5247 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5248 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5251 InitXLOGAccess(void)
5253 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5254 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5255 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5256 (void) GetRedoRecPtr();
5260 * Once spawned, a backend may update its local RedoRecPtr from
5261 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5262 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5267 /* use volatile pointer to prevent code rearrangement */
5268 volatile XLogCtlData *xlogctl = XLogCtl;
5270 SpinLockAcquire(&xlogctl->info_lck);
5271 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5272 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5273 SpinLockRelease(&xlogctl->info_lck);
5279 * Get the time of the last xlog segment switch
5282 GetLastSegSwitchTime(void)
5286 /* Need WALWriteLock, but shared lock is sufficient */
5287 LWLockAcquire(WALWriteLock, LW_SHARED);
5288 result = XLogCtl->Write.lastSegSwitchTime;
5289 LWLockRelease(WALWriteLock);
5295 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5297 * This is exported for use by code that would like to have 64-bit XIDs.
5298 * We don't really support such things, but all XIDs within the system
5299 * can be presumed "close to" the result, and thus the epoch associated
5300 * with them can be determined.
5303 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5305 uint32 ckptXidEpoch;
5306 TransactionId ckptXid;
5307 TransactionId nextXid;
5309 /* Must read checkpoint info first, else have race condition */
5311 /* use volatile pointer to prevent code rearrangement */
5312 volatile XLogCtlData *xlogctl = XLogCtl;
5314 SpinLockAcquire(&xlogctl->info_lck);
5315 ckptXidEpoch = xlogctl->ckptXidEpoch;
5316 ckptXid = xlogctl->ckptXid;
5317 SpinLockRelease(&xlogctl->info_lck);
5320 /* Now fetch current nextXid */
5321 nextXid = ReadNewTransactionId();
5324 * nextXid is certainly logically later than ckptXid. So if it's
5325 * numerically less, it must have wrapped into the next epoch.
5327 if (nextXid < ckptXid)
5331 *epoch = ckptXidEpoch;
5335 * This must be called ONCE during postmaster or standalone-backend shutdown
5338 ShutdownXLOG(int code, Datum arg)
5341 (errmsg("shutting down")));
5343 CreateCheckPoint(true, true);
5346 ShutdownMultiXact();
5349 (errmsg("database system is shut down")));
5353 * Perform a checkpoint --- either during shutdown, or on-the-fly
5355 * If force is true, we force a checkpoint regardless of whether any XLOG
5356 * activity has occurred since the last one.
5359 CreateCheckPoint(bool shutdown, bool force)
5361 CheckPoint checkPoint;
5363 XLogCtlInsert *Insert = &XLogCtl->Insert;
5369 int nsegsremoved = 0;
5370 int nsegsrecycled = 0;
5371 TransactionId *inCommitXids;
5375 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5376 * (This is just pro forma, since in the present system structure there is
5377 * only one process that is allowed to issue checkpoints at any given
5380 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5383 * Use a critical section to force system panic if we have trouble.
5385 START_CRIT_SECTION();
5389 ControlFile->state = DB_SHUTDOWNING;
5390 ControlFile->time = time(NULL);
5391 UpdateControlFile();
5394 MemSet(&checkPoint, 0, sizeof(checkPoint));
5395 checkPoint.ThisTimeLineID = ThisTimeLineID;
5396 checkPoint.time = time(NULL);
5399 * We must hold WALInsertLock while examining insert state to determine
5400 * the checkpoint REDO pointer.
5402 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5405 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5406 * any XLOG records since the start of the last checkpoint, skip the
5407 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5408 * when the system is idle. That wastes log space, and more importantly it
5409 * exposes us to possible loss of both current and previous checkpoint
5410 * records if the machine crashes just as we're writing the update.
5411 * (Perhaps it'd make even more sense to checkpoint only when the previous
5412 * checkpoint record is in a different xlog page?)
5414 * We have to make two tests to determine that nothing has happened since
5415 * the start of the last checkpoint: current insertion point must match
5416 * the end of the last checkpoint record, and its redo pointer must point
5419 if (!shutdown && !force)
5421 XLogRecPtr curInsert;
5423 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5424 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5425 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5426 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5427 ControlFile->checkPoint.xlogid ==
5428 ControlFile->checkPointCopy.redo.xlogid &&
5429 ControlFile->checkPoint.xrecoff ==
5430 ControlFile->checkPointCopy.redo.xrecoff)
5432 LWLockRelease(WALInsertLock);
5433 LWLockRelease(CheckpointLock);
5440 * Compute new REDO record ptr = location of next XLOG record.
5442 * NB: this is NOT necessarily where the checkpoint record itself will be,
5443 * since other backends may insert more XLOG records while we're off doing
5444 * the buffer flush work. Those XLOG records are logically after the
5445 * checkpoint, even though physically before it. Got that?
5447 freespace = INSERT_FREESPACE(Insert);
5448 if (freespace < SizeOfXLogRecord)
5450 (void) AdvanceXLInsertBuffer(false);
5451 /* OK to ignore update return flag, since we will do flush anyway */
5452 freespace = INSERT_FREESPACE(Insert);
5454 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5457 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5458 * must be done while holding the insert lock AND the info_lck.
5460 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5461 * pointing past where it really needs to point. This is okay; the only
5462 * consequence is that XLogInsert might back up whole buffers that it
5463 * didn't really need to. We can't postpone advancing RedoRecPtr because
5464 * XLogInserts that happen while we are dumping buffers must assume that
5465 * their buffer changes are not included in the checkpoint.
5468 /* use volatile pointer to prevent code rearrangement */
5469 volatile XLogCtlData *xlogctl = XLogCtl;
5471 SpinLockAcquire(&xlogctl->info_lck);
5472 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5473 SpinLockRelease(&xlogctl->info_lck);
5477 * Now we can release WAL insert lock, allowing other xacts to proceed
5478 * while we are flushing disk buffers.
5480 LWLockRelease(WALInsertLock);
5484 (errmsg("checkpoint starting")));
5487 * Before flushing data, we must wait for any transactions that are
5488 * currently in their commit critical sections. If an xact inserted its
5489 * commit record into XLOG just before the REDO point, then a crash
5490 * restart from the REDO point would not replay that record, which means
5491 * that our flushing had better include the xact's update of pg_clog. So
5492 * we wait till he's out of his commit critical section before proceeding.
5493 * See notes in RecordTransactionCommit().
5495 * Because we've already released WALInsertLock, this test is a bit fuzzy:
5496 * it is possible that we will wait for xacts we didn't really need to
5497 * wait for. But the delay should be short and it seems better to make
5498 * checkpoint take a bit longer than to hold locks longer than necessary.
5499 * (In fact, the whole reason we have this issue is that xact.c does
5500 * commit record XLOG insertion and clog update as two separate steps
5501 * protected by different locks, but again that seems best on grounds
5502 * of minimizing lock contention.)
5504 * A transaction that has not yet set inCommit when we look cannot be
5505 * at risk, since he's not inserted his commit record yet; and one that's
5506 * already cleared it is not at risk either, since he's done fixing clog
5507 * and we will correctly flush the update below. So we cannot miss any
5508 * xacts we need to wait for.
5510 nInCommit = GetTransactionsInCommit(&inCommitXids);
5514 pg_usleep(10000L); /* wait for 10 msec */
5515 } while (HaveTransactionsInCommit(inCommitXids, nInCommit));
5517 pfree(inCommitXids);
5520 * Get the other info we need for the checkpoint record.
5522 LWLockAcquire(XidGenLock, LW_SHARED);
5523 checkPoint.nextXid = ShmemVariableCache->nextXid;
5524 LWLockRelease(XidGenLock);
5526 /* Increase XID epoch if we've wrapped around since last checkpoint */
5527 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5528 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5529 checkPoint.nextXidEpoch++;
5531 LWLockAcquire(OidGenLock, LW_SHARED);
5532 checkPoint.nextOid = ShmemVariableCache->nextOid;
5534 checkPoint.nextOid += ShmemVariableCache->oidCount;
5535 LWLockRelease(OidGenLock);
5537 MultiXactGetCheckptMulti(shutdown,
5538 &checkPoint.nextMulti,
5539 &checkPoint.nextMultiOffset);
5542 * Having constructed the checkpoint record, ensure all shmem disk buffers
5543 * and commit-log buffers are flushed to disk.
5545 * This I/O could fail for various reasons. If so, we will fail to
5546 * complete the checkpoint, but there is no reason to force a system
5547 * panic. Accordingly, exit critical section while doing it.
5551 CheckPointGuts(checkPoint.redo);
5553 START_CRIT_SECTION();
5556 * Now insert the checkpoint record into XLOG.
5558 rdata.data = (char *) (&checkPoint);
5559 rdata.len = sizeof(checkPoint);
5560 rdata.buffer = InvalidBuffer;
5563 recptr = XLogInsert(RM_XLOG_ID,
5564 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5565 XLOG_CHECKPOINT_ONLINE,
5571 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5572 * = end of actual checkpoint record.
5574 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5576 (errmsg("concurrent transaction log activity while database system is shutting down")));
5579 * Select point at which we can truncate the log, which we base on the
5580 * prior checkpoint's earliest info.
5582 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5585 * Update the control file.
5587 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5589 ControlFile->state = DB_SHUTDOWNED;
5590 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5591 ControlFile->checkPoint = ProcLastRecPtr;
5592 ControlFile->checkPointCopy = checkPoint;
5593 ControlFile->time = time(NULL);
5594 UpdateControlFile();
5595 LWLockRelease(ControlFileLock);
5597 /* Update shared-memory copy of checkpoint XID/epoch */
5599 /* use volatile pointer to prevent code rearrangement */
5600 volatile XLogCtlData *xlogctl = XLogCtl;
5602 SpinLockAcquire(&xlogctl->info_lck);
5603 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5604 xlogctl->ckptXid = checkPoint.nextXid;
5605 SpinLockRelease(&xlogctl->info_lck);
5609 * We are now done with critical updates; no need for system panic if we
5610 * have trouble while fooling with offline log segments.
5615 * Delete offline log files (those no longer needed even for previous
5618 if (_logId || _logSeg)
5620 PrevLogSeg(_logId, _logSeg);
5621 MoveOfflineLogs(_logId, _logSeg, recptr,
5622 &nsegsremoved, &nsegsrecycled);
5626 * Make more log segments if needed. (Do this after deleting offline log
5627 * segments, to avoid having peak disk space usage higher than necessary.)
5630 nsegsadded = PreallocXlogFiles(recptr);
5633 * Truncate pg_subtrans if possible. We can throw away all data before
5634 * the oldest XMIN of any running transaction. No future transaction will
5635 * attempt to reference any pg_subtrans entry older than that (see Asserts
5636 * in subtrans.c). During recovery, though, we mustn't do this because
5637 * StartupSUBTRANS hasn't been called yet.
5640 TruncateSUBTRANS(GetOldestXmin(true, false));
5644 (errmsg("checkpoint complete; %d transaction log file(s) added, %d removed, %d recycled",
5645 nsegsadded, nsegsremoved, nsegsrecycled)));
5647 LWLockRelease(CheckpointLock);
5651 * Flush all data in shared memory to disk, and fsync
5653 * This is the common code shared between regular checkpoints and
5654 * recovery restartpoints.
5657 CheckPointGuts(XLogRecPtr checkPointRedo)
5660 CheckPointSUBTRANS();
5661 CheckPointMultiXact();
5662 FlushBufferPool(); /* performs all required fsyncs */
5663 /* We deliberately delay 2PC checkpointing as long as possible */
5664 CheckPointTwoPhase(checkPointRedo);
5668 * Set a recovery restart point if appropriate
5670 * This is similar to CreateCheckpoint, but is used during WAL recovery
5671 * to establish a point from which recovery can roll forward without
5672 * replaying the entire recovery log. This function is called each time
5673 * a checkpoint record is read from XLOG; it must determine whether a
5674 * restartpoint is needed or not.
5677 RecoveryRestartPoint(const CheckPoint *checkPoint)
5683 * Do nothing if the elapsed time since the last restartpoint is less than
5684 * half of checkpoint_timeout. (We use a value less than
5685 * checkpoint_timeout so that variations in the timing of checkpoints on
5686 * the master, or speed of transmission of WAL segments to a slave, won't
5687 * make the slave skip a restartpoint once it's synced with the master.)
5688 * Checking true elapsed time keeps us from doing restartpoints too often
5689 * while rapidly scanning large amounts of WAL.
5691 elapsed_secs = time(NULL) - ControlFile->time;
5692 if (elapsed_secs < CheckPointTimeout / 2)
5696 * Is it safe to checkpoint? We must ask each of the resource managers
5697 * whether they have any partial state information that might prevent a
5698 * correct restart from this point. If so, we skip this opportunity, but
5699 * return at the next checkpoint record for another try.
5701 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5703 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5704 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5709 * OK, force data out to disk
5711 CheckPointGuts(checkPoint->redo);
5714 * Update pg_control so that any subsequent crash will restart from this
5715 * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
5718 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5719 ControlFile->checkPoint = ReadRecPtr;
5720 ControlFile->checkPointCopy = *checkPoint;
5721 ControlFile->time = time(NULL);
5722 UpdateControlFile();
5725 (errmsg("recovery restart point at %X/%X",
5726 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5730 * Write a NEXTOID log record
5733 XLogPutNextOid(Oid nextOid)
5737 rdata.data = (char *) (&nextOid);
5738 rdata.len = sizeof(Oid);
5739 rdata.buffer = InvalidBuffer;
5741 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5744 * We need not flush the NEXTOID record immediately, because any of the
5745 * just-allocated OIDs could only reach disk as part of a tuple insert or
5746 * update that would have its own XLOG record that must follow the NEXTOID
5747 * record. Therefore, the standard buffer LSN interlock applied to those
5748 * records will ensure no such OID reaches disk before the NEXTOID record
5751 * Note, however, that the above statement only covers state "within" the
5752 * database. When we use a generated OID as a file or directory name,
5753 * we are in a sense violating the basic WAL rule, because that filesystem
5754 * change may reach disk before the NEXTOID WAL record does. The impact
5755 * of this is that if a database crash occurs immediately afterward,
5756 * we might after restart re-generate the same OID and find that it
5757 * conflicts with the leftover file or directory. But since for safety's
5758 * sake we always loop until finding a nonconflicting filename, this poses
5759 * no real problem in practice. See pgsql-hackers discussion 27-Sep-2006.
5764 * Write an XLOG SWITCH record.
5766 * Here we just blindly issue an XLogInsert request for the record.
5767 * All the magic happens inside XLogInsert.
5769 * The return value is either the end+1 address of the switch record,
5770 * or the end+1 address of the prior segment if we did not need to
5771 * write a switch record because we are already at segment start.
5774 RequestXLogSwitch(void)
5779 /* XLOG SWITCH, alone among xlog record types, has no data */
5780 rdata.buffer = InvalidBuffer;
5785 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5791 * XLOG resource manager's routines
5794 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5796 uint8 info = record->xl_info & ~XLR_INFO_MASK;
5798 if (info == XLOG_NEXTOID)
5802 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5803 if (ShmemVariableCache->nextOid < nextOid)
5805 ShmemVariableCache->nextOid = nextOid;
5806 ShmemVariableCache->oidCount = 0;
5809 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5811 CheckPoint checkPoint;
5813 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5814 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5815 ShmemVariableCache->nextXid = checkPoint.nextXid;
5816 ShmemVariableCache->nextOid = checkPoint.nextOid;
5817 ShmemVariableCache->oidCount = 0;
5818 MultiXactSetNextMXact(checkPoint.nextMulti,
5819 checkPoint.nextMultiOffset);
5821 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5822 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5823 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5826 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
5828 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5830 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5831 !list_member_int(expectedTLIs,
5832 (int) checkPoint.ThisTimeLineID))
5834 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5835 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5836 /* Following WAL records should be run with new TLI */
5837 ThisTimeLineID = checkPoint.ThisTimeLineID;
5840 RecoveryRestartPoint(&checkPoint);
5842 else if (info == XLOG_CHECKPOINT_ONLINE)
5844 CheckPoint checkPoint;
5846 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5847 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5848 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5849 checkPoint.nextXid))
5850 ShmemVariableCache->nextXid = checkPoint.nextXid;
5851 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5853 ShmemVariableCache->nextOid = checkPoint.nextOid;
5854 ShmemVariableCache->oidCount = 0;
5856 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
5857 checkPoint.nextMultiOffset);
5859 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5860 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5861 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5863 /* TLI should not change in an on-line checkpoint */
5864 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5866 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5867 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5869 RecoveryRestartPoint(&checkPoint);
5871 else if (info == XLOG_SWITCH)
5873 /* nothing to do here */
5878 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
5880 uint8 info = xl_info & ~XLR_INFO_MASK;
5882 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5883 info == XLOG_CHECKPOINT_ONLINE)
5885 CheckPoint *checkpoint = (CheckPoint *) rec;
5887 appendStringInfo(buf, "checkpoint: redo %X/%X; "
5888 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
5889 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5890 checkpoint->ThisTimeLineID,
5891 checkpoint->nextXidEpoch, checkpoint->nextXid,
5892 checkpoint->nextOid,
5893 checkpoint->nextMulti,
5894 checkpoint->nextMultiOffset,
5895 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
5897 else if (info == XLOG_NEXTOID)
5901 memcpy(&nextOid, rec, sizeof(Oid));
5902 appendStringInfo(buf, "nextOid: %u", nextOid);
5904 else if (info == XLOG_SWITCH)
5906 appendStringInfo(buf, "xlog switch");
5909 appendStringInfo(buf, "UNKNOWN");
5915 xlog_outrec(StringInfo buf, XLogRecord *record)
5919 appendStringInfo(buf, "prev %X/%X; xid %u",
5920 record->xl_prev.xlogid, record->xl_prev.xrecoff,
5923 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
5925 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
5926 appendStringInfo(buf, "; bkpb%d", i + 1);
5929 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
5931 #endif /* WAL_DEBUG */
5938 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
5940 int new_sync_method;
5943 if (pg_strcasecmp(method, "fsync") == 0)
5945 new_sync_method = SYNC_METHOD_FSYNC;
5948 #ifdef HAVE_FSYNC_WRITETHROUGH
5949 else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
5951 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
5955 #ifdef HAVE_FDATASYNC
5956 else if (pg_strcasecmp(method, "fdatasync") == 0)
5958 new_sync_method = SYNC_METHOD_FDATASYNC;
5962 #ifdef OPEN_SYNC_FLAG
5963 else if (pg_strcasecmp(method, "open_sync") == 0)
5965 new_sync_method = SYNC_METHOD_OPEN;
5966 new_sync_bit = OPEN_SYNC_FLAG;
5969 #ifdef OPEN_DATASYNC_FLAG
5970 else if (pg_strcasecmp(method, "open_datasync") == 0)
5972 new_sync_method = SYNC_METHOD_OPEN;
5973 new_sync_bit = OPEN_DATASYNC_FLAG;
5982 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
5985 * To ensure that no blocks escape unsynced, force an fsync on the
5986 * currently open log segment (if any). Also, if the open flag is
5987 * changing, close the log file so it will be reopened (with new flag
5990 if (openLogFile >= 0)
5992 if (pg_fsync(openLogFile) != 0)
5994 (errcode_for_file_access(),
5995 errmsg("could not fsync log file %u, segment %u: %m",
5996 openLogId, openLogSeg)));
5997 if (open_sync_bit != new_sync_bit)
6000 sync_method = new_sync_method;
6001 open_sync_bit = new_sync_bit;
6009 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6012 issue_xlog_fsync(void)
6014 switch (sync_method)
6016 case SYNC_METHOD_FSYNC:
6017 if (pg_fsync_no_writethrough(openLogFile) != 0)
6019 (errcode_for_file_access(),
6020 errmsg("could not fsync log file %u, segment %u: %m",
6021 openLogId, openLogSeg)));
6023 #ifdef HAVE_FSYNC_WRITETHROUGH
6024 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6025 if (pg_fsync_writethrough(openLogFile) != 0)
6027 (errcode_for_file_access(),
6028 errmsg("could not fsync write-through log file %u, segment %u: %m",
6029 openLogId, openLogSeg)));
6032 #ifdef HAVE_FDATASYNC
6033 case SYNC_METHOD_FDATASYNC:
6034 if (pg_fdatasync(openLogFile) != 0)
6036 (errcode_for_file_access(),
6037 errmsg("could not fdatasync log file %u, segment %u: %m",
6038 openLogId, openLogSeg)));
6041 case SYNC_METHOD_OPEN:
6042 /* write synced it already */
6045 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6052 * pg_start_backup: set up for taking an on-line backup dump
6054 * Essentially what this does is to create a backup label file in $PGDATA,
6055 * where it will be archived as part of the backup dump. The label file
6056 * contains the user-supplied label string (typically this would be used
6057 * to tell where the backup dump will be stored) and the starting time and
6058 * starting WAL location for the dump.
6061 pg_start_backup(PG_FUNCTION_ARGS)
6063 text *backupid = PG_GETARG_TEXT_P(0);
6066 XLogRecPtr checkpointloc;
6067 XLogRecPtr startpoint;
6070 char xlogfilename[MAXFNAMELEN];
6073 struct stat stat_buf;
6078 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6079 (errmsg("must be superuser to run a backup"))));
6081 if (!XLogArchivingActive())
6083 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6084 (errmsg("WAL archiving is not active"),
6085 (errhint("archive_command must be defined before "
6086 "online backups can be made safely.")))));
6088 backupidstr = DatumGetCString(DirectFunctionCall1(textout,
6089 PointerGetDatum(backupid)));
6092 * Mark backup active in shared memory. We must do full-page WAL writes
6093 * during an on-line backup even if not doing so at other times, because
6094 * it's quite possible for the backup dump to obtain a "torn" (partially
6095 * written) copy of a database page if it reads the page concurrently with
6096 * our write to the same page. This can be fixed as long as the first
6097 * write to the page in the WAL sequence is a full-page write. Hence, we
6098 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6099 * are no dirty pages in shared memory that might get dumped while the
6100 * backup is in progress without having a corresponding WAL record. (Once
6101 * the backup is complete, we need not force full-page writes anymore,
6102 * since we expect that any pages not modified during the backup interval
6103 * must have been correctly captured by the backup.)
6105 * We must hold WALInsertLock to change the value of forcePageWrites, to
6106 * ensure adequate interlocking against XLogInsert().
6108 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6109 if (XLogCtl->Insert.forcePageWrites)
6111 LWLockRelease(WALInsertLock);
6113 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6114 errmsg("a backup is already in progress"),
6115 errhint("Run pg_stop_backup() and try again.")));
6117 XLogCtl->Insert.forcePageWrites = true;
6118 LWLockRelease(WALInsertLock);
6120 /* Use a TRY block to ensure we release forcePageWrites if fail below */
6124 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6125 * page problems, this guarantees that two successive backup runs will
6126 * have different checkpoint positions and hence different history
6127 * file names, even if nothing happened in between.
6129 RequestCheckpoint(true, false);
6132 * Now we need to fetch the checkpoint record location, and also its
6133 * REDO pointer. The oldest point in WAL that would be needed to
6134 * restore starting from the checkpoint is precisely the REDO pointer.
6136 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6137 checkpointloc = ControlFile->checkPoint;
6138 startpoint = ControlFile->checkPointCopy.redo;
6139 LWLockRelease(ControlFileLock);
6141 XLByteToSeg(startpoint, _logId, _logSeg);
6142 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6145 * We deliberately use strftime/localtime not the src/timezone
6146 * functions, so that backup labels will consistently be recorded in
6147 * the same timezone regardless of TimeZone setting. This matches
6148 * elog.c's practice.
6150 stamp_time = time(NULL);
6151 strftime(strfbuf, sizeof(strfbuf),
6152 "%Y-%m-%d %H:%M:%S %Z",
6153 localtime(&stamp_time));
6156 * Check for existing backup label --- implies a backup is already
6157 * running. (XXX given that we checked forcePageWrites above, maybe
6158 * it would be OK to just unlink any such label file?)
6160 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6162 if (errno != ENOENT)
6164 (errcode_for_file_access(),
6165 errmsg("could not stat file \"%s\": %m",
6166 BACKUP_LABEL_FILE)));
6170 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6171 errmsg("a backup is already in progress"),
6172 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6173 BACKUP_LABEL_FILE)));
6176 * Okay, write the file
6178 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6181 (errcode_for_file_access(),
6182 errmsg("could not create file \"%s\": %m",
6183 BACKUP_LABEL_FILE)));
6184 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6185 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6186 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6187 checkpointloc.xlogid, checkpointloc.xrecoff);
6188 fprintf(fp, "START TIME: %s\n", strfbuf);
6189 fprintf(fp, "LABEL: %s\n", backupidstr);
6190 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6192 (errcode_for_file_access(),
6193 errmsg("could not write file \"%s\": %m",
6194 BACKUP_LABEL_FILE)));
6198 /* Turn off forcePageWrites on failure */
6199 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6200 XLogCtl->Insert.forcePageWrites = false;
6201 LWLockRelease(WALInsertLock);
6208 * We're done. As a convenience, return the starting WAL location.
6210 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6211 startpoint.xlogid, startpoint.xrecoff);
6212 result = DatumGetTextP(DirectFunctionCall1(textin,
6213 CStringGetDatum(xlogfilename)));
6214 PG_RETURN_TEXT_P(result);
6218 * pg_stop_backup: finish taking an on-line backup dump
6220 * We remove the backup label file created by pg_start_backup, and instead
6221 * create a backup history file in pg_xlog (whence it will immediately be
6222 * archived). The backup history file contains the same info found in
6223 * the label file, plus the backup-end time and WAL location.
6226 pg_stop_backup(PG_FUNCTION_ARGS)
6229 XLogRecPtr startpoint;
6230 XLogRecPtr stoppoint;
6233 char histfilepath[MAXPGPATH];
6234 char startxlogfilename[MAXFNAMELEN];
6235 char stopxlogfilename[MAXFNAMELEN];
6245 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6246 (errmsg("must be superuser to run a backup"))));
6249 * OK to clear forcePageWrites
6251 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6252 XLogCtl->Insert.forcePageWrites = false;
6253 LWLockRelease(WALInsertLock);
6256 * Force a switch to a new xlog segment file, so that the backup is valid
6257 * as soon as archiver moves out the current segment file. We'll report
6258 * the end address of the XLOG SWITCH record as the backup stopping point.
6260 stoppoint = RequestXLogSwitch();
6262 XLByteToSeg(stoppoint, _logId, _logSeg);
6263 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
6266 * We deliberately use strftime/localtime not the src/timezone functions,
6267 * so that backup labels will consistently be recorded in the same
6268 * timezone regardless of TimeZone setting. This matches elog.c's
6271 stamp_time = time(NULL);
6272 strftime(strfbuf, sizeof(strfbuf),
6273 "%Y-%m-%d %H:%M:%S %Z",
6274 localtime(&stamp_time));
6277 * Open the existing label file
6279 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6282 if (errno != ENOENT)
6284 (errcode_for_file_access(),
6285 errmsg("could not read file \"%s\": %m",
6286 BACKUP_LABEL_FILE)));
6288 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6289 errmsg("a backup is not in progress")));
6293 * Read and parse the START WAL LOCATION line (this code is pretty crude,
6294 * but we are not expecting any variability in the file format).
6296 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
6297 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6298 &ch) != 4 || ch != '\n')
6300 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6301 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6304 * Write the backup history file
6306 XLByteToSeg(startpoint, _logId, _logSeg);
6307 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6308 startpoint.xrecoff % XLogSegSize);
6309 fp = AllocateFile(histfilepath, "w");
6312 (errcode_for_file_access(),
6313 errmsg("could not create file \"%s\": %m",
6315 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6316 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
6317 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
6318 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
6319 /* transfer remaining lines from label to history file */
6320 while ((ich = fgetc(lfp)) != EOF)
6322 fprintf(fp, "STOP TIME: %s\n", strfbuf);
6323 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6325 (errcode_for_file_access(),
6326 errmsg("could not write file \"%s\": %m",
6330 * Close and remove the backup label file
6332 if (ferror(lfp) || FreeFile(lfp))
6334 (errcode_for_file_access(),
6335 errmsg("could not read file \"%s\": %m",
6336 BACKUP_LABEL_FILE)));
6337 if (unlink(BACKUP_LABEL_FILE) != 0)
6339 (errcode_for_file_access(),
6340 errmsg("could not remove file \"%s\": %m",
6341 BACKUP_LABEL_FILE)));
6344 * Clean out any no-longer-needed history files. As a side effect, this
6345 * will post a .ready file for the newly created history file, notifying
6346 * the archiver that history file may be archived immediately.
6348 CleanupBackupHistory();
6351 * We're done. As a convenience, return the ending WAL location.
6353 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
6354 stoppoint.xlogid, stoppoint.xrecoff);
6355 result = DatumGetTextP(DirectFunctionCall1(textin,
6356 CStringGetDatum(stopxlogfilename)));
6357 PG_RETURN_TEXT_P(result);
6361 * pg_switch_xlog: switch to next xlog file
6364 pg_switch_xlog(PG_FUNCTION_ARGS)
6367 XLogRecPtr switchpoint;
6368 char location[MAXFNAMELEN];
6372 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6373 (errmsg("must be superuser to switch transaction log files"))));
6375 switchpoint = RequestXLogSwitch();
6378 * As a convenience, return the WAL location of the switch record
6380 snprintf(location, sizeof(location), "%X/%X",
6381 switchpoint.xlogid, switchpoint.xrecoff);
6382 result = DatumGetTextP(DirectFunctionCall1(textin,
6383 CStringGetDatum(location)));
6384 PG_RETURN_TEXT_P(result);
6388 * Report the current WAL write location (same format as pg_start_backup etc)
6390 * This is useful for determining how much of WAL is visible to an external
6391 * archiving process. Note that the data before this point is written out
6392 * to the kernel, but is not necessarily synced to disk.
6395 pg_current_xlog_location(PG_FUNCTION_ARGS)
6398 char location[MAXFNAMELEN];
6400 /* Make sure we have an up-to-date local LogwrtResult */
6402 /* use volatile pointer to prevent code rearrangement */
6403 volatile XLogCtlData *xlogctl = XLogCtl;
6405 SpinLockAcquire(&xlogctl->info_lck);
6406 LogwrtResult = xlogctl->LogwrtResult;
6407 SpinLockRelease(&xlogctl->info_lck);
6410 snprintf(location, sizeof(location), "%X/%X",
6411 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
6413 result = DatumGetTextP(DirectFunctionCall1(textin,
6414 CStringGetDatum(location)));
6415 PG_RETURN_TEXT_P(result);
6419 * Report the current WAL insert location (same format as pg_start_backup etc)
6421 * This function is mostly for debugging purposes.
6424 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
6427 XLogCtlInsert *Insert = &XLogCtl->Insert;
6428 XLogRecPtr current_recptr;
6429 char location[MAXFNAMELEN];
6432 * Get the current end-of-WAL position ... shared lock is sufficient
6434 LWLockAcquire(WALInsertLock, LW_SHARED);
6435 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
6436 LWLockRelease(WALInsertLock);
6438 snprintf(location, sizeof(location), "%X/%X",
6439 current_recptr.xlogid, current_recptr.xrecoff);
6441 result = DatumGetTextP(DirectFunctionCall1(textin,
6442 CStringGetDatum(location)));
6443 PG_RETURN_TEXT_P(result);
6447 * Compute an xlog file name and decimal byte offset given a WAL location,
6448 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6450 * Note that a location exactly at a segment boundary is taken to be in
6451 * the previous segment. This is usually the right thing, since the
6452 * expected usage is to determine which xlog file(s) are ready to archive.
6455 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
6457 text *location = PG_GETARG_TEXT_P(0);
6459 unsigned int uxlogid;
6460 unsigned int uxrecoff;
6464 XLogRecPtr locationpoint;
6465 char xlogfilename[MAXFNAMELEN];
6468 TupleDesc resultTupleDesc;
6469 HeapTuple resultHeapTuple;
6473 * Read input and parse
6475 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6476 PointerGetDatum(location)));
6478 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6480 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6481 errmsg("could not parse transaction log location \"%s\"",
6484 locationpoint.xlogid = uxlogid;
6485 locationpoint.xrecoff = uxrecoff;
6488 * Construct a tuple descriptor for the result row. This must match this
6489 * function's pg_proc entry!
6491 resultTupleDesc = CreateTemplateTupleDesc(2, false);
6492 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
6494 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
6497 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
6502 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6503 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6505 values[0] = DirectFunctionCall1(textin,
6506 CStringGetDatum(xlogfilename));
6512 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
6514 values[1] = UInt32GetDatum(xrecoff);
6518 * Tuple jam: Having first prepared your Datums, then squash together
6520 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
6522 result = HeapTupleGetDatum(resultHeapTuple);
6524 PG_RETURN_DATUM(result);
6528 * Compute an xlog file name given a WAL location,
6529 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6532 pg_xlogfile_name(PG_FUNCTION_ARGS)
6534 text *location = PG_GETARG_TEXT_P(0);
6537 unsigned int uxlogid;
6538 unsigned int uxrecoff;
6541 XLogRecPtr locationpoint;
6542 char xlogfilename[MAXFNAMELEN];
6544 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6545 PointerGetDatum(location)));
6547 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6549 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6550 errmsg("could not parse transaction log location \"%s\"",
6553 locationpoint.xlogid = uxlogid;
6554 locationpoint.xrecoff = uxrecoff;
6556 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6557 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6559 result = DatumGetTextP(DirectFunctionCall1(textin,
6560 CStringGetDatum(xlogfilename)));
6561 PG_RETURN_TEXT_P(result);
6565 * read_backup_label: check to see if a backup_label file is present
6567 * If we see a backup_label during recovery, we assume that we are recovering
6568 * from a backup dump file, and we therefore roll forward from the checkpoint
6569 * identified by the label file, NOT what pg_control says. This avoids the
6570 * problem that pg_control might have been archived one or more checkpoints
6571 * later than the start of the dump, and so if we rely on it as the start
6572 * point, we will fail to restore a consistent database state.
6574 * We also attempt to retrieve the corresponding backup history file.
6575 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6578 * Returns TRUE if a backup_label was found (and fills the checkpoint
6579 * location into *checkPointLoc); returns FALSE if not.
6582 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6584 XLogRecPtr startpoint;
6585 XLogRecPtr stoppoint;
6586 char histfilename[MAXFNAMELEN];
6587 char histfilepath[MAXPGPATH];
6588 char startxlogfilename[MAXFNAMELEN];
6589 char stopxlogfilename[MAXFNAMELEN];
6597 /* Default is to not constrain recovery stop point */
6598 minRecoveryLoc->xlogid = 0;
6599 minRecoveryLoc->xrecoff = 0;
6602 * See if label file is present
6604 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6607 if (errno != ENOENT)
6609 (errcode_for_file_access(),
6610 errmsg("could not read file \"%s\": %m",
6611 BACKUP_LABEL_FILE)));
6612 return false; /* it's not there, all is fine */
6616 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
6617 * is pretty crude, but we are not expecting any variability in the file
6620 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
6621 &startpoint.xlogid, &startpoint.xrecoff, &tli,
6622 startxlogfilename, &ch) != 5 || ch != '\n')
6624 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6625 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6626 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
6627 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
6628 &ch) != 3 || ch != '\n')
6630 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6631 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6632 if (ferror(lfp) || FreeFile(lfp))
6634 (errcode_for_file_access(),
6635 errmsg("could not read file \"%s\": %m",
6636 BACKUP_LABEL_FILE)));
6639 * Try to retrieve the backup history file (no error if we can't)
6641 XLByteToSeg(startpoint, _logId, _logSeg);
6642 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
6643 startpoint.xrecoff % XLogSegSize);
6645 if (InArchiveRecovery)
6646 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
6648 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
6649 startpoint.xrecoff % XLogSegSize);
6651 fp = AllocateFile(histfilepath, "r");
6655 * Parse history file to identify stop point.
6657 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
6658 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6659 &ch) != 4 || ch != '\n')
6661 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6662 errmsg("invalid data in file \"%s\"", histfilename)));
6663 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
6664 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6665 &ch) != 4 || ch != '\n')
6667 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6668 errmsg("invalid data in file \"%s\"", histfilename)));
6669 *minRecoveryLoc = stoppoint;
6670 if (ferror(fp) || FreeFile(fp))
6672 (errcode_for_file_access(),
6673 errmsg("could not read file \"%s\": %m",
6681 * Error context callback for errors occurring during rm_redo().
6684 rm_redo_error_callback(void *arg)
6686 XLogRecord *record = (XLogRecord *) arg;
6689 initStringInfo(&buf);
6690 RmgrTable[record->xl_rmid].rm_desc(&buf,
6692 XLogRecGetData(record));
6694 /* don't bother emitting empty description */
6696 errcontext("xlog redo %s", buf.data);