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.270 2007/05/30 20:11:55 tgl Exp $
12 *-------------------------------------------------------------------------
26 #include "access/clog.h"
27 #include "access/heapam.h"
28 #include "access/multixact.h"
29 #include "access/subtrans.h"
30 #include "access/transam.h"
31 #include "access/tuptoaster.h"
32 #include "access/twophase.h"
33 #include "access/xact.h"
34 #include "access/xlog_internal.h"
35 #include "access/xlogdefs.h"
36 #include "access/xlogutils.h"
37 #include "catalog/catversion.h"
38 #include "catalog/pg_control.h"
39 #include "catalog/pg_type.h"
41 #include "miscadmin.h"
43 #include "postmaster/bgwriter.h"
44 #include "storage/bufpage.h"
45 #include "storage/fd.h"
46 #include "storage/pmsignal.h"
47 #include "storage/procarray.h"
48 #include "storage/spin.h"
49 #include "utils/builtins.h"
50 #include "utils/pg_locale.h"
54 /* File path names (all relative to $PGDATA) */
55 #define BACKUP_LABEL_FILE "backup_label"
56 #define BACKUP_LABEL_OLD "backup_label.old"
57 #define RECOVERY_COMMAND_FILE "recovery.conf"
58 #define RECOVERY_COMMAND_DONE "recovery.done"
61 /* User-settable parameters */
62 int CheckPointSegments = 3;
64 int XLogArchiveTimeout = 0;
65 char *XLogArchiveCommand = NULL;
66 char *XLOG_sync_method = NULL;
67 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
68 bool fullPageWrites = true;
71 bool XLOG_DEBUG = false;
75 * XLOGfileslop is used in the code as the allowed "fuzz" in the number of
76 * preallocated XLOG segments --- we try to have at least XLOGfiles advance
77 * segments but no more than XLOGfileslop segments. This could
78 * be made a separate GUC variable, but at present I think it's sufficient
79 * to hardwire it as 2*CheckPointSegments+1. Under normal conditions, a
80 * checkpoint will free no more than 2*CheckPointSegments log segments, and
81 * we want to recycle all of them; the +1 allows boundary cases to happen
82 * without wasting a delete/create-segment cycle.
85 #define XLOGfileslop (2*CheckPointSegments + 1)
88 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
89 int sync_method = DEFAULT_SYNC_METHOD;
90 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
92 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
96 * ThisTimeLineID will be same in all backends --- it identifies current
97 * WAL timeline for the database system.
99 TimeLineID ThisTimeLineID = 0;
101 /* Are we doing recovery from XLOG? */
102 bool InRecovery = false;
104 /* Are we recovering using offline XLOG archives? */
105 static bool InArchiveRecovery = false;
107 /* Was the last xlog file restored from archive, or local? */
108 static bool restoredFromArchive = false;
110 /* options taken from recovery.conf */
111 static char *recoveryRestoreCommand = NULL;
112 static bool recoveryTarget = false;
113 static bool recoveryTargetExact = false;
114 static bool recoveryTargetInclusive = true;
115 static TransactionId recoveryTargetXid;
116 static TimestampTz recoveryTargetTime;
118 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
119 static TransactionId recoveryStopXid;
120 static TimestampTz recoveryStopTime;
121 static bool recoveryStopAfter;
124 * During normal operation, the only timeline we care about is ThisTimeLineID.
125 * During recovery, however, things are more complicated. To simplify life
126 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
127 * scan through the WAL history (that is, it is the line that was active when
128 * the currently-scanned WAL record was generated). We also need these
131 * recoveryTargetTLI: the desired timeline that we want to end in.
133 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
134 * its known parents, newest first (so recoveryTargetTLI is always the
135 * first list member). Only these TLIs are expected to be seen in the WAL
136 * segments we read, and indeed only these TLIs will be considered as
137 * candidate WAL files to open at all.
139 * curFileTLI: the TLI appearing in the name of the current input WAL file.
140 * (This is not necessarily the same as ThisTimeLineID, because we could
141 * be scanning data that was copied from an ancestor timeline when the current
142 * file was created.) During a sequential scan we do not allow this value
145 static TimeLineID recoveryTargetTLI;
146 static List *expectedTLIs;
147 static TimeLineID curFileTLI;
150 * MyLastRecPtr points to the start of the last XLOG record inserted by the
151 * current transaction. If MyLastRecPtr.xrecoff == 0, then the current
152 * xact hasn't yet inserted any transaction-controlled XLOG records.
154 * Note that XLOG records inserted outside transaction control are not
155 * reflected into MyLastRecPtr. They do, however, cause MyXactMadeXLogEntry
156 * to be set true. The latter can be used to test whether the current xact
157 * made any loggable changes (including out-of-xact changes, such as
160 * When we insert/update/delete a tuple in a temporary relation, we do not
161 * make any XLOG record, since we don't care about recovering the state of
162 * the temp rel after a crash. However, we will still need to remember
163 * whether our transaction committed or aborted in that case. So, we must
164 * set MyXactMadeTempRelUpdate true to indicate that the XID will be of
167 XLogRecPtr MyLastRecPtr = {0, 0};
169 bool MyXactMadeXLogEntry = false;
171 bool MyXactMadeTempRelUpdate = false;
174 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
175 * current backend. It is updated for all inserts, transaction-controlled
176 * or not. ProcLastRecEnd is similar but points to end+1 of last record.
178 static XLogRecPtr ProcLastRecPtr = {0, 0};
180 XLogRecPtr ProcLastRecEnd = {0, 0};
183 * RedoRecPtr is this backend's local copy of the REDO record pointer
184 * (which is almost but not quite the same as a pointer to the most recent
185 * CHECKPOINT record). We update this from the shared-memory copy,
186 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
187 * hold the Insert lock). See XLogInsert for details. We are also allowed
188 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
189 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
192 static XLogRecPtr RedoRecPtr;
195 * Shared-memory data structures for XLOG control
197 * LogwrtRqst indicates a byte position that we need to write and/or fsync
198 * the log up to (all records before that point must be written or fsynced).
199 * LogwrtResult indicates the byte positions we have already written/fsynced.
200 * These structs are identical but are declared separately to indicate their
201 * slightly different functions.
203 * We do a lot of pushups to minimize the amount of access to lockable
204 * shared memory values. There are actually three shared-memory copies of
205 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
206 * XLogCtl->LogwrtResult is protected by info_lck
207 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
208 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
209 * One must hold the associated lock to read or write any of these, but
210 * of course no lock is needed to read/write the unshared LogwrtResult.
212 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
213 * right", since both are updated by a write or flush operation before
214 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
215 * is that it can be examined/modified by code that already holds WALWriteLock
216 * without needing to grab info_lck as well.
218 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
219 * but is updated when convenient. Again, it exists for the convenience of
220 * code that is already holding WALInsertLock but not the other locks.
222 * The unshared LogwrtResult may lag behind any or all of these, and again
223 * is updated when convenient.
225 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
226 * (protected by info_lck), but we don't need to cache any copies of it.
228 * Note that this all works because the request and result positions can only
229 * advance forward, never back up, and so we can easily determine which of two
230 * values is "more up to date".
232 * info_lck is only held long enough to read/update the protected variables,
233 * so it's a plain spinlock. The other locks are held longer (potentially
234 * over I/O operations), so we use LWLocks for them. These locks are:
236 * WALInsertLock: must be held to insert a record into the WAL buffers.
238 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
241 * ControlFileLock: must be held to read/update control file or create
244 * CheckpointLock: must be held to do a checkpoint (ensures only one
245 * checkpointer at a time; currently, with all checkpoints done by the
246 * bgwriter, this is just pro forma).
251 typedef struct XLogwrtRqst
253 XLogRecPtr Write; /* last byte + 1 to write out */
254 XLogRecPtr Flush; /* last byte + 1 to flush */
257 typedef struct XLogwrtResult
259 XLogRecPtr Write; /* last byte + 1 written out */
260 XLogRecPtr Flush; /* last byte + 1 flushed */
264 * Shared state data for XLogInsert.
266 typedef struct XLogCtlInsert
268 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
269 XLogRecPtr PrevRecord; /* start of previously-inserted record */
270 int curridx; /* current block index in cache */
271 XLogPageHeader currpage; /* points to header of block in cache */
272 char *currpos; /* current insertion point in cache */
273 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
274 bool forcePageWrites; /* forcing full-page writes for PITR? */
278 * Shared state data for XLogWrite/XLogFlush.
280 typedef struct XLogCtlWrite
282 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
283 int curridx; /* cache index of next block to write */
284 time_t lastSegSwitchTime; /* time of last xlog segment switch */
288 * Total shared-memory state for XLOG.
290 typedef struct XLogCtlData
292 /* Protected by WALInsertLock: */
293 XLogCtlInsert Insert;
295 /* Protected by info_lck: */
296 XLogwrtRqst LogwrtRqst;
297 XLogwrtResult LogwrtResult;
298 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
299 TransactionId ckptXid;
301 /* Protected by WALWriteLock: */
305 * These values do not change after startup, although the pointed-to pages
306 * and xlblocks values certainly do. Permission to read/write the pages
307 * and xlblocks values depends on WALInsertLock and WALWriteLock.
309 char *pages; /* buffers for unwritten XLOG pages */
310 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
311 Size XLogCacheByte; /* # bytes in xlog buffers */
312 int XLogCacheBlck; /* highest allocated xlog buffer index */
313 TimeLineID ThisTimeLineID;
315 slock_t info_lck; /* locks shared variables shown above */
318 static XLogCtlData *XLogCtl = NULL;
321 * We maintain an image of pg_control in shared memory.
323 static ControlFileData *ControlFile = NULL;
326 * Macros for managing XLogInsert state. In most cases, the calling routine
327 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
328 * so these are passed as parameters instead of being fetched via XLogCtl.
331 /* Free space remaining in the current xlog page buffer */
332 #define INSERT_FREESPACE(Insert) \
333 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
335 /* Construct XLogRecPtr value for current insertion point */
336 #define INSERT_RECPTR(recptr,Insert,curridx) \
338 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
340 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
343 #define PrevBufIdx(idx) \
344 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
346 #define NextBufIdx(idx) \
347 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
350 * Private, possibly out-of-date copy of shared LogwrtResult.
351 * See discussion above.
353 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
356 * openLogFile is -1 or a kernel FD for an open log file segment.
357 * When it's open, openLogOff is the current seek offset in the file.
358 * openLogId/openLogSeg identify the segment. These variables are only
359 * used to write the XLOG, and so will normally refer to the active segment.
361 static int openLogFile = -1;
362 static uint32 openLogId = 0;
363 static uint32 openLogSeg = 0;
364 static uint32 openLogOff = 0;
367 * These variables are used similarly to the ones above, but for reading
368 * the XLOG. Note, however, that readOff generally represents the offset
369 * of the page just read, not the seek position of the FD itself, which
370 * will be just past that page.
372 static int readFile = -1;
373 static uint32 readId = 0;
374 static uint32 readSeg = 0;
375 static uint32 readOff = 0;
377 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
378 static char *readBuf = NULL;
380 /* Buffer for current ReadRecord result (expandable) */
381 static char *readRecordBuf = NULL;
382 static uint32 readRecordBufSize = 0;
384 /* State information for XLOG reading */
385 static XLogRecPtr ReadRecPtr; /* start of last record read */
386 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
387 static XLogRecord *nextRecord = NULL;
388 static TimeLineID lastPageTLI = 0;
390 static bool InRedo = false;
393 static void XLogArchiveNotify(const char *xlog);
394 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
395 static bool XLogArchiveCheckDone(const char *xlog);
396 static void XLogArchiveCleanup(const char *xlog);
397 static void readRecoveryCommandFile(void);
398 static void exitArchiveRecovery(TimeLineID endTLI,
399 uint32 endLogId, uint32 endLogSeg);
400 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
401 static void CheckPointGuts(XLogRecPtr checkPointRedo);
403 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
404 XLogRecPtr *lsn, BkpBlock *bkpb);
405 static bool AdvanceXLInsertBuffer(bool new_segment);
406 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
407 static int XLogFileInit(uint32 log, uint32 seg,
408 bool *use_existent, bool use_lock);
409 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
410 bool find_free, int *max_advance,
412 static int XLogFileOpen(uint32 log, uint32 seg);
413 static int XLogFileRead(uint32 log, uint32 seg, int emode);
414 static void XLogFileClose(void);
415 static bool RestoreArchivedFile(char *path, const char *xlogfname,
416 const char *recovername, off_t expectedSize);
417 static int PreallocXlogFiles(XLogRecPtr endptr);
418 static void MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
419 int *nsegsremoved, int *nsegsrecycled);
420 static void CleanupBackupHistory(void);
421 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
422 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
423 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
424 static List *readTimeLineHistory(TimeLineID targetTLI);
425 static bool existsTimeLineHistory(TimeLineID probeTLI);
426 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
427 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
429 uint32 endLogId, uint32 endLogSeg);
430 static void WriteControlFile(void);
431 static void ReadControlFile(void);
432 static char *str_time(time_t tnow);
433 static void issue_xlog_fsync(void);
436 static void xlog_outrec(StringInfo buf, XLogRecord *record);
438 static bool read_backup_label(XLogRecPtr *checkPointLoc,
439 XLogRecPtr *minRecoveryLoc);
440 static void rm_redo_error_callback(void *arg);
444 * Insert an XLOG record having the specified RMID and info bytes,
445 * with the body of the record being the data chunk(s) described by
446 * the rdata chain (see xlog.h for notes about rdata).
448 * Returns XLOG pointer to end of record (beginning of next record).
449 * This can be used as LSN for data pages affected by the logged action.
450 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
451 * before the data page can be written out. This implements the basic
452 * WAL rule "write the log before the data".)
454 * NB: this routine feels free to scribble on the XLogRecData structs,
455 * though not on the data they reference. This is OK since the XLogRecData
456 * structs are always just temporaries in the calling code.
459 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
461 XLogCtlInsert *Insert = &XLogCtl->Insert;
463 XLogContRecord *contrecord;
465 XLogRecPtr WriteRqst;
469 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
470 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
471 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
472 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
473 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
474 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
475 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
480 XLogwrtRqst LogwrtRqst;
483 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
484 bool no_tran = (rmid == RM_XLOG_ID);
486 if (info & XLR_INFO_MASK)
488 if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
489 elog(PANIC, "invalid xlog info mask %02X", (info & XLR_INFO_MASK));
491 info &= ~XLR_INFO_MASK;
495 * In bootstrap mode, we don't actually log anything but XLOG resources;
496 * return a phony record pointer.
498 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
501 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
506 * Here we scan the rdata chain, determine which buffers must be backed
507 * up, and compute the CRC values for the data. Note that the record
508 * header isn't added into the CRC initially since we don't know the final
509 * length or info bits quite yet. Thus, the CRC will represent the CRC of
510 * the whole record in the order "rdata, then backup blocks, then record
513 * We may have to loop back to here if a race condition is detected below.
514 * We could prevent the race by doing all this work while holding the
515 * insert lock, but it seems better to avoid doing CRC calculations while
516 * holding the lock. This means we have to be careful about modifying the
517 * rdata chain until we know we aren't going to loop back again. The only
518 * change we allow ourselves to make earlier is to set rdt->data = NULL in
519 * chain items we have decided we will have to back up the whole buffer
520 * for. This is OK because we will certainly decide the same thing again
521 * for those items if we do it over; doing it here saves an extra pass
522 * over the chain later.
525 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
527 dtbuf[i] = InvalidBuffer;
528 dtbuf_bkp[i] = false;
532 * Decide if we need to do full-page writes in this XLOG record: true if
533 * full_page_writes is on or we have a PITR request for it. Since we
534 * don't yet have the insert lock, forcePageWrites could change under us,
535 * but we'll recheck it once we have the lock.
537 doPageWrites = fullPageWrites || Insert->forcePageWrites;
539 INIT_CRC32(rdata_crc);
543 if (rdt->buffer == InvalidBuffer)
545 /* Simple data, just include it */
547 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
551 /* Find info for buffer */
552 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
554 if (rdt->buffer == dtbuf[i])
556 /* Buffer already referenced by earlier chain item */
562 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
566 if (dtbuf[i] == InvalidBuffer)
568 /* OK, put it in this slot */
569 dtbuf[i] = rdt->buffer;
570 if (XLogCheckBuffer(rdt, doPageWrites,
571 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
579 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
584 if (i >= XLR_MAX_BKP_BLOCKS)
585 elog(PANIC, "can backup at most %d blocks per xlog record",
588 /* Break out of loop when rdt points to last chain item */
589 if (rdt->next == NULL)
595 * Now add the backup block headers and data into the CRC
597 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
601 BkpBlock *bkpb = &(dtbuf_xlg[i]);
604 COMP_CRC32(rdata_crc,
607 page = (char *) BufferGetBlock(dtbuf[i]);
608 if (bkpb->hole_length == 0)
610 COMP_CRC32(rdata_crc,
616 /* must skip the hole */
617 COMP_CRC32(rdata_crc,
620 COMP_CRC32(rdata_crc,
621 page + (bkpb->hole_offset + bkpb->hole_length),
622 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
628 * NOTE: We disallow len == 0 because it provides a useful bit of extra
629 * error checking in ReadRecord. This means that all callers of
630 * XLogInsert must supply at least some not-in-a-buffer data. However, we
631 * make an exception for XLOG SWITCH records because we don't want them to
632 * ever cross a segment boundary.
634 if (len == 0 && !isLogSwitch)
635 elog(PANIC, "invalid xlog record length %u", len);
637 START_CRIT_SECTION();
639 /* update LogwrtResult before doing cache fill check */
641 /* use volatile pointer to prevent code rearrangement */
642 volatile XLogCtlData *xlogctl = XLogCtl;
644 SpinLockAcquire(&xlogctl->info_lck);
645 LogwrtRqst = xlogctl->LogwrtRqst;
646 LogwrtResult = xlogctl->LogwrtResult;
647 SpinLockRelease(&xlogctl->info_lck);
651 * If cache is half filled then try to acquire write lock and do
652 * XLogWrite. Ignore any fractional blocks in performing this check.
654 LogwrtRqst.Write.xrecoff -= LogwrtRqst.Write.xrecoff % XLOG_BLCKSZ;
655 if (LogwrtRqst.Write.xlogid != LogwrtResult.Write.xlogid ||
656 (LogwrtRqst.Write.xrecoff >= LogwrtResult.Write.xrecoff +
657 XLogCtl->XLogCacheByte / 2))
659 if (LWLockConditionalAcquire(WALWriteLock, LW_EXCLUSIVE))
662 * Since the amount of data we write here is completely optional
663 * anyway, tell XLogWrite it can be "flexible" and stop at a
664 * convenient boundary. This allows writes triggered by this
665 * mechanism to synchronize with the cache boundaries, so that in
666 * a long transaction we'll basically dump alternating halves of
669 LogwrtResult = XLogCtl->Write.LogwrtResult;
670 if (XLByteLT(LogwrtResult.Write, LogwrtRqst.Write))
671 XLogWrite(LogwrtRqst, true, false);
672 LWLockRelease(WALWriteLock);
676 /* Now wait to get insert lock */
677 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
680 * Check to see if my RedoRecPtr is out of date. If so, may have to go
681 * back and recompute everything. This can only happen just after a
682 * checkpoint, so it's better to be slow in this case and fast otherwise.
684 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
685 * affect the contents of the XLOG record, so we'll update our local copy
686 * but not force a recomputation.
688 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
690 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
691 RedoRecPtr = Insert->RedoRecPtr;
695 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
697 if (dtbuf[i] == InvalidBuffer)
699 if (dtbuf_bkp[i] == false &&
700 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
703 * Oops, this buffer now needs to be backed up, but we
704 * didn't think so above. Start over.
706 LWLockRelease(WALInsertLock);
715 * Also check to see if forcePageWrites was just turned on; if we weren't
716 * already doing full-page writes then go back and recompute. (If it was
717 * just turned off, we could recompute the record without full pages, but
718 * we choose not to bother.)
720 if (Insert->forcePageWrites && !doPageWrites)
722 /* Oops, must redo it with full-page data */
723 LWLockRelease(WALInsertLock);
729 * Make additional rdata chain entries for the backup blocks, so that we
730 * don't need to special-case them in the write loop. Note that we have
731 * now irrevocably changed the input rdata chain. At the exit of this
732 * loop, write_len includes the backup block data.
734 * Also set the appropriate info bits to show which buffers were backed
735 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
736 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
739 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
747 info |= XLR_SET_BKP_BLOCK(i);
749 bkpb = &(dtbuf_xlg[i]);
750 page = (char *) BufferGetBlock(dtbuf[i]);
752 rdt->next = &(dtbuf_rdt1[i]);
755 rdt->data = (char *) bkpb;
756 rdt->len = sizeof(BkpBlock);
757 write_len += sizeof(BkpBlock);
759 rdt->next = &(dtbuf_rdt2[i]);
762 if (bkpb->hole_length == 0)
771 /* must skip the hole */
773 rdt->len = bkpb->hole_offset;
774 write_len += bkpb->hole_offset;
776 rdt->next = &(dtbuf_rdt3[i]);
779 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
780 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
781 write_len += rdt->len;
787 * If we backed up any full blocks and online backup is not in progress,
788 * mark the backup blocks as removable. This allows the WAL archiver to
789 * know whether it is safe to compress archived WAL data by transforming
790 * full-block records into the non-full-block format.
792 * Note: we could just set the flag whenever !forcePageWrites, but
793 * defining it like this leaves the info bit free for some potential
794 * other use in records without any backup blocks.
796 if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
797 info |= XLR_BKP_REMOVABLE;
800 * If there isn't enough space on the current XLOG page for a record
801 * header, advance to the next page (leaving the unused space as zeroes).
804 freespace = INSERT_FREESPACE(Insert);
805 if (freespace < SizeOfXLogRecord)
807 updrqst = AdvanceXLInsertBuffer(false);
808 freespace = INSERT_FREESPACE(Insert);
811 /* Compute record's XLOG location */
812 curridx = Insert->curridx;
813 INSERT_RECPTR(RecPtr, Insert, curridx);
816 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
817 * segment, we need not insert it (and don't want to because we'd like
818 * consecutive switch requests to be no-ops). Instead, make sure
819 * everything is written and flushed through the end of the prior segment,
820 * and return the prior segment's end address.
823 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
825 /* We can release insert lock immediately */
826 LWLockRelease(WALInsertLock);
828 RecPtr.xrecoff -= SizeOfXLogLongPHD;
829 if (RecPtr.xrecoff == 0)
831 /* crossing a logid boundary */
833 RecPtr.xrecoff = XLogFileSize;
836 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
837 LogwrtResult = XLogCtl->Write.LogwrtResult;
838 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
840 XLogwrtRqst FlushRqst;
842 FlushRqst.Write = RecPtr;
843 FlushRqst.Flush = RecPtr;
844 XLogWrite(FlushRqst, false, false);
846 LWLockRelease(WALWriteLock);
853 /* Insert record header */
855 record = (XLogRecord *) Insert->currpos;
856 record->xl_prev = Insert->PrevRecord;
857 record->xl_xid = GetCurrentTransactionIdIfAny();
858 record->xl_tot_len = SizeOfXLogRecord + write_len;
859 record->xl_len = len; /* doesn't include backup blocks */
860 record->xl_info = info;
861 record->xl_rmid = rmid;
863 /* Now we can finish computing the record's CRC */
864 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
865 SizeOfXLogRecord - sizeof(pg_crc32));
866 FIN_CRC32(rdata_crc);
867 record->xl_crc = rdata_crc;
874 initStringInfo(&buf);
875 appendStringInfo(&buf, "INSERT @ %X/%X: ",
876 RecPtr.xlogid, RecPtr.xrecoff);
877 xlog_outrec(&buf, record);
878 if (rdata->data != NULL)
880 appendStringInfo(&buf, " - ");
881 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
883 elog(LOG, "%s", buf.data);
888 /* Record begin of record in appropriate places */
890 MyLastRecPtr = RecPtr;
891 ProcLastRecPtr = RecPtr;
892 Insert->PrevRecord = RecPtr;
893 MyXactMadeXLogEntry = true;
895 Insert->currpos += SizeOfXLogRecord;
896 freespace -= SizeOfXLogRecord;
899 * Append the data, including backup blocks if any
903 while (rdata->data == NULL)
908 if (rdata->len > freespace)
910 memcpy(Insert->currpos, rdata->data, freespace);
911 rdata->data += freespace;
912 rdata->len -= freespace;
913 write_len -= freespace;
917 memcpy(Insert->currpos, rdata->data, rdata->len);
918 freespace -= rdata->len;
919 write_len -= rdata->len;
920 Insert->currpos += rdata->len;
926 /* Use next buffer */
927 updrqst = AdvanceXLInsertBuffer(false);
928 curridx = Insert->curridx;
929 /* Insert cont-record header */
930 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
931 contrecord = (XLogContRecord *) Insert->currpos;
932 contrecord->xl_rem_len = write_len;
933 Insert->currpos += SizeOfXLogContRecord;
934 freespace = INSERT_FREESPACE(Insert);
937 /* Ensure next record will be properly aligned */
938 Insert->currpos = (char *) Insert->currpage +
939 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
940 freespace = INSERT_FREESPACE(Insert);
943 * The recptr I return is the beginning of the *next* record. This will be
944 * stored as LSN for changed data pages...
946 INSERT_RECPTR(RecPtr, Insert, curridx);
949 * If the record is an XLOG_SWITCH, we must now write and flush all the
950 * existing data, and then forcibly advance to the start of the next
951 * segment. It's not good to do this I/O while holding the insert lock,
952 * but there seems too much risk of confusion if we try to release the
953 * lock sooner. Fortunately xlog switch needn't be a high-performance
954 * operation anyway...
958 XLogCtlWrite *Write = &XLogCtl->Write;
959 XLogwrtRqst FlushRqst;
960 XLogRecPtr OldSegEnd;
962 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
965 * Flush through the end of the page containing XLOG_SWITCH, and
966 * perform end-of-segment actions (eg, notifying archiver).
968 WriteRqst = XLogCtl->xlblocks[curridx];
969 FlushRqst.Write = WriteRqst;
970 FlushRqst.Flush = WriteRqst;
971 XLogWrite(FlushRqst, false, true);
973 /* Set up the next buffer as first page of next segment */
974 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
975 (void) AdvanceXLInsertBuffer(true);
977 /* There should be no unwritten data */
978 curridx = Insert->curridx;
979 Assert(curridx == Write->curridx);
981 /* Compute end address of old segment */
982 OldSegEnd = XLogCtl->xlblocks[curridx];
983 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
984 if (OldSegEnd.xrecoff == 0)
986 /* crossing a logid boundary */
987 OldSegEnd.xlogid -= 1;
988 OldSegEnd.xrecoff = XLogFileSize;
991 /* Make it look like we've written and synced all of old segment */
992 LogwrtResult.Write = OldSegEnd;
993 LogwrtResult.Flush = OldSegEnd;
996 * Update shared-memory status --- this code should match XLogWrite
999 /* use volatile pointer to prevent code rearrangement */
1000 volatile XLogCtlData *xlogctl = XLogCtl;
1002 SpinLockAcquire(&xlogctl->info_lck);
1003 xlogctl->LogwrtResult = LogwrtResult;
1004 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1005 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1006 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1007 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1008 SpinLockRelease(&xlogctl->info_lck);
1011 Write->LogwrtResult = LogwrtResult;
1013 LWLockRelease(WALWriteLock);
1015 updrqst = false; /* done already */
1019 /* normal case, ie not xlog switch */
1021 /* Need to update shared LogwrtRqst if some block was filled up */
1022 if (freespace < SizeOfXLogRecord)
1024 /* curridx is filled and available for writing out */
1029 /* if updrqst already set, write through end of previous buf */
1030 curridx = PrevBufIdx(curridx);
1032 WriteRqst = XLogCtl->xlblocks[curridx];
1035 LWLockRelease(WALInsertLock);
1039 /* use volatile pointer to prevent code rearrangement */
1040 volatile XLogCtlData *xlogctl = XLogCtl;
1042 SpinLockAcquire(&xlogctl->info_lck);
1043 /* advance global request to include new block(s) */
1044 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
1045 xlogctl->LogwrtRqst.Write = WriteRqst;
1046 /* update local result copy while I have the chance */
1047 LogwrtResult = xlogctl->LogwrtResult;
1048 SpinLockRelease(&xlogctl->info_lck);
1051 ProcLastRecEnd = RecPtr;
1059 * Determine whether the buffer referenced by an XLogRecData item has to
1060 * be backed up, and if so fill a BkpBlock struct for it. In any case
1061 * save the buffer's LSN at *lsn.
1064 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1065 XLogRecPtr *lsn, BkpBlock *bkpb)
1069 page = (PageHeader) BufferGetBlock(rdata->buffer);
1072 * XXX We assume page LSN is first data on *every* page that can be passed
1073 * to XLogInsert, whether it otherwise has the standard page layout or
1076 *lsn = page->pd_lsn;
1079 XLByteLE(page->pd_lsn, RedoRecPtr))
1082 * The page needs to be backed up, so set up *bkpb
1084 bkpb->node = BufferGetFileNode(rdata->buffer);
1085 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1087 if (rdata->buffer_std)
1089 /* Assume we can omit data between pd_lower and pd_upper */
1090 uint16 lower = page->pd_lower;
1091 uint16 upper = page->pd_upper;
1093 if (lower >= SizeOfPageHeaderData &&
1097 bkpb->hole_offset = lower;
1098 bkpb->hole_length = upper - lower;
1102 /* No "hole" to compress out */
1103 bkpb->hole_offset = 0;
1104 bkpb->hole_length = 0;
1109 /* Not a standard page header, don't try to eliminate "hole" */
1110 bkpb->hole_offset = 0;
1111 bkpb->hole_length = 0;
1114 return true; /* buffer requires backup */
1117 return false; /* buffer does not need to be backed up */
1123 * Create an archive notification file
1125 * The name of the notification file is the message that will be picked up
1126 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1127 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1128 * then when complete, rename it to 0000000100000001000000C6.done
1131 XLogArchiveNotify(const char *xlog)
1133 char archiveStatusPath[MAXPGPATH];
1136 /* insert an otherwise empty file called <XLOG>.ready */
1137 StatusFilePath(archiveStatusPath, xlog, ".ready");
1138 fd = AllocateFile(archiveStatusPath, "w");
1142 (errcode_for_file_access(),
1143 errmsg("could not create archive status file \"%s\": %m",
1144 archiveStatusPath)));
1150 (errcode_for_file_access(),
1151 errmsg("could not write archive status file \"%s\": %m",
1152 archiveStatusPath)));
1156 /* Notify archiver that it's got something to do */
1157 if (IsUnderPostmaster)
1158 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1162 * Convenience routine to notify using log/seg representation of filename
1165 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1167 char xlog[MAXFNAMELEN];
1169 XLogFileName(xlog, ThisTimeLineID, log, seg);
1170 XLogArchiveNotify(xlog);
1174 * XLogArchiveCheckDone
1176 * This is called when we are ready to delete or recycle an old XLOG segment
1177 * file or backup history file. If it is okay to delete it then return true.
1178 * If it is not time to delete it, make sure a .ready file exists, and return
1181 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1182 * then return false; else create <XLOG>.ready and return false.
1184 * The reason we do things this way is so that if the original attempt to
1185 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1188 XLogArchiveCheckDone(const char *xlog)
1190 char archiveStatusPath[MAXPGPATH];
1191 struct stat stat_buf;
1193 /* Always deletable if archiving is off */
1194 if (!XLogArchivingActive())
1197 /* First check for .done --- this means archiver is done with it */
1198 StatusFilePath(archiveStatusPath, xlog, ".done");
1199 if (stat(archiveStatusPath, &stat_buf) == 0)
1202 /* check for .ready --- this means archiver is still busy with it */
1203 StatusFilePath(archiveStatusPath, xlog, ".ready");
1204 if (stat(archiveStatusPath, &stat_buf) == 0)
1207 /* Race condition --- maybe archiver just finished, so recheck */
1208 StatusFilePath(archiveStatusPath, xlog, ".done");
1209 if (stat(archiveStatusPath, &stat_buf) == 0)
1212 /* Retry creation of the .ready file */
1213 XLogArchiveNotify(xlog);
1218 * XLogArchiveCleanup
1220 * Cleanup archive notification file(s) for a particular xlog segment
1223 XLogArchiveCleanup(const char *xlog)
1225 char archiveStatusPath[MAXPGPATH];
1227 /* Remove the .done file */
1228 StatusFilePath(archiveStatusPath, xlog, ".done");
1229 unlink(archiveStatusPath);
1230 /* should we complain about failure? */
1232 /* Remove the .ready file if present --- normally it shouldn't be */
1233 StatusFilePath(archiveStatusPath, xlog, ".ready");
1234 unlink(archiveStatusPath);
1235 /* should we complain about failure? */
1239 * Advance the Insert state to the next buffer page, writing out the next
1240 * buffer if it still contains unwritten data.
1242 * If new_segment is TRUE then we set up the next buffer page as the first
1243 * page of the next xlog segment file, possibly but not usually the next
1244 * consecutive file page.
1246 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1247 * just-filled page. If we can do this for free (without an extra lock),
1248 * we do so here. Otherwise the caller must do it. We return TRUE if the
1249 * request update still needs to be done, FALSE if we did it internally.
1251 * Must be called with WALInsertLock held.
1254 AdvanceXLInsertBuffer(bool new_segment)
1256 XLogCtlInsert *Insert = &XLogCtl->Insert;
1257 XLogCtlWrite *Write = &XLogCtl->Write;
1258 int nextidx = NextBufIdx(Insert->curridx);
1259 bool update_needed = true;
1260 XLogRecPtr OldPageRqstPtr;
1261 XLogwrtRqst WriteRqst;
1262 XLogRecPtr NewPageEndPtr;
1263 XLogPageHeader NewPage;
1265 /* Use Insert->LogwrtResult copy if it's more fresh */
1266 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1267 LogwrtResult = Insert->LogwrtResult;
1270 * Get ending-offset of the buffer page we need to replace (this may be
1271 * zero if the buffer hasn't been used yet). Fall through if it's already
1274 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1275 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1277 /* nope, got work to do... */
1278 XLogRecPtr FinishedPageRqstPtr;
1280 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1282 /* Before waiting, get info_lck and update LogwrtResult */
1284 /* use volatile pointer to prevent code rearrangement */
1285 volatile XLogCtlData *xlogctl = XLogCtl;
1287 SpinLockAcquire(&xlogctl->info_lck);
1288 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1289 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1290 LogwrtResult = xlogctl->LogwrtResult;
1291 SpinLockRelease(&xlogctl->info_lck);
1294 update_needed = false; /* Did the shared-request update */
1296 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1298 /* OK, someone wrote it already */
1299 Insert->LogwrtResult = LogwrtResult;
1303 /* Must acquire write lock */
1304 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1305 LogwrtResult = Write->LogwrtResult;
1306 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1308 /* OK, someone wrote it already */
1309 LWLockRelease(WALWriteLock);
1310 Insert->LogwrtResult = LogwrtResult;
1315 * Have to write buffers while holding insert lock. This is
1316 * not good, so only write as much as we absolutely must.
1318 WriteRqst.Write = OldPageRqstPtr;
1319 WriteRqst.Flush.xlogid = 0;
1320 WriteRqst.Flush.xrecoff = 0;
1321 XLogWrite(WriteRqst, false, false);
1322 LWLockRelease(WALWriteLock);
1323 Insert->LogwrtResult = LogwrtResult;
1329 * Now the next buffer slot is free and we can set it up to be the next
1332 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1336 /* force it to a segment start point */
1337 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1338 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1341 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1343 /* crossing a logid boundary */
1344 NewPageEndPtr.xlogid += 1;
1345 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1348 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1349 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1350 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1352 Insert->curridx = nextidx;
1353 Insert->currpage = NewPage;
1355 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1358 * Be sure to re-zero the buffer so that bytes beyond what we've written
1359 * will look like zeroes and not valid XLOG records...
1361 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1364 * Fill the new page's header
1366 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1368 /* NewPage->xlp_info = 0; */ /* done by memset */
1369 NewPage ->xlp_tli = ThisTimeLineID;
1370 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1371 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1374 * If first page of an XLOG segment file, make it a long header.
1376 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1378 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1380 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1381 NewLongPage->xlp_seg_size = XLogSegSize;
1382 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1383 NewPage ->xlp_info |= XLP_LONG_HEADER;
1385 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1388 return update_needed;
1392 * Write and/or fsync the log at least as far as WriteRqst indicates.
1394 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1395 * may stop at any convenient boundary (such as a cache or logfile boundary).
1396 * This option allows us to avoid uselessly issuing multiple writes when a
1397 * single one would do.
1399 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1400 * perform end-of-segment actions after writing the last page, even if
1401 * it's not physically the end of its segment. (NB: this will work properly
1402 * only if caller specifies WriteRqst == page-end and flexible == false,
1403 * and there is some data to write.)
1405 * Must be called with WALWriteLock held.
1408 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1410 XLogCtlWrite *Write = &XLogCtl->Write;
1412 bool last_iteration;
1420 /* We should always be inside a critical section here */
1421 Assert(CritSectionCount > 0);
1424 * Update local LogwrtResult (caller probably did this already, but...)
1426 LogwrtResult = Write->LogwrtResult;
1429 * Since successive pages in the xlog cache are consecutively allocated,
1430 * we can usually gather multiple pages together and issue just one
1431 * write() call. npages is the number of pages we have determined can be
1432 * written together; startidx is the cache block index of the first one,
1433 * and startoffset is the file offset at which it should go. The latter
1434 * two variables are only valid when npages > 0, but we must initialize
1435 * all of them to keep the compiler quiet.
1442 * Within the loop, curridx is the cache block index of the page to
1443 * consider writing. We advance Write->curridx only after successfully
1444 * writing pages. (Right now, this refinement is useless since we are
1445 * going to PANIC if any error occurs anyway; but someday it may come in
1448 curridx = Write->curridx;
1450 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1453 * Make sure we're not ahead of the insert process. This could happen
1454 * if we're passed a bogus WriteRqst.Write that is past the end of the
1455 * last page that's been initialized by AdvanceXLInsertBuffer.
1457 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1458 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1459 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1460 XLogCtl->xlblocks[curridx].xlogid,
1461 XLogCtl->xlblocks[curridx].xrecoff);
1463 /* Advance LogwrtResult.Write to end of current buffer page */
1464 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1465 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1467 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1470 * Switch to new logfile segment. We cannot have any pending
1471 * pages here (since we dump what we have at segment end).
1473 Assert(npages == 0);
1474 if (openLogFile >= 0)
1476 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1478 /* create/use new log file */
1479 use_existent = true;
1480 openLogFile = XLogFileInit(openLogId, openLogSeg,
1481 &use_existent, true);
1485 /* Make sure we have the current logfile open */
1486 if (openLogFile < 0)
1488 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1489 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1493 /* Add current page to the set of pending pages-to-dump */
1496 /* first of group */
1498 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1503 * Dump the set if this will be the last loop iteration, or if we are
1504 * at the last page of the cache area (since the next page won't be
1505 * contiguous in memory), or if we are at the end of the logfile
1508 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1510 finishing_seg = !ispartialpage &&
1511 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1513 if (last_iteration ||
1514 curridx == XLogCtl->XLogCacheBlck ||
1520 /* Need to seek in the file? */
1521 if (openLogOff != startoffset)
1523 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1525 (errcode_for_file_access(),
1526 errmsg("could not seek in log file %u, "
1527 "segment %u to offset %u: %m",
1528 openLogId, openLogSeg, startoffset)));
1529 openLogOff = startoffset;
1532 /* OK to write the page(s) */
1533 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1534 nbytes = npages * (Size) XLOG_BLCKSZ;
1536 if (write(openLogFile, from, nbytes) != nbytes)
1538 /* if write didn't set errno, assume no disk space */
1542 (errcode_for_file_access(),
1543 errmsg("could not write to log file %u, segment %u "
1544 "at offset %u, length %lu: %m",
1545 openLogId, openLogSeg,
1546 openLogOff, (unsigned long) nbytes)));
1549 /* Update state for write */
1550 openLogOff += nbytes;
1551 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1555 * If we just wrote the whole last page of a logfile segment,
1556 * fsync the segment immediately. This avoids having to go back
1557 * and re-open prior segments when an fsync request comes along
1558 * later. Doing it here ensures that one and only one backend will
1559 * perform this fsync.
1561 * We also do this if this is the last page written for an xlog
1564 * This is also the right place to notify the Archiver that the
1565 * segment is ready to copy to archival storage, and to update the
1566 * timer for archive_timeout, and to signal for a checkpoint if
1567 * too many logfile segments have been used since the last
1570 if (finishing_seg || (xlog_switch && last_iteration))
1573 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1575 if (XLogArchivingActive())
1576 XLogArchiveNotifySeg(openLogId, openLogSeg);
1578 Write->lastSegSwitchTime = time(NULL);
1581 * Signal bgwriter to start a checkpoint if it's been too long
1582 * since the last one. (We look at local copy of RedoRecPtr
1583 * which might be a little out of date, but should be close
1584 * enough for this purpose.)
1586 * A straight computation of segment number could overflow 32
1587 * bits. Rather than assuming we have working 64-bit
1588 * arithmetic, we compare the highest-order bits separately,
1589 * and force a checkpoint immediately when they change.
1591 if (IsUnderPostmaster)
1595 uint32 old_highbits,
1598 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1599 (RedoRecPtr.xrecoff / XLogSegSize);
1600 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1601 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile +
1603 new_highbits = openLogId / XLogSegSize;
1604 if (new_highbits != old_highbits ||
1605 new_segno >= old_segno + (uint32) (CheckPointSegments-1))
1609 elog(LOG, "time for a checkpoint, signaling bgwriter");
1611 RequestCheckpoint(false, true);
1619 /* Only asked to write a partial page */
1620 LogwrtResult.Write = WriteRqst.Write;
1623 curridx = NextBufIdx(curridx);
1625 /* If flexible, break out of loop as soon as we wrote something */
1626 if (flexible && npages == 0)
1630 Assert(npages == 0);
1631 Assert(curridx == Write->curridx);
1634 * If asked to flush, do so
1636 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1637 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1640 * Could get here without iterating above loop, in which case we might
1641 * have no open file or the wrong one. However, we do not need to
1642 * fsync more than one file.
1644 if (sync_method != SYNC_METHOD_OPEN)
1646 if (openLogFile >= 0 &&
1647 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1649 if (openLogFile < 0)
1651 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1652 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1657 LogwrtResult.Flush = LogwrtResult.Write;
1661 * Update shared-memory status
1663 * We make sure that the shared 'request' values do not fall behind the
1664 * 'result' values. This is not absolutely essential, but it saves some
1665 * code in a couple of places.
1668 /* use volatile pointer to prevent code rearrangement */
1669 volatile XLogCtlData *xlogctl = XLogCtl;
1671 SpinLockAcquire(&xlogctl->info_lck);
1672 xlogctl->LogwrtResult = LogwrtResult;
1673 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1674 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1675 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1676 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1677 SpinLockRelease(&xlogctl->info_lck);
1680 Write->LogwrtResult = LogwrtResult;
1684 * Ensure that all XLOG data through the given position is flushed to disk.
1686 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1687 * already held, and we try to avoid acquiring it if possible.
1690 XLogFlush(XLogRecPtr record)
1692 XLogRecPtr WriteRqstPtr;
1693 XLogwrtRqst WriteRqst;
1695 /* Disabled during REDO */
1699 /* Quick exit if already known flushed */
1700 if (XLByteLE(record, LogwrtResult.Flush))
1705 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1706 record.xlogid, record.xrecoff,
1707 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1708 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1711 START_CRIT_SECTION();
1714 * Since fsync is usually a horribly expensive operation, we try to
1715 * piggyback as much data as we can on each fsync: if we see any more data
1716 * entered into the xlog buffer, we'll write and fsync that too, so that
1717 * the final value of LogwrtResult.Flush is as large as possible. This
1718 * gives us some chance of avoiding another fsync immediately after.
1721 /* initialize to given target; may increase below */
1722 WriteRqstPtr = record;
1724 /* read LogwrtResult and update local state */
1726 /* use volatile pointer to prevent code rearrangement */
1727 volatile XLogCtlData *xlogctl = XLogCtl;
1729 SpinLockAcquire(&xlogctl->info_lck);
1730 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1731 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1732 LogwrtResult = xlogctl->LogwrtResult;
1733 SpinLockRelease(&xlogctl->info_lck);
1737 if (!XLByteLE(record, LogwrtResult.Flush))
1739 /* now wait for the write lock */
1740 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1741 LogwrtResult = XLogCtl->Write.LogwrtResult;
1742 if (!XLByteLE(record, LogwrtResult.Flush))
1744 /* try to write/flush later additions to XLOG as well */
1745 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1747 XLogCtlInsert *Insert = &XLogCtl->Insert;
1748 uint32 freespace = INSERT_FREESPACE(Insert);
1750 if (freespace < SizeOfXLogRecord) /* buffer is full */
1751 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1754 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1755 WriteRqstPtr.xrecoff -= freespace;
1757 LWLockRelease(WALInsertLock);
1758 WriteRqst.Write = WriteRqstPtr;
1759 WriteRqst.Flush = WriteRqstPtr;
1763 WriteRqst.Write = WriteRqstPtr;
1764 WriteRqst.Flush = record;
1766 XLogWrite(WriteRqst, false, false);
1768 LWLockRelease(WALWriteLock);
1774 * If we still haven't flushed to the request point then we have a
1775 * problem; most likely, the requested flush point is past end of XLOG.
1776 * This has been seen to occur when a disk page has a corrupted LSN.
1778 * Formerly we treated this as a PANIC condition, but that hurts the
1779 * system's robustness rather than helping it: we do not want to take down
1780 * the whole system due to corruption on one data page. In particular, if
1781 * the bad page is encountered again during recovery then we would be
1782 * unable to restart the database at all! (This scenario has actually
1783 * happened in the field several times with 7.1 releases. Note that we
1784 * cannot get here while InRedo is true, but if the bad page is brought in
1785 * and marked dirty during recovery then CreateCheckPoint will try to
1786 * flush it at the end of recovery.)
1788 * The current approach is to ERROR under normal conditions, but only
1789 * WARNING during recovery, so that the system can be brought up even if
1790 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1791 * be promoted to PANIC since xact.c calls this routine inside a critical
1792 * section. However, calls from bufmgr.c are not within critical sections
1793 * and so we will not force a restart for a bad LSN on a data page.
1795 if (XLByteLT(LogwrtResult.Flush, record))
1796 elog(InRecovery ? WARNING : ERROR,
1797 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1798 record.xlogid, record.xrecoff,
1799 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1803 * Test whether XLOG data has been flushed up to (at least) the given position.
1805 * Returns true if a flush is still needed. (It may be that someone else
1806 * is already in process of flushing that far, however.)
1809 XLogNeedsFlush(XLogRecPtr record)
1811 /* Quick exit if already known flushed */
1812 if (XLByteLE(record, LogwrtResult.Flush))
1815 /* read LogwrtResult and update local state */
1817 /* use volatile pointer to prevent code rearrangement */
1818 volatile XLogCtlData *xlogctl = XLogCtl;
1820 SpinLockAcquire(&xlogctl->info_lck);
1821 LogwrtResult = xlogctl->LogwrtResult;
1822 SpinLockRelease(&xlogctl->info_lck);
1826 if (XLByteLE(record, LogwrtResult.Flush))
1833 * Create a new XLOG file segment, or open a pre-existing one.
1835 * log, seg: identify segment to be created/opened.
1837 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1838 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1841 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1842 * place. This should be TRUE except during bootstrap log creation. The
1843 * caller must *not* hold the lock at call.
1845 * Returns FD of opened file.
1847 * Note: errors here are ERROR not PANIC because we might or might not be
1848 * inside a critical section (eg, during checkpoint there is no reason to
1849 * take down the system on failure). They will promote to PANIC if we are
1850 * in a critical section.
1853 XLogFileInit(uint32 log, uint32 seg,
1854 bool *use_existent, bool use_lock)
1856 char path[MAXPGPATH];
1857 char tmppath[MAXPGPATH];
1858 char zbuffer[XLOG_BLCKSZ];
1859 uint32 installed_log;
1860 uint32 installed_seg;
1865 XLogFilePath(path, ThisTimeLineID, log, seg);
1868 * Try to use existent file (checkpoint maker may have created it already)
1872 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1876 if (errno != ENOENT)
1878 (errcode_for_file_access(),
1879 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1887 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
1888 * another process is doing the same thing. If so, we will end up
1889 * pre-creating an extra log segment. That seems OK, and better than
1890 * holding the lock throughout this lengthy process.
1892 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1896 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1897 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1901 (errcode_for_file_access(),
1902 errmsg("could not create file \"%s\": %m", tmppath)));
1905 * Zero-fill the file. We have to do this the hard way to ensure that all
1906 * the file space has really been allocated --- on platforms that allow
1907 * "holes" in files, just seeking to the end doesn't allocate intermediate
1908 * space. This way, we know that we have all the space and (after the
1909 * fsync below) that all the indirect blocks are down on disk. Therefore,
1910 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
1913 MemSet(zbuffer, 0, sizeof(zbuffer));
1914 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(zbuffer))
1917 if ((int) write(fd, zbuffer, sizeof(zbuffer)) != (int) sizeof(zbuffer))
1919 int save_errno = errno;
1922 * If we fail to make the file, delete it to release disk space
1925 /* if write didn't set errno, assume problem is no disk space */
1926 errno = save_errno ? save_errno : ENOSPC;
1929 (errcode_for_file_access(),
1930 errmsg("could not write to file \"%s\": %m", tmppath)));
1934 if (pg_fsync(fd) != 0)
1936 (errcode_for_file_access(),
1937 errmsg("could not fsync file \"%s\": %m", tmppath)));
1941 (errcode_for_file_access(),
1942 errmsg("could not close file \"%s\": %m", tmppath)));
1945 * Now move the segment into place with its final name.
1947 * If caller didn't want to use a pre-existing file, get rid of any
1948 * pre-existing file. Otherwise, cope with possibility that someone else
1949 * has created the file while we were filling ours: if so, use ours to
1950 * pre-create a future log segment.
1952 installed_log = log;
1953 installed_seg = seg;
1954 max_advance = XLOGfileslop;
1955 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
1956 *use_existent, &max_advance,
1959 /* No need for any more future segments... */
1963 /* Set flag to tell caller there was no existent file */
1964 *use_existent = false;
1966 /* Now open original target segment (might not be file I just made) */
1967 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1971 (errcode_for_file_access(),
1972 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1979 * Create a new XLOG file segment by copying a pre-existing one.
1981 * log, seg: identify segment to be created.
1983 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
1984 * a different timeline)
1986 * Currently this is only used during recovery, and so there are no locking
1987 * considerations. But we should be just as tense as XLogFileInit to avoid
1988 * emplacing a bogus file.
1991 XLogFileCopy(uint32 log, uint32 seg,
1992 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
1994 char path[MAXPGPATH];
1995 char tmppath[MAXPGPATH];
1996 char buffer[XLOG_BLCKSZ];
2002 * Open the source file
2004 XLogFilePath(path, srcTLI, srclog, srcseg);
2005 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2008 (errcode_for_file_access(),
2009 errmsg("could not open file \"%s\": %m", path)));
2012 * Copy into a temp file name.
2014 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2018 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2019 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2023 (errcode_for_file_access(),
2024 errmsg("could not create file \"%s\": %m", tmppath)));
2027 * Do the data copying.
2029 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2032 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2036 (errcode_for_file_access(),
2037 errmsg("could not read file \"%s\": %m", path)));
2040 (errmsg("not enough data in file \"%s\"", path)));
2043 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2045 int save_errno = errno;
2048 * If we fail to make the file, delete it to release disk space
2051 /* if write didn't set errno, assume problem is no disk space */
2052 errno = save_errno ? save_errno : ENOSPC;
2055 (errcode_for_file_access(),
2056 errmsg("could not write to file \"%s\": %m", tmppath)));
2060 if (pg_fsync(fd) != 0)
2062 (errcode_for_file_access(),
2063 errmsg("could not fsync file \"%s\": %m", tmppath)));
2067 (errcode_for_file_access(),
2068 errmsg("could not close file \"%s\": %m", tmppath)));
2073 * Now move the segment into place with its final name.
2075 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2076 elog(ERROR, "InstallXLogFileSegment should not have failed");
2080 * Install a new XLOG segment file as a current or future log segment.
2082 * This is used both to install a newly-created segment (which has a temp
2083 * filename while it's being created) and to recycle an old segment.
2085 * *log, *seg: identify segment to install as (or first possible target).
2086 * When find_free is TRUE, these are modified on return to indicate the
2087 * actual installation location or last segment searched.
2089 * tmppath: initial name of file to install. It will be renamed into place.
2091 * find_free: if TRUE, install the new segment at the first empty log/seg
2092 * number at or after the passed numbers. If FALSE, install the new segment
2093 * exactly where specified, deleting any existing segment file there.
2095 * *max_advance: maximum number of log/seg slots to advance past the starting
2096 * point. Fail if no free slot is found in this range. On return, reduced
2097 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2098 * when find_free is FALSE.)
2100 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2101 * place. This should be TRUE except during bootstrap log creation. The
2102 * caller must *not* hold the lock at call.
2104 * Returns TRUE if file installed, FALSE if not installed because of
2105 * exceeding max_advance limit. On Windows, we also return FALSE if we
2106 * can't rename the file into place because someone's got it open.
2107 * (Any other kind of failure causes ereport().)
2110 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2111 bool find_free, int *max_advance,
2114 char path[MAXPGPATH];
2115 struct stat stat_buf;
2117 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2120 * We want to be sure that only one process does this at a time.
2123 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2127 /* Force installation: get rid of any pre-existing segment file */
2132 /* Find a free slot to put it in */
2133 while (stat(path, &stat_buf) == 0)
2135 if (*max_advance <= 0)
2137 /* Failed to find a free slot within specified range */
2139 LWLockRelease(ControlFileLock);
2142 NextLogSeg(*log, *seg);
2144 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2149 * Prefer link() to rename() here just to be really sure that we don't
2150 * overwrite an existing logfile. However, there shouldn't be one, so
2151 * rename() is an acceptable substitute except for the truly paranoid.
2153 #if HAVE_WORKING_LINK
2154 if (link(tmppath, path) < 0)
2156 (errcode_for_file_access(),
2157 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2158 tmppath, path, *log, *seg)));
2161 if (rename(tmppath, path) < 0)
2164 #if !defined(__CYGWIN__)
2165 if (GetLastError() == ERROR_ACCESS_DENIED)
2167 if (errno == EACCES)
2171 LWLockRelease(ControlFileLock);
2177 (errcode_for_file_access(),
2178 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2179 tmppath, path, *log, *seg)));
2184 LWLockRelease(ControlFileLock);
2190 * Open a pre-existing logfile segment for writing.
2193 XLogFileOpen(uint32 log, uint32 seg)
2195 char path[MAXPGPATH];
2198 XLogFilePath(path, ThisTimeLineID, log, seg);
2200 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2204 (errcode_for_file_access(),
2205 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2212 * Open a logfile segment for reading (during recovery).
2215 XLogFileRead(uint32 log, uint32 seg, int emode)
2217 char path[MAXPGPATH];
2218 char xlogfname[MAXFNAMELEN];
2223 * Loop looking for a suitable timeline ID: we might need to read any of
2224 * the timelines listed in expectedTLIs.
2226 * We expect curFileTLI on entry to be the TLI of the preceding file in
2227 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2228 * to go backwards; this prevents us from picking up the wrong file when a
2229 * parent timeline extends to higher segment numbers than the child we
2232 foreach(cell, expectedTLIs)
2234 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2236 if (tli < curFileTLI)
2237 break; /* don't bother looking at too-old TLIs */
2239 if (InArchiveRecovery)
2241 XLogFileName(xlogfname, tli, log, seg);
2242 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2247 XLogFilePath(path, tli, log, seg);
2249 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2256 if (errno != ENOENT) /* unexpected failure? */
2258 (errcode_for_file_access(),
2259 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2263 /* Couldn't find it. For simplicity, complain about front timeline */
2264 XLogFilePath(path, recoveryTargetTLI, log, seg);
2267 (errcode_for_file_access(),
2268 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2274 * Close the current logfile segment for writing.
2279 Assert(openLogFile >= 0);
2282 * posix_fadvise is problematic on many platforms: on older x86 Linux it
2283 * just dumps core, and there are reports of problems on PPC platforms as
2284 * well. The following is therefore disabled for the time being. We could
2285 * consider some kind of configure test to see if it's safe to use, but
2286 * since we lack hard evidence that there's any useful performance gain to
2287 * be had, spending time on that seems unprofitable for now.
2292 * WAL segment files will not be re-read in normal operation, so we advise
2293 * OS to release any cached pages. But do not do so if WAL archiving is
2294 * active, because archiver process could use the cache to read the WAL
2297 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
2298 * O_SYNC, and some platforms only have posix_fadvise().
2300 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2301 if (!XLogArchivingActive())
2302 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2304 #endif /* NOT_USED */
2306 if (close(openLogFile))
2308 (errcode_for_file_access(),
2309 errmsg("could not close log file %u, segment %u: %m",
2310 openLogId, openLogSeg)));
2315 * Attempt to retrieve the specified file from off-line archival storage.
2316 * If successful, fill "path" with its complete path (note that this will be
2317 * a temp file name that doesn't follow the normal naming convention), and
2320 * If not successful, fill "path" with the name of the normal on-line file
2321 * (which may or may not actually exist, but we'll try to use it), and return
2324 * For fixed-size files, the caller may pass the expected size as an
2325 * additional crosscheck on successful recovery. If the file size is not
2326 * known, set expectedSize = 0.
2329 RestoreArchivedFile(char *path, const char *xlogfname,
2330 const char *recovername, off_t expectedSize)
2332 char xlogpath[MAXPGPATH];
2333 char xlogRestoreCmd[MAXPGPATH];
2339 struct stat stat_buf;
2342 * When doing archive recovery, we always prefer an archived log file even
2343 * if a file of the same name exists in XLOGDIR. The reason is that the
2344 * file in XLOGDIR could be an old, un-filled or partly-filled version
2345 * that was copied and restored as part of backing up $PGDATA.
2347 * We could try to optimize this slightly by checking the local copy
2348 * lastchange timestamp against the archived copy, but we have no API to
2349 * do this, nor can we guarantee that the lastchange timestamp was
2350 * preserved correctly when we copied to archive. Our aim is robustness,
2351 * so we elect not to do this.
2353 * If we cannot obtain the log file from the archive, however, we will try
2354 * to use the XLOGDIR file if it exists. This is so that we can make use
2355 * of log segments that weren't yet transferred to the archive.
2357 * Notice that we don't actually overwrite any files when we copy back
2358 * from archive because the recoveryRestoreCommand may inadvertently
2359 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2360 * fallback to the segments remaining in current XLOGDIR later. The
2361 * copy-from-archive filename is always the same, ensuring that we don't
2362 * run out of disk space on long recoveries.
2364 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2367 * Make sure there is no existing file named recovername.
2369 if (stat(xlogpath, &stat_buf) != 0)
2371 if (errno != ENOENT)
2373 (errcode_for_file_access(),
2374 errmsg("could not stat file \"%s\": %m",
2379 if (unlink(xlogpath) != 0)
2381 (errcode_for_file_access(),
2382 errmsg("could not remove file \"%s\": %m",
2387 * construct the command to be executed
2389 dp = xlogRestoreCmd;
2390 endp = xlogRestoreCmd + MAXPGPATH - 1;
2393 for (sp = recoveryRestoreCommand; *sp; sp++)
2400 /* %p: relative path of target file */
2402 StrNCpy(dp, xlogpath, endp - dp);
2403 make_native_path(dp);
2407 /* %f: filename of desired file */
2409 StrNCpy(dp, xlogfname, endp - dp);
2413 /* convert %% to a single % */
2419 /* otherwise treat the % as not special */
2434 (errmsg_internal("executing restore command \"%s\"",
2438 * Copy xlog from archival storage to XLOGDIR
2440 rc = system(xlogRestoreCmd);
2444 * command apparently succeeded, but let's make sure the file is
2445 * really there now and has the correct size.
2447 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2448 * it, but is that too strong? We could try to plow ahead with a
2449 * local copy of the file ... but the problem is that there probably
2450 * isn't one, and we'd incorrectly conclude we've reached the end of
2451 * WAL and we're done recovering ...
2453 if (stat(xlogpath, &stat_buf) == 0)
2455 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2457 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2459 (unsigned long) stat_buf.st_size,
2460 (unsigned long) expectedSize)));
2464 (errmsg("restored log file \"%s\" from archive",
2466 strcpy(path, xlogpath);
2473 if (errno != ENOENT)
2475 (errcode_for_file_access(),
2476 errmsg("could not stat file \"%s\": %m",
2482 * Remember, we rollforward UNTIL the restore fails so failure here is
2483 * just part of the process... that makes it difficult to determine
2484 * whether the restore failed because there isn't an archive to restore,
2485 * or because the administrator has specified the restore program
2486 * incorrectly. We have to assume the former.
2488 * However, if the failure was due to any sort of signal, it's best to
2489 * punt and abort recovery. (If we "return false" here, upper levels
2490 * will assume that recovery is complete and start up the database!)
2491 * It's essential to abort on child SIGINT and SIGQUIT, because per spec
2492 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2493 * those it's a good bet we should have gotten it too. Aborting on other
2494 * signals such as SIGTERM seems a good idea as well.
2496 * Per the Single Unix Spec, shells report exit status > 128 when
2497 * a called command died on a signal. Also, 126 and 127 are used to
2498 * report problems such as an unfindable command; treat those as fatal
2501 signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;
2503 ereport(signaled ? FATAL : DEBUG2,
2504 (errmsg("could not restore file \"%s\" from archive: return code %d",
2508 * if an archived file is not available, there might still be a version of
2509 * this file in XLOGDIR, so return that as the filename to open.
2511 * In many recovery scenarios we expect this to fail also, but if so that
2512 * just means we've reached the end of WAL.
2514 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2519 * Preallocate log files beyond the specified log endpoint, according to
2520 * the XLOGfile user parameter.
2523 PreallocXlogFiles(XLogRecPtr endptr)
2531 XLByteToPrevSeg(endptr, _logId, _logSeg);
2532 if ((endptr.xrecoff - 1) % XLogSegSize >=
2533 (uint32) (0.75 * XLogSegSize))
2535 NextLogSeg(_logId, _logSeg);
2536 use_existent = true;
2537 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2546 * Remove or move offline all log files older or equal to passed log/seg#
2548 * endptr is current (or recent) end of xlog; this is used to determine
2549 * whether we want to recycle rather than delete no-longer-wanted log files.
2552 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
2553 int *nsegsremoved, int *nsegsrecycled)
2559 struct dirent *xlde;
2560 char lastoff[MAXFNAMELEN];
2561 char path[MAXPGPATH];
2567 * Initialize info about where to try to recycle to. We allow recycling
2568 * segments up to XLOGfileslop segments beyond the current XLOG location.
2570 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2571 max_advance = XLOGfileslop;
2573 xldir = AllocateDir(XLOGDIR);
2576 (errcode_for_file_access(),
2577 errmsg("could not open transaction log directory \"%s\": %m",
2580 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2582 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2585 * We ignore the timeline part of the XLOG segment identifiers in
2586 * deciding whether a segment is still needed. This ensures that we
2587 * won't prematurely remove a segment from a parent timeline. We could
2588 * probably be a little more proactive about removing segments of
2589 * non-parent timelines, but that would be a whole lot more
2592 * We use the alphanumeric sorting property of the filenames to decide
2593 * which ones are earlier than the lastoff segment.
2595 if (strlen(xlde->d_name) == 24 &&
2596 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2597 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2599 if (XLogArchiveCheckDone(xlde->d_name))
2601 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2604 * Before deleting the file, see if it can be recycled as a
2605 * future log segment.
2607 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2612 (errmsg("recycled transaction log file \"%s\"",
2615 /* Needn't recheck that slot on future iterations */
2616 if (max_advance > 0)
2618 NextLogSeg(endlogId, endlogSeg);
2624 /* No need for any more future segments... */
2626 (errmsg("removing transaction log file \"%s\"",
2632 XLogArchiveCleanup(xlde->d_name);
2641 * Remove previous backup history files. This also retries creation of
2642 * .ready files for any backup history files for which XLogArchiveNotify
2646 CleanupBackupHistory(void)
2649 struct dirent *xlde;
2650 char path[MAXPGPATH];
2652 xldir = AllocateDir(XLOGDIR);
2655 (errcode_for_file_access(),
2656 errmsg("could not open transaction log directory \"%s\": %m",
2659 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2661 if (strlen(xlde->d_name) > 24 &&
2662 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2663 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2666 if (XLogArchiveCheckDone(xlde->d_name))
2669 (errmsg("removing transaction log backup history file \"%s\"",
2671 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2673 XLogArchiveCleanup(xlde->d_name);
2682 * Restore the backup blocks present in an XLOG record, if any.
2684 * We assume all of the record has been read into memory at *record.
2686 * Note: when a backup block is available in XLOG, we restore it
2687 * unconditionally, even if the page in the database appears newer.
2688 * This is to protect ourselves against database pages that were partially
2689 * or incorrectly written during a crash. We assume that the XLOG data
2690 * must be good because it has passed a CRC check, while the database
2691 * page might not be. This will force us to replay all subsequent
2692 * modifications of the page that appear in XLOG, rather than possibly
2693 * ignoring them as already applied, but that's not a huge drawback.
2696 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2705 blk = (char *) XLogRecGetData(record) + record->xl_len;
2706 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2708 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2711 memcpy(&bkpb, blk, sizeof(BkpBlock));
2712 blk += sizeof(BkpBlock);
2714 reln = XLogOpenRelation(bkpb.node);
2715 buffer = XLogReadBuffer(reln, bkpb.block, true);
2716 Assert(BufferIsValid(buffer));
2717 page = (Page) BufferGetPage(buffer);
2719 if (bkpb.hole_length == 0)
2721 memcpy((char *) page, blk, BLCKSZ);
2725 /* must zero-fill the hole */
2726 MemSet((char *) page, 0, BLCKSZ);
2727 memcpy((char *) page, blk, bkpb.hole_offset);
2728 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2729 blk + bkpb.hole_offset,
2730 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2733 PageSetLSN(page, lsn);
2734 PageSetTLI(page, ThisTimeLineID);
2735 MarkBufferDirty(buffer);
2736 UnlockReleaseBuffer(buffer);
2738 blk += BLCKSZ - bkpb.hole_length;
2743 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2744 * record (other than to the minimal extent of computing the amount of
2745 * data to read in) until we've checked the CRCs.
2747 * We assume all of the record has been read into memory at *record.
2750 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2754 uint32 len = record->xl_len;
2758 /* First the rmgr data */
2760 COMP_CRC32(crc, XLogRecGetData(record), len);
2762 /* Add in the backup blocks, if any */
2763 blk = (char *) XLogRecGetData(record) + len;
2764 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2768 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2771 memcpy(&bkpb, blk, sizeof(BkpBlock));
2772 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2775 (errmsg("incorrect hole size in record at %X/%X",
2776 recptr.xlogid, recptr.xrecoff)));
2779 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2780 COMP_CRC32(crc, blk, blen);
2784 /* Check that xl_tot_len agrees with our calculation */
2785 if (blk != (char *) record + record->xl_tot_len)
2788 (errmsg("incorrect total length in record at %X/%X",
2789 recptr.xlogid, recptr.xrecoff)));
2793 /* Finally include the record header */
2794 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2795 SizeOfXLogRecord - sizeof(pg_crc32));
2798 if (!EQ_CRC32(record->xl_crc, crc))
2801 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2802 recptr.xlogid, recptr.xrecoff)));
2810 * Attempt to read an XLOG record.
2812 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2813 * try to read a record just after the last one previously read.
2815 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2816 * (emode must be either PANIC or LOG.)
2818 * The record is copied into readRecordBuf, so that on successful return,
2819 * the returned record pointer always points there.
2822 ReadRecord(XLogRecPtr *RecPtr, int emode)
2826 XLogRecPtr tmpRecPtr = EndRecPtr;
2827 bool randAccess = false;
2830 uint32 targetPageOff;
2831 uint32 targetRecOff;
2832 uint32 pageHeaderSize;
2834 if (readBuf == NULL)
2837 * First time through, permanently allocate readBuf. We do it this
2838 * way, rather than just making a static array, for two reasons: (1)
2839 * no need to waste the storage in most instantiations of the backend;
2840 * (2) a static char array isn't guaranteed to have any particular
2841 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2843 readBuf = (char *) malloc(XLOG_BLCKSZ);
2844 Assert(readBuf != NULL);
2849 RecPtr = &tmpRecPtr;
2850 /* fast case if next record is on same page */
2851 if (nextRecord != NULL)
2853 record = nextRecord;
2856 /* align old recptr to next page */
2857 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2858 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2859 if (tmpRecPtr.xrecoff >= XLogFileSize)
2861 (tmpRecPtr.xlogid)++;
2862 tmpRecPtr.xrecoff = 0;
2864 /* We will account for page header size below */
2868 if (!XRecOffIsValid(RecPtr->xrecoff))
2870 (errmsg("invalid record offset at %X/%X",
2871 RecPtr->xlogid, RecPtr->xrecoff)));
2874 * Since we are going to a random position in WAL, forget any prior
2875 * state about what timeline we were in, and allow it to be any
2876 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
2877 * to go backwards (but we can't reset that variable right here, since
2878 * we might not change files at all).
2880 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2881 randAccess = true; /* allow curFileTLI to go backwards too */
2884 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2889 XLByteToSeg(*RecPtr, readId, readSeg);
2892 /* Now it's okay to reset curFileTLI if random fetch */
2896 readFile = XLogFileRead(readId, readSeg, emode);
2898 goto next_record_is_invalid;
2901 * Whenever switching to a new WAL segment, we read the first page of
2902 * the file and validate its header, even if that's not where the
2903 * target record is. This is so that we can check the additional
2904 * identification info that is present in the first page's "long"
2908 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2911 (errcode_for_file_access(),
2912 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2913 readId, readSeg, readOff)));
2914 goto next_record_is_invalid;
2916 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2917 goto next_record_is_invalid;
2920 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2921 if (readOff != targetPageOff)
2923 readOff = targetPageOff;
2924 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2927 (errcode_for_file_access(),
2928 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2929 readId, readSeg, readOff)));
2930 goto next_record_is_invalid;
2932 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2935 (errcode_for_file_access(),
2936 errmsg("could not read from log file %u, segment %u at offset %u: %m",
2937 readId, readSeg, readOff)));
2938 goto next_record_is_invalid;
2940 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2941 goto next_record_is_invalid;
2943 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2944 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
2945 if (targetRecOff == 0)
2948 * Can only get here in the continuing-from-prev-page case, because
2949 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
2950 * to skip over the new page's header.
2952 tmpRecPtr.xrecoff += pageHeaderSize;
2953 targetRecOff = pageHeaderSize;
2955 else if (targetRecOff < pageHeaderSize)
2958 (errmsg("invalid record offset at %X/%X",
2959 RecPtr->xlogid, RecPtr->xrecoff)));
2960 goto next_record_is_invalid;
2962 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
2963 targetRecOff == pageHeaderSize)
2966 (errmsg("contrecord is requested by %X/%X",
2967 RecPtr->xlogid, RecPtr->xrecoff)));
2968 goto next_record_is_invalid;
2970 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
2975 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
2978 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
2980 if (record->xl_len != 0)
2983 (errmsg("invalid xlog switch record at %X/%X",
2984 RecPtr->xlogid, RecPtr->xrecoff)));
2985 goto next_record_is_invalid;
2988 else if (record->xl_len == 0)
2991 (errmsg("record with zero length at %X/%X",
2992 RecPtr->xlogid, RecPtr->xrecoff)));
2993 goto next_record_is_invalid;
2995 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
2996 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
2997 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3000 (errmsg("invalid record length at %X/%X",
3001 RecPtr->xlogid, RecPtr->xrecoff)));
3002 goto next_record_is_invalid;
3004 if (record->xl_rmid > RM_MAX_ID)
3007 (errmsg("invalid resource manager ID %u at %X/%X",
3008 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3009 goto next_record_is_invalid;
3014 * We can't exactly verify the prev-link, but surely it should be less
3015 * than the record's own address.
3017 if (!XLByteLT(record->xl_prev, *RecPtr))
3020 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3021 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3022 RecPtr->xlogid, RecPtr->xrecoff)));
3023 goto next_record_is_invalid;
3029 * Record's prev-link should exactly match our previous location. This
3030 * check guards against torn WAL pages where a stale but valid-looking
3031 * WAL record starts on a sector boundary.
3033 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3036 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3037 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3038 RecPtr->xlogid, RecPtr->xrecoff)));
3039 goto next_record_is_invalid;
3044 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3045 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3046 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3047 * enough for all "normal" records, but very large commit or abort records
3048 * might need more space.)
3050 total_len = record->xl_tot_len;
3051 if (total_len > readRecordBufSize)
3053 uint32 newSize = total_len;
3055 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3056 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3058 free(readRecordBuf);
3059 readRecordBuf = (char *) malloc(newSize);
3062 readRecordBufSize = 0;
3063 /* We treat this as a "bogus data" condition */
3065 (errmsg("record length %u at %X/%X too long",
3066 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3067 goto next_record_is_invalid;
3069 readRecordBufSize = newSize;
3072 buffer = readRecordBuf;
3074 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3075 if (total_len > len)
3077 /* Need to reassemble record */
3078 XLogContRecord *contrecord;
3079 uint32 gotlen = len;
3081 memcpy(buffer, record, len);
3082 record = (XLogRecord *) buffer;
3086 readOff += XLOG_BLCKSZ;
3087 if (readOff >= XLogSegSize)
3091 NextLogSeg(readId, readSeg);
3092 readFile = XLogFileRead(readId, readSeg, emode);
3094 goto next_record_is_invalid;
3097 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3100 (errcode_for_file_access(),
3101 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3102 readId, readSeg, readOff)));
3103 goto next_record_is_invalid;
3105 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3106 goto next_record_is_invalid;
3107 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3110 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3111 readId, readSeg, readOff)));
3112 goto next_record_is_invalid;
3114 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3115 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3116 if (contrecord->xl_rem_len == 0 ||
3117 total_len != (contrecord->xl_rem_len + gotlen))
3120 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3121 contrecord->xl_rem_len,
3122 readId, readSeg, readOff)));
3123 goto next_record_is_invalid;
3125 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3126 if (contrecord->xl_rem_len > len)
3128 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3133 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3134 contrecord->xl_rem_len);
3137 if (!RecordIsValid(record, *RecPtr, emode))
3138 goto next_record_is_invalid;
3139 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3140 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3141 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3143 nextRecord = (XLogRecord *) ((char *) contrecord +
3144 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3146 EndRecPtr.xlogid = readId;
3147 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3149 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3150 ReadRecPtr = *RecPtr;
3151 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3155 /* Record does not cross a page boundary */
3156 if (!RecordIsValid(record, *RecPtr, emode))
3157 goto next_record_is_invalid;
3158 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3159 MAXALIGN(total_len))
3160 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3161 EndRecPtr.xlogid = RecPtr->xlogid;
3162 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3163 ReadRecPtr = *RecPtr;
3164 memcpy(buffer, record, total_len);
3167 * Special processing if it's an XLOG SWITCH record
3169 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3171 /* Pretend it extends to end of segment */
3172 EndRecPtr.xrecoff += XLogSegSize - 1;
3173 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3174 nextRecord = NULL; /* definitely not on same page */
3177 * Pretend that readBuf contains the last page of the segment. This is
3178 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3181 readOff = XLogSegSize - XLOG_BLCKSZ;
3183 return (XLogRecord *) buffer;
3185 next_record_is_invalid:;
3193 * Check whether the xlog header of a page just read in looks valid.
3195 * This is just a convenience subroutine to avoid duplicated code in
3196 * ReadRecord. It's not intended for use from anywhere else.
3199 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3203 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3206 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3207 hdr->xlp_magic, readId, readSeg, readOff)));
3210 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3213 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3214 hdr->xlp_info, readId, readSeg, readOff)));
3217 if (hdr->xlp_info & XLP_LONG_HEADER)
3219 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3221 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3223 char fhdrident_str[32];
3224 char sysident_str[32];
3227 * Format sysids separately to keep platform-dependent format code
3228 * out of the translatable message string.
3230 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3231 longhdr->xlp_sysid);
3232 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3233 ControlFile->system_identifier);
3235 (errmsg("WAL file is from different system"),
3236 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3237 fhdrident_str, sysident_str)));
3240 if (longhdr->xlp_seg_size != XLogSegSize)
3243 (errmsg("WAL file is from different system"),
3244 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3247 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3250 (errmsg("WAL file is from different system"),
3251 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3255 else if (readOff == 0)
3257 /* hmm, first page of file doesn't have a long header? */
3259 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3260 hdr->xlp_info, readId, readSeg, readOff)));
3264 recaddr.xlogid = readId;
3265 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3266 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3269 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3270 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3271 readId, readSeg, readOff)));
3276 * Check page TLI is one of the expected values.
3278 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3281 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3283 readId, readSeg, readOff)));
3288 * Since child timelines are always assigned a TLI greater than their
3289 * immediate parent's TLI, we should never see TLI go backwards across
3290 * successive pages of a consistent WAL sequence.
3292 * Of course this check should only be applied when advancing sequentially
3293 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3294 * going to a random page.
3296 if (hdr->xlp_tli < lastPageTLI)
3299 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3300 hdr->xlp_tli, lastPageTLI,
3301 readId, readSeg, readOff)));
3304 lastPageTLI = hdr->xlp_tli;
3309 * Try to read a timeline's history file.
3311 * If successful, return the list of component TLIs (the given TLI followed by
3312 * its ancestor TLIs). If we can't find the history file, assume that the
3313 * timeline has no parents, and return a list of just the specified timeline
3317 readTimeLineHistory(TimeLineID targetTLI)
3320 char path[MAXPGPATH];
3321 char histfname[MAXFNAMELEN];
3322 char fline[MAXPGPATH];
3325 if (InArchiveRecovery)
3327 TLHistoryFileName(histfname, targetTLI);
3328 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3331 TLHistoryFilePath(path, targetTLI);
3333 fd = AllocateFile(path, "r");
3336 if (errno != ENOENT)
3338 (errcode_for_file_access(),
3339 errmsg("could not open file \"%s\": %m", path)));
3340 /* Not there, so assume no parents */
3341 return list_make1_int((int) targetTLI);
3349 while (fgets(fline, sizeof(fline), fd) != NULL)
3351 /* skip leading whitespace and check for # comment */
3356 for (ptr = fline; *ptr; ptr++)
3358 if (!isspace((unsigned char) *ptr))
3361 if (*ptr == '\0' || *ptr == '#')
3364 /* expect a numeric timeline ID as first field of line */
3365 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3368 (errmsg("syntax error in history file: %s", fline),
3369 errhint("Expected a numeric timeline ID.")));
3372 tli <= (TimeLineID) linitial_int(result))
3374 (errmsg("invalid data in history file: %s", fline),
3375 errhint("Timeline IDs must be in increasing sequence.")));
3377 /* Build list with newest item first */
3378 result = lcons_int((int) tli, result);
3380 /* we ignore the remainder of each line */
3386 targetTLI <= (TimeLineID) linitial_int(result))
3388 (errmsg("invalid data in history file \"%s\"", path),
3389 errhint("Timeline IDs must be less than child timeline's ID.")));
3391 result = lcons_int((int) targetTLI, result);
3394 (errmsg_internal("history of timeline %u is %s",
3395 targetTLI, nodeToString(result))));
3401 * Probe whether a timeline history file exists for the given timeline ID
3404 existsTimeLineHistory(TimeLineID probeTLI)
3406 char path[MAXPGPATH];
3407 char histfname[MAXFNAMELEN];
3410 if (InArchiveRecovery)
3412 TLHistoryFileName(histfname, probeTLI);
3413 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3416 TLHistoryFilePath(path, probeTLI);
3418 fd = AllocateFile(path, "r");
3426 if (errno != ENOENT)
3428 (errcode_for_file_access(),
3429 errmsg("could not open file \"%s\": %m", path)));
3435 * Find the newest existing timeline, assuming that startTLI exists.
3437 * Note: while this is somewhat heuristic, it does positively guarantee
3438 * that (result + 1) is not a known timeline, and therefore it should
3439 * be safe to assign that ID to a new timeline.
3442 findNewestTimeLine(TimeLineID startTLI)
3444 TimeLineID newestTLI;
3445 TimeLineID probeTLI;
3448 * The algorithm is just to probe for the existence of timeline history
3449 * files. XXX is it useful to allow gaps in the sequence?
3451 newestTLI = startTLI;
3453 for (probeTLI = startTLI + 1;; probeTLI++)
3455 if (existsTimeLineHistory(probeTLI))
3457 newestTLI = probeTLI; /* probeTLI exists */
3461 /* doesn't exist, assume we're done */
3470 * Create a new timeline history file.
3472 * newTLI: ID of the new timeline
3473 * parentTLI: ID of its immediate parent
3474 * endTLI et al: ID of the last used WAL file, for annotation purposes
3476 * Currently this is only used during recovery, and so there are no locking
3477 * considerations. But we should be just as tense as XLogFileInit to avoid
3478 * emplacing a bogus file.
3481 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3482 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3484 char path[MAXPGPATH];
3485 char tmppath[MAXPGPATH];
3486 char histfname[MAXFNAMELEN];
3487 char xlogfname[MAXFNAMELEN];
3488 char buffer[BLCKSZ];
3493 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3496 * Write into a temp file name.
3498 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3502 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3503 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3507 (errcode_for_file_access(),
3508 errmsg("could not create file \"%s\": %m", tmppath)));
3511 * If a history file exists for the parent, copy it verbatim
3513 if (InArchiveRecovery)
3515 TLHistoryFileName(histfname, parentTLI);
3516 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3519 TLHistoryFilePath(path, parentTLI);
3521 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3524 if (errno != ENOENT)
3526 (errcode_for_file_access(),
3527 errmsg("could not open file \"%s\": %m", path)));
3528 /* Not there, so assume parent has no parents */
3535 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3536 if (nbytes < 0 || errno != 0)
3538 (errcode_for_file_access(),
3539 errmsg("could not read file \"%s\": %m", path)));
3543 if ((int) write(fd, buffer, nbytes) != nbytes)
3545 int save_errno = errno;
3548 * If we fail to make the file, delete it to release disk
3554 * if write didn't set errno, assume problem is no disk space
3556 errno = save_errno ? save_errno : ENOSPC;
3559 (errcode_for_file_access(),
3560 errmsg("could not write to file \"%s\": %m", tmppath)));
3567 * Append one line with the details of this timeline split.
3569 * If we did have a parent file, insert an extra newline just in case the
3570 * parent file failed to end with one.
3572 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3574 snprintf(buffer, sizeof(buffer),
3575 "%s%u\t%s\t%s transaction %u at %s\n",
3576 (srcfd < 0) ? "" : "\n",
3579 recoveryStopAfter ? "after" : "before",
3581 timestamptz_to_str(recoveryStopTime));
3583 nbytes = strlen(buffer);
3585 if ((int) write(fd, buffer, nbytes) != nbytes)
3587 int save_errno = errno;
3590 * If we fail to make the file, delete it to release disk space
3593 /* if write didn't set errno, assume problem is no disk space */
3594 errno = save_errno ? save_errno : ENOSPC;
3597 (errcode_for_file_access(),
3598 errmsg("could not write to file \"%s\": %m", tmppath)));
3601 if (pg_fsync(fd) != 0)
3603 (errcode_for_file_access(),
3604 errmsg("could not fsync file \"%s\": %m", tmppath)));
3608 (errcode_for_file_access(),
3609 errmsg("could not close file \"%s\": %m", tmppath)));
3613 * Now move the completed history file into place with its final name.
3615 TLHistoryFilePath(path, newTLI);
3618 * Prefer link() to rename() here just to be really sure that we don't
3619 * overwrite an existing logfile. However, there shouldn't be one, so
3620 * rename() is an acceptable substitute except for the truly paranoid.
3622 #if HAVE_WORKING_LINK
3623 if (link(tmppath, path) < 0)
3625 (errcode_for_file_access(),
3626 errmsg("could not link file \"%s\" to \"%s\": %m",
3630 if (rename(tmppath, path) < 0)
3632 (errcode_for_file_access(),
3633 errmsg("could not rename file \"%s\" to \"%s\": %m",
3637 /* The history file can be archived immediately. */
3638 TLHistoryFileName(histfname, newTLI);
3639 XLogArchiveNotify(histfname);
3643 * I/O routines for pg_control
3645 * *ControlFile is a buffer in shared memory that holds an image of the
3646 * contents of pg_control. WriteControlFile() initializes pg_control
3647 * given a preloaded buffer, ReadControlFile() loads the buffer from
3648 * the pg_control file (during postmaster or standalone-backend startup),
3649 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3651 * For simplicity, WriteControlFile() initializes the fields of pg_control
3652 * that are related to checking backend/database compatibility, and
3653 * ReadControlFile() verifies they are correct. We could split out the
3654 * I/O and compatibility-check functions, but there seems no need currently.
3657 WriteControlFile(void)
3660 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3664 * Initialize version and compatibility-check fields
3666 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3667 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3669 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3670 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3672 ControlFile->blcksz = BLCKSZ;
3673 ControlFile->relseg_size = RELSEG_SIZE;
3674 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3675 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3677 ControlFile->nameDataLen = NAMEDATALEN;
3678 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3680 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
3682 #ifdef HAVE_INT64_TIMESTAMP
3683 ControlFile->enableIntTimes = TRUE;
3685 ControlFile->enableIntTimes = FALSE;
3688 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3689 localeptr = setlocale(LC_COLLATE, NULL);
3692 (errmsg("invalid LC_COLLATE setting")));
3693 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3694 localeptr = setlocale(LC_CTYPE, NULL);
3697 (errmsg("invalid LC_CTYPE setting")));
3698 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3700 /* Contents are protected with a CRC */
3701 INIT_CRC32(ControlFile->crc);
3702 COMP_CRC32(ControlFile->crc,
3703 (char *) ControlFile,
3704 offsetof(ControlFileData, crc));
3705 FIN_CRC32(ControlFile->crc);
3708 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3709 * excess over sizeof(ControlFileData). This reduces the odds of
3710 * premature-EOF errors when reading pg_control. We'll still fail when we
3711 * check the contents of the file, but hopefully with a more specific
3712 * error than "couldn't read pg_control".
3714 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3715 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3717 memset(buffer, 0, PG_CONTROL_SIZE);
3718 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3720 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3721 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3725 (errcode_for_file_access(),
3726 errmsg("could not create control file \"%s\": %m",
3727 XLOG_CONTROL_FILE)));
3730 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3732 /* if write didn't set errno, assume problem is no disk space */
3736 (errcode_for_file_access(),
3737 errmsg("could not write to control file: %m")));
3740 if (pg_fsync(fd) != 0)
3742 (errcode_for_file_access(),
3743 errmsg("could not fsync control file: %m")));
3747 (errcode_for_file_access(),
3748 errmsg("could not close control file: %m")));
3752 ReadControlFile(void)
3760 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3765 (errcode_for_file_access(),
3766 errmsg("could not open control file \"%s\": %m",
3767 XLOG_CONTROL_FILE)));
3769 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3771 (errcode_for_file_access(),
3772 errmsg("could not read from control file: %m")));
3777 * Check for expected pg_control format version. If this is wrong, the
3778 * CRC check will likely fail because we'll be checking the wrong number
3779 * of bytes. Complaining about wrong version will probably be more
3780 * enlightening than complaining about wrong CRC.
3782 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3784 (errmsg("database files are incompatible with server"),
3785 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3786 " but the server was compiled with PG_CONTROL_VERSION %d.",
3787 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3788 errhint("It looks like you need to initdb.")));
3789 /* Now check the CRC. */
3792 (char *) ControlFile,
3793 offsetof(ControlFileData, crc));
3796 if (!EQ_CRC32(crc, ControlFile->crc))
3798 (errmsg("incorrect checksum in control file")));
3801 * Do compatibility checking immediately. We do this here for 2 reasons:
3803 * (1) if the database isn't compatible with the backend executable, we
3804 * want to abort before we can possibly do any damage;
3806 * (2) this code is executed in the postmaster, so the setlocale() will
3807 * propagate to forked backends, which aren't going to read this file for
3808 * themselves. (These locale settings are considered critical
3809 * compatibility items because they can affect sort order of indexes.)
3811 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3813 (errmsg("database files are incompatible with server"),
3814 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3815 " but the server was compiled with CATALOG_VERSION_NO %d.",
3816 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3817 errhint("It looks like you need to initdb.")));
3818 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3820 (errmsg("database files are incompatible with server"),
3821 errdetail("The database cluster was initialized with MAXALIGN %d,"
3822 " but the server was compiled with MAXALIGN %d.",
3823 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3824 errhint("It looks like you need to initdb.")));
3825 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3827 (errmsg("database files are incompatible with server"),
3828 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3829 errhint("It looks like you need to initdb.")));
3830 if (ControlFile->blcksz != BLCKSZ)
3832 (errmsg("database files are incompatible with server"),
3833 errdetail("The database cluster was initialized with BLCKSZ %d,"
3834 " but the server was compiled with BLCKSZ %d.",
3835 ControlFile->blcksz, BLCKSZ),
3836 errhint("It looks like you need to recompile or initdb.")));
3837 if (ControlFile->relseg_size != RELSEG_SIZE)
3839 (errmsg("database files are incompatible with server"),
3840 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3841 " but the server was compiled with RELSEG_SIZE %d.",
3842 ControlFile->relseg_size, RELSEG_SIZE),
3843 errhint("It looks like you need to recompile or initdb.")));
3844 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3846 (errmsg("database files are incompatible with server"),
3847 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3848 " but the server was compiled with XLOG_BLCKSZ %d.",
3849 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3850 errhint("It looks like you need to recompile or initdb.")));
3851 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3853 (errmsg("database files are incompatible with server"),
3854 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3855 " but the server was compiled with XLOG_SEG_SIZE %d.",
3856 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3857 errhint("It looks like you need to recompile or initdb.")));
3858 if (ControlFile->nameDataLen != NAMEDATALEN)
3860 (errmsg("database files are incompatible with server"),
3861 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3862 " but the server was compiled with NAMEDATALEN %d.",
3863 ControlFile->nameDataLen, NAMEDATALEN),
3864 errhint("It looks like you need to recompile or initdb.")));
3865 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3867 (errmsg("database files are incompatible with server"),
3868 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3869 " but the server was compiled with INDEX_MAX_KEYS %d.",
3870 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3871 errhint("It looks like you need to recompile or initdb.")));
3872 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
3874 (errmsg("database files are incompatible with server"),
3875 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
3876 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
3877 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
3878 errhint("It looks like you need to recompile or initdb.")));
3880 #ifdef HAVE_INT64_TIMESTAMP
3881 if (ControlFile->enableIntTimes != TRUE)
3883 (errmsg("database files are incompatible with server"),
3884 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3885 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3886 errhint("It looks like you need to recompile or initdb.")));
3888 if (ControlFile->enableIntTimes != FALSE)
3890 (errmsg("database files are incompatible with server"),
3891 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3892 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3893 errhint("It looks like you need to recompile or initdb.")));
3896 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3898 (errmsg("database files are incompatible with server"),
3899 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3900 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3901 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3902 errhint("It looks like you need to recompile or initdb.")));
3903 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3905 (errmsg("database files are incompatible with operating system"),
3906 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3907 " which is not recognized by setlocale().",
3908 ControlFile->lc_collate),
3909 errhint("It looks like you need to initdb or install locale support.")));
3910 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3912 (errmsg("database files are incompatible with operating system"),
3913 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3914 " which is not recognized by setlocale().",
3915 ControlFile->lc_ctype),
3916 errhint("It looks like you need to initdb or install locale support.")));
3918 /* Make the fixed locale settings visible as GUC variables, too */
3919 SetConfigOption("lc_collate", ControlFile->lc_collate,
3920 PGC_INTERNAL, PGC_S_OVERRIDE);
3921 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3922 PGC_INTERNAL, PGC_S_OVERRIDE);
3926 UpdateControlFile(void)
3930 INIT_CRC32(ControlFile->crc);
3931 COMP_CRC32(ControlFile->crc,
3932 (char *) ControlFile,
3933 offsetof(ControlFileData, crc));
3934 FIN_CRC32(ControlFile->crc);
3936 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3941 (errcode_for_file_access(),
3942 errmsg("could not open control file \"%s\": %m",
3943 XLOG_CONTROL_FILE)));
3946 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3948 /* if write didn't set errno, assume problem is no disk space */
3952 (errcode_for_file_access(),
3953 errmsg("could not write to control file: %m")));
3956 if (pg_fsync(fd) != 0)
3958 (errcode_for_file_access(),
3959 errmsg("could not fsync control file: %m")));
3963 (errcode_for_file_access(),
3964 errmsg("could not close control file: %m")));
3968 * Initialization of shared memory for XLOG
3976 size = sizeof(XLogCtlData);
3977 /* xlblocks array */
3978 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
3979 /* extra alignment padding for XLOG I/O buffers */
3980 size = add_size(size, ALIGNOF_XLOG_BUFFER);
3981 /* and the buffers themselves */
3982 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
3985 * Note: we don't count ControlFileData, it comes out of the "slop factor"
3986 * added by CreateSharedMemoryAndSemaphores. This lets us use this
3987 * routine again below to compute the actual allocation size.
4000 ControlFile = (ControlFileData *)
4001 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4002 XLogCtl = (XLogCtlData *)
4003 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4005 if (foundCFile || foundXLog)
4007 /* both should be present or neither */
4008 Assert(foundCFile && foundXLog);
4012 memset(XLogCtl, 0, sizeof(XLogCtlData));
4015 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4016 * multiple of the alignment for same, so no extra alignment padding is
4019 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4020 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4021 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4022 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4025 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4027 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4028 XLogCtl->pages = allocptr;
4029 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4032 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4033 * in additional info.)
4035 XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
4037 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4038 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4039 SpinLockInit(&XLogCtl->info_lck);
4042 * If we are not in bootstrap mode, pg_control should already exist. Read
4043 * and validate it immediately (see comments in ReadControlFile() for the
4046 if (!IsBootstrapProcessingMode())
4051 * This func must be called ONCE on system install. It creates pg_control
4052 * and the initial XLOG segment.
4057 CheckPoint checkPoint;
4059 XLogPageHeader page;
4060 XLogLongPageHeader longpage;
4063 uint64 sysidentifier;
4068 * Select a hopefully-unique system identifier code for this installation.
4069 * We use the result of gettimeofday(), including the fractional seconds
4070 * field, as being about as unique as we can easily get. (Think not to
4071 * use random(), since it hasn't been seeded and there's no portable way
4072 * to seed it other than the system clock value...) The upper half of the
4073 * uint64 value is just the tv_sec part, while the lower half is the XOR
4074 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4075 * unnecessarily if "uint64" is really only 32 bits wide. A person
4076 * knowing this encoding can determine the initialization time of the
4077 * installation, which could perhaps be useful sometimes.
4079 gettimeofday(&tv, NULL);
4080 sysidentifier = ((uint64) tv.tv_sec) << 32;
4081 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4083 /* First timeline ID is always 1 */
4086 /* page buffer must be aligned suitably for O_DIRECT */
4087 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4088 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4089 memset(page, 0, XLOG_BLCKSZ);
4091 /* Set up information for the initial checkpoint record */
4092 checkPoint.redo.xlogid = 0;
4093 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4094 checkPoint.ThisTimeLineID = ThisTimeLineID;
4095 checkPoint.nextXidEpoch = 0;
4096 checkPoint.nextXid = FirstNormalTransactionId;
4097 checkPoint.nextOid = FirstBootstrapObjectId;
4098 checkPoint.nextMulti = FirstMultiXactId;
4099 checkPoint.nextMultiOffset = 0;
4100 checkPoint.time = time(NULL);
4102 ShmemVariableCache->nextXid = checkPoint.nextXid;
4103 ShmemVariableCache->nextOid = checkPoint.nextOid;
4104 ShmemVariableCache->oidCount = 0;
4105 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4107 /* Set up the XLOG page header */
4108 page->xlp_magic = XLOG_PAGE_MAGIC;
4109 page->xlp_info = XLP_LONG_HEADER;
4110 page->xlp_tli = ThisTimeLineID;
4111 page->xlp_pageaddr.xlogid = 0;
4112 page->xlp_pageaddr.xrecoff = 0;
4113 longpage = (XLogLongPageHeader) page;
4114 longpage->xlp_sysid = sysidentifier;
4115 longpage->xlp_seg_size = XLogSegSize;
4116 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4118 /* Insert the initial checkpoint record */
4119 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4120 record->xl_prev.xlogid = 0;
4121 record->xl_prev.xrecoff = 0;
4122 record->xl_xid = InvalidTransactionId;
4123 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4124 record->xl_len = sizeof(checkPoint);
4125 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4126 record->xl_rmid = RM_XLOG_ID;
4127 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4130 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4131 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4132 SizeOfXLogRecord - sizeof(pg_crc32));
4134 record->xl_crc = crc;
4136 /* Create first XLOG segment file */
4137 use_existent = false;
4138 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4140 /* Write the first page with the initial record */
4142 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4144 /* if write didn't set errno, assume problem is no disk space */
4148 (errcode_for_file_access(),
4149 errmsg("could not write bootstrap transaction log file: %m")));
4152 if (pg_fsync(openLogFile) != 0)
4154 (errcode_for_file_access(),
4155 errmsg("could not fsync bootstrap transaction log file: %m")));
4157 if (close(openLogFile))
4159 (errcode_for_file_access(),
4160 errmsg("could not close bootstrap transaction log file: %m")));
4164 /* Now create pg_control */
4166 memset(ControlFile, 0, sizeof(ControlFileData));
4167 /* Initialize pg_control status fields */
4168 ControlFile->system_identifier = sysidentifier;
4169 ControlFile->state = DB_SHUTDOWNED;
4170 ControlFile->time = checkPoint.time;
4171 ControlFile->checkPoint = checkPoint.redo;
4172 ControlFile->checkPointCopy = checkPoint;
4173 /* some additional ControlFile fields are set in WriteControlFile() */
4177 /* Bootstrap the commit log, too */
4179 BootStrapSUBTRANS();
4180 BootStrapMultiXact();
4186 str_time(time_t tnow)
4188 static char buf[128];
4190 strftime(buf, sizeof(buf),
4191 "%Y-%m-%d %H:%M:%S %Z",
4198 * See if there is a recovery command file (recovery.conf), and if so
4199 * read in parameters for archive recovery.
4201 * XXX longer term intention is to expand this to
4202 * cater for additional parameters and controls
4203 * possibly use a flex lexer similar to the GUC one
4206 readRecoveryCommandFile(void)
4209 char cmdline[MAXPGPATH];
4210 TimeLineID rtli = 0;
4211 bool rtliGiven = false;
4212 bool syntaxError = false;
4214 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4217 if (errno == ENOENT)
4218 return; /* not there, so no archive recovery */
4220 (errcode_for_file_access(),
4221 errmsg("could not open recovery command file \"%s\": %m",
4222 RECOVERY_COMMAND_FILE)));
4226 (errmsg("starting archive recovery")));
4231 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4233 /* skip leading whitespace and check for # comment */
4238 for (ptr = cmdline; *ptr; ptr++)
4240 if (!isspace((unsigned char) *ptr))
4243 if (*ptr == '\0' || *ptr == '#')
4246 /* identify the quoted parameter value */
4247 tok1 = strtok(ptr, "'");
4253 tok2 = strtok(NULL, "'");
4259 /* reparse to get just the parameter name */
4260 tok1 = strtok(ptr, " \t=");
4267 if (strcmp(tok1, "restore_command") == 0)
4269 recoveryRestoreCommand = pstrdup(tok2);
4271 (errmsg("restore_command = \"%s\"",
4272 recoveryRestoreCommand)));
4274 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4277 if (strcmp(tok2, "latest") == 0)
4282 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4283 if (errno == EINVAL || errno == ERANGE)
4285 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4290 (errmsg("recovery_target_timeline = %u", rtli)));
4293 (errmsg("recovery_target_timeline = latest")));
4295 else if (strcmp(tok1, "recovery_target_xid") == 0)
4298 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4299 if (errno == EINVAL || errno == ERANGE)
4301 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4304 (errmsg("recovery_target_xid = %u",
4305 recoveryTargetXid)));
4306 recoveryTarget = true;
4307 recoveryTargetExact = true;
4309 else if (strcmp(tok1, "recovery_target_time") == 0)
4312 * if recovery_target_xid specified, then this overrides
4313 * recovery_target_time
4315 if (recoveryTargetExact)
4317 recoveryTarget = true;
4318 recoveryTargetExact = false;
4321 * Convert the time string given by the user to TimestampTz form.
4323 recoveryTargetTime =
4324 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
4325 CStringGetDatum(tok2),
4326 ObjectIdGetDatum(InvalidOid),
4327 Int32GetDatum(-1)));
4329 (errmsg("recovery_target_time = %s",
4330 timestamptz_to_str(recoveryTargetTime))));
4332 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4335 * does nothing if a recovery_target is not also set
4337 if (strcmp(tok2, "true") == 0)
4338 recoveryTargetInclusive = true;
4341 recoveryTargetInclusive = false;
4345 (errmsg("recovery_target_inclusive = %s", tok2)));
4349 (errmsg("unrecognized recovery parameter \"%s\"",
4357 (errmsg("syntax error in recovery command file: %s",
4359 errhint("Lines should have the format parameter = 'value'.")));
4361 /* Check that required parameters were supplied */
4362 if (recoveryRestoreCommand == NULL)
4364 (errmsg("recovery command file \"%s\" did not specify restore_command",
4365 RECOVERY_COMMAND_FILE)));
4367 /* Enable fetching from archive recovery area */
4368 InArchiveRecovery = true;
4371 * If user specified recovery_target_timeline, validate it or compute the
4372 * "latest" value. We can't do this until after we've gotten the restore
4373 * command and set InArchiveRecovery, because we need to fetch timeline
4374 * history files from the archive.
4380 /* Timeline 1 does not have a history file, all else should */
4381 if (rtli != 1 && !existsTimeLineHistory(rtli))
4383 (errmsg("recovery_target_timeline %u does not exist",
4385 recoveryTargetTLI = rtli;
4389 /* We start the "latest" search from pg_control's timeline */
4390 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4396 * Exit archive-recovery state
4399 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4401 char recoveryPath[MAXPGPATH];
4402 char xlogpath[MAXPGPATH];
4405 * We are no longer in archive recovery state.
4407 InArchiveRecovery = false;
4410 * We should have the ending log segment currently open. Verify, and then
4411 * close it (to avoid problems on Windows with trying to rename or delete
4414 Assert(readFile >= 0);
4415 Assert(readId == endLogId);
4416 Assert(readSeg == endLogSeg);
4422 * If the segment was fetched from archival storage, we want to replace
4423 * the existing xlog segment (if any) with the archival version. This is
4424 * because whatever is in XLOGDIR is very possibly older than what we have
4425 * from the archives, since it could have come from restoring a PGDATA
4426 * backup. In any case, the archival version certainly is more
4427 * descriptive of what our current database state is, because that is what
4430 * Note that if we are establishing a new timeline, ThisTimeLineID is
4431 * already set to the new value, and so we will create a new file instead
4432 * of overwriting any existing file.
4434 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4435 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4437 if (restoredFromArchive)
4440 (errmsg_internal("moving last restored xlog to \"%s\"",
4442 unlink(xlogpath); /* might or might not exist */
4443 if (rename(recoveryPath, xlogpath) != 0)
4445 (errcode_for_file_access(),
4446 errmsg("could not rename file \"%s\" to \"%s\": %m",
4447 recoveryPath, xlogpath)));
4448 /* XXX might we need to fix permissions on the file? */
4453 * If the latest segment is not archival, but there's still a
4454 * RECOVERYXLOG laying about, get rid of it.
4456 unlink(recoveryPath); /* ignore any error */
4459 * If we are establishing a new timeline, we have to copy data from
4460 * the last WAL segment of the old timeline to create a starting WAL
4461 * segment for the new timeline.
4463 if (endTLI != ThisTimeLineID)
4464 XLogFileCopy(endLogId, endLogSeg,
4465 endTLI, endLogId, endLogSeg);
4469 * Let's just make real sure there are not .ready or .done flags posted
4470 * for the new segment.
4472 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4473 XLogArchiveCleanup(xlogpath);
4475 /* Get rid of any remaining recovered timeline-history file, too */
4476 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4477 unlink(recoveryPath); /* ignore any error */
4480 * Rename the config file out of the way, so that we don't accidentally
4481 * re-enter archive recovery mode in a subsequent crash.
4483 unlink(RECOVERY_COMMAND_DONE);
4484 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4486 (errcode_for_file_access(),
4487 errmsg("could not rename file \"%s\" to \"%s\": %m",
4488 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4491 (errmsg("archive recovery complete")));
4495 * For point-in-time recovery, this function decides whether we want to
4496 * stop applying the XLOG at or after the current record.
4498 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4499 * *includeThis is set TRUE if we should apply this record before stopping.
4500 * Also, some information is saved in recoveryStopXid et al for use in
4501 * annotating the new timeline's history file.
4504 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4508 TimestampTz recordXtime;
4510 /* Do we have a PITR target at all? */
4511 if (!recoveryTarget)
4514 /* We only consider stopping at COMMIT or ABORT records */
4515 if (record->xl_rmid != RM_XACT_ID)
4517 record_info = record->xl_info & ~XLR_INFO_MASK;
4518 if (record_info == XLOG_XACT_COMMIT)
4520 xl_xact_commit *recordXactCommitData;
4522 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4523 recordXtime = recordXactCommitData->xact_time;
4525 else if (record_info == XLOG_XACT_ABORT)
4527 xl_xact_abort *recordXactAbortData;
4529 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4530 recordXtime = recordXactAbortData->xact_time;
4535 if (recoveryTargetExact)
4538 * there can be only one transaction end record with this exact
4541 * when testing for an xid, we MUST test for equality only, since
4542 * transactions are numbered in the order they start, not the order
4543 * they complete. A higher numbered xid will complete before you about
4544 * 50% of the time...
4546 stopsHere = (record->xl_xid == recoveryTargetXid);
4548 *includeThis = recoveryTargetInclusive;
4553 * there can be many transactions that share the same commit time, so
4554 * we stop after the last one, if we are inclusive, or stop at the
4555 * first one if we are exclusive
4557 if (recoveryTargetInclusive)
4558 stopsHere = (recordXtime > recoveryTargetTime);
4560 stopsHere = (recordXtime >= recoveryTargetTime);
4562 *includeThis = false;
4567 recoveryStopXid = record->xl_xid;
4568 recoveryStopTime = recordXtime;
4569 recoveryStopAfter = *includeThis;
4571 if (record_info == XLOG_XACT_COMMIT)
4573 if (recoveryStopAfter)
4575 (errmsg("recovery stopping after commit of transaction %u, time %s",
4577 timestamptz_to_str(recoveryStopTime))));
4580 (errmsg("recovery stopping before commit of transaction %u, time %s",
4582 timestamptz_to_str(recoveryStopTime))));
4586 if (recoveryStopAfter)
4588 (errmsg("recovery stopping after abort of transaction %u, time %s",
4590 timestamptz_to_str(recoveryStopTime))));
4593 (errmsg("recovery stopping before abort of transaction %u, time %s",
4595 timestamptz_to_str(recoveryStopTime))));
4603 * This must be called ONCE during postmaster or standalone-backend startup
4608 XLogCtlInsert *Insert;
4609 CheckPoint checkPoint;
4611 bool needNewTimeLine = false;
4612 bool haveBackupLabel = false;
4622 TransactionId oldestActiveXID;
4625 * Read control file and check XLOG status looks valid.
4627 * Note: in most control paths, *ControlFile is already valid and we need
4628 * not do ReadControlFile() here, but might as well do it to be sure.
4632 if (ControlFile->state < DB_SHUTDOWNED ||
4633 ControlFile->state > DB_IN_PRODUCTION ||
4634 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4636 (errmsg("control file contains invalid data")));
4638 if (ControlFile->state == DB_SHUTDOWNED)
4640 (errmsg("database system was shut down at %s",
4641 str_time(ControlFile->time))));
4642 else if (ControlFile->state == DB_SHUTDOWNING)
4644 (errmsg("database system shutdown was interrupted; last known up at %s",
4645 str_time(ControlFile->time))));
4646 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4648 (errmsg("database system was interrupted while in recovery at %s",
4649 str_time(ControlFile->time)),
4650 errhint("This probably means that some data is corrupted and"
4651 " you will have to use the last backup for recovery.")));
4652 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4654 (errmsg("database system was interrupted while in recovery at log time %s",
4655 str_time(ControlFile->checkPointCopy.time)),
4656 errhint("If this has occurred more than once some data might be corrupted"
4657 " and you might need to choose an earlier recovery target.")));
4658 else if (ControlFile->state == DB_IN_PRODUCTION)
4660 (errmsg("database system was interrupted; last known up at %s",
4661 str_time(ControlFile->time))));
4663 /* This is just to allow attaching to startup process with a debugger */
4664 #ifdef XLOG_REPLAY_DELAY
4665 if (ControlFile->state != DB_SHUTDOWNED)
4666 pg_usleep(60000000L);
4670 * Initialize on the assumption we want to recover to the same timeline
4671 * that's active according to pg_control.
4673 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4676 * Check for recovery control file, and if so set up state for offline
4679 readRecoveryCommandFile();
4681 /* Now we can determine the list of expected TLIs */
4682 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4685 * If pg_control's timeline is not in expectedTLIs, then we cannot
4686 * proceed: the backup is not part of the history of the requested
4689 if (!list_member_int(expectedTLIs,
4690 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4692 (errmsg("requested timeline %u is not a child of database system timeline %u",
4694 ControlFile->checkPointCopy.ThisTimeLineID)));
4696 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4699 * When a backup_label file is present, we want to roll forward from
4700 * the checkpoint it identifies, rather than using pg_control.
4702 record = ReadCheckpointRecord(checkPointLoc, 0);
4706 (errmsg("checkpoint record is at %X/%X",
4707 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4708 InRecovery = true; /* force recovery even if SHUTDOWNED */
4713 (errmsg("could not locate required checkpoint record"),
4714 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4716 /* set flag to delete it later */
4717 haveBackupLabel = true;
4722 * Get the last valid checkpoint record. If the latest one according
4723 * to pg_control is broken, try the next-to-last one.
4725 checkPointLoc = ControlFile->checkPoint;
4726 record = ReadCheckpointRecord(checkPointLoc, 1);
4730 (errmsg("checkpoint record is at %X/%X",
4731 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4735 checkPointLoc = ControlFile->prevCheckPoint;
4736 record = ReadCheckpointRecord(checkPointLoc, 2);
4740 (errmsg("using previous checkpoint record at %X/%X",
4741 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4742 InRecovery = true; /* force recovery even if SHUTDOWNED */
4746 (errmsg("could not locate a valid checkpoint record")));
4750 LastRec = RecPtr = checkPointLoc;
4751 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4752 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4755 (errmsg("redo record is at %X/%X; shutdown %s",
4756 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4757 wasShutdown ? "TRUE" : "FALSE")));
4759 (errmsg("next transaction ID: %u/%u; next OID: %u",
4760 checkPoint.nextXidEpoch, checkPoint.nextXid,
4761 checkPoint.nextOid)));
4763 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4764 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4765 if (!TransactionIdIsNormal(checkPoint.nextXid))
4767 (errmsg("invalid next transaction ID")));
4769 ShmemVariableCache->nextXid = checkPoint.nextXid;
4770 ShmemVariableCache->nextOid = checkPoint.nextOid;
4771 ShmemVariableCache->oidCount = 0;
4772 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4775 * We must replay WAL entries using the same TimeLineID they were created
4776 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4777 * also xlog_redo()).
4779 ThisTimeLineID = checkPoint.ThisTimeLineID;
4781 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4783 if (XLByteLT(RecPtr, checkPoint.redo))
4785 (errmsg("invalid redo in checkpoint record")));
4788 * Check whether we need to force recovery from WAL. If it appears to
4789 * have been a clean shutdown and we did not have a recovery.conf file,
4790 * then assume no recovery needed.
4792 if (XLByteLT(checkPoint.redo, RecPtr))
4796 (errmsg("invalid redo record in shutdown checkpoint")));
4799 else if (ControlFile->state != DB_SHUTDOWNED)
4801 else if (InArchiveRecovery)
4803 /* force recovery due to presence of recovery.conf */
4813 * Update pg_control to show that we are recovering and to show the
4814 * selected checkpoint as the place we are starting from. We also mark
4815 * pg_control with any minimum recovery stop point obtained from a
4816 * backup history file.
4818 if (InArchiveRecovery)
4821 (errmsg("automatic recovery in progress")));
4822 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4827 (errmsg("database system was not properly shut down; "
4828 "automatic recovery in progress")));
4829 ControlFile->state = DB_IN_CRASH_RECOVERY;
4831 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4832 ControlFile->checkPoint = checkPointLoc;
4833 ControlFile->checkPointCopy = checkPoint;
4834 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4835 ControlFile->minRecoveryPoint = minRecoveryLoc;
4836 ControlFile->time = time(NULL);
4837 UpdateControlFile();
4840 * If there was a backup label file, it's done its job and the info
4841 * has now been propagated into pg_control. We must get rid of the
4842 * label file so that if we crash during recovery, we'll pick up at
4843 * the latest recovery restartpoint instead of going all the way back
4844 * to the backup start point. It seems prudent though to just rename
4845 * the file out of the way rather than delete it completely.
4847 if (haveBackupLabel)
4849 unlink(BACKUP_LABEL_OLD);
4850 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4852 (errcode_for_file_access(),
4853 errmsg("could not rename file \"%s\" to \"%s\": %m",
4854 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4857 /* Start up the recovery environment */
4858 XLogInitRelationCache();
4860 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4862 if (RmgrTable[rmid].rm_startup != NULL)
4863 RmgrTable[rmid].rm_startup();
4867 * Find the first record that logically follows the checkpoint --- it
4868 * might physically precede it, though.
4870 if (XLByteLT(checkPoint.redo, RecPtr))
4872 /* back up to find the record */
4873 record = ReadRecord(&(checkPoint.redo), PANIC);
4877 /* just have to read next record after CheckPoint */
4878 record = ReadRecord(NULL, LOG);
4883 bool recoveryContinue = true;
4884 bool recoveryApply = true;
4885 ErrorContextCallback errcontext;
4889 (errmsg("redo starts at %X/%X",
4890 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4893 * main redo apply loop
4902 initStringInfo(&buf);
4903 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4904 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4905 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4906 xlog_outrec(&buf, record);
4907 appendStringInfo(&buf, " - ");
4908 RmgrTable[record->xl_rmid].rm_desc(&buf,
4910 XLogRecGetData(record));
4911 elog(LOG, "%s", buf.data);
4917 * Have we reached our recovery target?
4919 if (recoveryStopsHere(record, &recoveryApply))
4921 needNewTimeLine = true; /* see below */
4922 recoveryContinue = false;
4927 /* Setup error traceback support for ereport() */
4928 errcontext.callback = rm_redo_error_callback;
4929 errcontext.arg = (void *) record;
4930 errcontext.previous = error_context_stack;
4931 error_context_stack = &errcontext;
4933 /* nextXid must be beyond record's xid */
4934 if (TransactionIdFollowsOrEquals(record->xl_xid,
4935 ShmemVariableCache->nextXid))
4937 ShmemVariableCache->nextXid = record->xl_xid;
4938 TransactionIdAdvance(ShmemVariableCache->nextXid);
4941 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4942 RestoreBkpBlocks(record, EndRecPtr);
4944 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4946 /* Pop the error context stack */
4947 error_context_stack = errcontext.previous;
4949 LastRec = ReadRecPtr;
4951 record = ReadRecord(NULL, LOG);
4952 } while (record != NULL && recoveryContinue);
4955 * end of main redo apply loop
4959 (errmsg("redo done at %X/%X",
4960 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4965 /* there are no WAL records following the checkpoint */
4967 (errmsg("redo is not required")));
4972 * Re-fetch the last valid or last applied record, so we can identify the
4973 * exact endpoint of what we consider the valid portion of WAL.
4975 record = ReadRecord(&LastRec, PANIC);
4976 EndOfLog = EndRecPtr;
4977 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4980 * Complain if we did not roll forward far enough to render the backup
4983 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
4985 if (needNewTimeLine) /* stopped because of stop request */
4987 (errmsg("requested recovery stop point is before end time of backup dump")));
4989 /* ran off end of WAL */
4991 (errmsg("WAL ends before end time of backup dump")));
4995 * Consider whether we need to assign a new timeline ID.
4997 * If we stopped short of the end of WAL during recovery, then we are
4998 * generating a new timeline and must assign it a unique new ID.
4999 * Otherwise, we can just extend the timeline we were in when we ran out
5002 if (needNewTimeLine)
5004 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5006 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5007 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5008 curFileTLI, endLogId, endLogSeg);
5011 /* Save the selected TimeLineID in shared memory, too */
5012 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5015 * We are now done reading the old WAL. Turn off archive fetching if it
5016 * was active, and make a writable copy of the last WAL segment. (Note
5017 * that we also have a copy of the last block of the old WAL in readBuf;
5018 * we will use that below.)
5020 if (InArchiveRecovery)
5021 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5024 * Prepare to write WAL starting at EndOfLog position, and init xlog
5025 * buffer cache using the block containing the last record from the
5026 * previous incarnation.
5028 openLogId = endLogId;
5029 openLogSeg = endLogSeg;
5030 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5032 Insert = &XLogCtl->Insert;
5033 Insert->PrevRecord = LastRec;
5034 XLogCtl->xlblocks[0].xlogid = openLogId;
5035 XLogCtl->xlblocks[0].xrecoff =
5036 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5039 * Tricky point here: readBuf contains the *last* block that the LastRec
5040 * record spans, not the one it starts in. The last block is indeed the
5041 * one we want to use.
5043 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5044 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5045 Insert->currpos = (char *) Insert->currpage +
5046 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5048 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5050 XLogCtl->Write.LogwrtResult = LogwrtResult;
5051 Insert->LogwrtResult = LogwrtResult;
5052 XLogCtl->LogwrtResult = LogwrtResult;
5054 XLogCtl->LogwrtRqst.Write = EndOfLog;
5055 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5057 freespace = INSERT_FREESPACE(Insert);
5060 /* Make sure rest of page is zero */
5061 MemSet(Insert->currpos, 0, freespace);
5062 XLogCtl->Write.curridx = 0;
5067 * Whenever Write.LogwrtResult points to exactly the end of a page,
5068 * Write.curridx must point to the *next* page (see XLogWrite()).
5070 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5071 * this is sufficient. The first actual attempt to insert a log
5072 * record will advance the insert state.
5074 XLogCtl->Write.curridx = NextBufIdx(0);
5077 /* Pre-scan prepared transactions to find out the range of XIDs present */
5078 oldestActiveXID = PrescanPreparedTransactions();
5085 * Allow resource managers to do any required cleanup.
5087 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5089 if (RmgrTable[rmid].rm_cleanup != NULL)
5090 RmgrTable[rmid].rm_cleanup();
5094 * Check to see if the XLOG sequence contained any unresolved
5095 * references to uninitialized pages.
5097 XLogCheckInvalidPages();
5100 * Reset pgstat data, because it may be invalid after recovery.
5105 * Perform a checkpoint to update all our recovery activity to disk.
5107 * Note that we write a shutdown checkpoint rather than an on-line
5108 * one. This is not particularly critical, but since we may be
5109 * assigning a new TLI, using a shutdown checkpoint allows us to have
5110 * the rule that TLI only changes in shutdown checkpoints, which
5111 * allows some extra error checking in xlog_redo.
5113 CreateCheckPoint(true, true);
5116 * Close down recovery environment
5118 XLogCloseRelationCache();
5122 * Preallocate additional log files, if wanted.
5124 (void) PreallocXlogFiles(EndOfLog);
5127 * Okay, we're officially UP.
5131 ControlFile->state = DB_IN_PRODUCTION;
5132 ControlFile->time = time(NULL);
5133 UpdateControlFile();
5135 /* start the archive_timeout timer running */
5136 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5138 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5139 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5140 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5142 /* Start up the commit log and related stuff, too */
5144 StartupSUBTRANS(oldestActiveXID);
5147 /* Reload shared-memory state for prepared transactions */
5148 RecoverPreparedTransactions();
5150 /* Shut down readFile facility, free space */
5163 free(readRecordBuf);
5164 readRecordBuf = NULL;
5165 readRecordBufSize = 0;
5170 * Subroutine to try to fetch and validate a prior checkpoint record.
5172 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5173 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5176 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5180 if (!XRecOffIsValid(RecPtr.xrecoff))
5186 (errmsg("invalid primary checkpoint link in control file")));
5190 (errmsg("invalid secondary checkpoint link in control file")));
5194 (errmsg("invalid checkpoint link in backup_label file")));
5200 record = ReadRecord(&RecPtr, LOG);
5208 (errmsg("invalid primary checkpoint record")));
5212 (errmsg("invalid secondary checkpoint record")));
5216 (errmsg("invalid checkpoint record")));
5221 if (record->xl_rmid != RM_XLOG_ID)
5227 (errmsg("invalid resource manager ID in primary checkpoint record")));
5231 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5235 (errmsg("invalid resource manager ID in checkpoint record")));
5240 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5241 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5247 (errmsg("invalid xl_info in primary checkpoint record")));
5251 (errmsg("invalid xl_info in secondary checkpoint record")));
5255 (errmsg("invalid xl_info in checkpoint record")));
5260 if (record->xl_len != sizeof(CheckPoint) ||
5261 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5267 (errmsg("invalid length of primary checkpoint record")));
5271 (errmsg("invalid length of secondary checkpoint record")));
5275 (errmsg("invalid length of checkpoint record")));
5284 * This must be called during startup of a backend process, except that
5285 * it need not be called in a standalone backend (which does StartupXLOG
5286 * instead). We need to initialize the local copies of ThisTimeLineID and
5289 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5290 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5291 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5294 InitXLOGAccess(void)
5296 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5297 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5298 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5299 (void) GetRedoRecPtr();
5303 * Once spawned, a backend may update its local RedoRecPtr from
5304 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5305 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5310 /* use volatile pointer to prevent code rearrangement */
5311 volatile XLogCtlData *xlogctl = XLogCtl;
5313 SpinLockAcquire(&xlogctl->info_lck);
5314 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5315 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5316 SpinLockRelease(&xlogctl->info_lck);
5322 * Get the time of the last xlog segment switch
5325 GetLastSegSwitchTime(void)
5329 /* Need WALWriteLock, but shared lock is sufficient */
5330 LWLockAcquire(WALWriteLock, LW_SHARED);
5331 result = XLogCtl->Write.lastSegSwitchTime;
5332 LWLockRelease(WALWriteLock);
5338 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5340 * This is exported for use by code that would like to have 64-bit XIDs.
5341 * We don't really support such things, but all XIDs within the system
5342 * can be presumed "close to" the result, and thus the epoch associated
5343 * with them can be determined.
5346 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5348 uint32 ckptXidEpoch;
5349 TransactionId ckptXid;
5350 TransactionId nextXid;
5352 /* Must read checkpoint info first, else have race condition */
5354 /* use volatile pointer to prevent code rearrangement */
5355 volatile XLogCtlData *xlogctl = XLogCtl;
5357 SpinLockAcquire(&xlogctl->info_lck);
5358 ckptXidEpoch = xlogctl->ckptXidEpoch;
5359 ckptXid = xlogctl->ckptXid;
5360 SpinLockRelease(&xlogctl->info_lck);
5363 /* Now fetch current nextXid */
5364 nextXid = ReadNewTransactionId();
5367 * nextXid is certainly logically later than ckptXid. So if it's
5368 * numerically less, it must have wrapped into the next epoch.
5370 if (nextXid < ckptXid)
5374 *epoch = ckptXidEpoch;
5378 * This must be called ONCE during postmaster or standalone-backend shutdown
5381 ShutdownXLOG(int code, Datum arg)
5384 (errmsg("shutting down")));
5386 CreateCheckPoint(true, true);
5389 ShutdownMultiXact();
5392 (errmsg("database system is shut down")));
5396 * Perform a checkpoint --- either during shutdown, or on-the-fly
5398 * If force is true, we force a checkpoint regardless of whether any XLOG
5399 * activity has occurred since the last one.
5402 CreateCheckPoint(bool shutdown, bool force)
5404 CheckPoint checkPoint;
5406 XLogCtlInsert *Insert = &XLogCtl->Insert;
5412 int nsegsremoved = 0;
5413 int nsegsrecycled = 0;
5414 TransactionId *inCommitXids;
5418 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5419 * (This is just pro forma, since in the present system structure there is
5420 * only one process that is allowed to issue checkpoints at any given
5423 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5426 * Use a critical section to force system panic if we have trouble.
5428 START_CRIT_SECTION();
5432 ControlFile->state = DB_SHUTDOWNING;
5433 ControlFile->time = time(NULL);
5434 UpdateControlFile();
5437 MemSet(&checkPoint, 0, sizeof(checkPoint));
5438 checkPoint.ThisTimeLineID = ThisTimeLineID;
5439 checkPoint.time = time(NULL);
5442 * We must hold WALInsertLock while examining insert state to determine
5443 * the checkpoint REDO pointer.
5445 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5448 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5449 * any XLOG records since the start of the last checkpoint, skip the
5450 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5451 * when the system is idle. That wastes log space, and more importantly it
5452 * exposes us to possible loss of both current and previous checkpoint
5453 * records if the machine crashes just as we're writing the update.
5454 * (Perhaps it'd make even more sense to checkpoint only when the previous
5455 * checkpoint record is in a different xlog page?)
5457 * We have to make two tests to determine that nothing has happened since
5458 * the start of the last checkpoint: current insertion point must match
5459 * the end of the last checkpoint record, and its redo pointer must point
5462 if (!shutdown && !force)
5464 XLogRecPtr curInsert;
5466 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5467 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5468 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5469 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5470 ControlFile->checkPoint.xlogid ==
5471 ControlFile->checkPointCopy.redo.xlogid &&
5472 ControlFile->checkPoint.xrecoff ==
5473 ControlFile->checkPointCopy.redo.xrecoff)
5475 LWLockRelease(WALInsertLock);
5476 LWLockRelease(CheckpointLock);
5483 * Compute new REDO record ptr = location of next XLOG record.
5485 * NB: this is NOT necessarily where the checkpoint record itself will be,
5486 * since other backends may insert more XLOG records while we're off doing
5487 * the buffer flush work. Those XLOG records are logically after the
5488 * checkpoint, even though physically before it. Got that?
5490 freespace = INSERT_FREESPACE(Insert);
5491 if (freespace < SizeOfXLogRecord)
5493 (void) AdvanceXLInsertBuffer(false);
5494 /* OK to ignore update return flag, since we will do flush anyway */
5495 freespace = INSERT_FREESPACE(Insert);
5497 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5500 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5501 * must be done while holding the insert lock AND the info_lck.
5503 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5504 * pointing past where it really needs to point. This is okay; the only
5505 * consequence is that XLogInsert might back up whole buffers that it
5506 * didn't really need to. We can't postpone advancing RedoRecPtr because
5507 * XLogInserts that happen while we are dumping buffers must assume that
5508 * their buffer changes are not included in the checkpoint.
5511 /* use volatile pointer to prevent code rearrangement */
5512 volatile XLogCtlData *xlogctl = XLogCtl;
5514 SpinLockAcquire(&xlogctl->info_lck);
5515 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5516 SpinLockRelease(&xlogctl->info_lck);
5520 * Now we can release WAL insert lock, allowing other xacts to proceed
5521 * while we are flushing disk buffers.
5523 LWLockRelease(WALInsertLock);
5527 (errmsg("checkpoint starting")));
5530 * Before flushing data, we must wait for any transactions that are
5531 * currently in their commit critical sections. If an xact inserted its
5532 * commit record into XLOG just before the REDO point, then a crash
5533 * restart from the REDO point would not replay that record, which means
5534 * that our flushing had better include the xact's update of pg_clog. So
5535 * we wait till he's out of his commit critical section before proceeding.
5536 * See notes in RecordTransactionCommit().
5538 * Because we've already released WALInsertLock, this test is a bit fuzzy:
5539 * it is possible that we will wait for xacts we didn't really need to
5540 * wait for. But the delay should be short and it seems better to make
5541 * checkpoint take a bit longer than to hold locks longer than necessary.
5542 * (In fact, the whole reason we have this issue is that xact.c does
5543 * commit record XLOG insertion and clog update as two separate steps
5544 * protected by different locks, but again that seems best on grounds
5545 * of minimizing lock contention.)
5547 * A transaction that has not yet set inCommit when we look cannot be
5548 * at risk, since he's not inserted his commit record yet; and one that's
5549 * already cleared it is not at risk either, since he's done fixing clog
5550 * and we will correctly flush the update below. So we cannot miss any
5551 * xacts we need to wait for.
5553 nInCommit = GetTransactionsInCommit(&inCommitXids);
5557 pg_usleep(10000L); /* wait for 10 msec */
5558 } while (HaveTransactionsInCommit(inCommitXids, nInCommit));
5560 pfree(inCommitXids);
5563 * Get the other info we need for the checkpoint record.
5565 LWLockAcquire(XidGenLock, LW_SHARED);
5566 checkPoint.nextXid = ShmemVariableCache->nextXid;
5567 LWLockRelease(XidGenLock);
5569 /* Increase XID epoch if we've wrapped around since last checkpoint */
5570 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5571 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5572 checkPoint.nextXidEpoch++;
5574 LWLockAcquire(OidGenLock, LW_SHARED);
5575 checkPoint.nextOid = ShmemVariableCache->nextOid;
5577 checkPoint.nextOid += ShmemVariableCache->oidCount;
5578 LWLockRelease(OidGenLock);
5580 MultiXactGetCheckptMulti(shutdown,
5581 &checkPoint.nextMulti,
5582 &checkPoint.nextMultiOffset);
5585 * Having constructed the checkpoint record, ensure all shmem disk buffers
5586 * and commit-log buffers are flushed to disk.
5588 * This I/O could fail for various reasons. If so, we will fail to
5589 * complete the checkpoint, but there is no reason to force a system
5590 * panic. Accordingly, exit critical section while doing it.
5594 CheckPointGuts(checkPoint.redo);
5596 START_CRIT_SECTION();
5599 * Now insert the checkpoint record into XLOG.
5601 rdata.data = (char *) (&checkPoint);
5602 rdata.len = sizeof(checkPoint);
5603 rdata.buffer = InvalidBuffer;
5606 recptr = XLogInsert(RM_XLOG_ID,
5607 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5608 XLOG_CHECKPOINT_ONLINE,
5614 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5615 * = end of actual checkpoint record.
5617 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5619 (errmsg("concurrent transaction log activity while database system is shutting down")));
5622 * Select point at which we can truncate the log, which we base on the
5623 * prior checkpoint's earliest info.
5625 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5628 * Update the control file.
5630 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5632 ControlFile->state = DB_SHUTDOWNED;
5633 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5634 ControlFile->checkPoint = ProcLastRecPtr;
5635 ControlFile->checkPointCopy = checkPoint;
5636 ControlFile->time = time(NULL);
5637 UpdateControlFile();
5638 LWLockRelease(ControlFileLock);
5640 /* Update shared-memory copy of checkpoint XID/epoch */
5642 /* use volatile pointer to prevent code rearrangement */
5643 volatile XLogCtlData *xlogctl = XLogCtl;
5645 SpinLockAcquire(&xlogctl->info_lck);
5646 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5647 xlogctl->ckptXid = checkPoint.nextXid;
5648 SpinLockRelease(&xlogctl->info_lck);
5652 * We are now done with critical updates; no need for system panic if we
5653 * have trouble while fooling with offline log segments.
5658 * Delete offline log files (those no longer needed even for previous
5661 if (_logId || _logSeg)
5663 PrevLogSeg(_logId, _logSeg);
5664 MoveOfflineLogs(_logId, _logSeg, recptr,
5665 &nsegsremoved, &nsegsrecycled);
5669 * Make more log segments if needed. (Do this after deleting offline log
5670 * segments, to avoid having peak disk space usage higher than necessary.)
5673 nsegsadded = PreallocXlogFiles(recptr);
5676 * Truncate pg_subtrans if possible. We can throw away all data before
5677 * the oldest XMIN of any running transaction. No future transaction will
5678 * attempt to reference any pg_subtrans entry older than that (see Asserts
5679 * in subtrans.c). During recovery, though, we mustn't do this because
5680 * StartupSUBTRANS hasn't been called yet.
5683 TruncateSUBTRANS(GetOldestXmin(true, false));
5687 (errmsg("checkpoint complete; %d transaction log file(s) added, %d removed, %d recycled",
5688 nsegsadded, nsegsremoved, nsegsrecycled)));
5690 LWLockRelease(CheckpointLock);
5694 * Flush all data in shared memory to disk, and fsync
5696 * This is the common code shared between regular checkpoints and
5697 * recovery restartpoints.
5700 CheckPointGuts(XLogRecPtr checkPointRedo)
5703 CheckPointSUBTRANS();
5704 CheckPointMultiXact();
5705 FlushBufferPool(); /* performs all required fsyncs */
5706 /* We deliberately delay 2PC checkpointing as long as possible */
5707 CheckPointTwoPhase(checkPointRedo);
5711 * Set a recovery restart point if appropriate
5713 * This is similar to CreateCheckpoint, but is used during WAL recovery
5714 * to establish a point from which recovery can roll forward without
5715 * replaying the entire recovery log. This function is called each time
5716 * a checkpoint record is read from XLOG; it must determine whether a
5717 * restartpoint is needed or not.
5720 RecoveryRestartPoint(const CheckPoint *checkPoint)
5726 * Do nothing if the elapsed time since the last restartpoint is less than
5727 * half of checkpoint_timeout. (We use a value less than
5728 * checkpoint_timeout so that variations in the timing of checkpoints on
5729 * the master, or speed of transmission of WAL segments to a slave, won't
5730 * make the slave skip a restartpoint once it's synced with the master.)
5731 * Checking true elapsed time keeps us from doing restartpoints too often
5732 * while rapidly scanning large amounts of WAL.
5734 elapsed_secs = time(NULL) - ControlFile->time;
5735 if (elapsed_secs < CheckPointTimeout / 2)
5739 * Is it safe to checkpoint? We must ask each of the resource managers
5740 * whether they have any partial state information that might prevent a
5741 * correct restart from this point. If so, we skip this opportunity, but
5742 * return at the next checkpoint record for another try.
5744 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5746 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5747 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5752 * OK, force data out to disk
5754 CheckPointGuts(checkPoint->redo);
5757 * Update pg_control so that any subsequent crash will restart from this
5758 * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
5761 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5762 ControlFile->checkPoint = ReadRecPtr;
5763 ControlFile->checkPointCopy = *checkPoint;
5764 ControlFile->time = time(NULL);
5765 UpdateControlFile();
5768 (errmsg("recovery restart point at %X/%X",
5769 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5773 * Write a NEXTOID log record
5776 XLogPutNextOid(Oid nextOid)
5780 rdata.data = (char *) (&nextOid);
5781 rdata.len = sizeof(Oid);
5782 rdata.buffer = InvalidBuffer;
5784 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5787 * We need not flush the NEXTOID record immediately, because any of the
5788 * just-allocated OIDs could only reach disk as part of a tuple insert or
5789 * update that would have its own XLOG record that must follow the NEXTOID
5790 * record. Therefore, the standard buffer LSN interlock applied to those
5791 * records will ensure no such OID reaches disk before the NEXTOID record
5794 * Note, however, that the above statement only covers state "within" the
5795 * database. When we use a generated OID as a file or directory name,
5796 * we are in a sense violating the basic WAL rule, because that filesystem
5797 * change may reach disk before the NEXTOID WAL record does. The impact
5798 * of this is that if a database crash occurs immediately afterward,
5799 * we might after restart re-generate the same OID and find that it
5800 * conflicts with the leftover file or directory. But since for safety's
5801 * sake we always loop until finding a nonconflicting filename, this poses
5802 * no real problem in practice. See pgsql-hackers discussion 27-Sep-2006.
5807 * Write an XLOG SWITCH record.
5809 * Here we just blindly issue an XLogInsert request for the record.
5810 * All the magic happens inside XLogInsert.
5812 * The return value is either the end+1 address of the switch record,
5813 * or the end+1 address of the prior segment if we did not need to
5814 * write a switch record because we are already at segment start.
5817 RequestXLogSwitch(void)
5822 /* XLOG SWITCH, alone among xlog record types, has no data */
5823 rdata.buffer = InvalidBuffer;
5828 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5834 * XLOG resource manager's routines
5837 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5839 uint8 info = record->xl_info & ~XLR_INFO_MASK;
5841 if (info == XLOG_NEXTOID)
5845 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5846 if (ShmemVariableCache->nextOid < nextOid)
5848 ShmemVariableCache->nextOid = nextOid;
5849 ShmemVariableCache->oidCount = 0;
5852 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5854 CheckPoint checkPoint;
5856 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5857 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5858 ShmemVariableCache->nextXid = checkPoint.nextXid;
5859 ShmemVariableCache->nextOid = checkPoint.nextOid;
5860 ShmemVariableCache->oidCount = 0;
5861 MultiXactSetNextMXact(checkPoint.nextMulti,
5862 checkPoint.nextMultiOffset);
5864 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5865 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5866 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5869 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
5871 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5873 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5874 !list_member_int(expectedTLIs,
5875 (int) checkPoint.ThisTimeLineID))
5877 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5878 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5879 /* Following WAL records should be run with new TLI */
5880 ThisTimeLineID = checkPoint.ThisTimeLineID;
5883 RecoveryRestartPoint(&checkPoint);
5885 else if (info == XLOG_CHECKPOINT_ONLINE)
5887 CheckPoint checkPoint;
5889 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5890 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5891 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5892 checkPoint.nextXid))
5893 ShmemVariableCache->nextXid = checkPoint.nextXid;
5894 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5896 ShmemVariableCache->nextOid = checkPoint.nextOid;
5897 ShmemVariableCache->oidCount = 0;
5899 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
5900 checkPoint.nextMultiOffset);
5902 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5903 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5904 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5906 /* TLI should not change in an on-line checkpoint */
5907 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5909 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5910 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5912 RecoveryRestartPoint(&checkPoint);
5914 else if (info == XLOG_NOOP)
5916 /* nothing to do here */
5918 else if (info == XLOG_SWITCH)
5920 /* nothing to do here */
5925 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
5927 uint8 info = xl_info & ~XLR_INFO_MASK;
5929 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5930 info == XLOG_CHECKPOINT_ONLINE)
5932 CheckPoint *checkpoint = (CheckPoint *) rec;
5934 appendStringInfo(buf, "checkpoint: redo %X/%X; "
5935 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
5936 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5937 checkpoint->ThisTimeLineID,
5938 checkpoint->nextXidEpoch, checkpoint->nextXid,
5939 checkpoint->nextOid,
5940 checkpoint->nextMulti,
5941 checkpoint->nextMultiOffset,
5942 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
5944 else if (info == XLOG_NOOP)
5946 appendStringInfo(buf, "xlog no-op");
5948 else if (info == XLOG_NEXTOID)
5952 memcpy(&nextOid, rec, sizeof(Oid));
5953 appendStringInfo(buf, "nextOid: %u", nextOid);
5955 else if (info == XLOG_SWITCH)
5957 appendStringInfo(buf, "xlog switch");
5960 appendStringInfo(buf, "UNKNOWN");
5966 xlog_outrec(StringInfo buf, XLogRecord *record)
5970 appendStringInfo(buf, "prev %X/%X; xid %u",
5971 record->xl_prev.xlogid, record->xl_prev.xrecoff,
5974 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
5976 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
5977 appendStringInfo(buf, "; bkpb%d", i + 1);
5980 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
5982 #endif /* WAL_DEBUG */
5989 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
5991 int new_sync_method;
5994 if (pg_strcasecmp(method, "fsync") == 0)
5996 new_sync_method = SYNC_METHOD_FSYNC;
5999 #ifdef HAVE_FSYNC_WRITETHROUGH
6000 else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
6002 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
6006 #ifdef HAVE_FDATASYNC
6007 else if (pg_strcasecmp(method, "fdatasync") == 0)
6009 new_sync_method = SYNC_METHOD_FDATASYNC;
6013 #ifdef OPEN_SYNC_FLAG
6014 else if (pg_strcasecmp(method, "open_sync") == 0)
6016 new_sync_method = SYNC_METHOD_OPEN;
6017 new_sync_bit = OPEN_SYNC_FLAG;
6020 #ifdef OPEN_DATASYNC_FLAG
6021 else if (pg_strcasecmp(method, "open_datasync") == 0)
6023 new_sync_method = SYNC_METHOD_OPEN;
6024 new_sync_bit = OPEN_DATASYNC_FLAG;
6033 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
6036 * To ensure that no blocks escape unsynced, force an fsync on the
6037 * currently open log segment (if any). Also, if the open flag is
6038 * changing, close the log file so it will be reopened (with new flag
6041 if (openLogFile >= 0)
6043 if (pg_fsync(openLogFile) != 0)
6045 (errcode_for_file_access(),
6046 errmsg("could not fsync log file %u, segment %u: %m",
6047 openLogId, openLogSeg)));
6048 if (open_sync_bit != new_sync_bit)
6051 sync_method = new_sync_method;
6052 open_sync_bit = new_sync_bit;
6060 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6063 issue_xlog_fsync(void)
6065 switch (sync_method)
6067 case SYNC_METHOD_FSYNC:
6068 if (pg_fsync_no_writethrough(openLogFile) != 0)
6070 (errcode_for_file_access(),
6071 errmsg("could not fsync log file %u, segment %u: %m",
6072 openLogId, openLogSeg)));
6074 #ifdef HAVE_FSYNC_WRITETHROUGH
6075 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6076 if (pg_fsync_writethrough(openLogFile) != 0)
6078 (errcode_for_file_access(),
6079 errmsg("could not fsync write-through log file %u, segment %u: %m",
6080 openLogId, openLogSeg)));
6083 #ifdef HAVE_FDATASYNC
6084 case SYNC_METHOD_FDATASYNC:
6085 if (pg_fdatasync(openLogFile) != 0)
6087 (errcode_for_file_access(),
6088 errmsg("could not fdatasync log file %u, segment %u: %m",
6089 openLogId, openLogSeg)));
6092 case SYNC_METHOD_OPEN:
6093 /* write synced it already */
6096 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6103 * pg_start_backup: set up for taking an on-line backup dump
6105 * Essentially what this does is to create a backup label file in $PGDATA,
6106 * where it will be archived as part of the backup dump. The label file
6107 * contains the user-supplied label string (typically this would be used
6108 * to tell where the backup dump will be stored) and the starting time and
6109 * starting WAL location for the dump.
6112 pg_start_backup(PG_FUNCTION_ARGS)
6114 text *backupid = PG_GETARG_TEXT_P(0);
6117 XLogRecPtr checkpointloc;
6118 XLogRecPtr startpoint;
6121 char xlogfilename[MAXFNAMELEN];
6124 struct stat stat_buf;
6129 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6130 (errmsg("must be superuser to run a backup"))));
6132 if (!XLogArchivingActive())
6134 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6135 (errmsg("WAL archiving is not active"),
6136 (errhint("archive_command must be defined before "
6137 "online backups can be made safely.")))));
6139 backupidstr = DatumGetCString(DirectFunctionCall1(textout,
6140 PointerGetDatum(backupid)));
6143 * Mark backup active in shared memory. We must do full-page WAL writes
6144 * during an on-line backup even if not doing so at other times, because
6145 * it's quite possible for the backup dump to obtain a "torn" (partially
6146 * written) copy of a database page if it reads the page concurrently with
6147 * our write to the same page. This can be fixed as long as the first
6148 * write to the page in the WAL sequence is a full-page write. Hence, we
6149 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6150 * are no dirty pages in shared memory that might get dumped while the
6151 * backup is in progress without having a corresponding WAL record. (Once
6152 * the backup is complete, we need not force full-page writes anymore,
6153 * since we expect that any pages not modified during the backup interval
6154 * must have been correctly captured by the backup.)
6156 * We must hold WALInsertLock to change the value of forcePageWrites, to
6157 * ensure adequate interlocking against XLogInsert().
6159 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6160 if (XLogCtl->Insert.forcePageWrites)
6162 LWLockRelease(WALInsertLock);
6164 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6165 errmsg("a backup is already in progress"),
6166 errhint("Run pg_stop_backup() and try again.")));
6168 XLogCtl->Insert.forcePageWrites = true;
6169 LWLockRelease(WALInsertLock);
6171 /* Use a TRY block to ensure we release forcePageWrites if fail below */
6175 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6176 * page problems, this guarantees that two successive backup runs will
6177 * have different checkpoint positions and hence different history
6178 * file names, even if nothing happened in between.
6180 RequestCheckpoint(true, false);
6183 * Now we need to fetch the checkpoint record location, and also its
6184 * REDO pointer. The oldest point in WAL that would be needed to
6185 * restore starting from the checkpoint is precisely the REDO pointer.
6187 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6188 checkpointloc = ControlFile->checkPoint;
6189 startpoint = ControlFile->checkPointCopy.redo;
6190 LWLockRelease(ControlFileLock);
6192 XLByteToSeg(startpoint, _logId, _logSeg);
6193 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6196 * We deliberately use strftime/localtime not the src/timezone
6197 * functions, so that backup labels will consistently be recorded in
6198 * the same timezone regardless of TimeZone setting. This matches
6199 * elog.c's practice.
6201 stamp_time = time(NULL);
6202 strftime(strfbuf, sizeof(strfbuf),
6203 "%Y-%m-%d %H:%M:%S %Z",
6204 localtime(&stamp_time));
6207 * Check for existing backup label --- implies a backup is already
6208 * running. (XXX given that we checked forcePageWrites above, maybe
6209 * it would be OK to just unlink any such label file?)
6211 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6213 if (errno != ENOENT)
6215 (errcode_for_file_access(),
6216 errmsg("could not stat file \"%s\": %m",
6217 BACKUP_LABEL_FILE)));
6221 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6222 errmsg("a backup is already in progress"),
6223 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6224 BACKUP_LABEL_FILE)));
6227 * Okay, write the file
6229 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6232 (errcode_for_file_access(),
6233 errmsg("could not create file \"%s\": %m",
6234 BACKUP_LABEL_FILE)));
6235 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6236 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6237 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6238 checkpointloc.xlogid, checkpointloc.xrecoff);
6239 fprintf(fp, "START TIME: %s\n", strfbuf);
6240 fprintf(fp, "LABEL: %s\n", backupidstr);
6241 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6243 (errcode_for_file_access(),
6244 errmsg("could not write file \"%s\": %m",
6245 BACKUP_LABEL_FILE)));
6249 /* Turn off forcePageWrites on failure */
6250 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6251 XLogCtl->Insert.forcePageWrites = false;
6252 LWLockRelease(WALInsertLock);
6259 * We're done. As a convenience, return the starting WAL location.
6261 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6262 startpoint.xlogid, startpoint.xrecoff);
6263 result = DatumGetTextP(DirectFunctionCall1(textin,
6264 CStringGetDatum(xlogfilename)));
6265 PG_RETURN_TEXT_P(result);
6269 * pg_stop_backup: finish taking an on-line backup dump
6271 * We remove the backup label file created by pg_start_backup, and instead
6272 * create a backup history file in pg_xlog (whence it will immediately be
6273 * archived). The backup history file contains the same info found in
6274 * the label file, plus the backup-end time and WAL location.
6277 pg_stop_backup(PG_FUNCTION_ARGS)
6280 XLogRecPtr startpoint;
6281 XLogRecPtr stoppoint;
6284 char histfilepath[MAXPGPATH];
6285 char startxlogfilename[MAXFNAMELEN];
6286 char stopxlogfilename[MAXFNAMELEN];
6296 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6297 (errmsg("must be superuser to run a backup"))));
6300 * OK to clear forcePageWrites
6302 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6303 XLogCtl->Insert.forcePageWrites = false;
6304 LWLockRelease(WALInsertLock);
6307 * Force a switch to a new xlog segment file, so that the backup is valid
6308 * as soon as archiver moves out the current segment file. We'll report
6309 * the end address of the XLOG SWITCH record as the backup stopping point.
6311 stoppoint = RequestXLogSwitch();
6313 XLByteToSeg(stoppoint, _logId, _logSeg);
6314 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
6317 * We deliberately use strftime/localtime not the src/timezone functions,
6318 * so that backup labels will consistently be recorded in the same
6319 * timezone regardless of TimeZone setting. This matches elog.c's
6322 stamp_time = time(NULL);
6323 strftime(strfbuf, sizeof(strfbuf),
6324 "%Y-%m-%d %H:%M:%S %Z",
6325 localtime(&stamp_time));
6328 * Open the existing label file
6330 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6333 if (errno != ENOENT)
6335 (errcode_for_file_access(),
6336 errmsg("could not read file \"%s\": %m",
6337 BACKUP_LABEL_FILE)));
6339 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6340 errmsg("a backup is not in progress")));
6344 * Read and parse the START WAL LOCATION line (this code is pretty crude,
6345 * but we are not expecting any variability in the file format).
6347 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
6348 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6349 &ch) != 4 || ch != '\n')
6351 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6352 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6355 * Write the backup history file
6357 XLByteToSeg(startpoint, _logId, _logSeg);
6358 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6359 startpoint.xrecoff % XLogSegSize);
6360 fp = AllocateFile(histfilepath, "w");
6363 (errcode_for_file_access(),
6364 errmsg("could not create file \"%s\": %m",
6366 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6367 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
6368 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
6369 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
6370 /* transfer remaining lines from label to history file */
6371 while ((ich = fgetc(lfp)) != EOF)
6373 fprintf(fp, "STOP TIME: %s\n", strfbuf);
6374 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6376 (errcode_for_file_access(),
6377 errmsg("could not write file \"%s\": %m",
6381 * Close and remove the backup label file
6383 if (ferror(lfp) || FreeFile(lfp))
6385 (errcode_for_file_access(),
6386 errmsg("could not read file \"%s\": %m",
6387 BACKUP_LABEL_FILE)));
6388 if (unlink(BACKUP_LABEL_FILE) != 0)
6390 (errcode_for_file_access(),
6391 errmsg("could not remove file \"%s\": %m",
6392 BACKUP_LABEL_FILE)));
6395 * Clean out any no-longer-needed history files. As a side effect, this
6396 * will post a .ready file for the newly created history file, notifying
6397 * the archiver that history file may be archived immediately.
6399 CleanupBackupHistory();
6402 * We're done. As a convenience, return the ending WAL location.
6404 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
6405 stoppoint.xlogid, stoppoint.xrecoff);
6406 result = DatumGetTextP(DirectFunctionCall1(textin,
6407 CStringGetDatum(stopxlogfilename)));
6408 PG_RETURN_TEXT_P(result);
6412 * pg_switch_xlog: switch to next xlog file
6415 pg_switch_xlog(PG_FUNCTION_ARGS)
6418 XLogRecPtr switchpoint;
6419 char location[MAXFNAMELEN];
6423 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6424 (errmsg("must be superuser to switch transaction log files"))));
6426 switchpoint = RequestXLogSwitch();
6429 * As a convenience, return the WAL location of the switch record
6431 snprintf(location, sizeof(location), "%X/%X",
6432 switchpoint.xlogid, switchpoint.xrecoff);
6433 result = DatumGetTextP(DirectFunctionCall1(textin,
6434 CStringGetDatum(location)));
6435 PG_RETURN_TEXT_P(result);
6439 * Report the current WAL write location (same format as pg_start_backup etc)
6441 * This is useful for determining how much of WAL is visible to an external
6442 * archiving process. Note that the data before this point is written out
6443 * to the kernel, but is not necessarily synced to disk.
6446 pg_current_xlog_location(PG_FUNCTION_ARGS)
6449 char location[MAXFNAMELEN];
6451 /* Make sure we have an up-to-date local LogwrtResult */
6453 /* use volatile pointer to prevent code rearrangement */
6454 volatile XLogCtlData *xlogctl = XLogCtl;
6456 SpinLockAcquire(&xlogctl->info_lck);
6457 LogwrtResult = xlogctl->LogwrtResult;
6458 SpinLockRelease(&xlogctl->info_lck);
6461 snprintf(location, sizeof(location), "%X/%X",
6462 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
6464 result = DatumGetTextP(DirectFunctionCall1(textin,
6465 CStringGetDatum(location)));
6466 PG_RETURN_TEXT_P(result);
6470 * Report the current WAL insert location (same format as pg_start_backup etc)
6472 * This function is mostly for debugging purposes.
6475 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
6478 XLogCtlInsert *Insert = &XLogCtl->Insert;
6479 XLogRecPtr current_recptr;
6480 char location[MAXFNAMELEN];
6483 * Get the current end-of-WAL position ... shared lock is sufficient
6485 LWLockAcquire(WALInsertLock, LW_SHARED);
6486 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
6487 LWLockRelease(WALInsertLock);
6489 snprintf(location, sizeof(location), "%X/%X",
6490 current_recptr.xlogid, current_recptr.xrecoff);
6492 result = DatumGetTextP(DirectFunctionCall1(textin,
6493 CStringGetDatum(location)));
6494 PG_RETURN_TEXT_P(result);
6498 * Compute an xlog file name and decimal byte offset given a WAL location,
6499 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6501 * Note that a location exactly at a segment boundary is taken to be in
6502 * the previous segment. This is usually the right thing, since the
6503 * expected usage is to determine which xlog file(s) are ready to archive.
6506 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
6508 text *location = PG_GETARG_TEXT_P(0);
6510 unsigned int uxlogid;
6511 unsigned int uxrecoff;
6515 XLogRecPtr locationpoint;
6516 char xlogfilename[MAXFNAMELEN];
6519 TupleDesc resultTupleDesc;
6520 HeapTuple resultHeapTuple;
6524 * Read input and parse
6526 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6527 PointerGetDatum(location)));
6529 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6531 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6532 errmsg("could not parse transaction log location \"%s\"",
6535 locationpoint.xlogid = uxlogid;
6536 locationpoint.xrecoff = uxrecoff;
6539 * Construct a tuple descriptor for the result row. This must match this
6540 * function's pg_proc entry!
6542 resultTupleDesc = CreateTemplateTupleDesc(2, false);
6543 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
6545 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
6548 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
6553 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6554 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6556 values[0] = DirectFunctionCall1(textin,
6557 CStringGetDatum(xlogfilename));
6563 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
6565 values[1] = UInt32GetDatum(xrecoff);
6569 * Tuple jam: Having first prepared your Datums, then squash together
6571 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
6573 result = HeapTupleGetDatum(resultHeapTuple);
6575 PG_RETURN_DATUM(result);
6579 * Compute an xlog file name given a WAL location,
6580 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6583 pg_xlogfile_name(PG_FUNCTION_ARGS)
6585 text *location = PG_GETARG_TEXT_P(0);
6588 unsigned int uxlogid;
6589 unsigned int uxrecoff;
6592 XLogRecPtr locationpoint;
6593 char xlogfilename[MAXFNAMELEN];
6595 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6596 PointerGetDatum(location)));
6598 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6600 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6601 errmsg("could not parse transaction log location \"%s\"",
6604 locationpoint.xlogid = uxlogid;
6605 locationpoint.xrecoff = uxrecoff;
6607 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6608 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6610 result = DatumGetTextP(DirectFunctionCall1(textin,
6611 CStringGetDatum(xlogfilename)));
6612 PG_RETURN_TEXT_P(result);
6616 * read_backup_label: check to see if a backup_label file is present
6618 * If we see a backup_label during recovery, we assume that we are recovering
6619 * from a backup dump file, and we therefore roll forward from the checkpoint
6620 * identified by the label file, NOT what pg_control says. This avoids the
6621 * problem that pg_control might have been archived one or more checkpoints
6622 * later than the start of the dump, and so if we rely on it as the start
6623 * point, we will fail to restore a consistent database state.
6625 * We also attempt to retrieve the corresponding backup history file.
6626 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6629 * Returns TRUE if a backup_label was found (and fills the checkpoint
6630 * location into *checkPointLoc); returns FALSE if not.
6633 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6635 XLogRecPtr startpoint;
6636 XLogRecPtr stoppoint;
6637 char histfilename[MAXFNAMELEN];
6638 char histfilepath[MAXPGPATH];
6639 char startxlogfilename[MAXFNAMELEN];
6640 char stopxlogfilename[MAXFNAMELEN];
6648 /* Default is to not constrain recovery stop point */
6649 minRecoveryLoc->xlogid = 0;
6650 minRecoveryLoc->xrecoff = 0;
6653 * See if label file is present
6655 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6658 if (errno != ENOENT)
6660 (errcode_for_file_access(),
6661 errmsg("could not read file \"%s\": %m",
6662 BACKUP_LABEL_FILE)));
6663 return false; /* it's not there, all is fine */
6667 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
6668 * is pretty crude, but we are not expecting any variability in the file
6671 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
6672 &startpoint.xlogid, &startpoint.xrecoff, &tli,
6673 startxlogfilename, &ch) != 5 || ch != '\n')
6675 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6676 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6677 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
6678 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
6679 &ch) != 3 || ch != '\n')
6681 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6682 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6683 if (ferror(lfp) || FreeFile(lfp))
6685 (errcode_for_file_access(),
6686 errmsg("could not read file \"%s\": %m",
6687 BACKUP_LABEL_FILE)));
6690 * Try to retrieve the backup history file (no error if we can't)
6692 XLByteToSeg(startpoint, _logId, _logSeg);
6693 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
6694 startpoint.xrecoff % XLogSegSize);
6696 if (InArchiveRecovery)
6697 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
6699 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
6700 startpoint.xrecoff % XLogSegSize);
6702 fp = AllocateFile(histfilepath, "r");
6706 * Parse history file to identify stop point.
6708 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
6709 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6710 &ch) != 4 || ch != '\n')
6712 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6713 errmsg("invalid data in file \"%s\"", histfilename)));
6714 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
6715 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6716 &ch) != 4 || ch != '\n')
6718 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6719 errmsg("invalid data in file \"%s\"", histfilename)));
6720 *minRecoveryLoc = stoppoint;
6721 if (ferror(fp) || FreeFile(fp))
6723 (errcode_for_file_access(),
6724 errmsg("could not read file \"%s\": %m",
6732 * Error context callback for errors occurring during rm_redo().
6735 rm_redo_error_callback(void *arg)
6737 XLogRecord *record = (XLogRecord *) arg;
6740 initStringInfo(&buf);
6741 RmgrTable[record->xl_rmid].rm_desc(&buf,
6743 XLogRecGetData(record));
6745 /* don't bother emitting empty description */
6747 errcontext("xlog redo %s", buf.data);