1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/access/transam/xlog.c,v 1.250 2006/10/04 00:29:49 momjian Exp $
12 *-------------------------------------------------------------------------
25 #include "access/clog.h"
26 #include "access/heapam.h"
27 #include "access/multixact.h"
28 #include "access/subtrans.h"
29 #include "access/transam.h"
30 #include "access/twophase.h"
31 #include "access/xact.h"
32 #include "access/xlog_internal.h"
33 #include "access/xlogutils.h"
34 #include "catalog/catversion.h"
35 #include "catalog/pg_control.h"
36 #include "catalog/pg_type.h"
38 #include "miscadmin.h"
40 #include "postmaster/bgwriter.h"
41 #include "storage/bufpage.h"
42 #include "storage/fd.h"
43 #include "storage/pmsignal.h"
44 #include "storage/procarray.h"
45 #include "storage/spin.h"
46 #include "utils/builtins.h"
47 #include "utils/nabstime.h"
48 #include "utils/pg_locale.h"
52 * Because O_DIRECT bypasses the kernel buffers, and because we never
53 * read those buffers except during crash recovery, it is a win to use
54 * it in all cases where we sync on each write(). We could allow O_DIRECT
55 * with fsync(), but because skipping the kernel buffer forces writes out
56 * quickly, it seems best just to use it for O_SYNC. It is hard to imagine
57 * how fsync() could be a win for O_DIRECT compared to O_SYNC and O_DIRECT.
58 * Also, O_DIRECT is never enough to force data to the drives, it merely
59 * tries to bypass the kernel cache, so we still need O_SYNC or fsync().
62 #define PG_O_DIRECT O_DIRECT
68 * This chunk of hackery attempts to determine which file sync methods
69 * are available on the current platform, and to choose an appropriate
70 * default method. We assume that fsync() is always available, and that
71 * configure determined whether fdatasync() is.
74 #define BARE_OPEN_SYNC_FLAG O_SYNC
75 #elif defined(O_FSYNC)
76 #define BARE_OPEN_SYNC_FLAG O_FSYNC
78 #ifdef BARE_OPEN_SYNC_FLAG
79 #define OPEN_SYNC_FLAG (BARE_OPEN_SYNC_FLAG | PG_O_DIRECT)
83 #if defined(OPEN_SYNC_FLAG)
84 /* O_DSYNC is distinct? */
85 #if O_DSYNC != BARE_OPEN_SYNC_FLAG
86 #define OPEN_DATASYNC_FLAG (O_DSYNC | PG_O_DIRECT)
88 #else /* !defined(OPEN_SYNC_FLAG) */
89 /* Win32 only has O_DSYNC */
90 #define OPEN_DATASYNC_FLAG (O_DSYNC | PG_O_DIRECT)
94 #if defined(OPEN_DATASYNC_FLAG)
95 #define DEFAULT_SYNC_METHOD_STR "open_datasync"
96 #define DEFAULT_SYNC_METHOD SYNC_METHOD_OPEN
97 #define DEFAULT_SYNC_FLAGBIT OPEN_DATASYNC_FLAG
98 #elif defined(HAVE_FDATASYNC)
99 #define DEFAULT_SYNC_METHOD_STR "fdatasync"
100 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FDATASYNC
101 #define DEFAULT_SYNC_FLAGBIT 0
102 #elif defined(HAVE_FSYNC_WRITETHROUGH_ONLY)
103 #define DEFAULT_SYNC_METHOD_STR "fsync_writethrough"
104 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FSYNC_WRITETHROUGH
105 #define DEFAULT_SYNC_FLAGBIT 0
107 #define DEFAULT_SYNC_METHOD_STR "fsync"
108 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FSYNC
109 #define DEFAULT_SYNC_FLAGBIT 0
114 * Limitation of buffer-alignment for direct IO depends on OS and filesystem,
115 * but XLOG_BLCKSZ is assumed to be enough for it.
118 #define ALIGNOF_XLOG_BUFFER XLOG_BLCKSZ
120 #define ALIGNOF_XLOG_BUFFER ALIGNOF_BUFFER
124 /* File path names (all relative to $PGDATA) */
125 #define BACKUP_LABEL_FILE "backup_label"
126 #define BACKUP_LABEL_OLD "backup_label.old"
127 #define RECOVERY_COMMAND_FILE "recovery.conf"
128 #define RECOVERY_COMMAND_DONE "recovery.done"
131 /* User-settable parameters */
132 int CheckPointSegments = 3;
134 int XLogArchiveTimeout = 0;
135 char *XLogArchiveCommand = NULL;
136 char *XLOG_sync_method = NULL;
137 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
138 bool fullPageWrites = true;
141 bool XLOG_DEBUG = false;
145 * XLOGfileslop is used in the code as the allowed "fuzz" in the number of
146 * preallocated XLOG segments --- we try to have at least XLOGfiles advance
147 * segments but no more than XLOGfileslop segments. This could
148 * be made a separate GUC variable, but at present I think it's sufficient
149 * to hardwire it as 2*CheckPointSegments+1. Under normal conditions, a
150 * checkpoint will free no more than 2*CheckPointSegments log segments, and
151 * we want to recycle all of them; the +1 allows boundary cases to happen
152 * without wasting a delete/create-segment cycle.
155 #define XLOGfileslop (2*CheckPointSegments + 1)
158 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
159 int sync_method = DEFAULT_SYNC_METHOD;
160 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
162 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
166 * ThisTimeLineID will be same in all backends --- it identifies current
167 * WAL timeline for the database system.
169 TimeLineID ThisTimeLineID = 0;
171 /* Are we doing recovery from XLOG? */
172 bool InRecovery = false;
174 /* Are we recovering using offline XLOG archives? */
175 static bool InArchiveRecovery = false;
177 /* Was the last xlog file restored from archive, or local? */
178 static bool restoredFromArchive = false;
180 /* options taken from recovery.conf */
181 static char *recoveryRestoreCommand = NULL;
182 static bool recoveryTarget = false;
183 static bool recoveryTargetExact = false;
184 static bool recoveryTargetInclusive = true;
185 static TransactionId recoveryTargetXid;
186 static time_t recoveryTargetTime;
188 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
189 static TransactionId recoveryStopXid;
190 static time_t recoveryStopTime;
191 static bool recoveryStopAfter;
194 * During normal operation, the only timeline we care about is ThisTimeLineID.
195 * During recovery, however, things are more complicated. To simplify life
196 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
197 * scan through the WAL history (that is, it is the line that was active when
198 * the currently-scanned WAL record was generated). We also need these
201 * recoveryTargetTLI: the desired timeline that we want to end in.
203 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
204 * its known parents, newest first (so recoveryTargetTLI is always the
205 * first list member). Only these TLIs are expected to be seen in the WAL
206 * segments we read, and indeed only these TLIs will be considered as
207 * candidate WAL files to open at all.
209 * curFileTLI: the TLI appearing in the name of the current input WAL file.
210 * (This is not necessarily the same as ThisTimeLineID, because we could
211 * be scanning data that was copied from an ancestor timeline when the current
212 * file was created.) During a sequential scan we do not allow this value
215 static TimeLineID recoveryTargetTLI;
216 static List *expectedTLIs;
217 static TimeLineID curFileTLI;
220 * MyLastRecPtr points to the start of the last XLOG record inserted by the
221 * current transaction. If MyLastRecPtr.xrecoff == 0, then the current
222 * xact hasn't yet inserted any transaction-controlled XLOG records.
224 * Note that XLOG records inserted outside transaction control are not
225 * reflected into MyLastRecPtr. They do, however, cause MyXactMadeXLogEntry
226 * to be set true. The latter can be used to test whether the current xact
227 * made any loggable changes (including out-of-xact changes, such as
230 * When we insert/update/delete a tuple in a temporary relation, we do not
231 * make any XLOG record, since we don't care about recovering the state of
232 * the temp rel after a crash. However, we will still need to remember
233 * whether our transaction committed or aborted in that case. So, we must
234 * set MyXactMadeTempRelUpdate true to indicate that the XID will be of
237 XLogRecPtr MyLastRecPtr = {0, 0};
239 bool MyXactMadeXLogEntry = false;
241 bool MyXactMadeTempRelUpdate = false;
244 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
245 * current backend. It is updated for all inserts, transaction-controlled
246 * or not. ProcLastRecEnd is similar but points to end+1 of last record.
248 static XLogRecPtr ProcLastRecPtr = {0, 0};
250 XLogRecPtr ProcLastRecEnd = {0, 0};
253 * RedoRecPtr is this backend's local copy of the REDO record pointer
254 * (which is almost but not quite the same as a pointer to the most recent
255 * CHECKPOINT record). We update this from the shared-memory copy,
256 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
257 * hold the Insert lock). See XLogInsert for details. We are also allowed
258 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
259 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
262 static XLogRecPtr RedoRecPtr;
265 * Shared-memory data structures for XLOG control
267 * LogwrtRqst indicates a byte position that we need to write and/or fsync
268 * the log up to (all records before that point must be written or fsynced).
269 * LogwrtResult indicates the byte positions we have already written/fsynced.
270 * These structs are identical but are declared separately to indicate their
271 * slightly different functions.
273 * We do a lot of pushups to minimize the amount of access to lockable
274 * shared memory values. There are actually three shared-memory copies of
275 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
276 * XLogCtl->LogwrtResult is protected by info_lck
277 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
278 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
279 * One must hold the associated lock to read or write any of these, but
280 * of course no lock is needed to read/write the unshared LogwrtResult.
282 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
283 * right", since both are updated by a write or flush operation before
284 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
285 * is that it can be examined/modified by code that already holds WALWriteLock
286 * without needing to grab info_lck as well.
288 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
289 * but is updated when convenient. Again, it exists for the convenience of
290 * code that is already holding WALInsertLock but not the other locks.
292 * The unshared LogwrtResult may lag behind any or all of these, and again
293 * is updated when convenient.
295 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
296 * (protected by info_lck), but we don't need to cache any copies of it.
298 * Note that this all works because the request and result positions can only
299 * advance forward, never back up, and so we can easily determine which of two
300 * values is "more up to date".
302 * info_lck is only held long enough to read/update the protected variables,
303 * so it's a plain spinlock. The other locks are held longer (potentially
304 * over I/O operations), so we use LWLocks for them. These locks are:
306 * WALInsertLock: must be held to insert a record into the WAL buffers.
308 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
311 * ControlFileLock: must be held to read/update control file or create
314 * CheckpointLock: must be held to do a checkpoint (ensures only one
315 * checkpointer at a time; currently, with all checkpoints done by the
316 * bgwriter, this is just pro forma).
321 typedef struct XLogwrtRqst
323 XLogRecPtr Write; /* last byte + 1 to write out */
324 XLogRecPtr Flush; /* last byte + 1 to flush */
327 typedef struct XLogwrtResult
329 XLogRecPtr Write; /* last byte + 1 written out */
330 XLogRecPtr Flush; /* last byte + 1 flushed */
334 * Shared state data for XLogInsert.
336 typedef struct XLogCtlInsert
338 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
339 XLogRecPtr PrevRecord; /* start of previously-inserted record */
340 int curridx; /* current block index in cache */
341 XLogPageHeader currpage; /* points to header of block in cache */
342 char *currpos; /* current insertion point in cache */
343 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
344 bool forcePageWrites; /* forcing full-page writes for PITR? */
348 * Shared state data for XLogWrite/XLogFlush.
350 typedef struct XLogCtlWrite
352 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
353 int curridx; /* cache index of next block to write */
354 time_t lastSegSwitchTime; /* time of last xlog segment switch */
358 * Total shared-memory state for XLOG.
360 typedef struct XLogCtlData
362 /* Protected by WALInsertLock: */
363 XLogCtlInsert Insert;
365 /* Protected by info_lck: */
366 XLogwrtRqst LogwrtRqst;
367 XLogwrtResult LogwrtResult;
368 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
369 TransactionId ckptXid;
371 /* Protected by WALWriteLock: */
375 * These values do not change after startup, although the pointed-to pages
376 * and xlblocks values certainly do. Permission to read/write the pages
377 * and xlblocks values depends on WALInsertLock and WALWriteLock.
379 char *pages; /* buffers for unwritten XLOG pages */
380 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
381 Size XLogCacheByte; /* # bytes in xlog buffers */
382 int XLogCacheBlck; /* highest allocated xlog buffer index */
383 TimeLineID ThisTimeLineID;
385 slock_t info_lck; /* locks shared variables shown above */
388 static XLogCtlData *XLogCtl = NULL;
391 * We maintain an image of pg_control in shared memory.
393 static ControlFileData *ControlFile = NULL;
396 * Macros for managing XLogInsert state. In most cases, the calling routine
397 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
398 * so these are passed as parameters instead of being fetched via XLogCtl.
401 /* Free space remaining in the current xlog page buffer */
402 #define INSERT_FREESPACE(Insert) \
403 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
405 /* Construct XLogRecPtr value for current insertion point */
406 #define INSERT_RECPTR(recptr,Insert,curridx) \
408 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
410 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
413 #define PrevBufIdx(idx) \
414 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
416 #define NextBufIdx(idx) \
417 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
420 * Private, possibly out-of-date copy of shared LogwrtResult.
421 * See discussion above.
423 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
426 * openLogFile is -1 or a kernel FD for an open log file segment.
427 * When it's open, openLogOff is the current seek offset in the file.
428 * openLogId/openLogSeg identify the segment. These variables are only
429 * used to write the XLOG, and so will normally refer to the active segment.
431 static int openLogFile = -1;
432 static uint32 openLogId = 0;
433 static uint32 openLogSeg = 0;
434 static uint32 openLogOff = 0;
437 * These variables are used similarly to the ones above, but for reading
438 * the XLOG. Note, however, that readOff generally represents the offset
439 * of the page just read, not the seek position of the FD itself, which
440 * will be just past that page.
442 static int readFile = -1;
443 static uint32 readId = 0;
444 static uint32 readSeg = 0;
445 static uint32 readOff = 0;
447 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
448 static char *readBuf = NULL;
450 /* Buffer for current ReadRecord result (expandable) */
451 static char *readRecordBuf = NULL;
452 static uint32 readRecordBufSize = 0;
454 /* State information for XLOG reading */
455 static XLogRecPtr ReadRecPtr; /* start of last record read */
456 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
457 static XLogRecord *nextRecord = NULL;
458 static TimeLineID lastPageTLI = 0;
460 static bool InRedo = false;
463 static void XLogArchiveNotify(const char *xlog);
464 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
465 static bool XLogArchiveCheckDone(const char *xlog);
466 static void XLogArchiveCleanup(const char *xlog);
467 static void readRecoveryCommandFile(void);
468 static void exitArchiveRecovery(TimeLineID endTLI,
469 uint32 endLogId, uint32 endLogSeg);
470 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
471 static void CheckPointGuts(XLogRecPtr checkPointRedo);
473 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
474 XLogRecPtr *lsn, BkpBlock *bkpb);
475 static bool AdvanceXLInsertBuffer(bool new_segment);
476 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
477 static int XLogFileInit(uint32 log, uint32 seg,
478 bool *use_existent, bool use_lock);
479 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
480 bool find_free, int *max_advance,
482 static int XLogFileOpen(uint32 log, uint32 seg);
483 static int XLogFileRead(uint32 log, uint32 seg, int emode);
484 static void XLogFileClose(void);
485 static bool RestoreArchivedFile(char *path, const char *xlogfname,
486 const char *recovername, off_t expectedSize);
487 static int PreallocXlogFiles(XLogRecPtr endptr);
488 static void MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
489 int *nsegsremoved, int *nsegsrecycled);
490 static void CleanupBackupHistory(void);
491 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
492 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
493 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
494 static List *readTimeLineHistory(TimeLineID targetTLI);
495 static bool existsTimeLineHistory(TimeLineID probeTLI);
496 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
497 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
499 uint32 endLogId, uint32 endLogSeg);
500 static void WriteControlFile(void);
501 static void ReadControlFile(void);
502 static char *str_time(time_t tnow);
503 static void issue_xlog_fsync(void);
506 static void xlog_outrec(StringInfo buf, XLogRecord *record);
508 static bool read_backup_label(XLogRecPtr *checkPointLoc,
509 XLogRecPtr *minRecoveryLoc);
510 static void rm_redo_error_callback(void *arg);
514 * Insert an XLOG record having the specified RMID and info bytes,
515 * with the body of the record being the data chunk(s) described by
516 * the rdata chain (see xlog.h for notes about rdata).
518 * Returns XLOG pointer to end of record (beginning of next record).
519 * This can be used as LSN for data pages affected by the logged action.
520 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
521 * before the data page can be written out. This implements the basic
522 * WAL rule "write the log before the data".)
524 * NB: this routine feels free to scribble on the XLogRecData structs,
525 * though not on the data they reference. This is OK since the XLogRecData
526 * structs are always just temporaries in the calling code.
529 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
531 XLogCtlInsert *Insert = &XLogCtl->Insert;
533 XLogContRecord *contrecord;
535 XLogRecPtr WriteRqst;
539 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
540 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
541 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
542 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
543 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
544 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
545 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
550 XLogwrtRqst LogwrtRqst;
553 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
554 bool no_tran = (rmid == RM_XLOG_ID);
556 if (info & XLR_INFO_MASK)
558 if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
559 elog(PANIC, "invalid xlog info mask %02X", (info & XLR_INFO_MASK));
561 info &= ~XLR_INFO_MASK;
565 * In bootstrap mode, we don't actually log anything but XLOG resources;
566 * return a phony record pointer.
568 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
571 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
576 * Here we scan the rdata chain, determine which buffers must be backed
577 * up, and compute the CRC values for the data. Note that the record
578 * header isn't added into the CRC initially since we don't know the final
579 * length or info bits quite yet. Thus, the CRC will represent the CRC of
580 * the whole record in the order "rdata, then backup blocks, then record
583 * We may have to loop back to here if a race condition is detected below.
584 * We could prevent the race by doing all this work while holding the
585 * insert lock, but it seems better to avoid doing CRC calculations while
586 * holding the lock. This means we have to be careful about modifying the
587 * rdata chain until we know we aren't going to loop back again. The only
588 * change we allow ourselves to make earlier is to set rdt->data = NULL in
589 * chain items we have decided we will have to back up the whole buffer
590 * for. This is OK because we will certainly decide the same thing again
591 * for those items if we do it over; doing it here saves an extra pass
592 * over the chain later.
595 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
597 dtbuf[i] = InvalidBuffer;
598 dtbuf_bkp[i] = false;
602 * Decide if we need to do full-page writes in this XLOG record: true if
603 * full_page_writes is on or we have a PITR request for it. Since we
604 * don't yet have the insert lock, forcePageWrites could change under us,
605 * but we'll recheck it once we have the lock.
607 doPageWrites = fullPageWrites || Insert->forcePageWrites;
609 INIT_CRC32(rdata_crc);
613 if (rdt->buffer == InvalidBuffer)
615 /* Simple data, just include it */
617 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
621 /* Find info for buffer */
622 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
624 if (rdt->buffer == dtbuf[i])
626 /* Buffer already referenced by earlier chain item */
632 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
636 if (dtbuf[i] == InvalidBuffer)
638 /* OK, put it in this slot */
639 dtbuf[i] = rdt->buffer;
640 if (XLogCheckBuffer(rdt, doPageWrites,
641 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
649 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
654 if (i >= XLR_MAX_BKP_BLOCKS)
655 elog(PANIC, "can backup at most %d blocks per xlog record",
658 /* Break out of loop when rdt points to last chain item */
659 if (rdt->next == NULL)
665 * Now add the backup block headers and data into the CRC
667 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
671 BkpBlock *bkpb = &(dtbuf_xlg[i]);
674 COMP_CRC32(rdata_crc,
677 page = (char *) BufferGetBlock(dtbuf[i]);
678 if (bkpb->hole_length == 0)
680 COMP_CRC32(rdata_crc,
686 /* must skip the hole */
687 COMP_CRC32(rdata_crc,
690 COMP_CRC32(rdata_crc,
691 page + (bkpb->hole_offset + bkpb->hole_length),
692 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
698 * NOTE: We disallow len == 0 because it provides a useful bit of extra
699 * error checking in ReadRecord. This means that all callers of
700 * XLogInsert must supply at least some not-in-a-buffer data. However, we
701 * make an exception for XLOG SWITCH records because we don't want them to
702 * ever cross a segment boundary.
704 if (len == 0 && !isLogSwitch)
705 elog(PANIC, "invalid xlog record length %u", len);
707 START_CRIT_SECTION();
709 /* update LogwrtResult before doing cache fill check */
711 /* use volatile pointer to prevent code rearrangement */
712 volatile XLogCtlData *xlogctl = XLogCtl;
714 SpinLockAcquire(&xlogctl->info_lck);
715 LogwrtRqst = xlogctl->LogwrtRqst;
716 LogwrtResult = xlogctl->LogwrtResult;
717 SpinLockRelease(&xlogctl->info_lck);
721 * If cache is half filled then try to acquire write lock and do
722 * XLogWrite. Ignore any fractional blocks in performing this check.
724 LogwrtRqst.Write.xrecoff -= LogwrtRqst.Write.xrecoff % XLOG_BLCKSZ;
725 if (LogwrtRqst.Write.xlogid != LogwrtResult.Write.xlogid ||
726 (LogwrtRqst.Write.xrecoff >= LogwrtResult.Write.xrecoff +
727 XLogCtl->XLogCacheByte / 2))
729 if (LWLockConditionalAcquire(WALWriteLock, LW_EXCLUSIVE))
732 * Since the amount of data we write here is completely optional
733 * anyway, tell XLogWrite it can be "flexible" and stop at a
734 * convenient boundary. This allows writes triggered by this
735 * mechanism to synchronize with the cache boundaries, so that in
736 * a long transaction we'll basically dump alternating halves of
739 LogwrtResult = XLogCtl->Write.LogwrtResult;
740 if (XLByteLT(LogwrtResult.Write, LogwrtRqst.Write))
741 XLogWrite(LogwrtRqst, true, false);
742 LWLockRelease(WALWriteLock);
746 /* Now wait to get insert lock */
747 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
750 * Check to see if my RedoRecPtr is out of date. If so, may have to go
751 * back and recompute everything. This can only happen just after a
752 * checkpoint, so it's better to be slow in this case and fast otherwise.
754 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
755 * affect the contents of the XLOG record, so we'll update our local copy
756 * but not force a recomputation.
758 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
760 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
761 RedoRecPtr = Insert->RedoRecPtr;
765 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
767 if (dtbuf[i] == InvalidBuffer)
769 if (dtbuf_bkp[i] == false &&
770 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
773 * Oops, this buffer now needs to be backed up, but we
774 * didn't think so above. Start over.
776 LWLockRelease(WALInsertLock);
785 * Also check to see if forcePageWrites was just turned on; if we weren't
786 * already doing full-page writes then go back and recompute. (If it was
787 * just turned off, we could recompute the record without full pages, but
788 * we choose not to bother.)
790 if (Insert->forcePageWrites && !doPageWrites)
792 /* Oops, must redo it with full-page data */
793 LWLockRelease(WALInsertLock);
799 * Make additional rdata chain entries for the backup blocks, so that we
800 * don't need to special-case them in the write loop. Note that we have
801 * now irrevocably changed the input rdata chain. At the exit of this
802 * loop, write_len includes the backup block data.
804 * Also set the appropriate info bits to show which buffers were backed
805 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
806 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
809 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
817 info |= XLR_SET_BKP_BLOCK(i);
819 bkpb = &(dtbuf_xlg[i]);
820 page = (char *) BufferGetBlock(dtbuf[i]);
822 rdt->next = &(dtbuf_rdt1[i]);
825 rdt->data = (char *) bkpb;
826 rdt->len = sizeof(BkpBlock);
827 write_len += sizeof(BkpBlock);
829 rdt->next = &(dtbuf_rdt2[i]);
832 if (bkpb->hole_length == 0)
841 /* must skip the hole */
843 rdt->len = bkpb->hole_offset;
844 write_len += bkpb->hole_offset;
846 rdt->next = &(dtbuf_rdt3[i]);
849 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
850 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
851 write_len += rdt->len;
857 * If there isn't enough space on the current XLOG page for a record
858 * header, advance to the next page (leaving the unused space as zeroes).
861 freespace = INSERT_FREESPACE(Insert);
862 if (freespace < SizeOfXLogRecord)
864 updrqst = AdvanceXLInsertBuffer(false);
865 freespace = INSERT_FREESPACE(Insert);
868 /* Compute record's XLOG location */
869 curridx = Insert->curridx;
870 INSERT_RECPTR(RecPtr, Insert, curridx);
873 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
874 * segment, we need not insert it (and don't want to because we'd like
875 * consecutive switch requests to be no-ops). Instead, make sure
876 * everything is written and flushed through the end of the prior segment,
877 * and return the prior segment's end address.
880 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
882 /* We can release insert lock immediately */
883 LWLockRelease(WALInsertLock);
885 RecPtr.xrecoff -= SizeOfXLogLongPHD;
886 if (RecPtr.xrecoff == 0)
888 /* crossing a logid boundary */
890 RecPtr.xrecoff = XLogFileSize;
893 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
894 LogwrtResult = XLogCtl->Write.LogwrtResult;
895 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
897 XLogwrtRqst FlushRqst;
899 FlushRqst.Write = RecPtr;
900 FlushRqst.Flush = RecPtr;
901 XLogWrite(FlushRqst, false, false);
903 LWLockRelease(WALWriteLock);
910 /* Insert record header */
912 record = (XLogRecord *) Insert->currpos;
913 record->xl_prev = Insert->PrevRecord;
914 record->xl_xid = GetCurrentTransactionIdIfAny();
915 record->xl_tot_len = SizeOfXLogRecord + write_len;
916 record->xl_len = len; /* doesn't include backup blocks */
917 record->xl_info = info;
918 record->xl_rmid = rmid;
920 /* Now we can finish computing the record's CRC */
921 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
922 SizeOfXLogRecord - sizeof(pg_crc32));
923 FIN_CRC32(rdata_crc);
924 record->xl_crc = rdata_crc;
931 initStringInfo(&buf);
932 appendStringInfo(&buf, "INSERT @ %X/%X: ",
933 RecPtr.xlogid, RecPtr.xrecoff);
934 xlog_outrec(&buf, record);
935 if (rdata->data != NULL)
937 appendStringInfo(&buf, " - ");
938 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
940 elog(LOG, "%s", buf.data);
945 /* Record begin of record in appropriate places */
947 MyLastRecPtr = RecPtr;
948 ProcLastRecPtr = RecPtr;
949 Insert->PrevRecord = RecPtr;
950 MyXactMadeXLogEntry = true;
952 Insert->currpos += SizeOfXLogRecord;
953 freespace -= SizeOfXLogRecord;
956 * Append the data, including backup blocks if any
960 while (rdata->data == NULL)
965 if (rdata->len > freespace)
967 memcpy(Insert->currpos, rdata->data, freespace);
968 rdata->data += freespace;
969 rdata->len -= freespace;
970 write_len -= freespace;
974 memcpy(Insert->currpos, rdata->data, rdata->len);
975 freespace -= rdata->len;
976 write_len -= rdata->len;
977 Insert->currpos += rdata->len;
983 /* Use next buffer */
984 updrqst = AdvanceXLInsertBuffer(false);
985 curridx = Insert->curridx;
986 /* Insert cont-record header */
987 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
988 contrecord = (XLogContRecord *) Insert->currpos;
989 contrecord->xl_rem_len = write_len;
990 Insert->currpos += SizeOfXLogContRecord;
991 freespace = INSERT_FREESPACE(Insert);
994 /* Ensure next record will be properly aligned */
995 Insert->currpos = (char *) Insert->currpage +
996 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
997 freespace = INSERT_FREESPACE(Insert);
1000 * The recptr I return is the beginning of the *next* record. This will be
1001 * stored as LSN for changed data pages...
1003 INSERT_RECPTR(RecPtr, Insert, curridx);
1006 * If the record is an XLOG_SWITCH, we must now write and flush all the
1007 * existing data, and then forcibly advance to the start of the next
1008 * segment. It's not good to do this I/O while holding the insert lock,
1009 * but there seems too much risk of confusion if we try to release the
1010 * lock sooner. Fortunately xlog switch needn't be a high-performance
1011 * operation anyway...
1015 XLogCtlWrite *Write = &XLogCtl->Write;
1016 XLogwrtRqst FlushRqst;
1017 XLogRecPtr OldSegEnd;
1019 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1022 * Flush through the end of the page containing XLOG_SWITCH, and
1023 * perform end-of-segment actions (eg, notifying archiver).
1025 WriteRqst = XLogCtl->xlblocks[curridx];
1026 FlushRqst.Write = WriteRqst;
1027 FlushRqst.Flush = WriteRqst;
1028 XLogWrite(FlushRqst, false, true);
1030 /* Set up the next buffer as first page of next segment */
1031 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
1032 (void) AdvanceXLInsertBuffer(true);
1034 /* There should be no unwritten data */
1035 curridx = Insert->curridx;
1036 Assert(curridx == Write->curridx);
1038 /* Compute end address of old segment */
1039 OldSegEnd = XLogCtl->xlblocks[curridx];
1040 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
1041 if (OldSegEnd.xrecoff == 0)
1043 /* crossing a logid boundary */
1044 OldSegEnd.xlogid -= 1;
1045 OldSegEnd.xrecoff = XLogFileSize;
1048 /* Make it look like we've written and synced all of old segment */
1049 LogwrtResult.Write = OldSegEnd;
1050 LogwrtResult.Flush = OldSegEnd;
1053 * Update shared-memory status --- this code should match XLogWrite
1056 /* use volatile pointer to prevent code rearrangement */
1057 volatile XLogCtlData *xlogctl = XLogCtl;
1059 SpinLockAcquire(&xlogctl->info_lck);
1060 xlogctl->LogwrtResult = LogwrtResult;
1061 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1062 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1063 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1064 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1065 SpinLockRelease(&xlogctl->info_lck);
1068 Write->LogwrtResult = LogwrtResult;
1070 LWLockRelease(WALWriteLock);
1072 updrqst = false; /* done already */
1076 /* normal case, ie not xlog switch */
1078 /* Need to update shared LogwrtRqst if some block was filled up */
1079 if (freespace < SizeOfXLogRecord)
1081 /* curridx is filled and available for writing out */
1086 /* if updrqst already set, write through end of previous buf */
1087 curridx = PrevBufIdx(curridx);
1089 WriteRqst = XLogCtl->xlblocks[curridx];
1092 LWLockRelease(WALInsertLock);
1096 /* use volatile pointer to prevent code rearrangement */
1097 volatile XLogCtlData *xlogctl = XLogCtl;
1099 SpinLockAcquire(&xlogctl->info_lck);
1100 /* advance global request to include new block(s) */
1101 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
1102 xlogctl->LogwrtRqst.Write = WriteRqst;
1103 /* update local result copy while I have the chance */
1104 LogwrtResult = xlogctl->LogwrtResult;
1105 SpinLockRelease(&xlogctl->info_lck);
1108 ProcLastRecEnd = RecPtr;
1116 * Determine whether the buffer referenced by an XLogRecData item has to
1117 * be backed up, and if so fill a BkpBlock struct for it. In any case
1118 * save the buffer's LSN at *lsn.
1121 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1122 XLogRecPtr *lsn, BkpBlock *bkpb)
1126 page = (PageHeader) BufferGetBlock(rdata->buffer);
1129 * XXX We assume page LSN is first data on *every* page that can be passed
1130 * to XLogInsert, whether it otherwise has the standard page layout or
1133 *lsn = page->pd_lsn;
1136 XLByteLE(page->pd_lsn, RedoRecPtr))
1139 * The page needs to be backed up, so set up *bkpb
1141 bkpb->node = BufferGetFileNode(rdata->buffer);
1142 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1144 if (rdata->buffer_std)
1146 /* Assume we can omit data between pd_lower and pd_upper */
1147 uint16 lower = page->pd_lower;
1148 uint16 upper = page->pd_upper;
1150 if (lower >= SizeOfPageHeaderData &&
1154 bkpb->hole_offset = lower;
1155 bkpb->hole_length = upper - lower;
1159 /* No "hole" to compress out */
1160 bkpb->hole_offset = 0;
1161 bkpb->hole_length = 0;
1166 /* Not a standard page header, don't try to eliminate "hole" */
1167 bkpb->hole_offset = 0;
1168 bkpb->hole_length = 0;
1171 return true; /* buffer requires backup */
1174 return false; /* buffer does not need to be backed up */
1180 * Create an archive notification file
1182 * The name of the notification file is the message that will be picked up
1183 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1184 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1185 * then when complete, rename it to 0000000100000001000000C6.done
1188 XLogArchiveNotify(const char *xlog)
1190 char archiveStatusPath[MAXPGPATH];
1193 /* insert an otherwise empty file called <XLOG>.ready */
1194 StatusFilePath(archiveStatusPath, xlog, ".ready");
1195 fd = AllocateFile(archiveStatusPath, "w");
1199 (errcode_for_file_access(),
1200 errmsg("could not create archive status file \"%s\": %m",
1201 archiveStatusPath)));
1207 (errcode_for_file_access(),
1208 errmsg("could not write archive status file \"%s\": %m",
1209 archiveStatusPath)));
1213 /* Notify archiver that it's got something to do */
1214 if (IsUnderPostmaster)
1215 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1219 * Convenience routine to notify using log/seg representation of filename
1222 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1224 char xlog[MAXFNAMELEN];
1226 XLogFileName(xlog, ThisTimeLineID, log, seg);
1227 XLogArchiveNotify(xlog);
1231 * XLogArchiveCheckDone
1233 * This is called when we are ready to delete or recycle an old XLOG segment
1234 * file or backup history file. If it is okay to delete it then return true.
1235 * If it is not time to delete it, make sure a .ready file exists, and return
1238 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1239 * then return false; else create <XLOG>.ready and return false.
1241 * The reason we do things this way is so that if the original attempt to
1242 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1245 XLogArchiveCheckDone(const char *xlog)
1247 char archiveStatusPath[MAXPGPATH];
1248 struct stat stat_buf;
1250 /* Always deletable if archiving is off */
1251 if (!XLogArchivingActive())
1254 /* First check for .done --- this means archiver is done with it */
1255 StatusFilePath(archiveStatusPath, xlog, ".done");
1256 if (stat(archiveStatusPath, &stat_buf) == 0)
1259 /* check for .ready --- this means archiver is still busy with it */
1260 StatusFilePath(archiveStatusPath, xlog, ".ready");
1261 if (stat(archiveStatusPath, &stat_buf) == 0)
1264 /* Race condition --- maybe archiver just finished, so recheck */
1265 StatusFilePath(archiveStatusPath, xlog, ".done");
1266 if (stat(archiveStatusPath, &stat_buf) == 0)
1269 /* Retry creation of the .ready file */
1270 XLogArchiveNotify(xlog);
1275 * XLogArchiveCleanup
1277 * Cleanup archive notification file(s) for a particular xlog segment
1280 XLogArchiveCleanup(const char *xlog)
1282 char archiveStatusPath[MAXPGPATH];
1284 /* Remove the .done file */
1285 StatusFilePath(archiveStatusPath, xlog, ".done");
1286 unlink(archiveStatusPath);
1287 /* should we complain about failure? */
1289 /* Remove the .ready file if present --- normally it shouldn't be */
1290 StatusFilePath(archiveStatusPath, xlog, ".ready");
1291 unlink(archiveStatusPath);
1292 /* should we complain about failure? */
1296 * Advance the Insert state to the next buffer page, writing out the next
1297 * buffer if it still contains unwritten data.
1299 * If new_segment is TRUE then we set up the next buffer page as the first
1300 * page of the next xlog segment file, possibly but not usually the next
1301 * consecutive file page.
1303 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1304 * just-filled page. If we can do this for free (without an extra lock),
1305 * we do so here. Otherwise the caller must do it. We return TRUE if the
1306 * request update still needs to be done, FALSE if we did it internally.
1308 * Must be called with WALInsertLock held.
1311 AdvanceXLInsertBuffer(bool new_segment)
1313 XLogCtlInsert *Insert = &XLogCtl->Insert;
1314 XLogCtlWrite *Write = &XLogCtl->Write;
1315 int nextidx = NextBufIdx(Insert->curridx);
1316 bool update_needed = true;
1317 XLogRecPtr OldPageRqstPtr;
1318 XLogwrtRqst WriteRqst;
1319 XLogRecPtr NewPageEndPtr;
1320 XLogPageHeader NewPage;
1322 /* Use Insert->LogwrtResult copy if it's more fresh */
1323 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1324 LogwrtResult = Insert->LogwrtResult;
1327 * Get ending-offset of the buffer page we need to replace (this may be
1328 * zero if the buffer hasn't been used yet). Fall through if it's already
1331 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1332 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1334 /* nope, got work to do... */
1335 XLogRecPtr FinishedPageRqstPtr;
1337 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1339 /* Before waiting, get info_lck and update LogwrtResult */
1341 /* use volatile pointer to prevent code rearrangement */
1342 volatile XLogCtlData *xlogctl = XLogCtl;
1344 SpinLockAcquire(&xlogctl->info_lck);
1345 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1346 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1347 LogwrtResult = xlogctl->LogwrtResult;
1348 SpinLockRelease(&xlogctl->info_lck);
1351 update_needed = false; /* Did the shared-request update */
1353 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1355 /* OK, someone wrote it already */
1356 Insert->LogwrtResult = LogwrtResult;
1360 /* Must acquire write lock */
1361 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1362 LogwrtResult = Write->LogwrtResult;
1363 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1365 /* OK, someone wrote it already */
1366 LWLockRelease(WALWriteLock);
1367 Insert->LogwrtResult = LogwrtResult;
1372 * Have to write buffers while holding insert lock. This is
1373 * not good, so only write as much as we absolutely must.
1375 WriteRqst.Write = OldPageRqstPtr;
1376 WriteRqst.Flush.xlogid = 0;
1377 WriteRqst.Flush.xrecoff = 0;
1378 XLogWrite(WriteRqst, false, false);
1379 LWLockRelease(WALWriteLock);
1380 Insert->LogwrtResult = LogwrtResult;
1386 * Now the next buffer slot is free and we can set it up to be the next
1389 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1393 /* force it to a segment start point */
1394 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1395 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1398 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1400 /* crossing a logid boundary */
1401 NewPageEndPtr.xlogid += 1;
1402 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1405 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1406 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1407 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1409 Insert->curridx = nextidx;
1410 Insert->currpage = NewPage;
1412 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1415 * Be sure to re-zero the buffer so that bytes beyond what we've written
1416 * will look like zeroes and not valid XLOG records...
1418 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1421 * Fill the new page's header
1423 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1425 /* NewPage->xlp_info = 0; */ /* done by memset */
1426 NewPage ->xlp_tli = ThisTimeLineID;
1427 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1428 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1431 * If first page of an XLOG segment file, make it a long header.
1433 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1435 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1437 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1438 NewLongPage->xlp_seg_size = XLogSegSize;
1439 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1440 NewPage ->xlp_info |= XLP_LONG_HEADER;
1442 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1445 return update_needed;
1449 * Write and/or fsync the log at least as far as WriteRqst indicates.
1451 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1452 * may stop at any convenient boundary (such as a cache or logfile boundary).
1453 * This option allows us to avoid uselessly issuing multiple writes when a
1454 * single one would do.
1456 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1457 * perform end-of-segment actions after writing the last page, even if
1458 * it's not physically the end of its segment. (NB: this will work properly
1459 * only if caller specifies WriteRqst == page-end and flexible == false,
1460 * and there is some data to write.)
1462 * Must be called with WALWriteLock held.
1465 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1467 XLogCtlWrite *Write = &XLogCtl->Write;
1469 bool last_iteration;
1477 /* We should always be inside a critical section here */
1478 Assert(CritSectionCount > 0);
1481 * Update local LogwrtResult (caller probably did this already, but...)
1483 LogwrtResult = Write->LogwrtResult;
1486 * Since successive pages in the xlog cache are consecutively allocated,
1487 * we can usually gather multiple pages together and issue just one
1488 * write() call. npages is the number of pages we have determined can be
1489 * written together; startidx is the cache block index of the first one,
1490 * and startoffset is the file offset at which it should go. The latter
1491 * two variables are only valid when npages > 0, but we must initialize
1492 * all of them to keep the compiler quiet.
1499 * Within the loop, curridx is the cache block index of the page to
1500 * consider writing. We advance Write->curridx only after successfully
1501 * writing pages. (Right now, this refinement is useless since we are
1502 * going to PANIC if any error occurs anyway; but someday it may come in
1505 curridx = Write->curridx;
1507 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1510 * Make sure we're not ahead of the insert process. This could happen
1511 * if we're passed a bogus WriteRqst.Write that is past the end of the
1512 * last page that's been initialized by AdvanceXLInsertBuffer.
1514 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1515 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1516 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1517 XLogCtl->xlblocks[curridx].xlogid,
1518 XLogCtl->xlblocks[curridx].xrecoff);
1520 /* Advance LogwrtResult.Write to end of current buffer page */
1521 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1522 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1524 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1527 * Switch to new logfile segment. We cannot have any pending
1528 * pages here (since we dump what we have at segment end).
1530 Assert(npages == 0);
1531 if (openLogFile >= 0)
1533 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1535 /* create/use new log file */
1536 use_existent = true;
1537 openLogFile = XLogFileInit(openLogId, openLogSeg,
1538 &use_existent, true);
1541 /* update pg_control, unless someone else already did */
1542 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1543 if (ControlFile->logId < openLogId ||
1544 (ControlFile->logId == openLogId &&
1545 ControlFile->logSeg < openLogSeg + 1))
1547 ControlFile->logId = openLogId;
1548 ControlFile->logSeg = openLogSeg + 1;
1549 ControlFile->time = time(NULL);
1550 UpdateControlFile();
1553 * Signal bgwriter to start a checkpoint if it's been too long
1554 * since the last one. (We look at local copy of RedoRecPtr
1555 * which might be a little out of date, but should be close
1556 * enough for this purpose.)
1558 * A straight computation of segment number could overflow 32
1559 * bits. Rather than assuming we have working 64-bit
1560 * arithmetic, we compare the highest-order bits separately,
1561 * and force a checkpoint immediately when they change.
1563 if (IsUnderPostmaster)
1567 uint32 old_highbits,
1570 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1571 (RedoRecPtr.xrecoff / XLogSegSize);
1572 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1573 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile +
1575 new_highbits = openLogId / XLogSegSize;
1576 if (new_highbits != old_highbits ||
1577 new_segno >= old_segno + (uint32) CheckPointSegments)
1581 elog(LOG, "time for a checkpoint, signaling bgwriter");
1583 RequestCheckpoint(false, true);
1587 LWLockRelease(ControlFileLock);
1590 /* Make sure we have the current logfile open */
1591 if (openLogFile < 0)
1593 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1594 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1598 /* Add current page to the set of pending pages-to-dump */
1601 /* first of group */
1603 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1608 * Dump the set if this will be the last loop iteration, or if we are
1609 * at the last page of the cache area (since the next page won't be
1610 * contiguous in memory), or if we are at the end of the logfile
1613 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1615 finishing_seg = !ispartialpage &&
1616 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1618 if (last_iteration ||
1619 curridx == XLogCtl->XLogCacheBlck ||
1625 /* Need to seek in the file? */
1626 if (openLogOff != startoffset)
1628 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1630 (errcode_for_file_access(),
1631 errmsg("could not seek in log file %u, "
1632 "segment %u to offset %u: %m",
1633 openLogId, openLogSeg, startoffset)));
1634 openLogOff = startoffset;
1637 /* OK to write the page(s) */
1638 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1639 nbytes = npages * (Size) XLOG_BLCKSZ;
1641 if (write(openLogFile, from, nbytes) != nbytes)
1643 /* if write didn't set errno, assume no disk space */
1647 (errcode_for_file_access(),
1648 errmsg("could not write to log file %u, segment %u "
1649 "at offset %u, length %lu: %m",
1650 openLogId, openLogSeg,
1651 openLogOff, (unsigned long) nbytes)));
1654 /* Update state for write */
1655 openLogOff += nbytes;
1656 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1660 * If we just wrote the whole last page of a logfile segment,
1661 * fsync the segment immediately. This avoids having to go back
1662 * and re-open prior segments when an fsync request comes along
1663 * later. Doing it here ensures that one and only one backend will
1664 * perform this fsync.
1666 * We also do this if this is the last page written for an xlog
1669 * This is also the right place to notify the Archiver that the
1670 * segment is ready to copy to archival storage, and to update the
1671 * timer for archive_timeout.
1673 if (finishing_seg || (xlog_switch && last_iteration))
1676 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1678 if (XLogArchivingActive())
1679 XLogArchiveNotifySeg(openLogId, openLogSeg);
1681 Write->lastSegSwitchTime = time(NULL);
1687 /* Only asked to write a partial page */
1688 LogwrtResult.Write = WriteRqst.Write;
1691 curridx = NextBufIdx(curridx);
1693 /* If flexible, break out of loop as soon as we wrote something */
1694 if (flexible && npages == 0)
1698 Assert(npages == 0);
1699 Assert(curridx == Write->curridx);
1702 * If asked to flush, do so
1704 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1705 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1708 * Could get here without iterating above loop, in which case we might
1709 * have no open file or the wrong one. However, we do not need to
1710 * fsync more than one file.
1712 if (sync_method != SYNC_METHOD_OPEN)
1714 if (openLogFile >= 0 &&
1715 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1717 if (openLogFile < 0)
1719 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1720 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1725 LogwrtResult.Flush = LogwrtResult.Write;
1729 * Update shared-memory status
1731 * We make sure that the shared 'request' values do not fall behind the
1732 * 'result' values. This is not absolutely essential, but it saves some
1733 * code in a couple of places.
1736 /* use volatile pointer to prevent code rearrangement */
1737 volatile XLogCtlData *xlogctl = XLogCtl;
1739 SpinLockAcquire(&xlogctl->info_lck);
1740 xlogctl->LogwrtResult = LogwrtResult;
1741 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1742 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1743 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1744 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1745 SpinLockRelease(&xlogctl->info_lck);
1748 Write->LogwrtResult = LogwrtResult;
1752 * Ensure that all XLOG data through the given position is flushed to disk.
1754 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1755 * already held, and we try to avoid acquiring it if possible.
1758 XLogFlush(XLogRecPtr record)
1760 XLogRecPtr WriteRqstPtr;
1761 XLogwrtRqst WriteRqst;
1763 /* Disabled during REDO */
1767 /* Quick exit if already known flushed */
1768 if (XLByteLE(record, LogwrtResult.Flush))
1773 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1774 record.xlogid, record.xrecoff,
1775 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1776 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1779 START_CRIT_SECTION();
1782 * Since fsync is usually a horribly expensive operation, we try to
1783 * piggyback as much data as we can on each fsync: if we see any more data
1784 * entered into the xlog buffer, we'll write and fsync that too, so that
1785 * the final value of LogwrtResult.Flush is as large as possible. This
1786 * gives us some chance of avoiding another fsync immediately after.
1789 /* initialize to given target; may increase below */
1790 WriteRqstPtr = record;
1792 /* read LogwrtResult and update local state */
1794 /* use volatile pointer to prevent code rearrangement */
1795 volatile XLogCtlData *xlogctl = XLogCtl;
1797 SpinLockAcquire(&xlogctl->info_lck);
1798 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1799 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1800 LogwrtResult = xlogctl->LogwrtResult;
1801 SpinLockRelease(&xlogctl->info_lck);
1805 if (!XLByteLE(record, LogwrtResult.Flush))
1807 /* now wait for the write lock */
1808 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1809 LogwrtResult = XLogCtl->Write.LogwrtResult;
1810 if (!XLByteLE(record, LogwrtResult.Flush))
1812 /* try to write/flush later additions to XLOG as well */
1813 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1815 XLogCtlInsert *Insert = &XLogCtl->Insert;
1816 uint32 freespace = INSERT_FREESPACE(Insert);
1818 if (freespace < SizeOfXLogRecord) /* buffer is full */
1819 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1822 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1823 WriteRqstPtr.xrecoff -= freespace;
1825 LWLockRelease(WALInsertLock);
1826 WriteRqst.Write = WriteRqstPtr;
1827 WriteRqst.Flush = WriteRqstPtr;
1831 WriteRqst.Write = WriteRqstPtr;
1832 WriteRqst.Flush = record;
1834 XLogWrite(WriteRqst, false, false);
1836 LWLockRelease(WALWriteLock);
1842 * If we still haven't flushed to the request point then we have a
1843 * problem; most likely, the requested flush point is past end of XLOG.
1844 * This has been seen to occur when a disk page has a corrupted LSN.
1846 * Formerly we treated this as a PANIC condition, but that hurts the
1847 * system's robustness rather than helping it: we do not want to take down
1848 * the whole system due to corruption on one data page. In particular, if
1849 * the bad page is encountered again during recovery then we would be
1850 * unable to restart the database at all! (This scenario has actually
1851 * happened in the field several times with 7.1 releases. Note that we
1852 * cannot get here while InRedo is true, but if the bad page is brought in
1853 * and marked dirty during recovery then CreateCheckPoint will try to
1854 * flush it at the end of recovery.)
1856 * The current approach is to ERROR under normal conditions, but only
1857 * WARNING during recovery, so that the system can be brought up even if
1858 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1859 * be promoted to PANIC since xact.c calls this routine inside a critical
1860 * section. However, calls from bufmgr.c are not within critical sections
1861 * and so we will not force a restart for a bad LSN on a data page.
1863 if (XLByteLT(LogwrtResult.Flush, record))
1864 elog(InRecovery ? WARNING : ERROR,
1865 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1866 record.xlogid, record.xrecoff,
1867 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1871 * Create a new XLOG file segment, or open a pre-existing one.
1873 * log, seg: identify segment to be created/opened.
1875 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1876 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1879 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1880 * place. This should be TRUE except during bootstrap log creation. The
1881 * caller must *not* hold the lock at call.
1883 * Returns FD of opened file.
1885 * Note: errors here are ERROR not PANIC because we might or might not be
1886 * inside a critical section (eg, during checkpoint there is no reason to
1887 * take down the system on failure). They will promote to PANIC if we are
1888 * in a critical section.
1891 XLogFileInit(uint32 log, uint32 seg,
1892 bool *use_existent, bool use_lock)
1894 char path[MAXPGPATH];
1895 char tmppath[MAXPGPATH];
1896 char zbuffer[XLOG_BLCKSZ];
1897 uint32 installed_log;
1898 uint32 installed_seg;
1903 XLogFilePath(path, ThisTimeLineID, log, seg);
1906 * Try to use existent file (checkpoint maker may have created it already)
1910 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1914 if (errno != ENOENT)
1916 (errcode_for_file_access(),
1917 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1925 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
1926 * another process is doing the same thing. If so, we will end up
1927 * pre-creating an extra log segment. That seems OK, and better than
1928 * holding the lock throughout this lengthy process.
1930 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1934 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1935 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1939 (errcode_for_file_access(),
1940 errmsg("could not create file \"%s\": %m", tmppath)));
1943 * Zero-fill the file. We have to do this the hard way to ensure that all
1944 * the file space has really been allocated --- on platforms that allow
1945 * "holes" in files, just seeking to the end doesn't allocate intermediate
1946 * space. This way, we know that we have all the space and (after the
1947 * fsync below) that all the indirect blocks are down on disk. Therefore,
1948 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
1951 MemSet(zbuffer, 0, sizeof(zbuffer));
1952 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(zbuffer))
1955 if ((int) write(fd, zbuffer, sizeof(zbuffer)) != (int) sizeof(zbuffer))
1957 int save_errno = errno;
1960 * If we fail to make the file, delete it to release disk space
1963 /* if write didn't set errno, assume problem is no disk space */
1964 errno = save_errno ? save_errno : ENOSPC;
1967 (errcode_for_file_access(),
1968 errmsg("could not write to file \"%s\": %m", tmppath)));
1972 if (pg_fsync(fd) != 0)
1974 (errcode_for_file_access(),
1975 errmsg("could not fsync file \"%s\": %m", tmppath)));
1979 (errcode_for_file_access(),
1980 errmsg("could not close file \"%s\": %m", tmppath)));
1983 * Now move the segment into place with its final name.
1985 * If caller didn't want to use a pre-existing file, get rid of any
1986 * pre-existing file. Otherwise, cope with possibility that someone else
1987 * has created the file while we were filling ours: if so, use ours to
1988 * pre-create a future log segment.
1990 installed_log = log;
1991 installed_seg = seg;
1992 max_advance = XLOGfileslop;
1993 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
1994 *use_existent, &max_advance,
1997 /* No need for any more future segments... */
2001 /* Set flag to tell caller there was no existent file */
2002 *use_existent = false;
2004 /* Now open original target segment (might not be file I just made) */
2005 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2009 (errcode_for_file_access(),
2010 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2017 * Create a new XLOG file segment by copying a pre-existing one.
2019 * log, seg: identify segment to be created.
2021 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
2022 * a different timeline)
2024 * Currently this is only used during recovery, and so there are no locking
2025 * considerations. But we should be just as tense as XLogFileInit to avoid
2026 * emplacing a bogus file.
2029 XLogFileCopy(uint32 log, uint32 seg,
2030 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
2032 char path[MAXPGPATH];
2033 char tmppath[MAXPGPATH];
2034 char buffer[XLOG_BLCKSZ];
2040 * Open the source file
2042 XLogFilePath(path, srcTLI, srclog, srcseg);
2043 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2046 (errcode_for_file_access(),
2047 errmsg("could not open file \"%s\": %m", path)));
2050 * Copy into a temp file name.
2052 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2056 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2057 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2061 (errcode_for_file_access(),
2062 errmsg("could not create file \"%s\": %m", tmppath)));
2065 * Do the data copying.
2067 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2070 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2074 (errcode_for_file_access(),
2075 errmsg("could not read file \"%s\": %m", path)));
2078 (errmsg("not enough data in file \"%s\"", path)));
2081 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2083 int save_errno = errno;
2086 * If we fail to make the file, delete it to release disk space
2089 /* if write didn't set errno, assume problem is no disk space */
2090 errno = save_errno ? save_errno : ENOSPC;
2093 (errcode_for_file_access(),
2094 errmsg("could not write to file \"%s\": %m", tmppath)));
2098 if (pg_fsync(fd) != 0)
2100 (errcode_for_file_access(),
2101 errmsg("could not fsync file \"%s\": %m", tmppath)));
2105 (errcode_for_file_access(),
2106 errmsg("could not close file \"%s\": %m", tmppath)));
2111 * Now move the segment into place with its final name.
2113 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2114 elog(ERROR, "InstallXLogFileSegment should not have failed");
2118 * Install a new XLOG segment file as a current or future log segment.
2120 * This is used both to install a newly-created segment (which has a temp
2121 * filename while it's being created) and to recycle an old segment.
2123 * *log, *seg: identify segment to install as (or first possible target).
2124 * When find_free is TRUE, these are modified on return to indicate the
2125 * actual installation location or last segment searched.
2127 * tmppath: initial name of file to install. It will be renamed into place.
2129 * find_free: if TRUE, install the new segment at the first empty log/seg
2130 * number at or after the passed numbers. If FALSE, install the new segment
2131 * exactly where specified, deleting any existing segment file there.
2133 * *max_advance: maximum number of log/seg slots to advance past the starting
2134 * point. Fail if no free slot is found in this range. On return, reduced
2135 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2136 * when find_free is FALSE.)
2138 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2139 * place. This should be TRUE except during bootstrap log creation. The
2140 * caller must *not* hold the lock at call.
2142 * Returns TRUE if file installed, FALSE if not installed because of
2143 * exceeding max_advance limit. (Any other kind of failure causes ereport().)
2146 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2147 bool find_free, int *max_advance,
2150 char path[MAXPGPATH];
2151 struct stat stat_buf;
2153 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2156 * We want to be sure that only one process does this at a time.
2159 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2163 /* Force installation: get rid of any pre-existing segment file */
2168 /* Find a free slot to put it in */
2169 while (stat(path, &stat_buf) == 0)
2171 if (*max_advance <= 0)
2173 /* Failed to find a free slot within specified range */
2175 LWLockRelease(ControlFileLock);
2178 NextLogSeg(*log, *seg);
2180 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2185 * Prefer link() to rename() here just to be really sure that we don't
2186 * overwrite an existing logfile. However, there shouldn't be one, so
2187 * rename() is an acceptable substitute except for the truly paranoid.
2189 #if HAVE_WORKING_LINK
2190 if (link(tmppath, path) < 0)
2192 (errcode_for_file_access(),
2193 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2194 tmppath, path, *log, *seg)));
2197 if (rename(tmppath, path) < 0)
2199 (errcode_for_file_access(),
2200 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2201 tmppath, path, *log, *seg)));
2205 LWLockRelease(ControlFileLock);
2211 * Open a pre-existing logfile segment for writing.
2214 XLogFileOpen(uint32 log, uint32 seg)
2216 char path[MAXPGPATH];
2219 XLogFilePath(path, ThisTimeLineID, log, seg);
2221 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2225 (errcode_for_file_access(),
2226 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2233 * Open a logfile segment for reading (during recovery).
2236 XLogFileRead(uint32 log, uint32 seg, int emode)
2238 char path[MAXPGPATH];
2239 char xlogfname[MAXFNAMELEN];
2244 * Loop looking for a suitable timeline ID: we might need to read any of
2245 * the timelines listed in expectedTLIs.
2247 * We expect curFileTLI on entry to be the TLI of the preceding file in
2248 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2249 * to go backwards; this prevents us from picking up the wrong file when a
2250 * parent timeline extends to higher segment numbers than the child we
2253 foreach(cell, expectedTLIs)
2255 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2257 if (tli < curFileTLI)
2258 break; /* don't bother looking at too-old TLIs */
2260 if (InArchiveRecovery)
2262 XLogFileName(xlogfname, tli, log, seg);
2263 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2268 XLogFilePath(path, tli, log, seg);
2270 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2277 if (errno != ENOENT) /* unexpected failure? */
2279 (errcode_for_file_access(),
2280 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2284 /* Couldn't find it. For simplicity, complain about front timeline */
2285 XLogFilePath(path, recoveryTargetTLI, log, seg);
2288 (errcode_for_file_access(),
2289 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2295 * Close the current logfile segment for writing.
2300 Assert(openLogFile >= 0);
2303 * posix_fadvise is problematic on many platforms: on older x86 Linux it
2304 * just dumps core, and there are reports of problems on PPC platforms as
2305 * well. The following is therefore disabled for the time being. We could
2306 * consider some kind of configure test to see if it's safe to use, but
2307 * since we lack hard evidence that there's any useful performance gain to
2308 * be had, spending time on that seems unprofitable for now.
2313 * WAL segment files will not be re-read in normal operation, so we advise
2314 * OS to release any cached pages. But do not do so if WAL archiving is
2315 * active, because archiver process could use the cache to read the WAL
2318 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
2319 * O_SYNC, and some platforms only have posix_fadvise().
2321 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2322 if (!XLogArchivingActive())
2323 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2325 #endif /* NOT_USED */
2327 if (close(openLogFile))
2329 (errcode_for_file_access(),
2330 errmsg("could not close log file %u, segment %u: %m",
2331 openLogId, openLogSeg)));
2336 * Attempt to retrieve the specified file from off-line archival storage.
2337 * If successful, fill "path" with its complete path (note that this will be
2338 * a temp file name that doesn't follow the normal naming convention), and
2341 * If not successful, fill "path" with the name of the normal on-line file
2342 * (which may or may not actually exist, but we'll try to use it), and return
2345 * For fixed-size files, the caller may pass the expected size as an
2346 * additional crosscheck on successful recovery. If the file size is not
2347 * known, set expectedSize = 0.
2350 RestoreArchivedFile(char *path, const char *xlogfname,
2351 const char *recovername, off_t expectedSize)
2353 char xlogpath[MAXPGPATH];
2354 char xlogRestoreCmd[MAXPGPATH];
2359 struct stat stat_buf;
2362 * When doing archive recovery, we always prefer an archived log file even
2363 * if a file of the same name exists in XLOGDIR. The reason is that the
2364 * file in XLOGDIR could be an old, un-filled or partly-filled version
2365 * that was copied and restored as part of backing up $PGDATA.
2367 * We could try to optimize this slightly by checking the local copy
2368 * lastchange timestamp against the archived copy, but we have no API to
2369 * do this, nor can we guarantee that the lastchange timestamp was
2370 * preserved correctly when we copied to archive. Our aim is robustness,
2371 * so we elect not to do this.
2373 * If we cannot obtain the log file from the archive, however, we will try
2374 * to use the XLOGDIR file if it exists. This is so that we can make use
2375 * of log segments that weren't yet transferred to the archive.
2377 * Notice that we don't actually overwrite any files when we copy back
2378 * from archive because the recoveryRestoreCommand may inadvertently
2379 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2380 * fallback to the segments remaining in current XLOGDIR later. The
2381 * copy-from-archive filename is always the same, ensuring that we don't
2382 * run out of disk space on long recoveries.
2384 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2387 * Make sure there is no existing file named recovername.
2389 if (stat(xlogpath, &stat_buf) != 0)
2391 if (errno != ENOENT)
2393 (errcode_for_file_access(),
2394 errmsg("could not stat file \"%s\": %m",
2399 if (unlink(xlogpath) != 0)
2401 (errcode_for_file_access(),
2402 errmsg("could not remove file \"%s\": %m",
2407 * construct the command to be executed
2409 dp = xlogRestoreCmd;
2410 endp = xlogRestoreCmd + MAXPGPATH - 1;
2413 for (sp = recoveryRestoreCommand; *sp; sp++)
2420 /* %p: full path of target file */
2422 StrNCpy(dp, xlogpath, endp - dp);
2423 make_native_path(dp);
2427 /* %f: filename of desired file */
2429 StrNCpy(dp, xlogfname, endp - dp);
2433 /* convert %% to a single % */
2439 /* otherwise treat the % as not special */
2454 (errmsg_internal("executing restore command \"%s\"",
2458 * Copy xlog from archival storage to XLOGDIR
2460 rc = system(xlogRestoreCmd);
2464 * command apparently succeeded, but let's make sure the file is
2465 * really there now and has the correct size.
2467 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2468 * it, but is that too strong? We could try to plow ahead with a
2469 * local copy of the file ... but the problem is that there probably
2470 * isn't one, and we'd incorrectly conclude we've reached the end of
2471 * WAL and we're done recovering ...
2473 if (stat(xlogpath, &stat_buf) == 0)
2475 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2477 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2479 (unsigned long) stat_buf.st_size,
2480 (unsigned long) expectedSize)));
2484 (errmsg("restored log file \"%s\" from archive",
2486 strcpy(path, xlogpath);
2493 if (errno != ENOENT)
2495 (errcode_for_file_access(),
2496 errmsg("could not stat file \"%s\": %m",
2502 * remember, we rollforward UNTIL the restore fails so failure here is
2503 * just part of the process... that makes it difficult to determine
2504 * whether the restore failed because there isn't an archive to restore,
2505 * or because the administrator has specified the restore program
2506 * incorrectly. We have to assume the former.
2509 (errmsg("could not restore file \"%s\" from archive: return code %d",
2513 * if an archived file is not available, there might still be a version of
2514 * this file in XLOGDIR, so return that as the filename to open.
2516 * In many recovery scenarios we expect this to fail also, but if so that
2517 * just means we've reached the end of WAL.
2519 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2524 * Preallocate log files beyond the specified log endpoint, according to
2525 * the XLOGfile user parameter.
2528 PreallocXlogFiles(XLogRecPtr endptr)
2536 XLByteToPrevSeg(endptr, _logId, _logSeg);
2537 if ((endptr.xrecoff - 1) % XLogSegSize >=
2538 (uint32) (0.75 * XLogSegSize))
2540 NextLogSeg(_logId, _logSeg);
2541 use_existent = true;
2542 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2551 * Remove or move offline all log files older or equal to passed log/seg#
2553 * endptr is current (or recent) end of xlog; this is used to determine
2554 * whether we want to recycle rather than delete no-longer-wanted log files.
2557 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
2558 int *nsegsremoved, int *nsegsrecycled)
2564 struct dirent *xlde;
2565 char lastoff[MAXFNAMELEN];
2566 char path[MAXPGPATH];
2572 * Initialize info about where to try to recycle to. We allow recycling
2573 * segments up to XLOGfileslop segments beyond the current XLOG location.
2575 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2576 max_advance = XLOGfileslop;
2578 xldir = AllocateDir(XLOGDIR);
2581 (errcode_for_file_access(),
2582 errmsg("could not open transaction log directory \"%s\": %m",
2585 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2587 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2590 * We ignore the timeline part of the XLOG segment identifiers in
2591 * deciding whether a segment is still needed. This ensures that we
2592 * won't prematurely remove a segment from a parent timeline. We could
2593 * probably be a little more proactive about removing segments of
2594 * non-parent timelines, but that would be a whole lot more
2597 * We use the alphanumeric sorting property of the filenames to decide
2598 * which ones are earlier than the lastoff segment.
2600 if (strlen(xlde->d_name) == 24 &&
2601 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2602 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2604 if (XLogArchiveCheckDone(xlde->d_name))
2606 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2609 * Before deleting the file, see if it can be recycled as a
2610 * future log segment.
2612 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2617 (errmsg("recycled transaction log file \"%s\"",
2620 /* Needn't recheck that slot on future iterations */
2621 if (max_advance > 0)
2623 NextLogSeg(endlogId, endlogSeg);
2629 /* No need for any more future segments... */
2631 (errmsg("removing transaction log file \"%s\"",
2637 XLogArchiveCleanup(xlde->d_name);
2646 * Remove previous backup history files. This also retries creation of
2647 * .ready files for any backup history files for which XLogArchiveNotify
2651 CleanupBackupHistory(void)
2654 struct dirent *xlde;
2655 char path[MAXPGPATH];
2657 xldir = AllocateDir(XLOGDIR);
2660 (errcode_for_file_access(),
2661 errmsg("could not open transaction log directory \"%s\": %m",
2664 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2666 if (strlen(xlde->d_name) > 24 &&
2667 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2668 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2671 if (XLogArchiveCheckDone(xlde->d_name))
2674 (errmsg("removing transaction log backup history file \"%s\"",
2676 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2678 XLogArchiveCleanup(xlde->d_name);
2687 * Restore the backup blocks present in an XLOG record, if any.
2689 * We assume all of the record has been read into memory at *record.
2691 * Note: when a backup block is available in XLOG, we restore it
2692 * unconditionally, even if the page in the database appears newer.
2693 * This is to protect ourselves against database pages that were partially
2694 * or incorrectly written during a crash. We assume that the XLOG data
2695 * must be good because it has passed a CRC check, while the database
2696 * page might not be. This will force us to replay all subsequent
2697 * modifications of the page that appear in XLOG, rather than possibly
2698 * ignoring them as already applied, but that's not a huge drawback.
2701 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2710 blk = (char *) XLogRecGetData(record) + record->xl_len;
2711 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2713 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2716 memcpy(&bkpb, blk, sizeof(BkpBlock));
2717 blk += sizeof(BkpBlock);
2719 reln = XLogOpenRelation(bkpb.node);
2720 buffer = XLogReadBuffer(reln, bkpb.block, true);
2721 Assert(BufferIsValid(buffer));
2722 page = (Page) BufferGetPage(buffer);
2724 if (bkpb.hole_length == 0)
2726 memcpy((char *) page, blk, BLCKSZ);
2730 /* must zero-fill the hole */
2731 MemSet((char *) page, 0, BLCKSZ);
2732 memcpy((char *) page, blk, bkpb.hole_offset);
2733 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2734 blk + bkpb.hole_offset,
2735 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2738 PageSetLSN(page, lsn);
2739 PageSetTLI(page, ThisTimeLineID);
2740 MarkBufferDirty(buffer);
2741 UnlockReleaseBuffer(buffer);
2743 blk += BLCKSZ - bkpb.hole_length;
2748 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2749 * record (other than to the minimal extent of computing the amount of
2750 * data to read in) until we've checked the CRCs.
2752 * We assume all of the record has been read into memory at *record.
2755 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2759 uint32 len = record->xl_len;
2763 /* First the rmgr data */
2765 COMP_CRC32(crc, XLogRecGetData(record), len);
2767 /* Add in the backup blocks, if any */
2768 blk = (char *) XLogRecGetData(record) + len;
2769 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2773 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2776 memcpy(&bkpb, blk, sizeof(BkpBlock));
2777 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2780 (errmsg("incorrect hole size in record at %X/%X",
2781 recptr.xlogid, recptr.xrecoff)));
2784 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2785 COMP_CRC32(crc, blk, blen);
2789 /* Check that xl_tot_len agrees with our calculation */
2790 if (blk != (char *) record + record->xl_tot_len)
2793 (errmsg("incorrect total length in record at %X/%X",
2794 recptr.xlogid, recptr.xrecoff)));
2798 /* Finally include the record header */
2799 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2800 SizeOfXLogRecord - sizeof(pg_crc32));
2803 if (!EQ_CRC32(record->xl_crc, crc))
2806 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2807 recptr.xlogid, recptr.xrecoff)));
2815 * Attempt to read an XLOG record.
2817 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2818 * try to read a record just after the last one previously read.
2820 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2821 * (emode must be either PANIC or LOG.)
2823 * The record is copied into readRecordBuf, so that on successful return,
2824 * the returned record pointer always points there.
2827 ReadRecord(XLogRecPtr *RecPtr, int emode)
2831 XLogRecPtr tmpRecPtr = EndRecPtr;
2832 bool randAccess = false;
2835 uint32 targetPageOff;
2836 uint32 targetRecOff;
2837 uint32 pageHeaderSize;
2839 if (readBuf == NULL)
2842 * First time through, permanently allocate readBuf. We do it this
2843 * way, rather than just making a static array, for two reasons: (1)
2844 * no need to waste the storage in most instantiations of the backend;
2845 * (2) a static char array isn't guaranteed to have any particular
2846 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2848 readBuf = (char *) malloc(XLOG_BLCKSZ);
2849 Assert(readBuf != NULL);
2854 RecPtr = &tmpRecPtr;
2855 /* fast case if next record is on same page */
2856 if (nextRecord != NULL)
2858 record = nextRecord;
2861 /* align old recptr to next page */
2862 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2863 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2864 if (tmpRecPtr.xrecoff >= XLogFileSize)
2866 (tmpRecPtr.xlogid)++;
2867 tmpRecPtr.xrecoff = 0;
2869 /* We will account for page header size below */
2873 if (!XRecOffIsValid(RecPtr->xrecoff))
2875 (errmsg("invalid record offset at %X/%X",
2876 RecPtr->xlogid, RecPtr->xrecoff)));
2879 * Since we are going to a random position in WAL, forget any prior
2880 * state about what timeline we were in, and allow it to be any
2881 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
2882 * to go backwards (but we can't reset that variable right here, since
2883 * we might not change files at all).
2885 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2886 randAccess = true; /* allow curFileTLI to go backwards too */
2889 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2894 XLByteToSeg(*RecPtr, readId, readSeg);
2897 /* Now it's okay to reset curFileTLI if random fetch */
2901 readFile = XLogFileRead(readId, readSeg, emode);
2903 goto next_record_is_invalid;
2906 * Whenever switching to a new WAL segment, we read the first page of
2907 * the file and validate its header, even if that's not where the
2908 * target record is. This is so that we can check the additional
2909 * identification info that is present in the first page's "long"
2913 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2916 (errcode_for_file_access(),
2917 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2918 readId, readSeg, readOff)));
2919 goto next_record_is_invalid;
2921 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2922 goto next_record_is_invalid;
2925 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2926 if (readOff != targetPageOff)
2928 readOff = targetPageOff;
2929 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2932 (errcode_for_file_access(),
2933 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2934 readId, readSeg, readOff)));
2935 goto next_record_is_invalid;
2937 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2940 (errcode_for_file_access(),
2941 errmsg("could not read from log file %u, segment %u at offset %u: %m",
2942 readId, readSeg, readOff)));
2943 goto next_record_is_invalid;
2945 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2946 goto next_record_is_invalid;
2948 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2949 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
2950 if (targetRecOff == 0)
2953 * Can only get here in the continuing-from-prev-page case, because
2954 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
2955 * to skip over the new page's header.
2957 tmpRecPtr.xrecoff += pageHeaderSize;
2958 targetRecOff = pageHeaderSize;
2960 else if (targetRecOff < pageHeaderSize)
2963 (errmsg("invalid record offset at %X/%X",
2964 RecPtr->xlogid, RecPtr->xrecoff)));
2965 goto next_record_is_invalid;
2967 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
2968 targetRecOff == pageHeaderSize)
2971 (errmsg("contrecord is requested by %X/%X",
2972 RecPtr->xlogid, RecPtr->xrecoff)));
2973 goto next_record_is_invalid;
2975 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
2980 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
2983 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
2985 if (record->xl_len != 0)
2988 (errmsg("invalid xlog switch record at %X/%X",
2989 RecPtr->xlogid, RecPtr->xrecoff)));
2990 goto next_record_is_invalid;
2993 else if (record->xl_len == 0)
2996 (errmsg("record with zero length at %X/%X",
2997 RecPtr->xlogid, RecPtr->xrecoff)));
2998 goto next_record_is_invalid;
3000 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3001 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3002 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3005 (errmsg("invalid record length at %X/%X",
3006 RecPtr->xlogid, RecPtr->xrecoff)));
3007 goto next_record_is_invalid;
3009 if (record->xl_rmid > RM_MAX_ID)
3012 (errmsg("invalid resource manager ID %u at %X/%X",
3013 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3014 goto next_record_is_invalid;
3019 * We can't exactly verify the prev-link, but surely it should be less
3020 * than the record's own address.
3022 if (!XLByteLT(record->xl_prev, *RecPtr))
3025 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3026 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3027 RecPtr->xlogid, RecPtr->xrecoff)));
3028 goto next_record_is_invalid;
3034 * Record's prev-link should exactly match our previous location. This
3035 * check guards against torn WAL pages where a stale but valid-looking
3036 * WAL record starts on a sector boundary.
3038 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3041 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3042 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3043 RecPtr->xlogid, RecPtr->xrecoff)));
3044 goto next_record_is_invalid;
3049 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3050 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3051 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3052 * enough for all "normal" records, but very large commit or abort records
3053 * might need more space.)
3055 total_len = record->xl_tot_len;
3056 if (total_len > readRecordBufSize)
3058 uint32 newSize = total_len;
3060 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3061 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3063 free(readRecordBuf);
3064 readRecordBuf = (char *) malloc(newSize);
3067 readRecordBufSize = 0;
3068 /* We treat this as a "bogus data" condition */
3070 (errmsg("record length %u at %X/%X too long",
3071 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3072 goto next_record_is_invalid;
3074 readRecordBufSize = newSize;
3077 buffer = readRecordBuf;
3079 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3080 if (total_len > len)
3082 /* Need to reassemble record */
3083 XLogContRecord *contrecord;
3084 uint32 gotlen = len;
3086 memcpy(buffer, record, len);
3087 record = (XLogRecord *) buffer;
3091 readOff += XLOG_BLCKSZ;
3092 if (readOff >= XLogSegSize)
3096 NextLogSeg(readId, readSeg);
3097 readFile = XLogFileRead(readId, readSeg, emode);
3099 goto next_record_is_invalid;
3102 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3105 (errcode_for_file_access(),
3106 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3107 readId, readSeg, readOff)));
3108 goto next_record_is_invalid;
3110 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3111 goto next_record_is_invalid;
3112 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3115 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3116 readId, readSeg, readOff)));
3117 goto next_record_is_invalid;
3119 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3120 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3121 if (contrecord->xl_rem_len == 0 ||
3122 total_len != (contrecord->xl_rem_len + gotlen))
3125 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3126 contrecord->xl_rem_len,
3127 readId, readSeg, readOff)));
3128 goto next_record_is_invalid;
3130 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3131 if (contrecord->xl_rem_len > len)
3133 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3138 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3139 contrecord->xl_rem_len);
3142 if (!RecordIsValid(record, *RecPtr, emode))
3143 goto next_record_is_invalid;
3144 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3145 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3146 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3148 nextRecord = (XLogRecord *) ((char *) contrecord +
3149 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3151 EndRecPtr.xlogid = readId;
3152 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3154 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3155 ReadRecPtr = *RecPtr;
3156 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3160 /* Record does not cross a page boundary */
3161 if (!RecordIsValid(record, *RecPtr, emode))
3162 goto next_record_is_invalid;
3163 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3164 MAXALIGN(total_len))
3165 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3166 EndRecPtr.xlogid = RecPtr->xlogid;
3167 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3168 ReadRecPtr = *RecPtr;
3169 memcpy(buffer, record, total_len);
3172 * Special processing if it's an XLOG SWITCH record
3174 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3176 /* Pretend it extends to end of segment */
3177 EndRecPtr.xrecoff += XLogSegSize - 1;
3178 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3179 nextRecord = NULL; /* definitely not on same page */
3182 * Pretend that readBuf contains the last page of the segment. This is
3183 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3186 readOff = XLogSegSize - XLOG_BLCKSZ;
3188 return (XLogRecord *) buffer;
3190 next_record_is_invalid:;
3198 * Check whether the xlog header of a page just read in looks valid.
3200 * This is just a convenience subroutine to avoid duplicated code in
3201 * ReadRecord. It's not intended for use from anywhere else.
3204 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3208 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3211 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3212 hdr->xlp_magic, readId, readSeg, readOff)));
3215 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3218 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3219 hdr->xlp_info, readId, readSeg, readOff)));
3222 if (hdr->xlp_info & XLP_LONG_HEADER)
3224 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3226 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3228 char fhdrident_str[32];
3229 char sysident_str[32];
3232 * Format sysids separately to keep platform-dependent format code
3233 * out of the translatable message string.
3235 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3236 longhdr->xlp_sysid);
3237 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3238 ControlFile->system_identifier);
3240 (errmsg("WAL file is from different system"),
3241 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3242 fhdrident_str, sysident_str)));
3245 if (longhdr->xlp_seg_size != XLogSegSize)
3248 (errmsg("WAL file is from different system"),
3249 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3252 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3255 (errmsg("WAL file is from different system"),
3256 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3260 else if (readOff == 0)
3262 /* hmm, first page of file doesn't have a long header? */
3264 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3265 hdr->xlp_info, readId, readSeg, readOff)));
3269 recaddr.xlogid = readId;
3270 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3271 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3274 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3275 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3276 readId, readSeg, readOff)));
3281 * Check page TLI is one of the expected values.
3283 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3286 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3288 readId, readSeg, readOff)));
3293 * Since child timelines are always assigned a TLI greater than their
3294 * immediate parent's TLI, we should never see TLI go backwards across
3295 * successive pages of a consistent WAL sequence.
3297 * Of course this check should only be applied when advancing sequentially
3298 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3299 * going to a random page.
3301 if (hdr->xlp_tli < lastPageTLI)
3304 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3305 hdr->xlp_tli, lastPageTLI,
3306 readId, readSeg, readOff)));
3309 lastPageTLI = hdr->xlp_tli;
3314 * Try to read a timeline's history file.
3316 * If successful, return the list of component TLIs (the given TLI followed by
3317 * its ancestor TLIs). If we can't find the history file, assume that the
3318 * timeline has no parents, and return a list of just the specified timeline
3322 readTimeLineHistory(TimeLineID targetTLI)
3325 char path[MAXPGPATH];
3326 char histfname[MAXFNAMELEN];
3327 char fline[MAXPGPATH];
3330 if (InArchiveRecovery)
3332 TLHistoryFileName(histfname, targetTLI);
3333 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3336 TLHistoryFilePath(path, targetTLI);
3338 fd = AllocateFile(path, "r");
3341 if (errno != ENOENT)
3343 (errcode_for_file_access(),
3344 errmsg("could not open file \"%s\": %m", path)));
3345 /* Not there, so assume no parents */
3346 return list_make1_int((int) targetTLI);
3354 while (fgets(fline, MAXPGPATH, fd) != NULL)
3356 /* skip leading whitespace and check for # comment */
3361 for (ptr = fline; *ptr; ptr++)
3363 if (!isspace((unsigned char) *ptr))
3366 if (*ptr == '\0' || *ptr == '#')
3369 /* expect a numeric timeline ID as first field of line */
3370 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3373 (errmsg("syntax error in history file: %s", fline),
3374 errhint("Expected a numeric timeline ID.")));
3377 tli <= (TimeLineID) linitial_int(result))
3379 (errmsg("invalid data in history file: %s", fline),
3380 errhint("Timeline IDs must be in increasing sequence.")));
3382 /* Build list with newest item first */
3383 result = lcons_int((int) tli, result);
3385 /* we ignore the remainder of each line */
3391 targetTLI <= (TimeLineID) linitial_int(result))
3393 (errmsg("invalid data in history file \"%s\"", path),
3394 errhint("Timeline IDs must be less than child timeline's ID.")));
3396 result = lcons_int((int) targetTLI, result);
3399 (errmsg_internal("history of timeline %u is %s",
3400 targetTLI, nodeToString(result))));
3406 * Probe whether a timeline history file exists for the given timeline ID
3409 existsTimeLineHistory(TimeLineID probeTLI)
3411 char path[MAXPGPATH];
3412 char histfname[MAXFNAMELEN];
3415 if (InArchiveRecovery)
3417 TLHistoryFileName(histfname, probeTLI);
3418 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3421 TLHistoryFilePath(path, probeTLI);
3423 fd = AllocateFile(path, "r");
3431 if (errno != ENOENT)
3433 (errcode_for_file_access(),
3434 errmsg("could not open file \"%s\": %m", path)));
3440 * Find the newest existing timeline, assuming that startTLI exists.
3442 * Note: while this is somewhat heuristic, it does positively guarantee
3443 * that (result + 1) is not a known timeline, and therefore it should
3444 * be safe to assign that ID to a new timeline.
3447 findNewestTimeLine(TimeLineID startTLI)
3449 TimeLineID newestTLI;
3450 TimeLineID probeTLI;
3453 * The algorithm is just to probe for the existence of timeline history
3454 * files. XXX is it useful to allow gaps in the sequence?
3456 newestTLI = startTLI;
3458 for (probeTLI = startTLI + 1;; probeTLI++)
3460 if (existsTimeLineHistory(probeTLI))
3462 newestTLI = probeTLI; /* probeTLI exists */
3466 /* doesn't exist, assume we're done */
3475 * Create a new timeline history file.
3477 * newTLI: ID of the new timeline
3478 * parentTLI: ID of its immediate parent
3479 * endTLI et al: ID of the last used WAL file, for annotation purposes
3481 * Currently this is only used during recovery, and so there are no locking
3482 * considerations. But we should be just as tense as XLogFileInit to avoid
3483 * emplacing a bogus file.
3486 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3487 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3489 char path[MAXPGPATH];
3490 char tmppath[MAXPGPATH];
3491 char histfname[MAXFNAMELEN];
3492 char xlogfname[MAXFNAMELEN];
3493 char buffer[BLCKSZ];
3498 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3501 * Write into a temp file name.
3503 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3507 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3508 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3512 (errcode_for_file_access(),
3513 errmsg("could not create file \"%s\": %m", tmppath)));
3516 * If a history file exists for the parent, copy it verbatim
3518 if (InArchiveRecovery)
3520 TLHistoryFileName(histfname, parentTLI);
3521 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3524 TLHistoryFilePath(path, parentTLI);
3526 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3529 if (errno != ENOENT)
3531 (errcode_for_file_access(),
3532 errmsg("could not open file \"%s\": %m", path)));
3533 /* Not there, so assume parent has no parents */
3540 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3541 if (nbytes < 0 || errno != 0)
3543 (errcode_for_file_access(),
3544 errmsg("could not read file \"%s\": %m", path)));
3548 if ((int) write(fd, buffer, nbytes) != nbytes)
3550 int save_errno = errno;
3553 * If we fail to make the file, delete it to release disk
3559 * if write didn't set errno, assume problem is no disk space
3561 errno = save_errno ? save_errno : ENOSPC;
3564 (errcode_for_file_access(),
3565 errmsg("could not write to file \"%s\": %m", tmppath)));
3572 * Append one line with the details of this timeline split.
3574 * If we did have a parent file, insert an extra newline just in case the
3575 * parent file failed to end with one.
3577 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3579 snprintf(buffer, sizeof(buffer),
3580 "%s%u\t%s\t%s transaction %u at %s\n",
3581 (srcfd < 0) ? "" : "\n",
3584 recoveryStopAfter ? "after" : "before",
3586 str_time(recoveryStopTime));
3588 nbytes = strlen(buffer);
3590 if ((int) write(fd, buffer, nbytes) != nbytes)
3592 int save_errno = errno;
3595 * If we fail to make the file, delete it to release disk space
3598 /* if write didn't set errno, assume problem is no disk space */
3599 errno = save_errno ? save_errno : ENOSPC;
3602 (errcode_for_file_access(),
3603 errmsg("could not write to file \"%s\": %m", tmppath)));
3606 if (pg_fsync(fd) != 0)
3608 (errcode_for_file_access(),
3609 errmsg("could not fsync file \"%s\": %m", tmppath)));
3613 (errcode_for_file_access(),
3614 errmsg("could not close file \"%s\": %m", tmppath)));
3618 * Now move the completed history file into place with its final name.
3620 TLHistoryFilePath(path, newTLI);
3623 * Prefer link() to rename() here just to be really sure that we don't
3624 * overwrite an existing logfile. However, there shouldn't be one, so
3625 * rename() is an acceptable substitute except for the truly paranoid.
3627 #if HAVE_WORKING_LINK
3628 if (link(tmppath, path) < 0)
3630 (errcode_for_file_access(),
3631 errmsg("could not link file \"%s\" to \"%s\": %m",
3635 if (rename(tmppath, path) < 0)
3637 (errcode_for_file_access(),
3638 errmsg("could not rename file \"%s\" to \"%s\": %m",
3642 /* The history file can be archived immediately. */
3643 TLHistoryFileName(histfname, newTLI);
3644 XLogArchiveNotify(histfname);
3648 * I/O routines for pg_control
3650 * *ControlFile is a buffer in shared memory that holds an image of the
3651 * contents of pg_control. WriteControlFile() initializes pg_control
3652 * given a preloaded buffer, ReadControlFile() loads the buffer from
3653 * the pg_control file (during postmaster or standalone-backend startup),
3654 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3656 * For simplicity, WriteControlFile() initializes the fields of pg_control
3657 * that are related to checking backend/database compatibility, and
3658 * ReadControlFile() verifies they are correct. We could split out the
3659 * I/O and compatibility-check functions, but there seems no need currently.
3662 WriteControlFile(void)
3665 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3669 * Initialize version and compatibility-check fields
3671 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3672 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3674 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3675 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3677 ControlFile->blcksz = BLCKSZ;
3678 ControlFile->relseg_size = RELSEG_SIZE;
3679 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3680 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3682 ControlFile->nameDataLen = NAMEDATALEN;
3683 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3685 #ifdef HAVE_INT64_TIMESTAMP
3686 ControlFile->enableIntTimes = TRUE;
3688 ControlFile->enableIntTimes = FALSE;
3691 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3692 localeptr = setlocale(LC_COLLATE, NULL);
3695 (errmsg("invalid LC_COLLATE setting")));
3696 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3697 localeptr = setlocale(LC_CTYPE, NULL);
3700 (errmsg("invalid LC_CTYPE setting")));
3701 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3703 /* Contents are protected with a CRC */
3704 INIT_CRC32(ControlFile->crc);
3705 COMP_CRC32(ControlFile->crc,
3706 (char *) ControlFile,
3707 offsetof(ControlFileData, crc));
3708 FIN_CRC32(ControlFile->crc);
3711 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3712 * excess over sizeof(ControlFileData). This reduces the odds of
3713 * premature-EOF errors when reading pg_control. We'll still fail when we
3714 * check the contents of the file, but hopefully with a more specific
3715 * error than "couldn't read pg_control".
3717 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3718 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3720 memset(buffer, 0, PG_CONTROL_SIZE);
3721 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3723 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3724 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3728 (errcode_for_file_access(),
3729 errmsg("could not create control file \"%s\": %m",
3730 XLOG_CONTROL_FILE)));
3733 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3735 /* if write didn't set errno, assume problem is no disk space */
3739 (errcode_for_file_access(),
3740 errmsg("could not write to control file: %m")));
3743 if (pg_fsync(fd) != 0)
3745 (errcode_for_file_access(),
3746 errmsg("could not fsync control file: %m")));
3750 (errcode_for_file_access(),
3751 errmsg("could not close control file: %m")));
3755 ReadControlFile(void)
3763 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3768 (errcode_for_file_access(),
3769 errmsg("could not open control file \"%s\": %m",
3770 XLOG_CONTROL_FILE)));
3772 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3774 (errcode_for_file_access(),
3775 errmsg("could not read from control file: %m")));
3780 * Check for expected pg_control format version. If this is wrong, the
3781 * CRC check will likely fail because we'll be checking the wrong number
3782 * of bytes. Complaining about wrong version will probably be more
3783 * enlightening than complaining about wrong CRC.
3785 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3787 (errmsg("database files are incompatible with server"),
3788 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3789 " but the server was compiled with PG_CONTROL_VERSION %d.",
3790 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3791 errhint("It looks like you need to initdb.")));
3792 /* Now check the CRC. */
3795 (char *) ControlFile,
3796 offsetof(ControlFileData, crc));
3799 if (!EQ_CRC32(crc, ControlFile->crc))
3801 (errmsg("incorrect checksum in control file")));
3804 * Do compatibility checking immediately. We do this here for 2 reasons:
3806 * (1) if the database isn't compatible with the backend executable, we
3807 * want to abort before we can possibly do any damage;
3809 * (2) this code is executed in the postmaster, so the setlocale() will
3810 * propagate to forked backends, which aren't going to read this file for
3811 * themselves. (These locale settings are considered critical
3812 * compatibility items because they can affect sort order of indexes.)
3814 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3816 (errmsg("database files are incompatible with server"),
3817 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3818 " but the server was compiled with CATALOG_VERSION_NO %d.",
3819 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3820 errhint("It looks like you need to initdb.")));
3821 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3823 (errmsg("database files are incompatible with server"),
3824 errdetail("The database cluster was initialized with MAXALIGN %d,"
3825 " but the server was compiled with MAXALIGN %d.",
3826 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3827 errhint("It looks like you need to initdb.")));
3828 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3830 (errmsg("database files are incompatible with server"),
3831 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3832 errhint("It looks like you need to initdb.")));
3833 if (ControlFile->blcksz != BLCKSZ)
3835 (errmsg("database files are incompatible with server"),
3836 errdetail("The database cluster was initialized with BLCKSZ %d,"
3837 " but the server was compiled with BLCKSZ %d.",
3838 ControlFile->blcksz, BLCKSZ),
3839 errhint("It looks like you need to recompile or initdb.")));
3840 if (ControlFile->relseg_size != RELSEG_SIZE)
3842 (errmsg("database files are incompatible with server"),
3843 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3844 " but the server was compiled with RELSEG_SIZE %d.",
3845 ControlFile->relseg_size, RELSEG_SIZE),
3846 errhint("It looks like you need to recompile or initdb.")));
3847 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3849 (errmsg("database files are incompatible with server"),
3850 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3851 " but the server was compiled with XLOG_BLCKSZ %d.",
3852 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3853 errhint("It looks like you need to recompile or initdb.")));
3854 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3856 (errmsg("database files are incompatible with server"),
3857 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3858 " but the server was compiled with XLOG_SEG_SIZE %d.",
3859 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3860 errhint("It looks like you need to recompile or initdb.")));
3861 if (ControlFile->nameDataLen != NAMEDATALEN)
3863 (errmsg("database files are incompatible with server"),
3864 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3865 " but the server was compiled with NAMEDATALEN %d.",
3866 ControlFile->nameDataLen, NAMEDATALEN),
3867 errhint("It looks like you need to recompile or initdb.")));
3868 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3870 (errmsg("database files are incompatible with server"),
3871 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3872 " but the server was compiled with INDEX_MAX_KEYS %d.",
3873 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3874 errhint("It looks like you need to recompile or initdb.")));
3876 #ifdef HAVE_INT64_TIMESTAMP
3877 if (ControlFile->enableIntTimes != TRUE)
3879 (errmsg("database files are incompatible with server"),
3880 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3881 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3882 errhint("It looks like you need to recompile or initdb.")));
3884 if (ControlFile->enableIntTimes != FALSE)
3886 (errmsg("database files are incompatible with server"),
3887 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3888 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3889 errhint("It looks like you need to recompile or initdb.")));
3892 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3894 (errmsg("database files are incompatible with server"),
3895 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3896 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3897 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3898 errhint("It looks like you need to recompile or initdb.")));
3899 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3901 (errmsg("database files are incompatible with operating system"),
3902 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3903 " which is not recognized by setlocale().",
3904 ControlFile->lc_collate),
3905 errhint("It looks like you need to initdb or install locale support.")));
3906 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3908 (errmsg("database files are incompatible with operating system"),
3909 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3910 " which is not recognized by setlocale().",
3911 ControlFile->lc_ctype),
3912 errhint("It looks like you need to initdb or install locale support.")));
3914 /* Make the fixed locale settings visible as GUC variables, too */
3915 SetConfigOption("lc_collate", ControlFile->lc_collate,
3916 PGC_INTERNAL, PGC_S_OVERRIDE);
3917 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3918 PGC_INTERNAL, PGC_S_OVERRIDE);
3922 UpdateControlFile(void)
3926 INIT_CRC32(ControlFile->crc);
3927 COMP_CRC32(ControlFile->crc,
3928 (char *) ControlFile,
3929 offsetof(ControlFileData, crc));
3930 FIN_CRC32(ControlFile->crc);
3932 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3937 (errcode_for_file_access(),
3938 errmsg("could not open control file \"%s\": %m",
3939 XLOG_CONTROL_FILE)));
3942 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3944 /* if write didn't set errno, assume problem is no disk space */
3948 (errcode_for_file_access(),
3949 errmsg("could not write to control file: %m")));
3952 if (pg_fsync(fd) != 0)
3954 (errcode_for_file_access(),
3955 errmsg("could not fsync control file: %m")));
3959 (errcode_for_file_access(),
3960 errmsg("could not close control file: %m")));
3964 * Initialization of shared memory for XLOG
3972 size = sizeof(XLogCtlData);
3973 /* xlblocks array */
3974 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
3975 /* extra alignment padding for XLOG I/O buffers */
3976 size = add_size(size, ALIGNOF_XLOG_BUFFER);
3977 /* and the buffers themselves */
3978 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
3981 * Note: we don't count ControlFileData, it comes out of the "slop factor"
3982 * added by CreateSharedMemoryAndSemaphores. This lets us use this
3983 * routine again below to compute the actual allocation size.
3996 ControlFile = (ControlFileData *)
3997 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
3998 XLogCtl = (XLogCtlData *)
3999 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4001 if (foundCFile || foundXLog)
4003 /* both should be present or neither */
4004 Assert(foundCFile && foundXLog);
4008 memset(XLogCtl, 0, sizeof(XLogCtlData));
4011 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4012 * multiple of the alignment for same, so no extra alignment padding is
4015 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4016 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4017 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4018 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4021 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4023 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4024 XLogCtl->pages = allocptr;
4025 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4028 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4029 * in additional info.)
4031 XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
4033 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4034 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4035 SpinLockInit(&XLogCtl->info_lck);
4038 * If we are not in bootstrap mode, pg_control should already exist. Read
4039 * and validate it immediately (see comments in ReadControlFile() for the
4042 if (!IsBootstrapProcessingMode())
4047 * This func must be called ONCE on system install. It creates pg_control
4048 * and the initial XLOG segment.
4053 CheckPoint checkPoint;
4055 XLogPageHeader page;
4056 XLogLongPageHeader longpage;
4059 uint64 sysidentifier;
4064 * Select a hopefully-unique system identifier code for this installation.
4065 * We use the result of gettimeofday(), including the fractional seconds
4066 * field, as being about as unique as we can easily get. (Think not to
4067 * use random(), since it hasn't been seeded and there's no portable way
4068 * to seed it other than the system clock value...) The upper half of the
4069 * uint64 value is just the tv_sec part, while the lower half is the XOR
4070 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4071 * unnecessarily if "uint64" is really only 32 bits wide. A person
4072 * knowing this encoding can determine the initialization time of the
4073 * installation, which could perhaps be useful sometimes.
4075 gettimeofday(&tv, NULL);
4076 sysidentifier = ((uint64) tv.tv_sec) << 32;
4077 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4079 /* First timeline ID is always 1 */
4082 /* page buffer must be aligned suitably for O_DIRECT */
4083 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4084 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4085 memset(page, 0, XLOG_BLCKSZ);
4087 /* Set up information for the initial checkpoint record */
4088 checkPoint.redo.xlogid = 0;
4089 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4090 checkPoint.undo = checkPoint.redo;
4091 checkPoint.ThisTimeLineID = ThisTimeLineID;
4092 checkPoint.nextXidEpoch = 0;
4093 checkPoint.nextXid = FirstNormalTransactionId;
4094 checkPoint.nextOid = FirstBootstrapObjectId;
4095 checkPoint.nextMulti = FirstMultiXactId;
4096 checkPoint.nextMultiOffset = 0;
4097 checkPoint.time = time(NULL);
4099 ShmemVariableCache->nextXid = checkPoint.nextXid;
4100 ShmemVariableCache->nextOid = checkPoint.nextOid;
4101 ShmemVariableCache->oidCount = 0;
4102 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4104 /* Set up the XLOG page header */
4105 page->xlp_magic = XLOG_PAGE_MAGIC;
4106 page->xlp_info = XLP_LONG_HEADER;
4107 page->xlp_tli = ThisTimeLineID;
4108 page->xlp_pageaddr.xlogid = 0;
4109 page->xlp_pageaddr.xrecoff = 0;
4110 longpage = (XLogLongPageHeader) page;
4111 longpage->xlp_sysid = sysidentifier;
4112 longpage->xlp_seg_size = XLogSegSize;
4113 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4115 /* Insert the initial checkpoint record */
4116 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4117 record->xl_prev.xlogid = 0;
4118 record->xl_prev.xrecoff = 0;
4119 record->xl_xid = InvalidTransactionId;
4120 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4121 record->xl_len = sizeof(checkPoint);
4122 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4123 record->xl_rmid = RM_XLOG_ID;
4124 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4127 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4128 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4129 SizeOfXLogRecord - sizeof(pg_crc32));
4131 record->xl_crc = crc;
4133 /* Create first XLOG segment file */
4134 use_existent = false;
4135 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4137 /* Write the first page with the initial record */
4139 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4141 /* if write didn't set errno, assume problem is no disk space */
4145 (errcode_for_file_access(),
4146 errmsg("could not write bootstrap transaction log file: %m")));
4149 if (pg_fsync(openLogFile) != 0)
4151 (errcode_for_file_access(),
4152 errmsg("could not fsync bootstrap transaction log file: %m")));
4154 if (close(openLogFile))
4156 (errcode_for_file_access(),
4157 errmsg("could not close bootstrap transaction log file: %m")));
4161 /* Now create pg_control */
4163 memset(ControlFile, 0, sizeof(ControlFileData));
4164 /* Initialize pg_control status fields */
4165 ControlFile->system_identifier = sysidentifier;
4166 ControlFile->state = DB_SHUTDOWNED;
4167 ControlFile->time = checkPoint.time;
4168 ControlFile->logId = 0;
4169 ControlFile->logSeg = 1;
4170 ControlFile->checkPoint = checkPoint.redo;
4171 ControlFile->checkPointCopy = checkPoint;
4172 /* some additional ControlFile fields are set in WriteControlFile() */
4176 /* Bootstrap the commit log, too */
4178 BootStrapSUBTRANS();
4179 BootStrapMultiXact();
4185 str_time(time_t tnow)
4187 static char buf[128];
4189 strftime(buf, sizeof(buf),
4190 "%Y-%m-%d %H:%M:%S %Z",
4197 * See if there is a recovery command file (recovery.conf), and if so
4198 * read in parameters for archive recovery.
4200 * XXX longer term intention is to expand this to
4201 * cater for additional parameters and controls
4202 * possibly use a flex lexer similar to the GUC one
4205 readRecoveryCommandFile(void)
4208 char cmdline[MAXPGPATH];
4209 TimeLineID rtli = 0;
4210 bool rtliGiven = false;
4211 bool syntaxError = false;
4213 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4216 if (errno == ENOENT)
4217 return; /* not there, so no archive recovery */
4219 (errcode_for_file_access(),
4220 errmsg("could not open recovery command file \"%s\": %m",
4221 RECOVERY_COMMAND_FILE)));
4225 (errmsg("starting archive recovery")));
4230 while (fgets(cmdline, MAXPGPATH, fd) != NULL)
4232 /* skip leading whitespace and check for # comment */
4237 for (ptr = cmdline; *ptr; ptr++)
4239 if (!isspace((unsigned char) *ptr))
4242 if (*ptr == '\0' || *ptr == '#')
4245 /* identify the quoted parameter value */
4246 tok1 = strtok(ptr, "'");
4252 tok2 = strtok(NULL, "'");
4258 /* reparse to get just the parameter name */
4259 tok1 = strtok(ptr, " \t=");
4266 if (strcmp(tok1, "restore_command") == 0)
4268 recoveryRestoreCommand = pstrdup(tok2);
4270 (errmsg("restore_command = \"%s\"",
4271 recoveryRestoreCommand)));
4273 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4276 if (strcmp(tok2, "latest") == 0)
4281 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4282 if (errno == EINVAL || errno == ERANGE)
4284 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4289 (errmsg("recovery_target_timeline = %u", rtli)));
4292 (errmsg("recovery_target_timeline = latest")));
4294 else if (strcmp(tok1, "recovery_target_xid") == 0)
4297 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4298 if (errno == EINVAL || errno == ERANGE)
4300 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4303 (errmsg("recovery_target_xid = %u",
4304 recoveryTargetXid)));
4305 recoveryTarget = true;
4306 recoveryTargetExact = true;
4308 else if (strcmp(tok1, "recovery_target_time") == 0)
4311 * if recovery_target_xid specified, then this overrides
4312 * recovery_target_time
4314 if (recoveryTargetExact)
4316 recoveryTarget = true;
4317 recoveryTargetExact = false;
4320 * Convert the time string given by the user to the time_t format.
4321 * We use type abstime's input converter because we know abstime
4322 * has the same representation as time_t.
4324 recoveryTargetTime = (time_t)
4325 DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
4326 CStringGetDatum(tok2)));
4328 (errmsg("recovery_target_time = %s",
4329 DatumGetCString(DirectFunctionCall1(abstimeout,
4330 AbsoluteTimeGetDatum((AbsoluteTime) 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)
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->xtime;
4525 else if (record_info == XLOG_XACT_ABORT)
4527 xl_xact_abort *recordXactAbortData;
4529 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4530 recordXtime = recordXactAbortData->xtime;
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",
4576 recoveryStopXid, str_time(recoveryStopTime))));
4579 (errmsg("recovery stopping before commit of transaction %u, time %s",
4580 recoveryStopXid, str_time(recoveryStopTime))));
4584 if (recoveryStopAfter)
4586 (errmsg("recovery stopping after abort of transaction %u, time %s",
4587 recoveryStopXid, str_time(recoveryStopTime))));
4590 (errmsg("recovery stopping before abort of transaction %u, time %s",
4591 recoveryStopXid, str_time(recoveryStopTime))));
4599 * This must be called ONCE during postmaster or standalone-backend startup
4604 XLogCtlInsert *Insert;
4605 CheckPoint checkPoint;
4607 bool needNewTimeLine = false;
4608 bool haveBackupLabel = false;
4618 TransactionId oldestActiveXID;
4623 * Read control file and check XLOG status looks valid.
4625 * Note: in most control paths, *ControlFile is already valid and we need
4626 * not do ReadControlFile() here, but might as well do it to be sure.
4630 if (ControlFile->logSeg == 0 ||
4631 ControlFile->state < DB_SHUTDOWNED ||
4632 ControlFile->state > DB_IN_PRODUCTION ||
4633 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4635 (errmsg("control file contains invalid data")));
4637 if (ControlFile->state == DB_SHUTDOWNED)
4639 (errmsg("database system was shut down at %s",
4640 str_time(ControlFile->time))));
4641 else if (ControlFile->state == DB_SHUTDOWNING)
4643 (errmsg("database system shutdown was interrupted at %s",
4644 str_time(ControlFile->time))));
4645 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4647 (errmsg("database system was interrupted while in recovery at %s",
4648 str_time(ControlFile->time)),
4649 errhint("This probably means that some data is corrupted and"
4650 " you will have to use the last backup for recovery.")));
4651 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4653 (errmsg("database system was interrupted while in recovery at log time %s",
4654 str_time(ControlFile->checkPointCopy.time)),
4655 errhint("If this has occurred more than once some data may be corrupted"
4656 " and you may need to choose an earlier recovery target.")));
4657 else if (ControlFile->state == DB_IN_PRODUCTION)
4659 (errmsg("database system was interrupted at %s",
4660 str_time(ControlFile->time))));
4662 /* This is just to allow attaching to startup process with a debugger */
4663 #ifdef XLOG_REPLAY_DELAY
4664 if (ControlFile->state != DB_SHUTDOWNED)
4665 pg_usleep(60000000L);
4669 * Initialize on the assumption we want to recover to the same timeline
4670 * that's active according to pg_control.
4672 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4675 * Check for recovery control file, and if so set up state for offline
4678 readRecoveryCommandFile();
4680 /* Now we can determine the list of expected TLIs */
4681 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4684 * If pg_control's timeline is not in expectedTLIs, then we cannot
4685 * proceed: the backup is not part of the history of the requested
4688 if (!list_member_int(expectedTLIs,
4689 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4691 (errmsg("requested timeline %u is not a child of database system timeline %u",
4693 ControlFile->checkPointCopy.ThisTimeLineID)));
4695 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4698 * When a backup_label file is present, we want to roll forward from
4699 * the checkpoint it identifies, rather than using pg_control.
4701 record = ReadCheckpointRecord(checkPointLoc, 0);
4705 (errmsg("checkpoint record is at %X/%X",
4706 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4707 InRecovery = true; /* force recovery even if SHUTDOWNED */
4712 (errmsg("could not locate required checkpoint record"),
4713 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4715 /* set flag to delete it later */
4716 haveBackupLabel = true;
4721 * Get the last valid checkpoint record. If the latest one according
4722 * to pg_control is broken, try the next-to-last one.
4724 checkPointLoc = ControlFile->checkPoint;
4725 record = ReadCheckpointRecord(checkPointLoc, 1);
4729 (errmsg("checkpoint record is at %X/%X",
4730 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4734 checkPointLoc = ControlFile->prevCheckPoint;
4735 record = ReadCheckpointRecord(checkPointLoc, 2);
4739 (errmsg("using previous checkpoint record at %X/%X",
4740 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4741 InRecovery = true; /* force recovery even if SHUTDOWNED */
4745 (errmsg("could not locate a valid checkpoint record")));
4749 LastRec = RecPtr = checkPointLoc;
4750 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4751 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4754 (errmsg("redo record is at %X/%X; undo record is at %X/%X; shutdown %s",
4755 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4756 checkPoint.undo.xlogid, checkPoint.undo.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")));
4786 if (checkPoint.undo.xrecoff == 0)
4787 checkPoint.undo = RecPtr;
4790 * Check whether we need to force recovery from WAL. If it appears to
4791 * have been a clean shutdown and we did not have a recovery.conf file,
4792 * then assume no recovery needed.
4794 if (XLByteLT(checkPoint.undo, RecPtr) ||
4795 XLByteLT(checkPoint.redo, RecPtr))
4799 (errmsg("invalid redo/undo record in shutdown checkpoint")));
4802 else if (ControlFile->state != DB_SHUTDOWNED)
4804 else if (InArchiveRecovery)
4806 /* force recovery due to presence of recovery.conf */
4816 * Update pg_control to show that we are recovering and to show the
4817 * selected checkpoint as the place we are starting from. We also mark
4818 * pg_control with any minimum recovery stop point obtained from a
4819 * backup history file.
4821 if (InArchiveRecovery)
4824 (errmsg("automatic recovery in progress")));
4825 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4830 (errmsg("database system was not properly shut down; "
4831 "automatic recovery in progress")));
4832 ControlFile->state = DB_IN_CRASH_RECOVERY;
4834 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4835 ControlFile->checkPoint = checkPointLoc;
4836 ControlFile->checkPointCopy = checkPoint;
4837 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4838 ControlFile->minRecoveryPoint = minRecoveryLoc;
4839 ControlFile->time = time(NULL);
4840 UpdateControlFile();
4843 * If there was a backup label file, it's done its job and the info
4844 * has now been propagated into pg_control. We must get rid of the
4845 * label file so that if we crash during recovery, we'll pick up at
4846 * the latest recovery restartpoint instead of going all the way back
4847 * to the backup start point. It seems prudent though to just rename
4848 * the file out of the way rather than delete it completely.
4850 if (haveBackupLabel)
4852 unlink(BACKUP_LABEL_OLD);
4853 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4855 (errcode_for_file_access(),
4856 errmsg("could not rename file \"%s\" to \"%s\": %m",
4857 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4860 /* Start up the recovery environment */
4861 XLogInitRelationCache();
4863 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4865 if (RmgrTable[rmid].rm_startup != NULL)
4866 RmgrTable[rmid].rm_startup();
4870 * Find the first record that logically follows the checkpoint --- it
4871 * might physically precede it, though.
4873 if (XLByteLT(checkPoint.redo, RecPtr))
4875 /* back up to find the record */
4876 record = ReadRecord(&(checkPoint.redo), PANIC);
4880 /* just have to read next record after CheckPoint */
4881 record = ReadRecord(NULL, LOG);
4886 bool recoveryContinue = true;
4887 bool recoveryApply = true;
4888 ErrorContextCallback errcontext;
4892 (errmsg("redo starts at %X/%X",
4893 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4896 * main redo apply loop
4905 initStringInfo(&buf);
4906 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4907 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4908 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4909 xlog_outrec(&buf, record);
4910 appendStringInfo(&buf, " - ");
4911 RmgrTable[record->xl_rmid].rm_desc(&buf,
4913 XLogRecGetData(record));
4914 elog(LOG, "%s", buf.data);
4920 * Have we reached our recovery target?
4922 if (recoveryStopsHere(record, &recoveryApply))
4924 needNewTimeLine = true; /* see below */
4925 recoveryContinue = false;
4930 /* Setup error traceback support for ereport() */
4931 errcontext.callback = rm_redo_error_callback;
4932 errcontext.arg = (void *) record;
4933 errcontext.previous = error_context_stack;
4934 error_context_stack = &errcontext;
4936 /* nextXid must be beyond record's xid */
4937 if (TransactionIdFollowsOrEquals(record->xl_xid,
4938 ShmemVariableCache->nextXid))
4940 ShmemVariableCache->nextXid = record->xl_xid;
4941 TransactionIdAdvance(ShmemVariableCache->nextXid);
4944 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4945 RestoreBkpBlocks(record, EndRecPtr);
4947 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4949 /* Pop the error context stack */
4950 error_context_stack = errcontext.previous;
4952 LastRec = ReadRecPtr;
4954 record = ReadRecord(NULL, LOG);
4955 } while (record != NULL && recoveryContinue);
4958 * end of main redo apply loop
4962 (errmsg("redo done at %X/%X",
4963 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4968 /* there are no WAL records following the checkpoint */
4970 (errmsg("redo is not required")));
4975 * Re-fetch the last valid or last applied record, so we can identify the
4976 * exact endpoint of what we consider the valid portion of WAL.
4978 record = ReadRecord(&LastRec, PANIC);
4979 EndOfLog = EndRecPtr;
4980 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4983 * Complain if we did not roll forward far enough to render the backup
4986 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
4988 if (needNewTimeLine) /* stopped because of stop request */
4990 (errmsg("requested recovery stop point is before end time of backup dump")));
4992 /* ran off end of WAL */
4994 (errmsg("WAL ends before end time of backup dump")));
4998 * Consider whether we need to assign a new timeline ID.
5000 * If we stopped short of the end of WAL during recovery, then we are
5001 * generating a new timeline and must assign it a unique new ID.
5002 * Otherwise, we can just extend the timeline we were in when we ran out
5005 if (needNewTimeLine)
5007 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5009 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5010 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5011 curFileTLI, endLogId, endLogSeg);
5014 /* Save the selected TimeLineID in shared memory, too */
5015 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5018 * We are now done reading the old WAL. Turn off archive fetching if it
5019 * was active, and make a writable copy of the last WAL segment. (Note
5020 * that we also have a copy of the last block of the old WAL in readBuf;
5021 * we will use that below.)
5023 if (InArchiveRecovery)
5024 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5027 * Prepare to write WAL starting at EndOfLog position, and init xlog
5028 * buffer cache using the block containing the last record from the
5029 * previous incarnation.
5031 openLogId = endLogId;
5032 openLogSeg = endLogSeg;
5033 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5035 ControlFile->logId = openLogId;
5036 ControlFile->logSeg = openLogSeg + 1;
5037 Insert = &XLogCtl->Insert;
5038 Insert->PrevRecord = LastRec;
5039 XLogCtl->xlblocks[0].xlogid = openLogId;
5040 XLogCtl->xlblocks[0].xrecoff =
5041 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5044 * Tricky point here: readBuf contains the *last* block that the LastRec
5045 * record spans, not the one it starts in. The last block is indeed the
5046 * one we want to use.
5048 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5049 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5050 Insert->currpos = (char *) Insert->currpage +
5051 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5053 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5055 XLogCtl->Write.LogwrtResult = LogwrtResult;
5056 Insert->LogwrtResult = LogwrtResult;
5057 XLogCtl->LogwrtResult = LogwrtResult;
5059 XLogCtl->LogwrtRqst.Write = EndOfLog;
5060 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5062 freespace = INSERT_FREESPACE(Insert);
5065 /* Make sure rest of page is zero */
5066 MemSet(Insert->currpos, 0, freespace);
5067 XLogCtl->Write.curridx = 0;
5072 * Whenever Write.LogwrtResult points to exactly the end of a page,
5073 * Write.curridx must point to the *next* page (see XLogWrite()).
5075 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5076 * this is sufficient. The first actual attempt to insert a log
5077 * record will advance the insert state.
5079 XLogCtl->Write.curridx = NextBufIdx(0);
5082 /* Pre-scan prepared transactions to find out the range of XIDs present */
5083 oldestActiveXID = PrescanPreparedTransactions();
5090 * Allow resource managers to do any required cleanup.
5092 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5094 if (RmgrTable[rmid].rm_cleanup != NULL)
5095 RmgrTable[rmid].rm_cleanup();
5099 * Check to see if the XLOG sequence contained any unresolved
5100 * references to uninitialized pages.
5102 XLogCheckInvalidPages();
5105 * Reset pgstat data, because it may be invalid after recovery.
5110 * Perform a checkpoint to update all our recovery activity to disk.
5112 * Note that we write a shutdown checkpoint rather than an on-line
5113 * one. This is not particularly critical, but since we may be
5114 * assigning a new TLI, using a shutdown checkpoint allows us to have
5115 * the rule that TLI only changes in shutdown checkpoints, which
5116 * allows some extra error checking in xlog_redo.
5118 CreateCheckPoint(true, true);
5121 * Close down recovery environment
5123 XLogCloseRelationCache();
5127 * Preallocate additional log files, if wanted.
5129 (void) PreallocXlogFiles(EndOfLog);
5132 * Okay, we're officially UP.
5136 ControlFile->state = DB_IN_PRODUCTION;
5137 ControlFile->time = time(NULL);
5138 UpdateControlFile();
5140 /* start the archive_timeout timer running */
5141 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5143 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5144 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5145 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5147 /* Start up the commit log and related stuff, too */
5149 StartupSUBTRANS(oldestActiveXID);
5152 /* Reload shared-memory state for prepared transactions */
5153 RecoverPreparedTransactions();
5156 (errmsg("database system is ready")));
5159 /* Shut down readFile facility, free space */
5172 free(readRecordBuf);
5173 readRecordBuf = NULL;
5174 readRecordBufSize = 0;
5179 * Subroutine to try to fetch and validate a prior checkpoint record.
5181 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5182 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5185 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5189 if (!XRecOffIsValid(RecPtr.xrecoff))
5195 (errmsg("invalid primary checkpoint link in control file")));
5199 (errmsg("invalid secondary checkpoint link in control file")));
5203 (errmsg("invalid checkpoint link in backup_label file")));
5209 record = ReadRecord(&RecPtr, LOG);
5217 (errmsg("invalid primary checkpoint record")));
5221 (errmsg("invalid secondary checkpoint record")));
5225 (errmsg("invalid checkpoint record")));
5230 if (record->xl_rmid != RM_XLOG_ID)
5236 (errmsg("invalid resource manager ID in primary checkpoint record")));
5240 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5244 (errmsg("invalid resource manager ID in checkpoint record")));
5249 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5250 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5256 (errmsg("invalid xl_info in primary checkpoint record")));
5260 (errmsg("invalid xl_info in secondary checkpoint record")));
5264 (errmsg("invalid xl_info in checkpoint record")));
5269 if (record->xl_len != sizeof(CheckPoint) ||
5270 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5276 (errmsg("invalid length of primary checkpoint record")));
5280 (errmsg("invalid length of secondary checkpoint record")));
5284 (errmsg("invalid length of checkpoint record")));
5293 * This must be called during startup of a backend process, except that
5294 * it need not be called in a standalone backend (which does StartupXLOG
5295 * instead). We need to initialize the local copies of ThisTimeLineID and
5298 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5299 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5300 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5303 InitXLOGAccess(void)
5305 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5306 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5307 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5308 (void) GetRedoRecPtr();
5312 * Once spawned, a backend may update its local RedoRecPtr from
5313 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5314 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5319 /* use volatile pointer to prevent code rearrangement */
5320 volatile XLogCtlData *xlogctl = XLogCtl;
5322 SpinLockAcquire(&xlogctl->info_lck);
5323 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5324 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5325 SpinLockRelease(&xlogctl->info_lck);
5331 * Get the time of the last xlog segment switch
5334 GetLastSegSwitchTime(void)
5338 /* Need WALWriteLock, but shared lock is sufficient */
5339 LWLockAcquire(WALWriteLock, LW_SHARED);
5340 result = XLogCtl->Write.lastSegSwitchTime;
5341 LWLockRelease(WALWriteLock);
5347 * GetRecentNextXid - get the nextXid value saved by the most recent checkpoint
5349 * This is currently used only by the autovacuum daemon. To check for
5350 * impending XID wraparound, autovac needs an approximate idea of the current
5351 * XID counter, and it needs it before choosing which DB to attach to, hence
5352 * before it sets up a PGPROC, hence before it can take any LWLocks. But it
5353 * has attached to shared memory, and so we can let it reach into the shared
5354 * ControlFile structure and pull out the last checkpoint nextXID.
5356 * Since we don't take any sort of lock, we have to assume that reading a
5357 * TransactionId is atomic ... but that assumption is made elsewhere, too,
5358 * and in any case the worst possible consequence of a bogus result is that
5359 * autovac issues an unnecessary database-wide VACUUM.
5361 * Note: we could also choose to read ShmemVariableCache->nextXid in an
5362 * unlocked fashion, thus getting a more up-to-date result; but since that
5363 * changes far more frequently than the controlfile checkpoint copy, it would
5364 * pose a far higher risk of bogus result if we did have a nonatomic-read
5367 * A (theoretically) completely safe answer is to read the actual pg_control
5368 * file into local process memory, but that certainly seems like overkill.
5371 GetRecentNextXid(void)
5373 return ControlFile->checkPointCopy.nextXid;
5377 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5379 * This is exported for use by code that would like to have 64-bit XIDs.
5380 * We don't really support such things, but all XIDs within the system
5381 * can be presumed "close to" the result, and thus the epoch associated
5382 * with them can be determined.
5385 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5387 uint32 ckptXidEpoch;
5388 TransactionId ckptXid;
5389 TransactionId nextXid;
5391 /* Must read checkpoint info first, else have race condition */
5393 /* use volatile pointer to prevent code rearrangement */
5394 volatile XLogCtlData *xlogctl = XLogCtl;
5396 SpinLockAcquire(&xlogctl->info_lck);
5397 ckptXidEpoch = xlogctl->ckptXidEpoch;
5398 ckptXid = xlogctl->ckptXid;
5399 SpinLockRelease(&xlogctl->info_lck);
5402 /* Now fetch current nextXid */
5403 nextXid = ReadNewTransactionId();
5406 * nextXid is certainly logically later than ckptXid. So if it's
5407 * numerically less, it must have wrapped into the next epoch.
5409 if (nextXid < ckptXid)
5413 *epoch = ckptXidEpoch;
5417 * This must be called ONCE during postmaster or standalone-backend shutdown
5420 ShutdownXLOG(int code, Datum arg)
5423 (errmsg("shutting down")));
5426 CreateCheckPoint(true, true);
5429 ShutdownMultiXact();
5433 (errmsg("database system is shut down")));
5437 * Perform a checkpoint --- either during shutdown, or on-the-fly
5439 * If force is true, we force a checkpoint regardless of whether any XLOG
5440 * activity has occurred since the last one.
5443 CreateCheckPoint(bool shutdown, bool force)
5445 CheckPoint checkPoint;
5447 XLogCtlInsert *Insert = &XLogCtl->Insert;
5453 int nsegsremoved = 0;
5454 int nsegsrecycled = 0;
5457 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5458 * (This is just pro forma, since in the present system structure there is
5459 * only one process that is allowed to issue checkpoints at any given
5462 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5465 * Use a critical section to force system panic if we have trouble.
5467 START_CRIT_SECTION();
5471 ControlFile->state = DB_SHUTDOWNING;
5472 ControlFile->time = time(NULL);
5473 UpdateControlFile();
5476 MemSet(&checkPoint, 0, sizeof(checkPoint));
5477 checkPoint.ThisTimeLineID = ThisTimeLineID;
5478 checkPoint.time = time(NULL);
5481 * We must hold CheckpointStartLock while determining the checkpoint REDO
5482 * pointer. This ensures that any concurrent transaction commits will be
5483 * either not yet logged, or logged and recorded in pg_clog. See notes in
5484 * RecordTransactionCommit().
5486 LWLockAcquire(CheckpointStartLock, LW_EXCLUSIVE);
5488 /* And we need WALInsertLock too */
5489 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5492 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5493 * any XLOG records since the start of the last checkpoint, skip the
5494 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5495 * when the system is idle. That wastes log space, and more importantly it
5496 * exposes us to possible loss of both current and previous checkpoint
5497 * records if the machine crashes just as we're writing the update.
5498 * (Perhaps it'd make even more sense to checkpoint only when the previous
5499 * checkpoint record is in a different xlog page?)
5501 * We have to make two tests to determine that nothing has happened since
5502 * the start of the last checkpoint: current insertion point must match
5503 * the end of the last checkpoint record, and its redo pointer must point
5506 if (!shutdown && !force)
5508 XLogRecPtr curInsert;
5510 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5511 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5512 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5513 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5514 ControlFile->checkPoint.xlogid ==
5515 ControlFile->checkPointCopy.redo.xlogid &&
5516 ControlFile->checkPoint.xrecoff ==
5517 ControlFile->checkPointCopy.redo.xrecoff)
5519 LWLockRelease(WALInsertLock);
5520 LWLockRelease(CheckpointStartLock);
5521 LWLockRelease(CheckpointLock);
5528 * Compute new REDO record ptr = location of next XLOG record.
5530 * NB: this is NOT necessarily where the checkpoint record itself will be,
5531 * since other backends may insert more XLOG records while we're off doing
5532 * the buffer flush work. Those XLOG records are logically after the
5533 * checkpoint, even though physically before it. Got that?
5535 freespace = INSERT_FREESPACE(Insert);
5536 if (freespace < SizeOfXLogRecord)
5538 (void) AdvanceXLInsertBuffer(false);
5539 /* OK to ignore update return flag, since we will do flush anyway */
5540 freespace = INSERT_FREESPACE(Insert);
5542 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5545 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5546 * must be done while holding the insert lock AND the info_lck.
5548 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5549 * pointing past where it really needs to point. This is okay; the only
5550 * consequence is that XLogInsert might back up whole buffers that it
5551 * didn't really need to. We can't postpone advancing RedoRecPtr because
5552 * XLogInserts that happen while we are dumping buffers must assume that
5553 * their buffer changes are not included in the checkpoint.
5556 /* use volatile pointer to prevent code rearrangement */
5557 volatile XLogCtlData *xlogctl = XLogCtl;
5559 SpinLockAcquire(&xlogctl->info_lck);
5560 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5561 SpinLockRelease(&xlogctl->info_lck);
5565 * Now we can release insert lock and checkpoint start lock, allowing
5566 * other xacts to proceed even while we are flushing disk buffers.
5568 LWLockRelease(WALInsertLock);
5570 LWLockRelease(CheckpointStartLock);
5574 (errmsg("checkpoint starting")));
5577 * Get the other info we need for the checkpoint record.
5579 LWLockAcquire(XidGenLock, LW_SHARED);
5580 checkPoint.nextXid = ShmemVariableCache->nextXid;
5581 LWLockRelease(XidGenLock);
5583 /* Increase XID epoch if we've wrapped around since last checkpoint */
5584 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5585 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5586 checkPoint.nextXidEpoch++;
5588 LWLockAcquire(OidGenLock, LW_SHARED);
5589 checkPoint.nextOid = ShmemVariableCache->nextOid;
5591 checkPoint.nextOid += ShmemVariableCache->oidCount;
5592 LWLockRelease(OidGenLock);
5594 MultiXactGetCheckptMulti(shutdown,
5595 &checkPoint.nextMulti,
5596 &checkPoint.nextMultiOffset);
5599 * Having constructed the checkpoint record, ensure all shmem disk buffers
5600 * and commit-log buffers are flushed to disk.
5602 * This I/O could fail for various reasons. If so, we will fail to
5603 * complete the checkpoint, but there is no reason to force a system
5604 * panic. Accordingly, exit critical section while doing it. (If we are
5605 * doing a shutdown checkpoint, we probably *should* panic --- but that
5606 * will happen anyway because we'll still be inside the critical section
5607 * established by ShutdownXLOG.)
5611 CheckPointGuts(checkPoint.redo);
5613 START_CRIT_SECTION();
5616 * Now insert the checkpoint record into XLOG.
5618 rdata.data = (char *) (&checkPoint);
5619 rdata.len = sizeof(checkPoint);
5620 rdata.buffer = InvalidBuffer;
5623 recptr = XLogInsert(RM_XLOG_ID,
5624 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5625 XLOG_CHECKPOINT_ONLINE,
5631 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5632 * = end of actual checkpoint record.
5634 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5636 (errmsg("concurrent transaction log activity while database system is shutting down")));
5639 * Select point at which we can truncate the log, which we base on the
5640 * prior checkpoint's earliest info.
5642 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5645 * Update the control file.
5647 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5649 ControlFile->state = DB_SHUTDOWNED;
5650 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5651 ControlFile->checkPoint = ProcLastRecPtr;
5652 ControlFile->checkPointCopy = checkPoint;
5653 ControlFile->time = time(NULL);
5654 UpdateControlFile();
5655 LWLockRelease(ControlFileLock);
5657 /* Update shared-memory copy of checkpoint XID/epoch */
5659 /* use volatile pointer to prevent code rearrangement */
5660 volatile XLogCtlData *xlogctl = XLogCtl;
5662 SpinLockAcquire(&xlogctl->info_lck);
5663 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5664 xlogctl->ckptXid = checkPoint.nextXid;
5665 SpinLockRelease(&xlogctl->info_lck);
5669 * We are now done with critical updates; no need for system panic if we
5670 * have trouble while fooling with offline log segments.
5675 * Delete offline log files (those no longer needed even for previous
5678 if (_logId || _logSeg)
5680 PrevLogSeg(_logId, _logSeg);
5681 MoveOfflineLogs(_logId, _logSeg, recptr,
5682 &nsegsremoved, &nsegsrecycled);
5686 * Make more log segments if needed. (Do this after deleting offline log
5687 * segments, to avoid having peak disk space usage higher than necessary.)
5690 nsegsadded = PreallocXlogFiles(recptr);
5693 * Truncate pg_subtrans if possible. We can throw away all data before
5694 * the oldest XMIN of any running transaction. No future transaction will
5695 * attempt to reference any pg_subtrans entry older than that (see Asserts
5696 * in subtrans.c). During recovery, though, we mustn't do this because
5697 * StartupSUBTRANS hasn't been called yet.
5700 TruncateSUBTRANS(GetOldestXmin(true, false));
5704 (errmsg("checkpoint complete; %d transaction log file(s) added, %d removed, %d recycled",
5705 nsegsadded, nsegsremoved, nsegsrecycled)));
5707 LWLockRelease(CheckpointLock);
5711 * Flush all data in shared memory to disk, and fsync
5713 * This is the common code shared between regular checkpoints and
5714 * recovery restartpoints.
5717 CheckPointGuts(XLogRecPtr checkPointRedo)
5720 CheckPointSUBTRANS();
5721 CheckPointMultiXact();
5722 FlushBufferPool(); /* performs all required fsyncs */
5723 /* We deliberately delay 2PC checkpointing as long as possible */
5724 CheckPointTwoPhase(checkPointRedo);
5728 * Set a recovery restart point if appropriate
5730 * This is similar to CreateCheckpoint, but is used during WAL recovery
5731 * to establish a point from which recovery can roll forward without
5732 * replaying the entire recovery log. This function is called each time
5733 * a checkpoint record is read from XLOG; it must determine whether a
5734 * restartpoint is needed or not.
5737 RecoveryRestartPoint(const CheckPoint *checkPoint)
5743 * Do nothing if the elapsed time since the last restartpoint is less than
5744 * half of checkpoint_timeout. (We use a value less than
5745 * checkpoint_timeout so that variations in the timing of checkpoints on
5746 * the master, or speed of transmission of WAL segments to a slave, won't
5747 * make the slave skip a restartpoint once it's synced with the master.)
5748 * Checking true elapsed time keeps us from doing restartpoints too often
5749 * while rapidly scanning large amounts of WAL.
5751 elapsed_secs = time(NULL) - ControlFile->time;
5752 if (elapsed_secs < CheckPointTimeout / 2)
5756 * Is it safe to checkpoint? We must ask each of the resource managers
5757 * whether they have any partial state information that might prevent a
5758 * correct restart from this point. If so, we skip this opportunity, but
5759 * return at the next checkpoint record for another try.
5761 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5763 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5764 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5769 * OK, force data out to disk
5771 CheckPointGuts(checkPoint->redo);
5774 * Update pg_control so that any subsequent crash will restart from this
5775 * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
5778 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5779 ControlFile->checkPoint = ReadRecPtr;
5780 ControlFile->checkPointCopy = *checkPoint;
5781 ControlFile->time = time(NULL);
5782 UpdateControlFile();
5785 (errmsg("recovery restart point at %X/%X",
5786 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5790 * Write a NEXTOID log record
5793 XLogPutNextOid(Oid nextOid)
5797 rdata.data = (char *) (&nextOid);
5798 rdata.len = sizeof(Oid);
5799 rdata.buffer = InvalidBuffer;
5801 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5804 * We need not flush the NEXTOID record immediately, because any of the
5805 * just-allocated OIDs could only reach disk as part of a tuple insert or
5806 * update that would have its own XLOG record that must follow the NEXTOID
5807 * record. Therefore, the standard buffer LSN interlock applied to those
5808 * records will ensure no such OID reaches disk before the NEXTOID record
5814 * Write an XLOG SWITCH record.
5816 * Here we just blindly issue an XLogInsert request for the record.
5817 * All the magic happens inside XLogInsert.
5819 * The return value is either the end+1 address of the switch record,
5820 * or the end+1 address of the prior segment if we did not need to
5821 * write a switch record because we are already at segment start.
5824 RequestXLogSwitch(void)
5829 /* XLOG SWITCH, alone among xlog record types, has no data */
5830 rdata.buffer = InvalidBuffer;
5835 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5841 * XLOG resource manager's routines
5844 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5846 uint8 info = record->xl_info & ~XLR_INFO_MASK;
5848 if (info == XLOG_NEXTOID)
5852 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5853 if (ShmemVariableCache->nextOid < nextOid)
5855 ShmemVariableCache->nextOid = nextOid;
5856 ShmemVariableCache->oidCount = 0;
5859 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5861 CheckPoint checkPoint;
5863 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5864 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5865 ShmemVariableCache->nextXid = checkPoint.nextXid;
5866 ShmemVariableCache->nextOid = checkPoint.nextOid;
5867 ShmemVariableCache->oidCount = 0;
5868 MultiXactSetNextMXact(checkPoint.nextMulti,
5869 checkPoint.nextMultiOffset);
5871 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5872 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5873 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5876 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
5878 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5880 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5881 !list_member_int(expectedTLIs,
5882 (int) checkPoint.ThisTimeLineID))
5884 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5885 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5886 /* Following WAL records should be run with new TLI */
5887 ThisTimeLineID = checkPoint.ThisTimeLineID;
5890 RecoveryRestartPoint(&checkPoint);
5892 else if (info == XLOG_CHECKPOINT_ONLINE)
5894 CheckPoint checkPoint;
5896 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5897 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5898 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5899 checkPoint.nextXid))
5900 ShmemVariableCache->nextXid = checkPoint.nextXid;
5901 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5903 ShmemVariableCache->nextOid = checkPoint.nextOid;
5904 ShmemVariableCache->oidCount = 0;
5906 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
5907 checkPoint.nextMultiOffset);
5909 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5910 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5911 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5913 /* TLI should not change in an on-line checkpoint */
5914 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5916 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5917 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5919 RecoveryRestartPoint(&checkPoint);
5921 else if (info == XLOG_SWITCH)
5923 /* nothing to do here */
5928 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
5930 uint8 info = xl_info & ~XLR_INFO_MASK;
5932 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5933 info == XLOG_CHECKPOINT_ONLINE)
5935 CheckPoint *checkpoint = (CheckPoint *) rec;
5937 appendStringInfo(buf, "checkpoint: redo %X/%X; undo %X/%X; "
5938 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
5939 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5940 checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
5941 checkpoint->ThisTimeLineID,
5942 checkpoint->nextXidEpoch, checkpoint->nextXid,
5943 checkpoint->nextOid,
5944 checkpoint->nextMulti,
5945 checkpoint->nextMultiOffset,
5946 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
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 xlog 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 xlog 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 xlog 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);