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.264 2007/02/14 05:00:40 momjian 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/twophase.h"
32 #include "access/xact.h"
33 #include "access/xlog_internal.h"
34 #include "access/xlogdefs.h"
35 #include "access/xlogutils.h"
36 #include "catalog/catversion.h"
37 #include "catalog/pg_control.h"
38 #include "catalog/pg_type.h"
40 #include "miscadmin.h"
42 #include "postmaster/bgwriter.h"
43 #include "storage/bufpage.h"
44 #include "storage/fd.h"
45 #include "storage/pmsignal.h"
46 #include "storage/procarray.h"
47 #include "storage/spin.h"
48 #include "utils/builtins.h"
49 #include "utils/nabstime.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 time_t recoveryTargetTime;
118 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
119 static TransactionId recoveryStopXid;
120 static time_t 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 str_time(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 #ifdef HAVE_INT64_TIMESTAMP
3638 ControlFile->enableIntTimes = TRUE;
3640 ControlFile->enableIntTimes = FALSE;
3643 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3644 localeptr = setlocale(LC_COLLATE, NULL);
3647 (errmsg("invalid LC_COLLATE setting")));
3648 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3649 localeptr = setlocale(LC_CTYPE, NULL);
3652 (errmsg("invalid LC_CTYPE setting")));
3653 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3655 /* Contents are protected with a CRC */
3656 INIT_CRC32(ControlFile->crc);
3657 COMP_CRC32(ControlFile->crc,
3658 (char *) ControlFile,
3659 offsetof(ControlFileData, crc));
3660 FIN_CRC32(ControlFile->crc);
3663 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3664 * excess over sizeof(ControlFileData). This reduces the odds of
3665 * premature-EOF errors when reading pg_control. We'll still fail when we
3666 * check the contents of the file, but hopefully with a more specific
3667 * error than "couldn't read pg_control".
3669 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3670 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3672 memset(buffer, 0, PG_CONTROL_SIZE);
3673 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3675 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3676 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3680 (errcode_for_file_access(),
3681 errmsg("could not create control file \"%s\": %m",
3682 XLOG_CONTROL_FILE)));
3685 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3687 /* if write didn't set errno, assume problem is no disk space */
3691 (errcode_for_file_access(),
3692 errmsg("could not write to control file: %m")));
3695 if (pg_fsync(fd) != 0)
3697 (errcode_for_file_access(),
3698 errmsg("could not fsync control file: %m")));
3702 (errcode_for_file_access(),
3703 errmsg("could not close control file: %m")));
3707 ReadControlFile(void)
3715 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3720 (errcode_for_file_access(),
3721 errmsg("could not open control file \"%s\": %m",
3722 XLOG_CONTROL_FILE)));
3724 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3726 (errcode_for_file_access(),
3727 errmsg("could not read from control file: %m")));
3732 * Check for expected pg_control format version. If this is wrong, the
3733 * CRC check will likely fail because we'll be checking the wrong number
3734 * of bytes. Complaining about wrong version will probably be more
3735 * enlightening than complaining about wrong CRC.
3737 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3739 (errmsg("database files are incompatible with server"),
3740 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3741 " but the server was compiled with PG_CONTROL_VERSION %d.",
3742 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3743 errhint("It looks like you need to initdb.")));
3744 /* Now check the CRC. */
3747 (char *) ControlFile,
3748 offsetof(ControlFileData, crc));
3751 if (!EQ_CRC32(crc, ControlFile->crc))
3753 (errmsg("incorrect checksum in control file")));
3756 * Do compatibility checking immediately. We do this here for 2 reasons:
3758 * (1) if the database isn't compatible with the backend executable, we
3759 * want to abort before we can possibly do any damage;
3761 * (2) this code is executed in the postmaster, so the setlocale() will
3762 * propagate to forked backends, which aren't going to read this file for
3763 * themselves. (These locale settings are considered critical
3764 * compatibility items because they can affect sort order of indexes.)
3766 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3768 (errmsg("database files are incompatible with server"),
3769 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3770 " but the server was compiled with CATALOG_VERSION_NO %d.",
3771 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3772 errhint("It looks like you need to initdb.")));
3773 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3775 (errmsg("database files are incompatible with server"),
3776 errdetail("The database cluster was initialized with MAXALIGN %d,"
3777 " but the server was compiled with MAXALIGN %d.",
3778 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3779 errhint("It looks like you need to initdb.")));
3780 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3782 (errmsg("database files are incompatible with server"),
3783 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3784 errhint("It looks like you need to initdb.")));
3785 if (ControlFile->blcksz != BLCKSZ)
3787 (errmsg("database files are incompatible with server"),
3788 errdetail("The database cluster was initialized with BLCKSZ %d,"
3789 " but the server was compiled with BLCKSZ %d.",
3790 ControlFile->blcksz, BLCKSZ),
3791 errhint("It looks like you need to recompile or initdb.")));
3792 if (ControlFile->relseg_size != RELSEG_SIZE)
3794 (errmsg("database files are incompatible with server"),
3795 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3796 " but the server was compiled with RELSEG_SIZE %d.",
3797 ControlFile->relseg_size, RELSEG_SIZE),
3798 errhint("It looks like you need to recompile or initdb.")));
3799 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3801 (errmsg("database files are incompatible with server"),
3802 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3803 " but the server was compiled with XLOG_BLCKSZ %d.",
3804 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3805 errhint("It looks like you need to recompile or initdb.")));
3806 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3808 (errmsg("database files are incompatible with server"),
3809 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3810 " but the server was compiled with XLOG_SEG_SIZE %d.",
3811 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3812 errhint("It looks like you need to recompile or initdb.")));
3813 if (ControlFile->nameDataLen != NAMEDATALEN)
3815 (errmsg("database files are incompatible with server"),
3816 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3817 " but the server was compiled with NAMEDATALEN %d.",
3818 ControlFile->nameDataLen, NAMEDATALEN),
3819 errhint("It looks like you need to recompile or initdb.")));
3820 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3822 (errmsg("database files are incompatible with server"),
3823 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3824 " but the server was compiled with INDEX_MAX_KEYS %d.",
3825 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3826 errhint("It looks like you need to recompile or initdb.")));
3828 #ifdef HAVE_INT64_TIMESTAMP
3829 if (ControlFile->enableIntTimes != TRUE)
3831 (errmsg("database files are incompatible with server"),
3832 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3833 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3834 errhint("It looks like you need to recompile or initdb.")));
3836 if (ControlFile->enableIntTimes != FALSE)
3838 (errmsg("database files are incompatible with server"),
3839 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3840 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3841 errhint("It looks like you need to recompile or initdb.")));
3844 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3846 (errmsg("database files are incompatible with server"),
3847 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3848 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3849 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3850 errhint("It looks like you need to recompile or initdb.")));
3851 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3853 (errmsg("database files are incompatible with operating system"),
3854 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3855 " which is not recognized by setlocale().",
3856 ControlFile->lc_collate),
3857 errhint("It looks like you need to initdb or install locale support.")));
3858 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3860 (errmsg("database files are incompatible with operating system"),
3861 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3862 " which is not recognized by setlocale().",
3863 ControlFile->lc_ctype),
3864 errhint("It looks like you need to initdb or install locale support.")));
3866 /* Make the fixed locale settings visible as GUC variables, too */
3867 SetConfigOption("lc_collate", ControlFile->lc_collate,
3868 PGC_INTERNAL, PGC_S_OVERRIDE);
3869 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3870 PGC_INTERNAL, PGC_S_OVERRIDE);
3874 UpdateControlFile(void)
3878 INIT_CRC32(ControlFile->crc);
3879 COMP_CRC32(ControlFile->crc,
3880 (char *) ControlFile,
3881 offsetof(ControlFileData, crc));
3882 FIN_CRC32(ControlFile->crc);
3884 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3889 (errcode_for_file_access(),
3890 errmsg("could not open control file \"%s\": %m",
3891 XLOG_CONTROL_FILE)));
3894 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3896 /* if write didn't set errno, assume problem is no disk space */
3900 (errcode_for_file_access(),
3901 errmsg("could not write to control file: %m")));
3904 if (pg_fsync(fd) != 0)
3906 (errcode_for_file_access(),
3907 errmsg("could not fsync control file: %m")));
3911 (errcode_for_file_access(),
3912 errmsg("could not close control file: %m")));
3916 * Initialization of shared memory for XLOG
3924 size = sizeof(XLogCtlData);
3925 /* xlblocks array */
3926 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
3927 /* extra alignment padding for XLOG I/O buffers */
3928 size = add_size(size, ALIGNOF_XLOG_BUFFER);
3929 /* and the buffers themselves */
3930 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
3933 * Note: we don't count ControlFileData, it comes out of the "slop factor"
3934 * added by CreateSharedMemoryAndSemaphores. This lets us use this
3935 * routine again below to compute the actual allocation size.
3948 ControlFile = (ControlFileData *)
3949 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
3950 XLogCtl = (XLogCtlData *)
3951 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
3953 if (foundCFile || foundXLog)
3955 /* both should be present or neither */
3956 Assert(foundCFile && foundXLog);
3960 memset(XLogCtl, 0, sizeof(XLogCtlData));
3963 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
3964 * multiple of the alignment for same, so no extra alignment padding is
3967 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
3968 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
3969 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
3970 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
3973 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
3975 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
3976 XLogCtl->pages = allocptr;
3977 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
3980 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
3981 * in additional info.)
3983 XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
3985 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
3986 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
3987 SpinLockInit(&XLogCtl->info_lck);
3990 * If we are not in bootstrap mode, pg_control should already exist. Read
3991 * and validate it immediately (see comments in ReadControlFile() for the
3994 if (!IsBootstrapProcessingMode())
3999 * This func must be called ONCE on system install. It creates pg_control
4000 * and the initial XLOG segment.
4005 CheckPoint checkPoint;
4007 XLogPageHeader page;
4008 XLogLongPageHeader longpage;
4011 uint64 sysidentifier;
4016 * Select a hopefully-unique system identifier code for this installation.
4017 * We use the result of gettimeofday(), including the fractional seconds
4018 * field, as being about as unique as we can easily get. (Think not to
4019 * use random(), since it hasn't been seeded and there's no portable way
4020 * to seed it other than the system clock value...) The upper half of the
4021 * uint64 value is just the tv_sec part, while the lower half is the XOR
4022 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4023 * unnecessarily if "uint64" is really only 32 bits wide. A person
4024 * knowing this encoding can determine the initialization time of the
4025 * installation, which could perhaps be useful sometimes.
4027 gettimeofday(&tv, NULL);
4028 sysidentifier = ((uint64) tv.tv_sec) << 32;
4029 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4031 /* First timeline ID is always 1 */
4034 /* page buffer must be aligned suitably for O_DIRECT */
4035 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4036 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4037 memset(page, 0, XLOG_BLCKSZ);
4039 /* Set up information for the initial checkpoint record */
4040 checkPoint.redo.xlogid = 0;
4041 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4042 checkPoint.undo = checkPoint.redo;
4043 checkPoint.ThisTimeLineID = ThisTimeLineID;
4044 checkPoint.nextXidEpoch = 0;
4045 checkPoint.nextXid = FirstNormalTransactionId;
4046 checkPoint.nextOid = FirstBootstrapObjectId;
4047 checkPoint.nextMulti = FirstMultiXactId;
4048 checkPoint.nextMultiOffset = 0;
4049 checkPoint.time = time(NULL);
4051 ShmemVariableCache->nextXid = checkPoint.nextXid;
4052 ShmemVariableCache->nextOid = checkPoint.nextOid;
4053 ShmemVariableCache->oidCount = 0;
4054 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4056 /* Set up the XLOG page header */
4057 page->xlp_magic = XLOG_PAGE_MAGIC;
4058 page->xlp_info = XLP_LONG_HEADER;
4059 page->xlp_tli = ThisTimeLineID;
4060 page->xlp_pageaddr.xlogid = 0;
4061 page->xlp_pageaddr.xrecoff = 0;
4062 longpage = (XLogLongPageHeader) page;
4063 longpage->xlp_sysid = sysidentifier;
4064 longpage->xlp_seg_size = XLogSegSize;
4065 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4067 /* Insert the initial checkpoint record */
4068 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4069 record->xl_prev.xlogid = 0;
4070 record->xl_prev.xrecoff = 0;
4071 record->xl_xid = InvalidTransactionId;
4072 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4073 record->xl_len = sizeof(checkPoint);
4074 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4075 record->xl_rmid = RM_XLOG_ID;
4076 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4079 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4080 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4081 SizeOfXLogRecord - sizeof(pg_crc32));
4083 record->xl_crc = crc;
4085 /* Create first XLOG segment file */
4086 use_existent = false;
4087 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4089 /* Write the first page with the initial record */
4091 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4093 /* if write didn't set errno, assume problem is no disk space */
4097 (errcode_for_file_access(),
4098 errmsg("could not write bootstrap transaction log file: %m")));
4101 if (pg_fsync(openLogFile) != 0)
4103 (errcode_for_file_access(),
4104 errmsg("could not fsync bootstrap transaction log file: %m")));
4106 if (close(openLogFile))
4108 (errcode_for_file_access(),
4109 errmsg("could not close bootstrap transaction log file: %m")));
4113 /* Now create pg_control */
4115 memset(ControlFile, 0, sizeof(ControlFileData));
4116 /* Initialize pg_control status fields */
4117 ControlFile->system_identifier = sysidentifier;
4118 ControlFile->state = DB_SHUTDOWNED;
4119 ControlFile->time = checkPoint.time;
4120 ControlFile->checkPoint = checkPoint.redo;
4121 ControlFile->checkPointCopy = checkPoint;
4122 /* some additional ControlFile fields are set in WriteControlFile() */
4126 /* Bootstrap the commit log, too */
4128 BootStrapSUBTRANS();
4129 BootStrapMultiXact();
4135 str_time(time_t tnow)
4137 static char buf[128];
4139 strftime(buf, sizeof(buf),
4140 "%Y-%m-%d %H:%M:%S %Z",
4147 * See if there is a recovery command file (recovery.conf), and if so
4148 * read in parameters for archive recovery.
4150 * XXX longer term intention is to expand this to
4151 * cater for additional parameters and controls
4152 * possibly use a flex lexer similar to the GUC one
4155 readRecoveryCommandFile(void)
4158 char cmdline[MAXPGPATH];
4159 TimeLineID rtli = 0;
4160 bool rtliGiven = false;
4161 bool syntaxError = false;
4163 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4166 if (errno == ENOENT)
4167 return; /* not there, so no archive recovery */
4169 (errcode_for_file_access(),
4170 errmsg("could not open recovery command file \"%s\": %m",
4171 RECOVERY_COMMAND_FILE)));
4175 (errmsg("starting archive recovery")));
4180 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4182 /* skip leading whitespace and check for # comment */
4187 for (ptr = cmdline; *ptr; ptr++)
4189 if (!isspace((unsigned char) *ptr))
4192 if (*ptr == '\0' || *ptr == '#')
4195 /* identify the quoted parameter value */
4196 tok1 = strtok(ptr, "'");
4202 tok2 = strtok(NULL, "'");
4208 /* reparse to get just the parameter name */
4209 tok1 = strtok(ptr, " \t=");
4216 if (strcmp(tok1, "restore_command") == 0)
4218 recoveryRestoreCommand = pstrdup(tok2);
4220 (errmsg("restore_command = \"%s\"",
4221 recoveryRestoreCommand)));
4223 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4226 if (strcmp(tok2, "latest") == 0)
4231 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4232 if (errno == EINVAL || errno == ERANGE)
4234 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4239 (errmsg("recovery_target_timeline = %u", rtli)));
4242 (errmsg("recovery_target_timeline = latest")));
4244 else if (strcmp(tok1, "recovery_target_xid") == 0)
4247 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4248 if (errno == EINVAL || errno == ERANGE)
4250 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4253 (errmsg("recovery_target_xid = %u",
4254 recoveryTargetXid)));
4255 recoveryTarget = true;
4256 recoveryTargetExact = true;
4258 else if (strcmp(tok1, "recovery_target_time") == 0)
4261 * if recovery_target_xid specified, then this overrides
4262 * recovery_target_time
4264 if (recoveryTargetExact)
4266 recoveryTarget = true;
4267 recoveryTargetExact = false;
4270 * Convert the time string given by the user to the time_t format.
4271 * We use type abstime's input converter because we know abstime
4272 * has the same representation as time_t.
4274 recoveryTargetTime = (time_t)
4275 DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
4276 CStringGetDatum(tok2)));
4278 (errmsg("recovery_target_time = %s",
4279 DatumGetCString(DirectFunctionCall1(abstimeout,
4280 AbsoluteTimeGetDatum((AbsoluteTime) recoveryTargetTime))))));
4282 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4285 * does nothing if a recovery_target is not also set
4287 if (strcmp(tok2, "true") == 0)
4288 recoveryTargetInclusive = true;
4291 recoveryTargetInclusive = false;
4295 (errmsg("recovery_target_inclusive = %s", tok2)));
4299 (errmsg("unrecognized recovery parameter \"%s\"",
4307 (errmsg("syntax error in recovery command file: %s",
4309 errhint("Lines should have the format parameter = 'value'.")));
4311 /* Check that required parameters were supplied */
4312 if (recoveryRestoreCommand == NULL)
4314 (errmsg("recovery command file \"%s\" did not specify restore_command",
4315 RECOVERY_COMMAND_FILE)));
4317 /* Enable fetching from archive recovery area */
4318 InArchiveRecovery = true;
4321 * If user specified recovery_target_timeline, validate it or compute the
4322 * "latest" value. We can't do this until after we've gotten the restore
4323 * command and set InArchiveRecovery, because we need to fetch timeline
4324 * history files from the archive.
4330 /* Timeline 1 does not have a history file, all else should */
4331 if (rtli != 1 && !existsTimeLineHistory(rtli))
4333 (errmsg("recovery_target_timeline %u does not exist",
4335 recoveryTargetTLI = rtli;
4339 /* We start the "latest" search from pg_control's timeline */
4340 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4346 * Exit archive-recovery state
4349 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4351 char recoveryPath[MAXPGPATH];
4352 char xlogpath[MAXPGPATH];
4355 * We are no longer in archive recovery state.
4357 InArchiveRecovery = false;
4360 * We should have the ending log segment currently open. Verify, and then
4361 * close it (to avoid problems on Windows with trying to rename or delete
4364 Assert(readFile >= 0);
4365 Assert(readId == endLogId);
4366 Assert(readSeg == endLogSeg);
4372 * If the segment was fetched from archival storage, we want to replace
4373 * the existing xlog segment (if any) with the archival version. This is
4374 * because whatever is in XLOGDIR is very possibly older than what we have
4375 * from the archives, since it could have come from restoring a PGDATA
4376 * backup. In any case, the archival version certainly is more
4377 * descriptive of what our current database state is, because that is what
4380 * Note that if we are establishing a new timeline, ThisTimeLineID is
4381 * already set to the new value, and so we will create a new file instead
4382 * of overwriting any existing file.
4384 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4385 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4387 if (restoredFromArchive)
4390 (errmsg_internal("moving last restored xlog to \"%s\"",
4392 unlink(xlogpath); /* might or might not exist */
4393 if (rename(recoveryPath, xlogpath) != 0)
4395 (errcode_for_file_access(),
4396 errmsg("could not rename file \"%s\" to \"%s\": %m",
4397 recoveryPath, xlogpath)));
4398 /* XXX might we need to fix permissions on the file? */
4403 * If the latest segment is not archival, but there's still a
4404 * RECOVERYXLOG laying about, get rid of it.
4406 unlink(recoveryPath); /* ignore any error */
4409 * If we are establishing a new timeline, we have to copy data from
4410 * the last WAL segment of the old timeline to create a starting WAL
4411 * segment for the new timeline.
4413 if (endTLI != ThisTimeLineID)
4414 XLogFileCopy(endLogId, endLogSeg,
4415 endTLI, endLogId, endLogSeg);
4419 * Let's just make real sure there are not .ready or .done flags posted
4420 * for the new segment.
4422 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4423 XLogArchiveCleanup(xlogpath);
4425 /* Get rid of any remaining recovered timeline-history file, too */
4426 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4427 unlink(recoveryPath); /* ignore any error */
4430 * Rename the config file out of the way, so that we don't accidentally
4431 * re-enter archive recovery mode in a subsequent crash.
4433 unlink(RECOVERY_COMMAND_DONE);
4434 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4436 (errcode_for_file_access(),
4437 errmsg("could not rename file \"%s\" to \"%s\": %m",
4438 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4441 (errmsg("archive recovery complete")));
4445 * For point-in-time recovery, this function decides whether we want to
4446 * stop applying the XLOG at or after the current record.
4448 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4449 * *includeThis is set TRUE if we should apply this record before stopping.
4450 * Also, some information is saved in recoveryStopXid et al for use in
4451 * annotating the new timeline's history file.
4454 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4460 /* Do we have a PITR target at all? */
4461 if (!recoveryTarget)
4464 /* We only consider stopping at COMMIT or ABORT records */
4465 if (record->xl_rmid != RM_XACT_ID)
4467 record_info = record->xl_info & ~XLR_INFO_MASK;
4468 if (record_info == XLOG_XACT_COMMIT)
4470 xl_xact_commit *recordXactCommitData;
4472 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4473 recordXtime = recordXactCommitData->xtime;
4475 else if (record_info == XLOG_XACT_ABORT)
4477 xl_xact_abort *recordXactAbortData;
4479 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4480 recordXtime = recordXactAbortData->xtime;
4485 if (recoveryTargetExact)
4488 * there can be only one transaction end record with this exact
4491 * when testing for an xid, we MUST test for equality only, since
4492 * transactions are numbered in the order they start, not the order
4493 * they complete. A higher numbered xid will complete before you about
4494 * 50% of the time...
4496 stopsHere = (record->xl_xid == recoveryTargetXid);
4498 *includeThis = recoveryTargetInclusive;
4503 * there can be many transactions that share the same commit time, so
4504 * we stop after the last one, if we are inclusive, or stop at the
4505 * first one if we are exclusive
4507 if (recoveryTargetInclusive)
4508 stopsHere = (recordXtime > recoveryTargetTime);
4510 stopsHere = (recordXtime >= recoveryTargetTime);
4512 *includeThis = false;
4517 recoveryStopXid = record->xl_xid;
4518 recoveryStopTime = recordXtime;
4519 recoveryStopAfter = *includeThis;
4521 if (record_info == XLOG_XACT_COMMIT)
4523 if (recoveryStopAfter)
4525 (errmsg("recovery stopping after commit of transaction %u, time %s",
4526 recoveryStopXid, str_time(recoveryStopTime))));
4529 (errmsg("recovery stopping before commit of transaction %u, time %s",
4530 recoveryStopXid, str_time(recoveryStopTime))));
4534 if (recoveryStopAfter)
4536 (errmsg("recovery stopping after abort of transaction %u, time %s",
4537 recoveryStopXid, str_time(recoveryStopTime))));
4540 (errmsg("recovery stopping before abort of transaction %u, time %s",
4541 recoveryStopXid, str_time(recoveryStopTime))));
4549 * This must be called ONCE during postmaster or standalone-backend startup
4554 XLogCtlInsert *Insert;
4555 CheckPoint checkPoint;
4557 bool needNewTimeLine = false;
4558 bool haveBackupLabel = false;
4568 TransactionId oldestActiveXID;
4571 * Read control file and check XLOG status looks valid.
4573 * Note: in most control paths, *ControlFile is already valid and we need
4574 * not do ReadControlFile() here, but might as well do it to be sure.
4578 if (ControlFile->state < DB_SHUTDOWNED ||
4579 ControlFile->state > DB_IN_PRODUCTION ||
4580 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4582 (errmsg("control file contains invalid data")));
4584 if (ControlFile->state == DB_SHUTDOWNED)
4586 (errmsg("database system was shut down at %s",
4587 str_time(ControlFile->time))));
4588 else if (ControlFile->state == DB_SHUTDOWNING)
4590 (errmsg("database system shutdown was interrupted; last known up at %s",
4591 str_time(ControlFile->time))));
4592 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4594 (errmsg("database system was interrupted while in recovery at %s",
4595 str_time(ControlFile->time)),
4596 errhint("This probably means that some data is corrupted and"
4597 " you will have to use the last backup for recovery.")));
4598 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4600 (errmsg("database system was interrupted while in recovery at log time %s",
4601 str_time(ControlFile->checkPointCopy.time)),
4602 errhint("If this has occurred more than once some data might be corrupted"
4603 " and you might need to choose an earlier recovery target.")));
4604 else if (ControlFile->state == DB_IN_PRODUCTION)
4606 (errmsg("database system was interrupted; last known up at %s",
4607 str_time(ControlFile->time))));
4609 /* This is just to allow attaching to startup process with a debugger */
4610 #ifdef XLOG_REPLAY_DELAY
4611 if (ControlFile->state != DB_SHUTDOWNED)
4612 pg_usleep(60000000L);
4616 * Initialize on the assumption we want to recover to the same timeline
4617 * that's active according to pg_control.
4619 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4622 * Check for recovery control file, and if so set up state for offline
4625 readRecoveryCommandFile();
4627 /* Now we can determine the list of expected TLIs */
4628 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4631 * If pg_control's timeline is not in expectedTLIs, then we cannot
4632 * proceed: the backup is not part of the history of the requested
4635 if (!list_member_int(expectedTLIs,
4636 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4638 (errmsg("requested timeline %u is not a child of database system timeline %u",
4640 ControlFile->checkPointCopy.ThisTimeLineID)));
4642 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4645 * When a backup_label file is present, we want to roll forward from
4646 * the checkpoint it identifies, rather than using pg_control.
4648 record = ReadCheckpointRecord(checkPointLoc, 0);
4652 (errmsg("checkpoint record is at %X/%X",
4653 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4654 InRecovery = true; /* force recovery even if SHUTDOWNED */
4659 (errmsg("could not locate required checkpoint record"),
4660 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4662 /* set flag to delete it later */
4663 haveBackupLabel = true;
4668 * Get the last valid checkpoint record. If the latest one according
4669 * to pg_control is broken, try the next-to-last one.
4671 checkPointLoc = ControlFile->checkPoint;
4672 record = ReadCheckpointRecord(checkPointLoc, 1);
4676 (errmsg("checkpoint record is at %X/%X",
4677 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4681 checkPointLoc = ControlFile->prevCheckPoint;
4682 record = ReadCheckpointRecord(checkPointLoc, 2);
4686 (errmsg("using previous checkpoint record at %X/%X",
4687 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4688 InRecovery = true; /* force recovery even if SHUTDOWNED */
4692 (errmsg("could not locate a valid checkpoint record")));
4696 LastRec = RecPtr = checkPointLoc;
4697 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4698 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4701 (errmsg("redo record is at %X/%X; undo record is at %X/%X; shutdown %s",
4702 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4703 checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
4704 wasShutdown ? "TRUE" : "FALSE")));
4706 (errmsg("next transaction ID: %u/%u; next OID: %u",
4707 checkPoint.nextXidEpoch, checkPoint.nextXid,
4708 checkPoint.nextOid)));
4710 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4711 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4712 if (!TransactionIdIsNormal(checkPoint.nextXid))
4714 (errmsg("invalid next transaction ID")));
4716 ShmemVariableCache->nextXid = checkPoint.nextXid;
4717 ShmemVariableCache->nextOid = checkPoint.nextOid;
4718 ShmemVariableCache->oidCount = 0;
4719 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4722 * We must replay WAL entries using the same TimeLineID they were created
4723 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4724 * also xlog_redo()).
4726 ThisTimeLineID = checkPoint.ThisTimeLineID;
4728 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4730 if (XLByteLT(RecPtr, checkPoint.redo))
4732 (errmsg("invalid redo in checkpoint record")));
4733 if (checkPoint.undo.xrecoff == 0)
4734 checkPoint.undo = RecPtr;
4737 * Check whether we need to force recovery from WAL. If it appears to
4738 * have been a clean shutdown and we did not have a recovery.conf file,
4739 * then assume no recovery needed.
4741 if (XLByteLT(checkPoint.undo, RecPtr) ||
4742 XLByteLT(checkPoint.redo, RecPtr))
4746 (errmsg("invalid redo/undo record in shutdown checkpoint")));
4749 else if (ControlFile->state != DB_SHUTDOWNED)
4751 else if (InArchiveRecovery)
4753 /* force recovery due to presence of recovery.conf */
4763 * Update pg_control to show that we are recovering and to show the
4764 * selected checkpoint as the place we are starting from. We also mark
4765 * pg_control with any minimum recovery stop point obtained from a
4766 * backup history file.
4768 if (InArchiveRecovery)
4771 (errmsg("automatic recovery in progress")));
4772 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4777 (errmsg("database system was not properly shut down; "
4778 "automatic recovery in progress")));
4779 ControlFile->state = DB_IN_CRASH_RECOVERY;
4781 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4782 ControlFile->checkPoint = checkPointLoc;
4783 ControlFile->checkPointCopy = checkPoint;
4784 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4785 ControlFile->minRecoveryPoint = minRecoveryLoc;
4786 ControlFile->time = time(NULL);
4787 UpdateControlFile();
4790 * If there was a backup label file, it's done its job and the info
4791 * has now been propagated into pg_control. We must get rid of the
4792 * label file so that if we crash during recovery, we'll pick up at
4793 * the latest recovery restartpoint instead of going all the way back
4794 * to the backup start point. It seems prudent though to just rename
4795 * the file out of the way rather than delete it completely.
4797 if (haveBackupLabel)
4799 unlink(BACKUP_LABEL_OLD);
4800 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4802 (errcode_for_file_access(),
4803 errmsg("could not rename file \"%s\" to \"%s\": %m",
4804 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4807 /* Start up the recovery environment */
4808 XLogInitRelationCache();
4810 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4812 if (RmgrTable[rmid].rm_startup != NULL)
4813 RmgrTable[rmid].rm_startup();
4817 * Find the first record that logically follows the checkpoint --- it
4818 * might physically precede it, though.
4820 if (XLByteLT(checkPoint.redo, RecPtr))
4822 /* back up to find the record */
4823 record = ReadRecord(&(checkPoint.redo), PANIC);
4827 /* just have to read next record after CheckPoint */
4828 record = ReadRecord(NULL, LOG);
4833 bool recoveryContinue = true;
4834 bool recoveryApply = true;
4835 ErrorContextCallback errcontext;
4839 (errmsg("redo starts at %X/%X",
4840 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4843 * main redo apply loop
4852 initStringInfo(&buf);
4853 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4854 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4855 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4856 xlog_outrec(&buf, record);
4857 appendStringInfo(&buf, " - ");
4858 RmgrTable[record->xl_rmid].rm_desc(&buf,
4860 XLogRecGetData(record));
4861 elog(LOG, "%s", buf.data);
4867 * Have we reached our recovery target?
4869 if (recoveryStopsHere(record, &recoveryApply))
4871 needNewTimeLine = true; /* see below */
4872 recoveryContinue = false;
4877 /* Setup error traceback support for ereport() */
4878 errcontext.callback = rm_redo_error_callback;
4879 errcontext.arg = (void *) record;
4880 errcontext.previous = error_context_stack;
4881 error_context_stack = &errcontext;
4883 /* nextXid must be beyond record's xid */
4884 if (TransactionIdFollowsOrEquals(record->xl_xid,
4885 ShmemVariableCache->nextXid))
4887 ShmemVariableCache->nextXid = record->xl_xid;
4888 TransactionIdAdvance(ShmemVariableCache->nextXid);
4891 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4892 RestoreBkpBlocks(record, EndRecPtr);
4894 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4896 /* Pop the error context stack */
4897 error_context_stack = errcontext.previous;
4899 LastRec = ReadRecPtr;
4901 record = ReadRecord(NULL, LOG);
4902 } while (record != NULL && recoveryContinue);
4905 * end of main redo apply loop
4909 (errmsg("redo done at %X/%X",
4910 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4915 /* there are no WAL records following the checkpoint */
4917 (errmsg("redo is not required")));
4922 * Re-fetch the last valid or last applied record, so we can identify the
4923 * exact endpoint of what we consider the valid portion of WAL.
4925 record = ReadRecord(&LastRec, PANIC);
4926 EndOfLog = EndRecPtr;
4927 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4930 * Complain if we did not roll forward far enough to render the backup
4933 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
4935 if (needNewTimeLine) /* stopped because of stop request */
4937 (errmsg("requested recovery stop point is before end time of backup dump")));
4939 /* ran off end of WAL */
4941 (errmsg("WAL ends before end time of backup dump")));
4945 * Consider whether we need to assign a new timeline ID.
4947 * If we stopped short of the end of WAL during recovery, then we are
4948 * generating a new timeline and must assign it a unique new ID.
4949 * Otherwise, we can just extend the timeline we were in when we ran out
4952 if (needNewTimeLine)
4954 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
4956 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
4957 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
4958 curFileTLI, endLogId, endLogSeg);
4961 /* Save the selected TimeLineID in shared memory, too */
4962 XLogCtl->ThisTimeLineID = ThisTimeLineID;
4965 * We are now done reading the old WAL. Turn off archive fetching if it
4966 * was active, and make a writable copy of the last WAL segment. (Note
4967 * that we also have a copy of the last block of the old WAL in readBuf;
4968 * we will use that below.)
4970 if (InArchiveRecovery)
4971 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
4974 * Prepare to write WAL starting at EndOfLog position, and init xlog
4975 * buffer cache using the block containing the last record from the
4976 * previous incarnation.
4978 openLogId = endLogId;
4979 openLogSeg = endLogSeg;
4980 openLogFile = XLogFileOpen(openLogId, openLogSeg);
4982 Insert = &XLogCtl->Insert;
4983 Insert->PrevRecord = LastRec;
4984 XLogCtl->xlblocks[0].xlogid = openLogId;
4985 XLogCtl->xlblocks[0].xrecoff =
4986 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
4989 * Tricky point here: readBuf contains the *last* block that the LastRec
4990 * record spans, not the one it starts in. The last block is indeed the
4991 * one we want to use.
4993 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
4994 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
4995 Insert->currpos = (char *) Insert->currpage +
4996 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
4998 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5000 XLogCtl->Write.LogwrtResult = LogwrtResult;
5001 Insert->LogwrtResult = LogwrtResult;
5002 XLogCtl->LogwrtResult = LogwrtResult;
5004 XLogCtl->LogwrtRqst.Write = EndOfLog;
5005 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5007 freespace = INSERT_FREESPACE(Insert);
5010 /* Make sure rest of page is zero */
5011 MemSet(Insert->currpos, 0, freespace);
5012 XLogCtl->Write.curridx = 0;
5017 * Whenever Write.LogwrtResult points to exactly the end of a page,
5018 * Write.curridx must point to the *next* page (see XLogWrite()).
5020 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5021 * this is sufficient. The first actual attempt to insert a log
5022 * record will advance the insert state.
5024 XLogCtl->Write.curridx = NextBufIdx(0);
5027 /* Pre-scan prepared transactions to find out the range of XIDs present */
5028 oldestActiveXID = PrescanPreparedTransactions();
5035 * Allow resource managers to do any required cleanup.
5037 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5039 if (RmgrTable[rmid].rm_cleanup != NULL)
5040 RmgrTable[rmid].rm_cleanup();
5044 * Check to see if the XLOG sequence contained any unresolved
5045 * references to uninitialized pages.
5047 XLogCheckInvalidPages();
5050 * Reset pgstat data, because it may be invalid after recovery.
5055 * Perform a checkpoint to update all our recovery activity to disk.
5057 * Note that we write a shutdown checkpoint rather than an on-line
5058 * one. This is not particularly critical, but since we may be
5059 * assigning a new TLI, using a shutdown checkpoint allows us to have
5060 * the rule that TLI only changes in shutdown checkpoints, which
5061 * allows some extra error checking in xlog_redo.
5063 CreateCheckPoint(true, true);
5066 * Close down recovery environment
5068 XLogCloseRelationCache();
5072 * Preallocate additional log files, if wanted.
5074 (void) PreallocXlogFiles(EndOfLog);
5077 * Okay, we're officially UP.
5081 ControlFile->state = DB_IN_PRODUCTION;
5082 ControlFile->time = time(NULL);
5083 UpdateControlFile();
5085 /* start the archive_timeout timer running */
5086 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5088 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5089 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5090 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5092 /* Start up the commit log and related stuff, too */
5094 StartupSUBTRANS(oldestActiveXID);
5097 /* Reload shared-memory state for prepared transactions */
5098 RecoverPreparedTransactions();
5100 /* Shut down readFile facility, free space */
5113 free(readRecordBuf);
5114 readRecordBuf = NULL;
5115 readRecordBufSize = 0;
5120 * Subroutine to try to fetch and validate a prior checkpoint record.
5122 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5123 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5126 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5130 if (!XRecOffIsValid(RecPtr.xrecoff))
5136 (errmsg("invalid primary checkpoint link in control file")));
5140 (errmsg("invalid secondary checkpoint link in control file")));
5144 (errmsg("invalid checkpoint link in backup_label file")));
5150 record = ReadRecord(&RecPtr, LOG);
5158 (errmsg("invalid primary checkpoint record")));
5162 (errmsg("invalid secondary checkpoint record")));
5166 (errmsg("invalid checkpoint record")));
5171 if (record->xl_rmid != RM_XLOG_ID)
5177 (errmsg("invalid resource manager ID in primary checkpoint record")));
5181 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5185 (errmsg("invalid resource manager ID in checkpoint record")));
5190 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5191 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5197 (errmsg("invalid xl_info in primary checkpoint record")));
5201 (errmsg("invalid xl_info in secondary checkpoint record")));
5205 (errmsg("invalid xl_info in checkpoint record")));
5210 if (record->xl_len != sizeof(CheckPoint) ||
5211 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5217 (errmsg("invalid length of primary checkpoint record")));
5221 (errmsg("invalid length of secondary checkpoint record")));
5225 (errmsg("invalid length of checkpoint record")));
5234 * This must be called during startup of a backend process, except that
5235 * it need not be called in a standalone backend (which does StartupXLOG
5236 * instead). We need to initialize the local copies of ThisTimeLineID and
5239 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5240 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5241 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5244 InitXLOGAccess(void)
5246 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5247 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5248 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5249 (void) GetRedoRecPtr();
5253 * Once spawned, a backend may update its local RedoRecPtr from
5254 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5255 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5260 /* use volatile pointer to prevent code rearrangement */
5261 volatile XLogCtlData *xlogctl = XLogCtl;
5263 SpinLockAcquire(&xlogctl->info_lck);
5264 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5265 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5266 SpinLockRelease(&xlogctl->info_lck);
5272 * Get the time of the last xlog segment switch
5275 GetLastSegSwitchTime(void)
5279 /* Need WALWriteLock, but shared lock is sufficient */
5280 LWLockAcquire(WALWriteLock, LW_SHARED);
5281 result = XLogCtl->Write.lastSegSwitchTime;
5282 LWLockRelease(WALWriteLock);
5288 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5290 * This is exported for use by code that would like to have 64-bit XIDs.
5291 * We don't really support such things, but all XIDs within the system
5292 * can be presumed "close to" the result, and thus the epoch associated
5293 * with them can be determined.
5296 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5298 uint32 ckptXidEpoch;
5299 TransactionId ckptXid;
5300 TransactionId nextXid;
5302 /* Must read checkpoint info first, else have race condition */
5304 /* use volatile pointer to prevent code rearrangement */
5305 volatile XLogCtlData *xlogctl = XLogCtl;
5307 SpinLockAcquire(&xlogctl->info_lck);
5308 ckptXidEpoch = xlogctl->ckptXidEpoch;
5309 ckptXid = xlogctl->ckptXid;
5310 SpinLockRelease(&xlogctl->info_lck);
5313 /* Now fetch current nextXid */
5314 nextXid = ReadNewTransactionId();
5317 * nextXid is certainly logically later than ckptXid. So if it's
5318 * numerically less, it must have wrapped into the next epoch.
5320 if (nextXid < ckptXid)
5324 *epoch = ckptXidEpoch;
5328 * This must be called ONCE during postmaster or standalone-backend shutdown
5331 ShutdownXLOG(int code, Datum arg)
5334 (errmsg("shutting down")));
5336 CreateCheckPoint(true, true);
5339 ShutdownMultiXact();
5342 (errmsg("database system is shut down")));
5346 * Perform a checkpoint --- either during shutdown, or on-the-fly
5348 * If force is true, we force a checkpoint regardless of whether any XLOG
5349 * activity has occurred since the last one.
5352 CreateCheckPoint(bool shutdown, bool force)
5354 CheckPoint checkPoint;
5356 XLogCtlInsert *Insert = &XLogCtl->Insert;
5362 int nsegsremoved = 0;
5363 int nsegsrecycled = 0;
5366 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5367 * (This is just pro forma, since in the present system structure there is
5368 * only one process that is allowed to issue checkpoints at any given
5371 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5374 * Use a critical section to force system panic if we have trouble.
5376 START_CRIT_SECTION();
5380 ControlFile->state = DB_SHUTDOWNING;
5381 ControlFile->time = time(NULL);
5382 UpdateControlFile();
5385 MemSet(&checkPoint, 0, sizeof(checkPoint));
5386 checkPoint.ThisTimeLineID = ThisTimeLineID;
5387 checkPoint.time = time(NULL);
5390 * We must hold CheckpointStartLock while determining the checkpoint REDO
5391 * pointer. This ensures that any concurrent transaction commits will be
5392 * either not yet logged, or logged and recorded in pg_clog. See notes in
5393 * RecordTransactionCommit().
5395 LWLockAcquire(CheckpointStartLock, LW_EXCLUSIVE);
5397 /* And we need WALInsertLock too */
5398 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5401 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5402 * any XLOG records since the start of the last checkpoint, skip the
5403 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5404 * when the system is idle. That wastes log space, and more importantly it
5405 * exposes us to possible loss of both current and previous checkpoint
5406 * records if the machine crashes just as we're writing the update.
5407 * (Perhaps it'd make even more sense to checkpoint only when the previous
5408 * checkpoint record is in a different xlog page?)
5410 * We have to make two tests to determine that nothing has happened since
5411 * the start of the last checkpoint: current insertion point must match
5412 * the end of the last checkpoint record, and its redo pointer must point
5415 if (!shutdown && !force)
5417 XLogRecPtr curInsert;
5419 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5420 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5421 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5422 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5423 ControlFile->checkPoint.xlogid ==
5424 ControlFile->checkPointCopy.redo.xlogid &&
5425 ControlFile->checkPoint.xrecoff ==
5426 ControlFile->checkPointCopy.redo.xrecoff)
5428 LWLockRelease(WALInsertLock);
5429 LWLockRelease(CheckpointStartLock);
5430 LWLockRelease(CheckpointLock);
5437 * Compute new REDO record ptr = location of next XLOG record.
5439 * NB: this is NOT necessarily where the checkpoint record itself will be,
5440 * since other backends may insert more XLOG records while we're off doing
5441 * the buffer flush work. Those XLOG records are logically after the
5442 * checkpoint, even though physically before it. Got that?
5444 freespace = INSERT_FREESPACE(Insert);
5445 if (freespace < SizeOfXLogRecord)
5447 (void) AdvanceXLInsertBuffer(false);
5448 /* OK to ignore update return flag, since we will do flush anyway */
5449 freespace = INSERT_FREESPACE(Insert);
5451 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5454 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5455 * must be done while holding the insert lock AND the info_lck.
5457 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5458 * pointing past where it really needs to point. This is okay; the only
5459 * consequence is that XLogInsert might back up whole buffers that it
5460 * didn't really need to. We can't postpone advancing RedoRecPtr because
5461 * XLogInserts that happen while we are dumping buffers must assume that
5462 * their buffer changes are not included in the checkpoint.
5465 /* use volatile pointer to prevent code rearrangement */
5466 volatile XLogCtlData *xlogctl = XLogCtl;
5468 SpinLockAcquire(&xlogctl->info_lck);
5469 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5470 SpinLockRelease(&xlogctl->info_lck);
5474 * Now we can release insert lock and checkpoint start lock, allowing
5475 * other xacts to proceed even while we are flushing disk buffers.
5477 LWLockRelease(WALInsertLock);
5479 LWLockRelease(CheckpointStartLock);
5483 (errmsg("checkpoint starting")));
5486 * Get the other info we need for the checkpoint record.
5488 LWLockAcquire(XidGenLock, LW_SHARED);
5489 checkPoint.nextXid = ShmemVariableCache->nextXid;
5490 LWLockRelease(XidGenLock);
5492 /* Increase XID epoch if we've wrapped around since last checkpoint */
5493 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5494 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5495 checkPoint.nextXidEpoch++;
5497 LWLockAcquire(OidGenLock, LW_SHARED);
5498 checkPoint.nextOid = ShmemVariableCache->nextOid;
5500 checkPoint.nextOid += ShmemVariableCache->oidCount;
5501 LWLockRelease(OidGenLock);
5503 MultiXactGetCheckptMulti(shutdown,
5504 &checkPoint.nextMulti,
5505 &checkPoint.nextMultiOffset);
5508 * Having constructed the checkpoint record, ensure all shmem disk buffers
5509 * and commit-log buffers are flushed to disk.
5511 * This I/O could fail for various reasons. If so, we will fail to
5512 * complete the checkpoint, but there is no reason to force a system
5513 * panic. Accordingly, exit critical section while doing it.
5517 CheckPointGuts(checkPoint.redo);
5519 START_CRIT_SECTION();
5522 * Now insert the checkpoint record into XLOG.
5524 rdata.data = (char *) (&checkPoint);
5525 rdata.len = sizeof(checkPoint);
5526 rdata.buffer = InvalidBuffer;
5529 recptr = XLogInsert(RM_XLOG_ID,
5530 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5531 XLOG_CHECKPOINT_ONLINE,
5537 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5538 * = end of actual checkpoint record.
5540 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5542 (errmsg("concurrent transaction log activity while database system is shutting down")));
5545 * Select point at which we can truncate the log, which we base on the
5546 * prior checkpoint's earliest info.
5548 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5551 * Update the control file.
5553 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5555 ControlFile->state = DB_SHUTDOWNED;
5556 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5557 ControlFile->checkPoint = ProcLastRecPtr;
5558 ControlFile->checkPointCopy = checkPoint;
5559 ControlFile->time = time(NULL);
5560 UpdateControlFile();
5561 LWLockRelease(ControlFileLock);
5563 /* Update shared-memory copy of checkpoint XID/epoch */
5565 /* use volatile pointer to prevent code rearrangement */
5566 volatile XLogCtlData *xlogctl = XLogCtl;
5568 SpinLockAcquire(&xlogctl->info_lck);
5569 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5570 xlogctl->ckptXid = checkPoint.nextXid;
5571 SpinLockRelease(&xlogctl->info_lck);
5575 * We are now done with critical updates; no need for system panic if we
5576 * have trouble while fooling with offline log segments.
5581 * Delete offline log files (those no longer needed even for previous
5584 if (_logId || _logSeg)
5586 PrevLogSeg(_logId, _logSeg);
5587 MoveOfflineLogs(_logId, _logSeg, recptr,
5588 &nsegsremoved, &nsegsrecycled);
5592 * Make more log segments if needed. (Do this after deleting offline log
5593 * segments, to avoid having peak disk space usage higher than necessary.)
5596 nsegsadded = PreallocXlogFiles(recptr);
5599 * Truncate pg_subtrans if possible. We can throw away all data before
5600 * the oldest XMIN of any running transaction. No future transaction will
5601 * attempt to reference any pg_subtrans entry older than that (see Asserts
5602 * in subtrans.c). During recovery, though, we mustn't do this because
5603 * StartupSUBTRANS hasn't been called yet.
5606 TruncateSUBTRANS(GetOldestXmin(true, false));
5610 (errmsg("checkpoint complete; %d transaction log file(s) added, %d removed, %d recycled",
5611 nsegsadded, nsegsremoved, nsegsrecycled)));
5613 LWLockRelease(CheckpointLock);
5617 * Flush all data in shared memory to disk, and fsync
5619 * This is the common code shared between regular checkpoints and
5620 * recovery restartpoints.
5623 CheckPointGuts(XLogRecPtr checkPointRedo)
5626 CheckPointSUBTRANS();
5627 CheckPointMultiXact();
5628 FlushBufferPool(); /* performs all required fsyncs */
5629 /* We deliberately delay 2PC checkpointing as long as possible */
5630 CheckPointTwoPhase(checkPointRedo);
5634 * Set a recovery restart point if appropriate
5636 * This is similar to CreateCheckpoint, but is used during WAL recovery
5637 * to establish a point from which recovery can roll forward without
5638 * replaying the entire recovery log. This function is called each time
5639 * a checkpoint record is read from XLOG; it must determine whether a
5640 * restartpoint is needed or not.
5643 RecoveryRestartPoint(const CheckPoint *checkPoint)
5649 * Do nothing if the elapsed time since the last restartpoint is less than
5650 * half of checkpoint_timeout. (We use a value less than
5651 * checkpoint_timeout so that variations in the timing of checkpoints on
5652 * the master, or speed of transmission of WAL segments to a slave, won't
5653 * make the slave skip a restartpoint once it's synced with the master.)
5654 * Checking true elapsed time keeps us from doing restartpoints too often
5655 * while rapidly scanning large amounts of WAL.
5657 elapsed_secs = time(NULL) - ControlFile->time;
5658 if (elapsed_secs < CheckPointTimeout / 2)
5662 * Is it safe to checkpoint? We must ask each of the resource managers
5663 * whether they have any partial state information that might prevent a
5664 * correct restart from this point. If so, we skip this opportunity, but
5665 * return at the next checkpoint record for another try.
5667 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5669 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5670 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5675 * OK, force data out to disk
5677 CheckPointGuts(checkPoint->redo);
5680 * Update pg_control so that any subsequent crash will restart from this
5681 * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
5684 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5685 ControlFile->checkPoint = ReadRecPtr;
5686 ControlFile->checkPointCopy = *checkPoint;
5687 ControlFile->time = time(NULL);
5688 UpdateControlFile();
5691 (errmsg("recovery restart point at %X/%X",
5692 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5696 * Write a NEXTOID log record
5699 XLogPutNextOid(Oid nextOid)
5703 rdata.data = (char *) (&nextOid);
5704 rdata.len = sizeof(Oid);
5705 rdata.buffer = InvalidBuffer;
5707 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5710 * We need not flush the NEXTOID record immediately, because any of the
5711 * just-allocated OIDs could only reach disk as part of a tuple insert or
5712 * update that would have its own XLOG record that must follow the NEXTOID
5713 * record. Therefore, the standard buffer LSN interlock applied to those
5714 * records will ensure no such OID reaches disk before the NEXTOID record
5717 * Note, however, that the above statement only covers state "within" the
5718 * database. When we use a generated OID as a file or directory name,
5719 * we are in a sense violating the basic WAL rule, because that filesystem
5720 * change may reach disk before the NEXTOID WAL record does. The impact
5721 * of this is that if a database crash occurs immediately afterward,
5722 * we might after restart re-generate the same OID and find that it
5723 * conflicts with the leftover file or directory. But since for safety's
5724 * sake we always loop until finding a nonconflicting filename, this poses
5725 * no real problem in practice. See pgsql-hackers discussion 27-Sep-2006.
5730 * Write an XLOG SWITCH record.
5732 * Here we just blindly issue an XLogInsert request for the record.
5733 * All the magic happens inside XLogInsert.
5735 * The return value is either the end+1 address of the switch record,
5736 * or the end+1 address of the prior segment if we did not need to
5737 * write a switch record because we are already at segment start.
5740 RequestXLogSwitch(void)
5745 /* XLOG SWITCH, alone among xlog record types, has no data */
5746 rdata.buffer = InvalidBuffer;
5751 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5757 * XLOG resource manager's routines
5760 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5762 uint8 info = record->xl_info & ~XLR_INFO_MASK;
5764 if (info == XLOG_NEXTOID)
5768 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5769 if (ShmemVariableCache->nextOid < nextOid)
5771 ShmemVariableCache->nextOid = nextOid;
5772 ShmemVariableCache->oidCount = 0;
5775 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5777 CheckPoint checkPoint;
5779 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5780 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5781 ShmemVariableCache->nextXid = checkPoint.nextXid;
5782 ShmemVariableCache->nextOid = checkPoint.nextOid;
5783 ShmemVariableCache->oidCount = 0;
5784 MultiXactSetNextMXact(checkPoint.nextMulti,
5785 checkPoint.nextMultiOffset);
5787 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5788 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5789 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5792 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
5794 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5796 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5797 !list_member_int(expectedTLIs,
5798 (int) checkPoint.ThisTimeLineID))
5800 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5801 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5802 /* Following WAL records should be run with new TLI */
5803 ThisTimeLineID = checkPoint.ThisTimeLineID;
5806 RecoveryRestartPoint(&checkPoint);
5808 else if (info == XLOG_CHECKPOINT_ONLINE)
5810 CheckPoint checkPoint;
5812 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5813 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5814 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5815 checkPoint.nextXid))
5816 ShmemVariableCache->nextXid = checkPoint.nextXid;
5817 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5819 ShmemVariableCache->nextOid = checkPoint.nextOid;
5820 ShmemVariableCache->oidCount = 0;
5822 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
5823 checkPoint.nextMultiOffset);
5825 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5826 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5827 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5829 /* TLI should not change in an on-line checkpoint */
5830 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5832 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5833 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5835 RecoveryRestartPoint(&checkPoint);
5837 else if (info == XLOG_SWITCH)
5839 /* nothing to do here */
5844 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
5846 uint8 info = xl_info & ~XLR_INFO_MASK;
5848 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5849 info == XLOG_CHECKPOINT_ONLINE)
5851 CheckPoint *checkpoint = (CheckPoint *) rec;
5853 appendStringInfo(buf, "checkpoint: redo %X/%X; undo %X/%X; "
5854 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
5855 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5856 checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
5857 checkpoint->ThisTimeLineID,
5858 checkpoint->nextXidEpoch, checkpoint->nextXid,
5859 checkpoint->nextOid,
5860 checkpoint->nextMulti,
5861 checkpoint->nextMultiOffset,
5862 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
5864 else if (info == XLOG_NEXTOID)
5868 memcpy(&nextOid, rec, sizeof(Oid));
5869 appendStringInfo(buf, "nextOid: %u", nextOid);
5871 else if (info == XLOG_SWITCH)
5873 appendStringInfo(buf, "xlog switch");
5876 appendStringInfo(buf, "UNKNOWN");
5882 xlog_outrec(StringInfo buf, XLogRecord *record)
5886 appendStringInfo(buf, "prev %X/%X; xid %u",
5887 record->xl_prev.xlogid, record->xl_prev.xrecoff,
5890 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
5892 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
5893 appendStringInfo(buf, "; bkpb%d", i + 1);
5896 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
5898 #endif /* WAL_DEBUG */
5905 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
5907 int new_sync_method;
5910 if (pg_strcasecmp(method, "fsync") == 0)
5912 new_sync_method = SYNC_METHOD_FSYNC;
5915 #ifdef HAVE_FSYNC_WRITETHROUGH
5916 else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
5918 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
5922 #ifdef HAVE_FDATASYNC
5923 else if (pg_strcasecmp(method, "fdatasync") == 0)
5925 new_sync_method = SYNC_METHOD_FDATASYNC;
5929 #ifdef OPEN_SYNC_FLAG
5930 else if (pg_strcasecmp(method, "open_sync") == 0)
5932 new_sync_method = SYNC_METHOD_OPEN;
5933 new_sync_bit = OPEN_SYNC_FLAG;
5936 #ifdef OPEN_DATASYNC_FLAG
5937 else if (pg_strcasecmp(method, "open_datasync") == 0)
5939 new_sync_method = SYNC_METHOD_OPEN;
5940 new_sync_bit = OPEN_DATASYNC_FLAG;
5949 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
5952 * To ensure that no blocks escape unsynced, force an fsync on the
5953 * currently open log segment (if any). Also, if the open flag is
5954 * changing, close the log file so it will be reopened (with new flag
5957 if (openLogFile >= 0)
5959 if (pg_fsync(openLogFile) != 0)
5961 (errcode_for_file_access(),
5962 errmsg("could not fsync log file %u, segment %u: %m",
5963 openLogId, openLogSeg)));
5964 if (open_sync_bit != new_sync_bit)
5967 sync_method = new_sync_method;
5968 open_sync_bit = new_sync_bit;
5976 * Issue appropriate kind of fsync (if any) on the current XLOG output file
5979 issue_xlog_fsync(void)
5981 switch (sync_method)
5983 case SYNC_METHOD_FSYNC:
5984 if (pg_fsync_no_writethrough(openLogFile) != 0)
5986 (errcode_for_file_access(),
5987 errmsg("could not fsync log file %u, segment %u: %m",
5988 openLogId, openLogSeg)));
5990 #ifdef HAVE_FSYNC_WRITETHROUGH
5991 case SYNC_METHOD_FSYNC_WRITETHROUGH:
5992 if (pg_fsync_writethrough(openLogFile) != 0)
5994 (errcode_for_file_access(),
5995 errmsg("could not fsync write-through log file %u, segment %u: %m",
5996 openLogId, openLogSeg)));
5999 #ifdef HAVE_FDATASYNC
6000 case SYNC_METHOD_FDATASYNC:
6001 if (pg_fdatasync(openLogFile) != 0)
6003 (errcode_for_file_access(),
6004 errmsg("could not fdatasync log file %u, segment %u: %m",
6005 openLogId, openLogSeg)));
6008 case SYNC_METHOD_OPEN:
6009 /* write synced it already */
6012 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6019 * pg_start_backup: set up for taking an on-line backup dump
6021 * Essentially what this does is to create a backup label file in $PGDATA,
6022 * where it will be archived as part of the backup dump. The label file
6023 * contains the user-supplied label string (typically this would be used
6024 * to tell where the backup dump will be stored) and the starting time and
6025 * starting WAL location for the dump.
6028 pg_start_backup(PG_FUNCTION_ARGS)
6030 text *backupid = PG_GETARG_TEXT_P(0);
6033 XLogRecPtr checkpointloc;
6034 XLogRecPtr startpoint;
6037 char xlogfilename[MAXFNAMELEN];
6040 struct stat stat_buf;
6045 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6046 (errmsg("must be superuser to run a backup"))));
6048 if (!XLogArchivingActive())
6050 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6051 (errmsg("WAL archiving is not active"),
6052 (errhint("archive_command must be defined before "
6053 "online backups can be made safely.")))));
6055 backupidstr = DatumGetCString(DirectFunctionCall1(textout,
6056 PointerGetDatum(backupid)));
6059 * Mark backup active in shared memory. We must do full-page WAL writes
6060 * during an on-line backup even if not doing so at other times, because
6061 * it's quite possible for the backup dump to obtain a "torn" (partially
6062 * written) copy of a database page if it reads the page concurrently with
6063 * our write to the same page. This can be fixed as long as the first
6064 * write to the page in the WAL sequence is a full-page write. Hence, we
6065 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6066 * are no dirty pages in shared memory that might get dumped while the
6067 * backup is in progress without having a corresponding WAL record. (Once
6068 * the backup is complete, we need not force full-page writes anymore,
6069 * since we expect that any pages not modified during the backup interval
6070 * must have been correctly captured by the backup.)
6072 * We must hold WALInsertLock to change the value of forcePageWrites, to
6073 * ensure adequate interlocking against XLogInsert().
6075 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6076 if (XLogCtl->Insert.forcePageWrites)
6078 LWLockRelease(WALInsertLock);
6080 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6081 errmsg("a backup is already in progress"),
6082 errhint("Run pg_stop_backup() and try again.")));
6084 XLogCtl->Insert.forcePageWrites = true;
6085 LWLockRelease(WALInsertLock);
6087 /* Use a TRY block to ensure we release forcePageWrites if fail below */
6091 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6092 * page problems, this guarantees that two successive backup runs will
6093 * have different checkpoint positions and hence different history
6094 * file names, even if nothing happened in between.
6096 RequestCheckpoint(true, false);
6099 * Now we need to fetch the checkpoint record location, and also its
6100 * REDO pointer. The oldest point in WAL that would be needed to
6101 * restore starting from the checkpoint is precisely the REDO pointer.
6103 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6104 checkpointloc = ControlFile->checkPoint;
6105 startpoint = ControlFile->checkPointCopy.redo;
6106 LWLockRelease(ControlFileLock);
6108 XLByteToSeg(startpoint, _logId, _logSeg);
6109 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6112 * We deliberately use strftime/localtime not the src/timezone
6113 * functions, so that backup labels will consistently be recorded in
6114 * the same timezone regardless of TimeZone setting. This matches
6115 * elog.c's practice.
6117 stamp_time = time(NULL);
6118 strftime(strfbuf, sizeof(strfbuf),
6119 "%Y-%m-%d %H:%M:%S %Z",
6120 localtime(&stamp_time));
6123 * Check for existing backup label --- implies a backup is already
6124 * running. (XXX given that we checked forcePageWrites above, maybe
6125 * it would be OK to just unlink any such label file?)
6127 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6129 if (errno != ENOENT)
6131 (errcode_for_file_access(),
6132 errmsg("could not stat file \"%s\": %m",
6133 BACKUP_LABEL_FILE)));
6137 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6138 errmsg("a backup is already in progress"),
6139 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6140 BACKUP_LABEL_FILE)));
6143 * Okay, write the file
6145 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6148 (errcode_for_file_access(),
6149 errmsg("could not create file \"%s\": %m",
6150 BACKUP_LABEL_FILE)));
6151 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6152 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6153 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6154 checkpointloc.xlogid, checkpointloc.xrecoff);
6155 fprintf(fp, "START TIME: %s\n", strfbuf);
6156 fprintf(fp, "LABEL: %s\n", backupidstr);
6157 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6159 (errcode_for_file_access(),
6160 errmsg("could not write file \"%s\": %m",
6161 BACKUP_LABEL_FILE)));
6165 /* Turn off forcePageWrites on failure */
6166 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6167 XLogCtl->Insert.forcePageWrites = false;
6168 LWLockRelease(WALInsertLock);
6175 * We're done. As a convenience, return the starting WAL location.
6177 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6178 startpoint.xlogid, startpoint.xrecoff);
6179 result = DatumGetTextP(DirectFunctionCall1(textin,
6180 CStringGetDatum(xlogfilename)));
6181 PG_RETURN_TEXT_P(result);
6185 * pg_stop_backup: finish taking an on-line backup dump
6187 * We remove the backup label file created by pg_start_backup, and instead
6188 * create a backup history file in pg_xlog (whence it will immediately be
6189 * archived). The backup history file contains the same info found in
6190 * the label file, plus the backup-end time and WAL location.
6193 pg_stop_backup(PG_FUNCTION_ARGS)
6196 XLogRecPtr startpoint;
6197 XLogRecPtr stoppoint;
6200 char histfilepath[MAXPGPATH];
6201 char startxlogfilename[MAXFNAMELEN];
6202 char stopxlogfilename[MAXFNAMELEN];
6212 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6213 (errmsg("must be superuser to run a backup"))));
6216 * OK to clear forcePageWrites
6218 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6219 XLogCtl->Insert.forcePageWrites = false;
6220 LWLockRelease(WALInsertLock);
6223 * Force a switch to a new xlog segment file, so that the backup is valid
6224 * as soon as archiver moves out the current segment file. We'll report
6225 * the end address of the XLOG SWITCH record as the backup stopping point.
6227 stoppoint = RequestXLogSwitch();
6229 XLByteToSeg(stoppoint, _logId, _logSeg);
6230 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
6233 * We deliberately use strftime/localtime not the src/timezone functions,
6234 * so that backup labels will consistently be recorded in the same
6235 * timezone regardless of TimeZone setting. This matches elog.c's
6238 stamp_time = time(NULL);
6239 strftime(strfbuf, sizeof(strfbuf),
6240 "%Y-%m-%d %H:%M:%S %Z",
6241 localtime(&stamp_time));
6244 * Open the existing label file
6246 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6249 if (errno != ENOENT)
6251 (errcode_for_file_access(),
6252 errmsg("could not read file \"%s\": %m",
6253 BACKUP_LABEL_FILE)));
6255 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6256 errmsg("a backup is not in progress")));
6260 * Read and parse the START WAL LOCATION line (this code is pretty crude,
6261 * but we are not expecting any variability in the file format).
6263 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
6264 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6265 &ch) != 4 || ch != '\n')
6267 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6268 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6271 * Write the backup history file
6273 XLByteToSeg(startpoint, _logId, _logSeg);
6274 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6275 startpoint.xrecoff % XLogSegSize);
6276 fp = AllocateFile(histfilepath, "w");
6279 (errcode_for_file_access(),
6280 errmsg("could not create file \"%s\": %m",
6282 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6283 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
6284 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
6285 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
6286 /* transfer remaining lines from label to history file */
6287 while ((ich = fgetc(lfp)) != EOF)
6289 fprintf(fp, "STOP TIME: %s\n", strfbuf);
6290 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6292 (errcode_for_file_access(),
6293 errmsg("could not write file \"%s\": %m",
6297 * Close and remove the backup label file
6299 if (ferror(lfp) || FreeFile(lfp))
6301 (errcode_for_file_access(),
6302 errmsg("could not read file \"%s\": %m",
6303 BACKUP_LABEL_FILE)));
6304 if (unlink(BACKUP_LABEL_FILE) != 0)
6306 (errcode_for_file_access(),
6307 errmsg("could not remove file \"%s\": %m",
6308 BACKUP_LABEL_FILE)));
6311 * Clean out any no-longer-needed history files. As a side effect, this
6312 * will post a .ready file for the newly created history file, notifying
6313 * the archiver that history file may be archived immediately.
6315 CleanupBackupHistory();
6318 * We're done. As a convenience, return the ending WAL location.
6320 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
6321 stoppoint.xlogid, stoppoint.xrecoff);
6322 result = DatumGetTextP(DirectFunctionCall1(textin,
6323 CStringGetDatum(stopxlogfilename)));
6324 PG_RETURN_TEXT_P(result);
6328 * pg_switch_xlog: switch to next xlog file
6331 pg_switch_xlog(PG_FUNCTION_ARGS)
6334 XLogRecPtr switchpoint;
6335 char location[MAXFNAMELEN];
6339 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6340 (errmsg("must be superuser to switch transaction log files"))));
6342 switchpoint = RequestXLogSwitch();
6345 * As a convenience, return the WAL location of the switch record
6347 snprintf(location, sizeof(location), "%X/%X",
6348 switchpoint.xlogid, switchpoint.xrecoff);
6349 result = DatumGetTextP(DirectFunctionCall1(textin,
6350 CStringGetDatum(location)));
6351 PG_RETURN_TEXT_P(result);
6355 * Report the current WAL write location (same format as pg_start_backup etc)
6357 * This is useful for determining how much of WAL is visible to an external
6358 * archiving process. Note that the data before this point is written out
6359 * to the kernel, but is not necessarily synced to disk.
6362 pg_current_xlog_location(PG_FUNCTION_ARGS)
6365 char location[MAXFNAMELEN];
6367 /* Make sure we have an up-to-date local LogwrtResult */
6369 /* use volatile pointer to prevent code rearrangement */
6370 volatile XLogCtlData *xlogctl = XLogCtl;
6372 SpinLockAcquire(&xlogctl->info_lck);
6373 LogwrtResult = xlogctl->LogwrtResult;
6374 SpinLockRelease(&xlogctl->info_lck);
6377 snprintf(location, sizeof(location), "%X/%X",
6378 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
6380 result = DatumGetTextP(DirectFunctionCall1(textin,
6381 CStringGetDatum(location)));
6382 PG_RETURN_TEXT_P(result);
6386 * Report the current WAL insert location (same format as pg_start_backup etc)
6388 * This function is mostly for debugging purposes.
6391 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
6394 XLogCtlInsert *Insert = &XLogCtl->Insert;
6395 XLogRecPtr current_recptr;
6396 char location[MAXFNAMELEN];
6399 * Get the current end-of-WAL position ... shared lock is sufficient
6401 LWLockAcquire(WALInsertLock, LW_SHARED);
6402 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
6403 LWLockRelease(WALInsertLock);
6405 snprintf(location, sizeof(location), "%X/%X",
6406 current_recptr.xlogid, current_recptr.xrecoff);
6408 result = DatumGetTextP(DirectFunctionCall1(textin,
6409 CStringGetDatum(location)));
6410 PG_RETURN_TEXT_P(result);
6414 * Compute an xlog file name and decimal byte offset given a WAL location,
6415 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6417 * Note that a location exactly at a segment boundary is taken to be in
6418 * the previous segment. This is usually the right thing, since the
6419 * expected usage is to determine which xlog file(s) are ready to archive.
6422 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
6424 text *location = PG_GETARG_TEXT_P(0);
6426 unsigned int uxlogid;
6427 unsigned int uxrecoff;
6431 XLogRecPtr locationpoint;
6432 char xlogfilename[MAXFNAMELEN];
6435 TupleDesc resultTupleDesc;
6436 HeapTuple resultHeapTuple;
6440 * Read input and parse
6442 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6443 PointerGetDatum(location)));
6445 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6447 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6448 errmsg("could not parse transaction log location \"%s\"",
6451 locationpoint.xlogid = uxlogid;
6452 locationpoint.xrecoff = uxrecoff;
6455 * Construct a tuple descriptor for the result row. This must match this
6456 * function's pg_proc entry!
6458 resultTupleDesc = CreateTemplateTupleDesc(2, false);
6459 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
6461 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
6464 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
6469 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6470 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6472 values[0] = DirectFunctionCall1(textin,
6473 CStringGetDatum(xlogfilename));
6479 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
6481 values[1] = UInt32GetDatum(xrecoff);
6485 * Tuple jam: Having first prepared your Datums, then squash together
6487 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
6489 result = HeapTupleGetDatum(resultHeapTuple);
6491 PG_RETURN_DATUM(result);
6495 * Compute an xlog file name given a WAL location,
6496 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6499 pg_xlogfile_name(PG_FUNCTION_ARGS)
6501 text *location = PG_GETARG_TEXT_P(0);
6504 unsigned int uxlogid;
6505 unsigned int uxrecoff;
6508 XLogRecPtr locationpoint;
6509 char xlogfilename[MAXFNAMELEN];
6511 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6512 PointerGetDatum(location)));
6514 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6516 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6517 errmsg("could not parse transaction log location \"%s\"",
6520 locationpoint.xlogid = uxlogid;
6521 locationpoint.xrecoff = uxrecoff;
6523 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6524 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6526 result = DatumGetTextP(DirectFunctionCall1(textin,
6527 CStringGetDatum(xlogfilename)));
6528 PG_RETURN_TEXT_P(result);
6532 * read_backup_label: check to see if a backup_label file is present
6534 * If we see a backup_label during recovery, we assume that we are recovering
6535 * from a backup dump file, and we therefore roll forward from the checkpoint
6536 * identified by the label file, NOT what pg_control says. This avoids the
6537 * problem that pg_control might have been archived one or more checkpoints
6538 * later than the start of the dump, and so if we rely on it as the start
6539 * point, we will fail to restore a consistent database state.
6541 * We also attempt to retrieve the corresponding backup history file.
6542 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6545 * Returns TRUE if a backup_label was found (and fills the checkpoint
6546 * location into *checkPointLoc); returns FALSE if not.
6549 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6551 XLogRecPtr startpoint;
6552 XLogRecPtr stoppoint;
6553 char histfilename[MAXFNAMELEN];
6554 char histfilepath[MAXPGPATH];
6555 char startxlogfilename[MAXFNAMELEN];
6556 char stopxlogfilename[MAXFNAMELEN];
6564 /* Default is to not constrain recovery stop point */
6565 minRecoveryLoc->xlogid = 0;
6566 minRecoveryLoc->xrecoff = 0;
6569 * See if label file is present
6571 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6574 if (errno != ENOENT)
6576 (errcode_for_file_access(),
6577 errmsg("could not read file \"%s\": %m",
6578 BACKUP_LABEL_FILE)));
6579 return false; /* it's not there, all is fine */
6583 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
6584 * is pretty crude, but we are not expecting any variability in the file
6587 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
6588 &startpoint.xlogid, &startpoint.xrecoff, &tli,
6589 startxlogfilename, &ch) != 5 || ch != '\n')
6591 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6592 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6593 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
6594 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
6595 &ch) != 3 || ch != '\n')
6597 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6598 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6599 if (ferror(lfp) || FreeFile(lfp))
6601 (errcode_for_file_access(),
6602 errmsg("could not read file \"%s\": %m",
6603 BACKUP_LABEL_FILE)));
6606 * Try to retrieve the backup history file (no error if we can't)
6608 XLByteToSeg(startpoint, _logId, _logSeg);
6609 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
6610 startpoint.xrecoff % XLogSegSize);
6612 if (InArchiveRecovery)
6613 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
6615 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
6616 startpoint.xrecoff % XLogSegSize);
6618 fp = AllocateFile(histfilepath, "r");
6622 * Parse history file to identify stop point.
6624 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
6625 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6626 &ch) != 4 || ch != '\n')
6628 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6629 errmsg("invalid data in file \"%s\"", histfilename)));
6630 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
6631 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6632 &ch) != 4 || ch != '\n')
6634 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6635 errmsg("invalid data in file \"%s\"", histfilename)));
6636 *minRecoveryLoc = stoppoint;
6637 if (ferror(fp) || FreeFile(fp))
6639 (errcode_for_file_access(),
6640 errmsg("could not read file \"%s\": %m",
6648 * Error context callback for errors occurring during rm_redo().
6651 rm_redo_error_callback(void *arg)
6653 XLogRecord *record = (XLogRecord *) arg;
6656 initStringInfo(&buf);
6657 RmgrTable[record->xl_rmid].rm_desc(&buf,
6659 XLogRecGetData(record));
6661 /* don't bother emitting empty description */
6663 errcontext("xlog redo %s", buf.data);