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.249 2006/08/21 16:16:31 tgl 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,
701 * we make an exception for XLOG SWITCH records because we don't want
702 * them to 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
756 * copy 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
786 * weren't already doing full-page writes then go back and recompute.
787 * (If it was just turned off, we could recompute the record without
788 * full pages, but 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
874 * of a segment, we need not insert it (and don't want to because
875 * we'd like consecutive switch requests to be no-ops). Instead,
876 * make sure everything is written and flushed through the end of
877 * the prior segment, 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,
1023 * and 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
1671 * the 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
2304 * it just dumps core, and there are reports of problems on PPC platforms
2305 * as well. The following is therefore disabled for the time being.
2306 * We could consider some kind of configure test to see if it's safe to
2307 * use, but since we lack hard evidence that there's any useful performance
2308 * gain to 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()
2319 * and 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);
2326 #endif /* NOT_USED */
2328 if (close(openLogFile))
2330 (errcode_for_file_access(),
2331 errmsg("could not close log file %u, segment %u: %m",
2332 openLogId, openLogSeg)));
2337 * Attempt to retrieve the specified file from off-line archival storage.
2338 * If successful, fill "path" with its complete path (note that this will be
2339 * a temp file name that doesn't follow the normal naming convention), and
2342 * If not successful, fill "path" with the name of the normal on-line file
2343 * (which may or may not actually exist, but we'll try to use it), and return
2346 * For fixed-size files, the caller may pass the expected size as an
2347 * additional crosscheck on successful recovery. If the file size is not
2348 * known, set expectedSize = 0.
2351 RestoreArchivedFile(char *path, const char *xlogfname,
2352 const char *recovername, off_t expectedSize)
2354 char xlogpath[MAXPGPATH];
2355 char xlogRestoreCmd[MAXPGPATH];
2360 struct stat stat_buf;
2363 * When doing archive recovery, we always prefer an archived log file even
2364 * if a file of the same name exists in XLOGDIR. The reason is that the
2365 * file in XLOGDIR could be an old, un-filled or partly-filled version
2366 * that was copied and restored as part of backing up $PGDATA.
2368 * We could try to optimize this slightly by checking the local copy
2369 * lastchange timestamp against the archived copy, but we have no API to
2370 * do this, nor can we guarantee that the lastchange timestamp was
2371 * preserved correctly when we copied to archive. Our aim is robustness,
2372 * so we elect not to do this.
2374 * If we cannot obtain the log file from the archive, however, we will try
2375 * to use the XLOGDIR file if it exists. This is so that we can make use
2376 * of log segments that weren't yet transferred to the archive.
2378 * Notice that we don't actually overwrite any files when we copy back
2379 * from archive because the recoveryRestoreCommand may inadvertently
2380 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2381 * fallback to the segments remaining in current XLOGDIR later. The
2382 * copy-from-archive filename is always the same, ensuring that we don't
2383 * run out of disk space on long recoveries.
2385 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2388 * Make sure there is no existing file named recovername.
2390 if (stat(xlogpath, &stat_buf) != 0)
2392 if (errno != ENOENT)
2394 (errcode_for_file_access(),
2395 errmsg("could not stat file \"%s\": %m",
2400 if (unlink(xlogpath) != 0)
2402 (errcode_for_file_access(),
2403 errmsg("could not remove file \"%s\": %m",
2408 * construct the command to be executed
2410 dp = xlogRestoreCmd;
2411 endp = xlogRestoreCmd + MAXPGPATH - 1;
2414 for (sp = recoveryRestoreCommand; *sp; sp++)
2421 /* %p: full path of target file */
2423 StrNCpy(dp, xlogpath, endp - dp);
2424 make_native_path(dp);
2428 /* %f: filename of desired file */
2430 StrNCpy(dp, xlogfname, endp - dp);
2434 /* convert %% to a single % */
2440 /* otherwise treat the % as not special */
2455 (errmsg_internal("executing restore command \"%s\"",
2459 * Copy xlog from archival storage to XLOGDIR
2461 rc = system(xlogRestoreCmd);
2465 * command apparently succeeded, but let's make sure the file is
2466 * really there now and has the correct size.
2468 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2469 * it, but is that too strong? We could try to plow ahead with a
2470 * local copy of the file ... but the problem is that there probably
2471 * isn't one, and we'd incorrectly conclude we've reached the end of
2472 * WAL and we're done recovering ...
2474 if (stat(xlogpath, &stat_buf) == 0)
2476 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2478 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2480 (unsigned long) stat_buf.st_size,
2481 (unsigned long) expectedSize)));
2485 (errmsg("restored log file \"%s\" from archive",
2487 strcpy(path, xlogpath);
2494 if (errno != ENOENT)
2496 (errcode_for_file_access(),
2497 errmsg("could not stat file \"%s\": %m",
2503 * remember, we rollforward UNTIL the restore fails so failure here is
2504 * just part of the process... that makes it difficult to determine
2505 * whether the restore failed because there isn't an archive to restore,
2506 * or because the administrator has specified the restore program
2507 * incorrectly. We have to assume the former.
2510 (errmsg("could not restore file \"%s\" from archive: return code %d",
2514 * if an archived file is not available, there might still be a version of
2515 * this file in XLOGDIR, so return that as the filename to open.
2517 * In many recovery scenarios we expect this to fail also, but if so that
2518 * just means we've reached the end of WAL.
2520 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2525 * Preallocate log files beyond the specified log endpoint, according to
2526 * the XLOGfile user parameter.
2529 PreallocXlogFiles(XLogRecPtr endptr)
2537 XLByteToPrevSeg(endptr, _logId, _logSeg);
2538 if ((endptr.xrecoff - 1) % XLogSegSize >=
2539 (uint32) (0.75 * XLogSegSize))
2541 NextLogSeg(_logId, _logSeg);
2542 use_existent = true;
2543 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2552 * Remove or move offline all log files older or equal to passed log/seg#
2554 * endptr is current (or recent) end of xlog; this is used to determine
2555 * whether we want to recycle rather than delete no-longer-wanted log files.
2558 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr,
2559 int *nsegsremoved, int *nsegsrecycled)
2565 struct dirent *xlde;
2566 char lastoff[MAXFNAMELEN];
2567 char path[MAXPGPATH];
2573 * Initialize info about where to try to recycle to. We allow recycling
2574 * segments up to XLOGfileslop segments beyond the current XLOG location.
2576 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2577 max_advance = XLOGfileslop;
2579 xldir = AllocateDir(XLOGDIR);
2582 (errcode_for_file_access(),
2583 errmsg("could not open transaction log directory \"%s\": %m",
2586 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2588 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2591 * We ignore the timeline part of the XLOG segment identifiers in
2592 * deciding whether a segment is still needed. This ensures that we
2593 * won't prematurely remove a segment from a parent timeline. We could
2594 * probably be a little more proactive about removing segments of
2595 * non-parent timelines, but that would be a whole lot more
2598 * We use the alphanumeric sorting property of the filenames to decide
2599 * which ones are earlier than the lastoff segment.
2601 if (strlen(xlde->d_name) == 24 &&
2602 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2603 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2605 if (XLogArchiveCheckDone(xlde->d_name))
2607 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2610 * Before deleting the file, see if it can be recycled as a
2611 * future log segment.
2613 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2618 (errmsg("recycled transaction log file \"%s\"",
2621 /* Needn't recheck that slot on future iterations */
2622 if (max_advance > 0)
2624 NextLogSeg(endlogId, endlogSeg);
2630 /* No need for any more future segments... */
2632 (errmsg("removing transaction log file \"%s\"",
2638 XLogArchiveCleanup(xlde->d_name);
2647 * Remove previous backup history files. This also retries creation of
2648 * .ready files for any backup history files for which XLogArchiveNotify
2652 CleanupBackupHistory(void)
2655 struct dirent *xlde;
2656 char path[MAXPGPATH];
2658 xldir = AllocateDir(XLOGDIR);
2661 (errcode_for_file_access(),
2662 errmsg("could not open transaction log directory \"%s\": %m",
2665 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2667 if (strlen(xlde->d_name) > 24 &&
2668 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2669 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2672 if (XLogArchiveCheckDone(xlde->d_name))
2675 (errmsg("removing transaction log backup history file \"%s\"",
2677 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2679 XLogArchiveCleanup(xlde->d_name);
2688 * Restore the backup blocks present in an XLOG record, if any.
2690 * We assume all of the record has been read into memory at *record.
2692 * Note: when a backup block is available in XLOG, we restore it
2693 * unconditionally, even if the page in the database appears newer.
2694 * This is to protect ourselves against database pages that were partially
2695 * or incorrectly written during a crash. We assume that the XLOG data
2696 * must be good because it has passed a CRC check, while the database
2697 * page might not be. This will force us to replay all subsequent
2698 * modifications of the page that appear in XLOG, rather than possibly
2699 * ignoring them as already applied, but that's not a huge drawback.
2702 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2711 blk = (char *) XLogRecGetData(record) + record->xl_len;
2712 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2714 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2717 memcpy(&bkpb, blk, sizeof(BkpBlock));
2718 blk += sizeof(BkpBlock);
2720 reln = XLogOpenRelation(bkpb.node);
2721 buffer = XLogReadBuffer(reln, bkpb.block, true);
2722 Assert(BufferIsValid(buffer));
2723 page = (Page) BufferGetPage(buffer);
2725 if (bkpb.hole_length == 0)
2727 memcpy((char *) page, blk, BLCKSZ);
2731 /* must zero-fill the hole */
2732 MemSet((char *) page, 0, BLCKSZ);
2733 memcpy((char *) page, blk, bkpb.hole_offset);
2734 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2735 blk + bkpb.hole_offset,
2736 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2739 PageSetLSN(page, lsn);
2740 PageSetTLI(page, ThisTimeLineID);
2741 MarkBufferDirty(buffer);
2742 UnlockReleaseBuffer(buffer);
2744 blk += BLCKSZ - bkpb.hole_length;
2749 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2750 * record (other than to the minimal extent of computing the amount of
2751 * data to read in) until we've checked the CRCs.
2753 * We assume all of the record has been read into memory at *record.
2756 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2760 uint32 len = record->xl_len;
2764 /* First the rmgr data */
2766 COMP_CRC32(crc, XLogRecGetData(record), len);
2768 /* Add in the backup blocks, if any */
2769 blk = (char *) XLogRecGetData(record) + len;
2770 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2774 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2777 memcpy(&bkpb, blk, sizeof(BkpBlock));
2778 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2781 (errmsg("incorrect hole size in record at %X/%X",
2782 recptr.xlogid, recptr.xrecoff)));
2785 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2786 COMP_CRC32(crc, blk, blen);
2790 /* Check that xl_tot_len agrees with our calculation */
2791 if (blk != (char *) record + record->xl_tot_len)
2794 (errmsg("incorrect total length in record at %X/%X",
2795 recptr.xlogid, recptr.xrecoff)));
2799 /* Finally include the record header */
2800 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2801 SizeOfXLogRecord - sizeof(pg_crc32));
2804 if (!EQ_CRC32(record->xl_crc, crc))
2807 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2808 recptr.xlogid, recptr.xrecoff)));
2816 * Attempt to read an XLOG record.
2818 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2819 * try to read a record just after the last one previously read.
2821 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2822 * (emode must be either PANIC or LOG.)
2824 * The record is copied into readRecordBuf, so that on successful return,
2825 * the returned record pointer always points there.
2828 ReadRecord(XLogRecPtr *RecPtr, int emode)
2832 XLogRecPtr tmpRecPtr = EndRecPtr;
2833 bool randAccess = false;
2836 uint32 targetPageOff;
2837 uint32 targetRecOff;
2838 uint32 pageHeaderSize;
2840 if (readBuf == NULL)
2843 * First time through, permanently allocate readBuf. We do it this
2844 * way, rather than just making a static array, for two reasons: (1)
2845 * no need to waste the storage in most instantiations of the backend;
2846 * (2) a static char array isn't guaranteed to have any particular
2847 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2849 readBuf = (char *) malloc(XLOG_BLCKSZ);
2850 Assert(readBuf != NULL);
2855 RecPtr = &tmpRecPtr;
2856 /* fast case if next record is on same page */
2857 if (nextRecord != NULL)
2859 record = nextRecord;
2862 /* align old recptr to next page */
2863 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2864 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2865 if (tmpRecPtr.xrecoff >= XLogFileSize)
2867 (tmpRecPtr.xlogid)++;
2868 tmpRecPtr.xrecoff = 0;
2870 /* We will account for page header size below */
2874 if (!XRecOffIsValid(RecPtr->xrecoff))
2876 (errmsg("invalid record offset at %X/%X",
2877 RecPtr->xlogid, RecPtr->xrecoff)));
2880 * Since we are going to a random position in WAL, forget any prior
2881 * state about what timeline we were in, and allow it to be any
2882 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
2883 * to go backwards (but we can't reset that variable right here, since
2884 * we might not change files at all).
2886 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2887 randAccess = true; /* allow curFileTLI to go backwards too */
2890 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2895 XLByteToSeg(*RecPtr, readId, readSeg);
2898 /* Now it's okay to reset curFileTLI if random fetch */
2902 readFile = XLogFileRead(readId, readSeg, emode);
2904 goto next_record_is_invalid;
2907 * Whenever switching to a new WAL segment, we read the first page of
2908 * the file and validate its header, even if that's not where the
2909 * target record is. This is so that we can check the additional
2910 * identification info that is present in the first page's "long"
2914 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2917 (errcode_for_file_access(),
2918 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2919 readId, readSeg, readOff)));
2920 goto next_record_is_invalid;
2922 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2923 goto next_record_is_invalid;
2926 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2927 if (readOff != targetPageOff)
2929 readOff = targetPageOff;
2930 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2933 (errcode_for_file_access(),
2934 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2935 readId, readSeg, readOff)));
2936 goto next_record_is_invalid;
2938 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2941 (errcode_for_file_access(),
2942 errmsg("could not read from log file %u, segment %u at offset %u: %m",
2943 readId, readSeg, readOff)));
2944 goto next_record_is_invalid;
2946 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2947 goto next_record_is_invalid;
2949 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2950 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
2951 if (targetRecOff == 0)
2954 * Can only get here in the continuing-from-prev-page case, because
2955 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
2956 * to skip over the new page's header.
2958 tmpRecPtr.xrecoff += pageHeaderSize;
2959 targetRecOff = pageHeaderSize;
2961 else if (targetRecOff < pageHeaderSize)
2964 (errmsg("invalid record offset at %X/%X",
2965 RecPtr->xlogid, RecPtr->xrecoff)));
2966 goto next_record_is_invalid;
2968 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
2969 targetRecOff == pageHeaderSize)
2972 (errmsg("contrecord is requested by %X/%X",
2973 RecPtr->xlogid, RecPtr->xrecoff)));
2974 goto next_record_is_invalid;
2976 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
2981 * xl_len == 0 is bad data for everything except XLOG SWITCH, where
2984 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
2986 if (record->xl_len != 0)
2989 (errmsg("invalid xlog switch record at %X/%X",
2990 RecPtr->xlogid, RecPtr->xrecoff)));
2991 goto next_record_is_invalid;
2994 else if (record->xl_len == 0)
2997 (errmsg("record with zero length at %X/%X",
2998 RecPtr->xlogid, RecPtr->xrecoff)));
2999 goto next_record_is_invalid;
3001 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3002 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3003 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3006 (errmsg("invalid record length at %X/%X",
3007 RecPtr->xlogid, RecPtr->xrecoff)));
3008 goto next_record_is_invalid;
3010 if (record->xl_rmid > RM_MAX_ID)
3013 (errmsg("invalid resource manager ID %u at %X/%X",
3014 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3015 goto next_record_is_invalid;
3020 * We can't exactly verify the prev-link, but surely it should be less
3021 * than the record's own address.
3023 if (!XLByteLT(record->xl_prev, *RecPtr))
3026 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3027 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3028 RecPtr->xlogid, RecPtr->xrecoff)));
3029 goto next_record_is_invalid;
3035 * Record's prev-link should exactly match our previous location. This
3036 * check guards against torn WAL pages where a stale but valid-looking
3037 * WAL record starts on a sector boundary.
3039 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3042 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3043 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3044 RecPtr->xlogid, RecPtr->xrecoff)));
3045 goto next_record_is_invalid;
3050 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3051 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3052 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3053 * enough for all "normal" records, but very large commit or abort records
3054 * might need more space.)
3056 total_len = record->xl_tot_len;
3057 if (total_len > readRecordBufSize)
3059 uint32 newSize = total_len;
3061 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3062 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3064 free(readRecordBuf);
3065 readRecordBuf = (char *) malloc(newSize);
3068 readRecordBufSize = 0;
3069 /* We treat this as a "bogus data" condition */
3071 (errmsg("record length %u at %X/%X too long",
3072 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3073 goto next_record_is_invalid;
3075 readRecordBufSize = newSize;
3078 buffer = readRecordBuf;
3080 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3081 if (total_len > len)
3083 /* Need to reassemble record */
3084 XLogContRecord *contrecord;
3085 uint32 gotlen = len;
3087 memcpy(buffer, record, len);
3088 record = (XLogRecord *) buffer;
3092 readOff += XLOG_BLCKSZ;
3093 if (readOff >= XLogSegSize)
3097 NextLogSeg(readId, readSeg);
3098 readFile = XLogFileRead(readId, readSeg, emode);
3100 goto next_record_is_invalid;
3103 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3106 (errcode_for_file_access(),
3107 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3108 readId, readSeg, readOff)));
3109 goto next_record_is_invalid;
3111 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3112 goto next_record_is_invalid;
3113 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3116 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3117 readId, readSeg, readOff)));
3118 goto next_record_is_invalid;
3120 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3121 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3122 if (contrecord->xl_rem_len == 0 ||
3123 total_len != (contrecord->xl_rem_len + gotlen))
3126 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3127 contrecord->xl_rem_len,
3128 readId, readSeg, readOff)));
3129 goto next_record_is_invalid;
3131 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3132 if (contrecord->xl_rem_len > len)
3134 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3139 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3140 contrecord->xl_rem_len);
3143 if (!RecordIsValid(record, *RecPtr, emode))
3144 goto next_record_is_invalid;
3145 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3146 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3147 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3149 nextRecord = (XLogRecord *) ((char *) contrecord +
3150 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3152 EndRecPtr.xlogid = readId;
3153 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3155 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3156 ReadRecPtr = *RecPtr;
3157 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3161 /* Record does not cross a page boundary */
3162 if (!RecordIsValid(record, *RecPtr, emode))
3163 goto next_record_is_invalid;
3164 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3165 MAXALIGN(total_len))
3166 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3167 EndRecPtr.xlogid = RecPtr->xlogid;
3168 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3169 ReadRecPtr = *RecPtr;
3170 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 */
3181 * Pretend that readBuf contains the last page of the segment.
3182 * This is just to avoid Assert failure in StartupXLOG if XLOG
3183 * ends with this segment.
3185 readOff = XLogSegSize - XLOG_BLCKSZ;
3187 return (XLogRecord *) buffer;
3189 next_record_is_invalid:;
3197 * Check whether the xlog header of a page just read in looks valid.
3199 * This is just a convenience subroutine to avoid duplicated code in
3200 * ReadRecord. It's not intended for use from anywhere else.
3203 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3207 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3210 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3211 hdr->xlp_magic, readId, readSeg, readOff)));
3214 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3217 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3218 hdr->xlp_info, readId, readSeg, readOff)));
3221 if (hdr->xlp_info & XLP_LONG_HEADER)
3223 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3225 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3227 char fhdrident_str[32];
3228 char sysident_str[32];
3231 * Format sysids separately to keep platform-dependent format code
3232 * out of the translatable message string.
3234 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3235 longhdr->xlp_sysid);
3236 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3237 ControlFile->system_identifier);
3239 (errmsg("WAL file is from different system"),
3240 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3241 fhdrident_str, sysident_str)));
3244 if (longhdr->xlp_seg_size != XLogSegSize)
3247 (errmsg("WAL file is from different system"),
3248 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3251 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3254 (errmsg("WAL file is from different system"),
3255 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3259 else if (readOff == 0)
3261 /* hmm, first page of file doesn't have a long header? */
3263 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3264 hdr->xlp_info, readId, readSeg, readOff)));
3268 recaddr.xlogid = readId;
3269 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3270 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3273 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3274 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3275 readId, readSeg, readOff)));
3280 * Check page TLI is one of the expected values.
3282 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3285 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3287 readId, readSeg, readOff)));
3292 * Since child timelines are always assigned a TLI greater than their
3293 * immediate parent's TLI, we should never see TLI go backwards across
3294 * successive pages of a consistent WAL sequence.
3296 * Of course this check should only be applied when advancing sequentially
3297 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3298 * going to a random page.
3300 if (hdr->xlp_tli < lastPageTLI)
3303 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3304 hdr->xlp_tli, lastPageTLI,
3305 readId, readSeg, readOff)));
3308 lastPageTLI = hdr->xlp_tli;
3313 * Try to read a timeline's history file.
3315 * If successful, return the list of component TLIs (the given TLI followed by
3316 * its ancestor TLIs). If we can't find the history file, assume that the
3317 * timeline has no parents, and return a list of just the specified timeline
3321 readTimeLineHistory(TimeLineID targetTLI)
3324 char path[MAXPGPATH];
3325 char histfname[MAXFNAMELEN];
3326 char fline[MAXPGPATH];
3329 if (InArchiveRecovery)
3331 TLHistoryFileName(histfname, targetTLI);
3332 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3335 TLHistoryFilePath(path, targetTLI);
3337 fd = AllocateFile(path, "r");
3340 if (errno != ENOENT)
3342 (errcode_for_file_access(),
3343 errmsg("could not open file \"%s\": %m", path)));
3344 /* Not there, so assume no parents */
3345 return list_make1_int((int) targetTLI);
3353 while (fgets(fline, MAXPGPATH, fd) != NULL)
3355 /* skip leading whitespace and check for # comment */
3360 for (ptr = fline; *ptr; ptr++)
3362 if (!isspace((unsigned char) *ptr))
3365 if (*ptr == '\0' || *ptr == '#')
3368 /* expect a numeric timeline ID as first field of line */
3369 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3372 (errmsg("syntax error in history file: %s", fline),
3373 errhint("Expected a numeric timeline ID.")));
3376 tli <= (TimeLineID) linitial_int(result))
3378 (errmsg("invalid data in history file: %s", fline),
3379 errhint("Timeline IDs must be in increasing sequence.")));
3381 /* Build list with newest item first */
3382 result = lcons_int((int) tli, result);
3384 /* we ignore the remainder of each line */
3390 targetTLI <= (TimeLineID) linitial_int(result))
3392 (errmsg("invalid data in history file \"%s\"", path),
3393 errhint("Timeline IDs must be less than child timeline's ID.")));
3395 result = lcons_int((int) targetTLI, result);
3398 (errmsg_internal("history of timeline %u is %s",
3399 targetTLI, nodeToString(result))));
3405 * Probe whether a timeline history file exists for the given timeline ID
3408 existsTimeLineHistory(TimeLineID probeTLI)
3410 char path[MAXPGPATH];
3411 char histfname[MAXFNAMELEN];
3414 if (InArchiveRecovery)
3416 TLHistoryFileName(histfname, probeTLI);
3417 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3420 TLHistoryFilePath(path, probeTLI);
3422 fd = AllocateFile(path, "r");
3430 if (errno != ENOENT)
3432 (errcode_for_file_access(),
3433 errmsg("could not open file \"%s\": %m", path)));
3439 * Find the newest existing timeline, assuming that startTLI exists.
3441 * Note: while this is somewhat heuristic, it does positively guarantee
3442 * that (result + 1) is not a known timeline, and therefore it should
3443 * be safe to assign that ID to a new timeline.
3446 findNewestTimeLine(TimeLineID startTLI)
3448 TimeLineID newestTLI;
3449 TimeLineID probeTLI;
3452 * The algorithm is just to probe for the existence of timeline history
3453 * files. XXX is it useful to allow gaps in the sequence?
3455 newestTLI = startTLI;
3457 for (probeTLI = startTLI + 1;; probeTLI++)
3459 if (existsTimeLineHistory(probeTLI))
3461 newestTLI = probeTLI; /* probeTLI exists */
3465 /* doesn't exist, assume we're done */
3474 * Create a new timeline history file.
3476 * newTLI: ID of the new timeline
3477 * parentTLI: ID of its immediate parent
3478 * endTLI et al: ID of the last used WAL file, for annotation purposes
3480 * Currently this is only used during recovery, and so there are no locking
3481 * considerations. But we should be just as tense as XLogFileInit to avoid
3482 * emplacing a bogus file.
3485 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3486 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3488 char path[MAXPGPATH];
3489 char tmppath[MAXPGPATH];
3490 char histfname[MAXFNAMELEN];
3491 char xlogfname[MAXFNAMELEN];
3492 char buffer[BLCKSZ];
3497 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3500 * Write into a temp file name.
3502 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3506 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3507 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3511 (errcode_for_file_access(),
3512 errmsg("could not create file \"%s\": %m", tmppath)));
3515 * If a history file exists for the parent, copy it verbatim
3517 if (InArchiveRecovery)
3519 TLHistoryFileName(histfname, parentTLI);
3520 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3523 TLHistoryFilePath(path, parentTLI);
3525 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3528 if (errno != ENOENT)
3530 (errcode_for_file_access(),
3531 errmsg("could not open file \"%s\": %m", path)));
3532 /* Not there, so assume parent has no parents */
3539 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3540 if (nbytes < 0 || errno != 0)
3542 (errcode_for_file_access(),
3543 errmsg("could not read file \"%s\": %m", path)));
3547 if ((int) write(fd, buffer, nbytes) != nbytes)
3549 int save_errno = errno;
3552 * If we fail to make the file, delete it to release disk
3558 * if write didn't set errno, assume problem is no disk space
3560 errno = save_errno ? save_errno : ENOSPC;
3563 (errcode_for_file_access(),
3564 errmsg("could not write to file \"%s\": %m", tmppath)));
3571 * Append one line with the details of this timeline split.
3573 * If we did have a parent file, insert an extra newline just in case the
3574 * parent file failed to end with one.
3576 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3578 snprintf(buffer, sizeof(buffer),
3579 "%s%u\t%s\t%s transaction %u at %s\n",
3580 (srcfd < 0) ? "" : "\n",
3583 recoveryStopAfter ? "after" : "before",
3585 str_time(recoveryStopTime));
3587 nbytes = strlen(buffer);
3589 if ((int) write(fd, buffer, nbytes) != nbytes)
3591 int save_errno = errno;
3594 * If we fail to make the file, delete it to release disk space
3597 /* if write didn't set errno, assume problem is no disk space */
3598 errno = save_errno ? save_errno : ENOSPC;
3601 (errcode_for_file_access(),
3602 errmsg("could not write to file \"%s\": %m", tmppath)));
3605 if (pg_fsync(fd) != 0)
3607 (errcode_for_file_access(),
3608 errmsg("could not fsync file \"%s\": %m", tmppath)));
3612 (errcode_for_file_access(),
3613 errmsg("could not close file \"%s\": %m", tmppath)));
3617 * Now move the completed history file into place with its final name.
3619 TLHistoryFilePath(path, newTLI);
3622 * Prefer link() to rename() here just to be really sure that we don't
3623 * overwrite an existing logfile. However, there shouldn't be one, so
3624 * rename() is an acceptable substitute except for the truly paranoid.
3626 #if HAVE_WORKING_LINK
3627 if (link(tmppath, path) < 0)
3629 (errcode_for_file_access(),
3630 errmsg("could not link file \"%s\" to \"%s\": %m",
3634 if (rename(tmppath, path) < 0)
3636 (errcode_for_file_access(),
3637 errmsg("could not rename file \"%s\" to \"%s\": %m",
3641 /* The history file can be archived immediately. */
3642 TLHistoryFileName(histfname, newTLI);
3643 XLogArchiveNotify(histfname);
3647 * I/O routines for pg_control
3649 * *ControlFile is a buffer in shared memory that holds an image of the
3650 * contents of pg_control. WriteControlFile() initializes pg_control
3651 * given a preloaded buffer, ReadControlFile() loads the buffer from
3652 * the pg_control file (during postmaster or standalone-backend startup),
3653 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3655 * For simplicity, WriteControlFile() initializes the fields of pg_control
3656 * that are related to checking backend/database compatibility, and
3657 * ReadControlFile() verifies they are correct. We could split out the
3658 * I/O and compatibility-check functions, but there seems no need currently.
3661 WriteControlFile(void)
3664 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3668 * Initialize version and compatibility-check fields
3670 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3671 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3673 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3674 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3676 ControlFile->blcksz = BLCKSZ;
3677 ControlFile->relseg_size = RELSEG_SIZE;
3678 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3679 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3681 ControlFile->nameDataLen = NAMEDATALEN;
3682 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3684 #ifdef HAVE_INT64_TIMESTAMP
3685 ControlFile->enableIntTimes = TRUE;
3687 ControlFile->enableIntTimes = FALSE;
3690 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3691 localeptr = setlocale(LC_COLLATE, NULL);
3694 (errmsg("invalid LC_COLLATE setting")));
3695 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3696 localeptr = setlocale(LC_CTYPE, NULL);
3699 (errmsg("invalid LC_CTYPE setting")));
3700 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3702 /* Contents are protected with a CRC */
3703 INIT_CRC32(ControlFile->crc);
3704 COMP_CRC32(ControlFile->crc,
3705 (char *) ControlFile,
3706 offsetof(ControlFileData, crc));
3707 FIN_CRC32(ControlFile->crc);
3710 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3711 * excess over sizeof(ControlFileData). This reduces the odds of
3712 * premature-EOF errors when reading pg_control. We'll still fail when we
3713 * check the contents of the file, but hopefully with a more specific
3714 * error than "couldn't read pg_control".
3716 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3717 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3719 memset(buffer, 0, PG_CONTROL_SIZE);
3720 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3722 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3723 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3727 (errcode_for_file_access(),
3728 errmsg("could not create control file \"%s\": %m",
3729 XLOG_CONTROL_FILE)));
3732 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3734 /* if write didn't set errno, assume problem is no disk space */
3738 (errcode_for_file_access(),
3739 errmsg("could not write to control file: %m")));
3742 if (pg_fsync(fd) != 0)
3744 (errcode_for_file_access(),
3745 errmsg("could not fsync control file: %m")));
3749 (errcode_for_file_access(),
3750 errmsg("could not close control file: %m")));
3754 ReadControlFile(void)
3762 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3767 (errcode_for_file_access(),
3768 errmsg("could not open control file \"%s\": %m",
3769 XLOG_CONTROL_FILE)));
3771 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3773 (errcode_for_file_access(),
3774 errmsg("could not read from control file: %m")));
3779 * Check for expected pg_control format version. If this is wrong, the
3780 * CRC check will likely fail because we'll be checking the wrong number
3781 * of bytes. Complaining about wrong version will probably be more
3782 * enlightening than complaining about wrong CRC.
3784 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3786 (errmsg("database files are incompatible with server"),
3787 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3788 " but the server was compiled with PG_CONTROL_VERSION %d.",
3789 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3790 errhint("It looks like you need to initdb.")));
3791 /* Now check the CRC. */
3794 (char *) ControlFile,
3795 offsetof(ControlFileData, crc));
3798 if (!EQ_CRC32(crc, ControlFile->crc))
3800 (errmsg("incorrect checksum in control file")));
3803 * Do compatibility checking immediately. We do this here for 2 reasons:
3805 * (1) if the database isn't compatible with the backend executable, we
3806 * want to abort before we can possibly do any damage;
3808 * (2) this code is executed in the postmaster, so the setlocale() will
3809 * propagate to forked backends, which aren't going to read this file for
3810 * themselves. (These locale settings are considered critical
3811 * compatibility items because they can affect sort order of indexes.)
3813 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3815 (errmsg("database files are incompatible with server"),
3816 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3817 " but the server was compiled with CATALOG_VERSION_NO %d.",
3818 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3819 errhint("It looks like you need to initdb.")));
3820 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3822 (errmsg("database files are incompatible with server"),
3823 errdetail("The database cluster was initialized with MAXALIGN %d,"
3824 " but the server was compiled with MAXALIGN %d.",
3825 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3826 errhint("It looks like you need to initdb.")));
3827 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3829 (errmsg("database files are incompatible with server"),
3830 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3831 errhint("It looks like you need to initdb.")));
3832 if (ControlFile->blcksz != BLCKSZ)
3834 (errmsg("database files are incompatible with server"),
3835 errdetail("The database cluster was initialized with BLCKSZ %d,"
3836 " but the server was compiled with BLCKSZ %d.",
3837 ControlFile->blcksz, BLCKSZ),
3838 errhint("It looks like you need to recompile or initdb.")));
3839 if (ControlFile->relseg_size != RELSEG_SIZE)
3841 (errmsg("database files are incompatible with server"),
3842 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3843 " but the server was compiled with RELSEG_SIZE %d.",
3844 ControlFile->relseg_size, RELSEG_SIZE),
3845 errhint("It looks like you need to recompile or initdb.")));
3846 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3848 (errmsg("database files are incompatible with server"),
3849 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3850 " but the server was compiled with XLOG_BLCKSZ %d.",
3851 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3852 errhint("It looks like you need to recompile or initdb.")));
3853 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3855 (errmsg("database files are incompatible with server"),
3856 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3857 " but the server was compiled with XLOG_SEG_SIZE %d.",
3858 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3859 errhint("It looks like you need to recompile or initdb.")));
3860 if (ControlFile->nameDataLen != NAMEDATALEN)
3862 (errmsg("database files are incompatible with server"),
3863 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3864 " but the server was compiled with NAMEDATALEN %d.",
3865 ControlFile->nameDataLen, NAMEDATALEN),
3866 errhint("It looks like you need to recompile or initdb.")));
3867 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3869 (errmsg("database files are incompatible with server"),
3870 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3871 " but the server was compiled with INDEX_MAX_KEYS %d.",
3872 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3873 errhint("It looks like you need to recompile or initdb.")));
3875 #ifdef HAVE_INT64_TIMESTAMP
3876 if (ControlFile->enableIntTimes != TRUE)
3878 (errmsg("database files are incompatible with server"),
3879 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3880 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3881 errhint("It looks like you need to recompile or initdb.")));
3883 if (ControlFile->enableIntTimes != FALSE)
3885 (errmsg("database files are incompatible with server"),
3886 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3887 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3888 errhint("It looks like you need to recompile or initdb.")));
3891 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3893 (errmsg("database files are incompatible with server"),
3894 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3895 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3896 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3897 errhint("It looks like you need to recompile or initdb.")));
3898 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3900 (errmsg("database files are incompatible with operating system"),
3901 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3902 " which is not recognized by setlocale().",
3903 ControlFile->lc_collate),
3904 errhint("It looks like you need to initdb or install locale support.")));
3905 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3907 (errmsg("database files are incompatible with operating system"),
3908 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3909 " which is not recognized by setlocale().",
3910 ControlFile->lc_ctype),
3911 errhint("It looks like you need to initdb or install locale support.")));
3913 /* Make the fixed locale settings visible as GUC variables, too */
3914 SetConfigOption("lc_collate", ControlFile->lc_collate,
3915 PGC_INTERNAL, PGC_S_OVERRIDE);
3916 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3917 PGC_INTERNAL, PGC_S_OVERRIDE);
3921 UpdateControlFile(void)
3925 INIT_CRC32(ControlFile->crc);
3926 COMP_CRC32(ControlFile->crc,
3927 (char *) ControlFile,
3928 offsetof(ControlFileData, crc));
3929 FIN_CRC32(ControlFile->crc);
3931 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3936 (errcode_for_file_access(),
3937 errmsg("could not open control file \"%s\": %m",
3938 XLOG_CONTROL_FILE)));
3941 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3943 /* if write didn't set errno, assume problem is no disk space */
3947 (errcode_for_file_access(),
3948 errmsg("could not write to control file: %m")));
3951 if (pg_fsync(fd) != 0)
3953 (errcode_for_file_access(),
3954 errmsg("could not fsync control file: %m")));
3958 (errcode_for_file_access(),
3959 errmsg("could not close control file: %m")));
3963 * Initialization of shared memory for XLOG
3971 size = sizeof(XLogCtlData);
3972 /* xlblocks array */
3973 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
3974 /* extra alignment padding for XLOG I/O buffers */
3975 size = add_size(size, ALIGNOF_XLOG_BUFFER);
3976 /* and the buffers themselves */
3977 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
3980 * Note: we don't count ControlFileData, it comes out of the "slop factor"
3981 * added by CreateSharedMemoryAndSemaphores. This lets us use this
3982 * routine again below to compute the actual allocation size.
3995 ControlFile = (ControlFileData *)
3996 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
3997 XLogCtl = (XLogCtlData *)
3998 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4000 if (foundCFile || foundXLog)
4002 /* both should be present or neither */
4003 Assert(foundCFile && foundXLog);
4007 memset(XLogCtl, 0, sizeof(XLogCtlData));
4010 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4011 * multiple of the alignment for same, so no extra alignment padding is
4014 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4015 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4016 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4017 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4020 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4022 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4023 XLogCtl->pages = allocptr;
4024 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4027 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4028 * in additional info.)
4030 XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ * XLOGbuffers;
4032 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4033 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4034 SpinLockInit(&XLogCtl->info_lck);
4037 * If we are not in bootstrap mode, pg_control should already exist. Read
4038 * and validate it immediately (see comments in ReadControlFile() for the
4041 if (!IsBootstrapProcessingMode())
4046 * This func must be called ONCE on system install. It creates pg_control
4047 * and the initial XLOG segment.
4052 CheckPoint checkPoint;
4054 XLogPageHeader page;
4055 XLogLongPageHeader longpage;
4058 uint64 sysidentifier;
4063 * Select a hopefully-unique system identifier code for this installation.
4064 * We use the result of gettimeofday(), including the fractional seconds
4065 * field, as being about as unique as we can easily get. (Think not to
4066 * use random(), since it hasn't been seeded and there's no portable way
4067 * to seed it other than the system clock value...) The upper half of the
4068 * uint64 value is just the tv_sec part, while the lower half is the XOR
4069 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4070 * unnecessarily if "uint64" is really only 32 bits wide. A person
4071 * knowing this encoding can determine the initialization time of the
4072 * installation, which could perhaps be useful sometimes.
4074 gettimeofday(&tv, NULL);
4075 sysidentifier = ((uint64) tv.tv_sec) << 32;
4076 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4078 /* First timeline ID is always 1 */
4081 /* page buffer must be aligned suitably for O_DIRECT */
4082 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4083 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4084 memset(page, 0, XLOG_BLCKSZ);
4086 /* Set up information for the initial checkpoint record */
4087 checkPoint.redo.xlogid = 0;
4088 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4089 checkPoint.undo = checkPoint.redo;
4090 checkPoint.ThisTimeLineID = ThisTimeLineID;
4091 checkPoint.nextXidEpoch = 0;
4092 checkPoint.nextXid = FirstNormalTransactionId;
4093 checkPoint.nextOid = FirstBootstrapObjectId;
4094 checkPoint.nextMulti = FirstMultiXactId;
4095 checkPoint.nextMultiOffset = 0;
4096 checkPoint.time = time(NULL);
4098 ShmemVariableCache->nextXid = checkPoint.nextXid;
4099 ShmemVariableCache->nextOid = checkPoint.nextOid;
4100 ShmemVariableCache->oidCount = 0;
4101 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4103 /* Set up the XLOG page header */
4104 page->xlp_magic = XLOG_PAGE_MAGIC;
4105 page->xlp_info = XLP_LONG_HEADER;
4106 page->xlp_tli = ThisTimeLineID;
4107 page->xlp_pageaddr.xlogid = 0;
4108 page->xlp_pageaddr.xrecoff = 0;
4109 longpage = (XLogLongPageHeader) page;
4110 longpage->xlp_sysid = sysidentifier;
4111 longpage->xlp_seg_size = XLogSegSize;
4112 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4114 /* Insert the initial checkpoint record */
4115 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4116 record->xl_prev.xlogid = 0;
4117 record->xl_prev.xrecoff = 0;
4118 record->xl_xid = InvalidTransactionId;
4119 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4120 record->xl_len = sizeof(checkPoint);
4121 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4122 record->xl_rmid = RM_XLOG_ID;
4123 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4126 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4127 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4128 SizeOfXLogRecord - sizeof(pg_crc32));
4130 record->xl_crc = crc;
4132 /* Create first XLOG segment file */
4133 use_existent = false;
4134 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4136 /* Write the first page with the initial record */
4138 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4140 /* if write didn't set errno, assume problem is no disk space */
4144 (errcode_for_file_access(),
4145 errmsg("could not write bootstrap transaction log file: %m")));
4148 if (pg_fsync(openLogFile) != 0)
4150 (errcode_for_file_access(),
4151 errmsg("could not fsync bootstrap transaction log file: %m")));
4153 if (close(openLogFile))
4155 (errcode_for_file_access(),
4156 errmsg("could not close bootstrap transaction log file: %m")));
4160 /* Now create pg_control */
4162 memset(ControlFile, 0, sizeof(ControlFileData));
4163 /* Initialize pg_control status fields */
4164 ControlFile->system_identifier = sysidentifier;
4165 ControlFile->state = DB_SHUTDOWNED;
4166 ControlFile->time = checkPoint.time;
4167 ControlFile->logId = 0;
4168 ControlFile->logSeg = 1;
4169 ControlFile->checkPoint = checkPoint.redo;
4170 ControlFile->checkPointCopy = checkPoint;
4171 /* some additional ControlFile fields are set in WriteControlFile() */
4175 /* Bootstrap the commit log, too */
4177 BootStrapSUBTRANS();
4178 BootStrapMultiXact();
4184 str_time(time_t tnow)
4186 static char buf[128];
4188 strftime(buf, sizeof(buf),
4189 "%Y-%m-%d %H:%M:%S %Z",
4196 * See if there is a recovery command file (recovery.conf), and if so
4197 * read in parameters for archive recovery.
4199 * XXX longer term intention is to expand this to
4200 * cater for additional parameters and controls
4201 * possibly use a flex lexer similar to the GUC one
4204 readRecoveryCommandFile(void)
4207 char cmdline[MAXPGPATH];
4208 TimeLineID rtli = 0;
4209 bool rtliGiven = false;
4210 bool syntaxError = false;
4212 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4215 if (errno == ENOENT)
4216 return; /* not there, so no archive recovery */
4218 (errcode_for_file_access(),
4219 errmsg("could not open recovery command file \"%s\": %m",
4220 RECOVERY_COMMAND_FILE)));
4224 (errmsg("starting archive recovery")));
4229 while (fgets(cmdline, MAXPGPATH, fd) != NULL)
4231 /* skip leading whitespace and check for # comment */
4236 for (ptr = cmdline; *ptr; ptr++)
4238 if (!isspace((unsigned char) *ptr))
4241 if (*ptr == '\0' || *ptr == '#')
4244 /* identify the quoted parameter value */
4245 tok1 = strtok(ptr, "'");
4251 tok2 = strtok(NULL, "'");
4257 /* reparse to get just the parameter name */
4258 tok1 = strtok(ptr, " \t=");
4265 if (strcmp(tok1, "restore_command") == 0)
4267 recoveryRestoreCommand = pstrdup(tok2);
4269 (errmsg("restore_command = \"%s\"",
4270 recoveryRestoreCommand)));
4272 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4275 if (strcmp(tok2, "latest") == 0)
4280 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4281 if (errno == EINVAL || errno == ERANGE)
4283 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4288 (errmsg("recovery_target_timeline = %u", rtli)));
4291 (errmsg("recovery_target_timeline = latest")));
4293 else if (strcmp(tok1, "recovery_target_xid") == 0)
4296 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4297 if (errno == EINVAL || errno == ERANGE)
4299 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4302 (errmsg("recovery_target_xid = %u",
4303 recoveryTargetXid)));
4304 recoveryTarget = true;
4305 recoveryTargetExact = true;
4307 else if (strcmp(tok1, "recovery_target_time") == 0)
4310 * if recovery_target_xid specified, then this overrides
4311 * recovery_target_time
4313 if (recoveryTargetExact)
4315 recoveryTarget = true;
4316 recoveryTargetExact = false;
4319 * Convert the time string given by the user to the time_t format.
4320 * We use type abstime's input converter because we know abstime
4321 * has the same representation as time_t.
4323 recoveryTargetTime = (time_t)
4324 DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
4325 CStringGetDatum(tok2)));
4327 (errmsg("recovery_target_time = %s",
4328 DatumGetCString(DirectFunctionCall1(abstimeout,
4329 AbsoluteTimeGetDatum((AbsoluteTime) recoveryTargetTime))))));
4331 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4334 * does nothing if a recovery_target is not also set
4336 if (strcmp(tok2, "true") == 0)
4337 recoveryTargetInclusive = true;
4340 recoveryTargetInclusive = false;
4344 (errmsg("recovery_target_inclusive = %s", tok2)));
4348 (errmsg("unrecognized recovery parameter \"%s\"",
4356 (errmsg("syntax error in recovery command file: %s",
4358 errhint("Lines should have the format parameter = 'value'.")));
4360 /* Check that required parameters were supplied */
4361 if (recoveryRestoreCommand == NULL)
4363 (errmsg("recovery command file \"%s\" did not specify restore_command",
4364 RECOVERY_COMMAND_FILE)));
4366 /* Enable fetching from archive recovery area */
4367 InArchiveRecovery = true;
4370 * If user specified recovery_target_timeline, validate it or compute the
4371 * "latest" value. We can't do this until after we've gotten the restore
4372 * command and set InArchiveRecovery, because we need to fetch timeline
4373 * history files from the archive.
4379 /* Timeline 1 does not have a history file, all else should */
4380 if (rtli != 1 && !existsTimeLineHistory(rtli))
4382 (errmsg("recovery_target_timeline %u does not exist",
4384 recoveryTargetTLI = rtli;
4388 /* We start the "latest" search from pg_control's timeline */
4389 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4395 * Exit archive-recovery state
4398 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4400 char recoveryPath[MAXPGPATH];
4401 char xlogpath[MAXPGPATH];
4404 * We are no longer in archive recovery state.
4406 InArchiveRecovery = false;
4409 * We should have the ending log segment currently open. Verify, and then
4410 * close it (to avoid problems on Windows with trying to rename or delete
4413 Assert(readFile >= 0);
4414 Assert(readId == endLogId);
4415 Assert(readSeg == endLogSeg);
4421 * If the segment was fetched from archival storage, we want to replace
4422 * the existing xlog segment (if any) with the archival version. This is
4423 * because whatever is in XLOGDIR is very possibly older than what we have
4424 * from the archives, since it could have come from restoring a PGDATA
4425 * backup. In any case, the archival version certainly is more
4426 * descriptive of what our current database state is, because that is what
4429 * Note that if we are establishing a new timeline, ThisTimeLineID is
4430 * already set to the new value, and so we will create a new file instead
4431 * of overwriting any existing file.
4433 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4434 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4436 if (restoredFromArchive)
4439 (errmsg_internal("moving last restored xlog to \"%s\"",
4441 unlink(xlogpath); /* might or might not exist */
4442 if (rename(recoveryPath, xlogpath) != 0)
4444 (errcode_for_file_access(),
4445 errmsg("could not rename file \"%s\" to \"%s\": %m",
4446 recoveryPath, xlogpath)));
4447 /* XXX might we need to fix permissions on the file? */
4452 * If the latest segment is not archival, but there's still a
4453 * RECOVERYXLOG laying about, get rid of it.
4455 unlink(recoveryPath); /* ignore any error */
4458 * If we are establishing a new timeline, we have to copy data from
4459 * the last WAL segment of the old timeline to create a starting WAL
4460 * segment for the new timeline.
4462 if (endTLI != ThisTimeLineID)
4463 XLogFileCopy(endLogId, endLogSeg,
4464 endTLI, endLogId, endLogSeg);
4468 * Let's just make real sure there are not .ready or .done flags posted
4469 * for the new segment.
4471 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4472 XLogArchiveCleanup(xlogpath);
4474 /* Get rid of any remaining recovered timeline-history file, too */
4475 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4476 unlink(recoveryPath); /* ignore any error */
4479 * Rename the config file out of the way, so that we don't accidentally
4480 * re-enter archive recovery mode in a subsequent crash.
4482 unlink(RECOVERY_COMMAND_DONE);
4483 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4485 (errcode_for_file_access(),
4486 errmsg("could not rename file \"%s\" to \"%s\": %m",
4487 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4490 (errmsg("archive recovery complete")));
4494 * For point-in-time recovery, this function decides whether we want to
4495 * stop applying the XLOG at or after the current record.
4497 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4498 * *includeThis is set TRUE if we should apply this record before stopping.
4499 * Also, some information is saved in recoveryStopXid et al for use in
4500 * annotating the new timeline's history file.
4503 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4509 /* Do we have a PITR target at all? */
4510 if (!recoveryTarget)
4513 /* We only consider stopping at COMMIT or ABORT records */
4514 if (record->xl_rmid != RM_XACT_ID)
4516 record_info = record->xl_info & ~XLR_INFO_MASK;
4517 if (record_info == XLOG_XACT_COMMIT)
4519 xl_xact_commit *recordXactCommitData;
4521 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4522 recordXtime = recordXactCommitData->xtime;
4524 else if (record_info == XLOG_XACT_ABORT)
4526 xl_xact_abort *recordXactAbortData;
4528 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4529 recordXtime = recordXactAbortData->xtime;
4534 if (recoveryTargetExact)
4537 * there can be only one transaction end record with this exact
4540 * when testing for an xid, we MUST test for equality only, since
4541 * transactions are numbered in the order they start, not the order
4542 * they complete. A higher numbered xid will complete before you about
4543 * 50% of the time...
4545 stopsHere = (record->xl_xid == recoveryTargetXid);
4547 *includeThis = recoveryTargetInclusive;
4552 * there can be many transactions that share the same commit time, so
4553 * we stop after the last one, if we are inclusive, or stop at the
4554 * first one if we are exclusive
4556 if (recoveryTargetInclusive)
4557 stopsHere = (recordXtime > recoveryTargetTime);
4559 stopsHere = (recordXtime >= recoveryTargetTime);
4561 *includeThis = false;
4566 recoveryStopXid = record->xl_xid;
4567 recoveryStopTime = recordXtime;
4568 recoveryStopAfter = *includeThis;
4570 if (record_info == XLOG_XACT_COMMIT)
4572 if (recoveryStopAfter)
4574 (errmsg("recovery stopping after commit of transaction %u, time %s",
4575 recoveryStopXid, str_time(recoveryStopTime))));
4578 (errmsg("recovery stopping before commit of transaction %u, time %s",
4579 recoveryStopXid, str_time(recoveryStopTime))));
4583 if (recoveryStopAfter)
4585 (errmsg("recovery stopping after abort of transaction %u, time %s",
4586 recoveryStopXid, str_time(recoveryStopTime))));
4589 (errmsg("recovery stopping before abort of transaction %u, time %s",
4590 recoveryStopXid, str_time(recoveryStopTime))));
4598 * This must be called ONCE during postmaster or standalone-backend startup
4603 XLogCtlInsert *Insert;
4604 CheckPoint checkPoint;
4606 bool needNewTimeLine = false;
4607 bool haveBackupLabel = false;
4617 TransactionId oldestActiveXID;
4622 * Read control file and check XLOG status looks valid.
4624 * Note: in most control paths, *ControlFile is already valid and we need
4625 * not do ReadControlFile() here, but might as well do it to be sure.
4629 if (ControlFile->logSeg == 0 ||
4630 ControlFile->state < DB_SHUTDOWNED ||
4631 ControlFile->state > DB_IN_PRODUCTION ||
4632 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4634 (errmsg("control file contains invalid data")));
4636 if (ControlFile->state == DB_SHUTDOWNED)
4638 (errmsg("database system was shut down at %s",
4639 str_time(ControlFile->time))));
4640 else if (ControlFile->state == DB_SHUTDOWNING)
4642 (errmsg("database system shutdown was interrupted at %s",
4643 str_time(ControlFile->time))));
4644 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4646 (errmsg("database system was interrupted while in recovery at %s",
4647 str_time(ControlFile->time)),
4648 errhint("This probably means that some data is corrupted and"
4649 " you will have to use the last backup for recovery.")));
4650 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4652 (errmsg("database system was interrupted while in recovery at log time %s",
4653 str_time(ControlFile->checkPointCopy.time)),
4654 errhint("If this has occurred more than once some data may be corrupted"
4655 " and you may need to choose an earlier recovery target.")));
4656 else if (ControlFile->state == DB_IN_PRODUCTION)
4658 (errmsg("database system was interrupted at %s",
4659 str_time(ControlFile->time))));
4661 /* This is just to allow attaching to startup process with a debugger */
4662 #ifdef XLOG_REPLAY_DELAY
4663 if (ControlFile->state != DB_SHUTDOWNED)
4664 pg_usleep(60000000L);
4668 * Initialize on the assumption we want to recover to the same timeline
4669 * that's active according to pg_control.
4671 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4674 * Check for recovery control file, and if so set up state for offline
4677 readRecoveryCommandFile();
4679 /* Now we can determine the list of expected TLIs */
4680 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4683 * If pg_control's timeline is not in expectedTLIs, then we cannot
4684 * proceed: the backup is not part of the history of the requested
4687 if (!list_member_int(expectedTLIs,
4688 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4690 (errmsg("requested timeline %u is not a child of database system timeline %u",
4692 ControlFile->checkPointCopy.ThisTimeLineID)));
4694 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4697 * When a backup_label file is present, we want to roll forward from
4698 * the checkpoint it identifies, rather than using pg_control.
4700 record = ReadCheckpointRecord(checkPointLoc, 0);
4704 (errmsg("checkpoint record is at %X/%X",
4705 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4706 InRecovery = true; /* force recovery even if SHUTDOWNED */
4711 (errmsg("could not locate required checkpoint record"),
4712 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4714 /* set flag to delete it later */
4715 haveBackupLabel = true;
4720 * Get the last valid checkpoint record. If the latest one according
4721 * to pg_control is broken, try the next-to-last one.
4723 checkPointLoc = ControlFile->checkPoint;
4724 record = ReadCheckpointRecord(checkPointLoc, 1);
4728 (errmsg("checkpoint record is at %X/%X",
4729 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4733 checkPointLoc = ControlFile->prevCheckPoint;
4734 record = ReadCheckpointRecord(checkPointLoc, 2);
4738 (errmsg("using previous checkpoint record at %X/%X",
4739 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4740 InRecovery = true; /* force recovery even if SHUTDOWNED */
4744 (errmsg("could not locate a valid checkpoint record")));
4748 LastRec = RecPtr = checkPointLoc;
4749 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4750 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4753 (errmsg("redo record is at %X/%X; undo record is at %X/%X; shutdown %s",
4754 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4755 checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
4756 wasShutdown ? "TRUE" : "FALSE")));
4758 (errmsg("next transaction ID: %u/%u; next OID: %u",
4759 checkPoint.nextXidEpoch, checkPoint.nextXid,
4760 checkPoint.nextOid)));
4762 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4763 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4764 if (!TransactionIdIsNormal(checkPoint.nextXid))
4766 (errmsg("invalid next transaction ID")));
4768 ShmemVariableCache->nextXid = checkPoint.nextXid;
4769 ShmemVariableCache->nextOid = checkPoint.nextOid;
4770 ShmemVariableCache->oidCount = 0;
4771 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4774 * We must replay WAL entries using the same TimeLineID they were created
4775 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4776 * also xlog_redo()).
4778 ThisTimeLineID = checkPoint.ThisTimeLineID;
4780 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4782 if (XLByteLT(RecPtr, checkPoint.redo))
4784 (errmsg("invalid redo in checkpoint record")));
4785 if (checkPoint.undo.xrecoff == 0)
4786 checkPoint.undo = RecPtr;
4789 * Check whether we need to force recovery from WAL. If it appears to
4790 * have been a clean shutdown and we did not have a recovery.conf file,
4791 * then assume no recovery needed.
4793 if (XLByteLT(checkPoint.undo, RecPtr) ||
4794 XLByteLT(checkPoint.redo, RecPtr))
4798 (errmsg("invalid redo/undo record in shutdown checkpoint")));
4801 else if (ControlFile->state != DB_SHUTDOWNED)
4803 else if (InArchiveRecovery)
4805 /* force recovery due to presence of recovery.conf */
4815 * Update pg_control to show that we are recovering and to show
4816 * the selected checkpoint as the place we are starting from.
4817 * We also mark pg_control with any minimum recovery stop point
4818 * obtained from a backup history file.
4820 if (InArchiveRecovery)
4823 (errmsg("automatic recovery in progress")));
4824 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4829 (errmsg("database system was not properly shut down; "
4830 "automatic recovery in progress")));
4831 ControlFile->state = DB_IN_CRASH_RECOVERY;
4833 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4834 ControlFile->checkPoint = checkPointLoc;
4835 ControlFile->checkPointCopy = checkPoint;
4836 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4837 ControlFile->minRecoveryPoint = minRecoveryLoc;
4838 ControlFile->time = time(NULL);
4839 UpdateControlFile();
4842 * If there was a backup label file, it's done its job and the
4843 * info has now been propagated into pg_control. We must get rid of
4844 * the label file so that if we crash during recovery, we'll pick up
4845 * at the latest recovery restartpoint instead of going all the way
4846 * back to the backup start point. It seems prudent though to just
4847 * rename the file out of the way rather than delete it completely.
4849 if (haveBackupLabel)
4851 unlink(BACKUP_LABEL_OLD);
4852 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4854 (errcode_for_file_access(),
4855 errmsg("could not rename file \"%s\" to \"%s\": %m",
4856 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4859 /* Start up the recovery environment */
4860 XLogInitRelationCache();
4862 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4864 if (RmgrTable[rmid].rm_startup != NULL)
4865 RmgrTable[rmid].rm_startup();
4869 * Find the first record that logically follows the checkpoint --- it
4870 * might physically precede it, though.
4872 if (XLByteLT(checkPoint.redo, RecPtr))
4874 /* back up to find the record */
4875 record = ReadRecord(&(checkPoint.redo), PANIC);
4879 /* just have to read next record after CheckPoint */
4880 record = ReadRecord(NULL, LOG);
4885 bool recoveryContinue = true;
4886 bool recoveryApply = true;
4887 ErrorContextCallback errcontext;
4891 (errmsg("redo starts at %X/%X",
4892 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4895 * main redo apply loop
4904 initStringInfo(&buf);
4905 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4906 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4907 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4908 xlog_outrec(&buf, record);
4909 appendStringInfo(&buf, " - ");
4910 RmgrTable[record->xl_rmid].rm_desc(&buf,
4912 XLogRecGetData(record));
4913 elog(LOG, "%s", buf.data);
4919 * Have we reached our recovery target?
4921 if (recoveryStopsHere(record, &recoveryApply))
4923 needNewTimeLine = true; /* see below */
4924 recoveryContinue = false;
4929 /* Setup error traceback support for ereport() */
4930 errcontext.callback = rm_redo_error_callback;
4931 errcontext.arg = (void *) record;
4932 errcontext.previous = error_context_stack;
4933 error_context_stack = &errcontext;
4935 /* nextXid must be beyond record's xid */
4936 if (TransactionIdFollowsOrEquals(record->xl_xid,
4937 ShmemVariableCache->nextXid))
4939 ShmemVariableCache->nextXid = record->xl_xid;
4940 TransactionIdAdvance(ShmemVariableCache->nextXid);
4943 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4944 RestoreBkpBlocks(record, EndRecPtr);
4946 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4948 /* Pop the error context stack */
4949 error_context_stack = errcontext.previous;
4951 LastRec = ReadRecPtr;
4953 record = ReadRecord(NULL, LOG);
4954 } while (record != NULL && recoveryContinue);
4957 * end of main redo apply loop
4961 (errmsg("redo done at %X/%X",
4962 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4967 /* there are no WAL records following the checkpoint */
4969 (errmsg("redo is not required")));
4974 * Re-fetch the last valid or last applied record, so we can identify the
4975 * exact endpoint of what we consider the valid portion of WAL.
4977 record = ReadRecord(&LastRec, PANIC);
4978 EndOfLog = EndRecPtr;
4979 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4982 * Complain if we did not roll forward far enough to render the backup
4985 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
4987 if (needNewTimeLine) /* stopped because of stop request */
4989 (errmsg("requested recovery stop point is before end time of backup dump")));
4991 /* ran off end of WAL */
4993 (errmsg("WAL ends before end time of backup dump")));
4997 * Consider whether we need to assign a new timeline ID.
4999 * If we stopped short of the end of WAL during recovery, then we are
5000 * generating a new timeline and must assign it a unique new ID.
5001 * Otherwise, we can just extend the timeline we were in when we ran out
5004 if (needNewTimeLine)
5006 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5008 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5009 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5010 curFileTLI, endLogId, endLogSeg);
5013 /* Save the selected TimeLineID in shared memory, too */
5014 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5017 * We are now done reading the old WAL. Turn off archive fetching if it
5018 * was active, and make a writable copy of the last WAL segment. (Note
5019 * that we also have a copy of the last block of the old WAL in readBuf;
5020 * we will use that below.)
5022 if (InArchiveRecovery)
5023 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5026 * Prepare to write WAL starting at EndOfLog position, and init xlog
5027 * buffer cache using the block containing the last record from the
5028 * previous incarnation.
5030 openLogId = endLogId;
5031 openLogSeg = endLogSeg;
5032 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5034 ControlFile->logId = openLogId;
5035 ControlFile->logSeg = openLogSeg + 1;
5036 Insert = &XLogCtl->Insert;
5037 Insert->PrevRecord = LastRec;
5038 XLogCtl->xlblocks[0].xlogid = openLogId;
5039 XLogCtl->xlblocks[0].xrecoff =
5040 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5043 * Tricky point here: readBuf contains the *last* block that the LastRec
5044 * record spans, not the one it starts in. The last block is indeed the
5045 * one we want to use.
5047 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5048 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5049 Insert->currpos = (char *) Insert->currpage +
5050 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5052 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5054 XLogCtl->Write.LogwrtResult = LogwrtResult;
5055 Insert->LogwrtResult = LogwrtResult;
5056 XLogCtl->LogwrtResult = LogwrtResult;
5058 XLogCtl->LogwrtRqst.Write = EndOfLog;
5059 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5061 freespace = INSERT_FREESPACE(Insert);
5064 /* Make sure rest of page is zero */
5065 MemSet(Insert->currpos, 0, freespace);
5066 XLogCtl->Write.curridx = 0;
5071 * Whenever Write.LogwrtResult points to exactly the end of a page,
5072 * Write.curridx must point to the *next* page (see XLogWrite()).
5074 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5075 * this is sufficient. The first actual attempt to insert a log
5076 * record will advance the insert state.
5078 XLogCtl->Write.curridx = NextBufIdx(0);
5081 /* Pre-scan prepared transactions to find out the range of XIDs present */
5082 oldestActiveXID = PrescanPreparedTransactions();
5089 * Allow resource managers to do any required cleanup.
5091 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5093 if (RmgrTable[rmid].rm_cleanup != NULL)
5094 RmgrTable[rmid].rm_cleanup();
5098 * Check to see if the XLOG sequence contained any unresolved
5099 * references to uninitialized pages.
5101 XLogCheckInvalidPages();
5104 * Reset pgstat data, because it may be invalid after recovery.
5109 * Perform a checkpoint to update all our recovery activity to disk.
5111 * Note that we write a shutdown checkpoint rather than an on-line
5112 * one. This is not particularly critical, but since we may be
5113 * assigning a new TLI, using a shutdown checkpoint allows us to have
5114 * the rule that TLI only changes in shutdown checkpoints, which
5115 * allows some extra error checking in xlog_redo.
5117 CreateCheckPoint(true, true);
5120 * Close down recovery environment
5122 XLogCloseRelationCache();
5126 * Preallocate additional log files, if wanted.
5128 (void) PreallocXlogFiles(EndOfLog);
5131 * Okay, we're officially UP.
5135 ControlFile->state = DB_IN_PRODUCTION;
5136 ControlFile->time = time(NULL);
5137 UpdateControlFile();
5139 /* start the archive_timeout timer running */
5140 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5142 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5143 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5144 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5146 /* Start up the commit log and related stuff, too */
5148 StartupSUBTRANS(oldestActiveXID);
5151 /* Reload shared-memory state for prepared transactions */
5152 RecoverPreparedTransactions();
5155 (errmsg("database system is ready")));
5158 /* Shut down readFile facility, free space */
5171 free(readRecordBuf);
5172 readRecordBuf = NULL;
5173 readRecordBufSize = 0;
5178 * Subroutine to try to fetch and validate a prior checkpoint record.
5180 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5181 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5184 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5188 if (!XRecOffIsValid(RecPtr.xrecoff))
5194 (errmsg("invalid primary checkpoint link in control file")));
5198 (errmsg("invalid secondary checkpoint link in control file")));
5202 (errmsg("invalid checkpoint link in backup_label file")));
5208 record = ReadRecord(&RecPtr, LOG);
5216 (errmsg("invalid primary checkpoint record")));
5220 (errmsg("invalid secondary checkpoint record")));
5224 (errmsg("invalid checkpoint record")));
5229 if (record->xl_rmid != RM_XLOG_ID)
5235 (errmsg("invalid resource manager ID in primary checkpoint record")));
5239 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5243 (errmsg("invalid resource manager ID in checkpoint record")));
5248 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5249 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5255 (errmsg("invalid xl_info in primary checkpoint record")));
5259 (errmsg("invalid xl_info in secondary checkpoint record")));
5263 (errmsg("invalid xl_info in checkpoint record")));
5268 if (record->xl_len != sizeof(CheckPoint) ||
5269 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5275 (errmsg("invalid length of primary checkpoint record")));
5279 (errmsg("invalid length of secondary checkpoint record")));
5283 (errmsg("invalid length of checkpoint record")));
5292 * This must be called during startup of a backend process, except that
5293 * it need not be called in a standalone backend (which does StartupXLOG
5294 * instead). We need to initialize the local copies of ThisTimeLineID and
5297 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5298 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5299 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5302 InitXLOGAccess(void)
5304 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5305 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5306 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5307 (void) GetRedoRecPtr();
5311 * Once spawned, a backend may update its local RedoRecPtr from
5312 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5313 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5318 /* use volatile pointer to prevent code rearrangement */
5319 volatile XLogCtlData *xlogctl = XLogCtl;
5321 SpinLockAcquire(&xlogctl->info_lck);
5322 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5323 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5324 SpinLockRelease(&xlogctl->info_lck);
5330 * Get the time of the last xlog segment switch
5333 GetLastSegSwitchTime(void)
5337 /* Need WALWriteLock, but shared lock is sufficient */
5338 LWLockAcquire(WALWriteLock, LW_SHARED);
5339 result = XLogCtl->Write.lastSegSwitchTime;
5340 LWLockRelease(WALWriteLock);
5346 * GetRecentNextXid - get the nextXid value saved by the most recent checkpoint
5348 * This is currently used only by the autovacuum daemon. To check for
5349 * impending XID wraparound, autovac needs an approximate idea of the current
5350 * XID counter, and it needs it before choosing which DB to attach to, hence
5351 * before it sets up a PGPROC, hence before it can take any LWLocks. But it
5352 * has attached to shared memory, and so we can let it reach into the shared
5353 * ControlFile structure and pull out the last checkpoint nextXID.
5355 * Since we don't take any sort of lock, we have to assume that reading a
5356 * TransactionId is atomic ... but that assumption is made elsewhere, too,
5357 * and in any case the worst possible consequence of a bogus result is that
5358 * autovac issues an unnecessary database-wide VACUUM.
5360 * Note: we could also choose to read ShmemVariableCache->nextXid in an
5361 * unlocked fashion, thus getting a more up-to-date result; but since that
5362 * changes far more frequently than the controlfile checkpoint copy, it would
5363 * pose a far higher risk of bogus result if we did have a nonatomic-read
5366 * A (theoretically) completely safe answer is to read the actual pg_control
5367 * file into local process memory, but that certainly seems like overkill.
5370 GetRecentNextXid(void)
5372 return ControlFile->checkPointCopy.nextXid;
5376 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5378 * This is exported for use by code that would like to have 64-bit XIDs.
5379 * We don't really support such things, but all XIDs within the system
5380 * can be presumed "close to" the result, and thus the epoch associated
5381 * with them can be determined.
5384 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5386 uint32 ckptXidEpoch;
5387 TransactionId ckptXid;
5388 TransactionId nextXid;
5390 /* Must read checkpoint info first, else have race condition */
5392 /* use volatile pointer to prevent code rearrangement */
5393 volatile XLogCtlData *xlogctl = XLogCtl;
5395 SpinLockAcquire(&xlogctl->info_lck);
5396 ckptXidEpoch = xlogctl->ckptXidEpoch;
5397 ckptXid = xlogctl->ckptXid;
5398 SpinLockRelease(&xlogctl->info_lck);
5401 /* Now fetch current nextXid */
5402 nextXid = ReadNewTransactionId();
5405 * nextXid is certainly logically later than ckptXid. So if it's
5406 * numerically less, it must have wrapped into the next epoch.
5408 if (nextXid < ckptXid)
5412 *epoch = ckptXidEpoch;
5416 * This must be called ONCE during postmaster or standalone-backend shutdown
5419 ShutdownXLOG(int code, Datum arg)
5422 (errmsg("shutting down")));
5425 CreateCheckPoint(true, true);
5428 ShutdownMultiXact();
5432 (errmsg("database system is shut down")));
5436 * Perform a checkpoint --- either during shutdown, or on-the-fly
5438 * If force is true, we force a checkpoint regardless of whether any XLOG
5439 * activity has occurred since the last one.
5442 CreateCheckPoint(bool shutdown, bool force)
5444 CheckPoint checkPoint;
5446 XLogCtlInsert *Insert = &XLogCtl->Insert;
5452 int nsegsremoved = 0;
5453 int nsegsrecycled = 0;
5456 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5457 * (This is just pro forma, since in the present system structure there is
5458 * only one process that is allowed to issue checkpoints at any given
5461 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5464 * Use a critical section to force system panic if we have trouble.
5466 START_CRIT_SECTION();
5470 ControlFile->state = DB_SHUTDOWNING;
5471 ControlFile->time = time(NULL);
5472 UpdateControlFile();
5475 MemSet(&checkPoint, 0, sizeof(checkPoint));
5476 checkPoint.ThisTimeLineID = ThisTimeLineID;
5477 checkPoint.time = time(NULL);
5480 * We must hold CheckpointStartLock while determining the checkpoint REDO
5481 * pointer. This ensures that any concurrent transaction commits will be
5482 * either not yet logged, or logged and recorded in pg_clog. See notes in
5483 * RecordTransactionCommit().
5485 LWLockAcquire(CheckpointStartLock, LW_EXCLUSIVE);
5487 /* And we need WALInsertLock too */
5488 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5491 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5492 * any XLOG records since the start of the last checkpoint, skip the
5493 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5494 * when the system is idle. That wastes log space, and more importantly it
5495 * exposes us to possible loss of both current and previous checkpoint
5496 * records if the machine crashes just as we're writing the update.
5497 * (Perhaps it'd make even more sense to checkpoint only when the previous
5498 * checkpoint record is in a different xlog page?)
5500 * We have to make two tests to determine that nothing has happened since
5501 * the start of the last checkpoint: current insertion point must match
5502 * the end of the last checkpoint record, and its redo pointer must point
5505 if (!shutdown && !force)
5507 XLogRecPtr curInsert;
5509 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5510 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5511 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5512 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5513 ControlFile->checkPoint.xlogid ==
5514 ControlFile->checkPointCopy.redo.xlogid &&
5515 ControlFile->checkPoint.xrecoff ==
5516 ControlFile->checkPointCopy.redo.xrecoff)
5518 LWLockRelease(WALInsertLock);
5519 LWLockRelease(CheckpointStartLock);
5520 LWLockRelease(CheckpointLock);
5527 * Compute new REDO record ptr = location of next XLOG record.
5529 * NB: this is NOT necessarily where the checkpoint record itself will be,
5530 * since other backends may insert more XLOG records while we're off doing
5531 * the buffer flush work. Those XLOG records are logically after the
5532 * checkpoint, even though physically before it. Got that?
5534 freespace = INSERT_FREESPACE(Insert);
5535 if (freespace < SizeOfXLogRecord)
5537 (void) AdvanceXLInsertBuffer(false);
5538 /* OK to ignore update return flag, since we will do flush anyway */
5539 freespace = INSERT_FREESPACE(Insert);
5541 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5544 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5545 * must be done while holding the insert lock AND the info_lck.
5547 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5548 * pointing past where it really needs to point. This is okay; the only
5549 * consequence is that XLogInsert might back up whole buffers that it
5550 * didn't really need to. We can't postpone advancing RedoRecPtr because
5551 * XLogInserts that happen while we are dumping buffers must assume that
5552 * their buffer changes are not included in the checkpoint.
5555 /* use volatile pointer to prevent code rearrangement */
5556 volatile XLogCtlData *xlogctl = XLogCtl;
5558 SpinLockAcquire(&xlogctl->info_lck);
5559 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5560 SpinLockRelease(&xlogctl->info_lck);
5564 * Now we can release insert lock and checkpoint start lock, allowing
5565 * other xacts to proceed even while we are flushing disk buffers.
5567 LWLockRelease(WALInsertLock);
5569 LWLockRelease(CheckpointStartLock);
5573 (errmsg("checkpoint starting")));
5576 * Get the other info we need for the checkpoint record.
5578 LWLockAcquire(XidGenLock, LW_SHARED);
5579 checkPoint.nextXid = ShmemVariableCache->nextXid;
5580 LWLockRelease(XidGenLock);
5582 /* Increase XID epoch if we've wrapped around since last checkpoint */
5583 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5584 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5585 checkPoint.nextXidEpoch++;
5587 LWLockAcquire(OidGenLock, LW_SHARED);
5588 checkPoint.nextOid = ShmemVariableCache->nextOid;
5590 checkPoint.nextOid += ShmemVariableCache->oidCount;
5591 LWLockRelease(OidGenLock);
5593 MultiXactGetCheckptMulti(shutdown,
5594 &checkPoint.nextMulti,
5595 &checkPoint.nextMultiOffset);
5598 * Having constructed the checkpoint record, ensure all shmem disk buffers
5599 * and commit-log buffers are flushed to disk.
5601 * This I/O could fail for various reasons. If so, we will fail to
5602 * complete the checkpoint, but there is no reason to force a system
5603 * panic. Accordingly, exit critical section while doing it. (If we are
5604 * doing a shutdown checkpoint, we probably *should* panic --- but that
5605 * will happen anyway because we'll still be inside the critical section
5606 * established by ShutdownXLOG.)
5610 CheckPointGuts(checkPoint.redo);
5612 START_CRIT_SECTION();
5615 * Now insert the checkpoint record into XLOG.
5617 rdata.data = (char *) (&checkPoint);
5618 rdata.len = sizeof(checkPoint);
5619 rdata.buffer = InvalidBuffer;
5622 recptr = XLogInsert(RM_XLOG_ID,
5623 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5624 XLOG_CHECKPOINT_ONLINE,
5630 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5631 * = end of actual checkpoint record.
5633 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5635 (errmsg("concurrent transaction log activity while database system is shutting down")));
5638 * Select point at which we can truncate the log, which we base on the
5639 * prior checkpoint's earliest info.
5641 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5644 * Update the control file.
5646 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5648 ControlFile->state = DB_SHUTDOWNED;
5649 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5650 ControlFile->checkPoint = ProcLastRecPtr;
5651 ControlFile->checkPointCopy = checkPoint;
5652 ControlFile->time = time(NULL);
5653 UpdateControlFile();
5654 LWLockRelease(ControlFileLock);
5656 /* Update shared-memory copy of checkpoint XID/epoch */
5658 /* use volatile pointer to prevent code rearrangement */
5659 volatile XLogCtlData *xlogctl = XLogCtl;
5661 SpinLockAcquire(&xlogctl->info_lck);
5662 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5663 xlogctl->ckptXid = checkPoint.nextXid;
5664 SpinLockRelease(&xlogctl->info_lck);
5668 * We are now done with critical updates; no need for system panic if we
5669 * have trouble while fooling with offline log segments.
5674 * Delete offline log files (those no longer needed even for previous
5677 if (_logId || _logSeg)
5679 PrevLogSeg(_logId, _logSeg);
5680 MoveOfflineLogs(_logId, _logSeg, recptr,
5681 &nsegsremoved, &nsegsrecycled);
5685 * Make more log segments if needed. (Do this after deleting offline log
5686 * segments, to avoid having peak disk space usage higher than necessary.)
5689 nsegsadded = PreallocXlogFiles(recptr);
5692 * Truncate pg_subtrans if possible. We can throw away all data before
5693 * the oldest XMIN of any running transaction. No future transaction will
5694 * attempt to reference any pg_subtrans entry older than that (see Asserts
5695 * in subtrans.c). During recovery, though, we mustn't do this because
5696 * StartupSUBTRANS hasn't been called yet.
5699 TruncateSUBTRANS(GetOldestXmin(true, false));
5703 (errmsg("checkpoint complete; %d transaction log file(s) added, %d removed, %d recycled",
5704 nsegsadded, nsegsremoved, nsegsrecycled)));
5706 LWLockRelease(CheckpointLock);
5710 * Flush all data in shared memory to disk, and fsync
5712 * This is the common code shared between regular checkpoints and
5713 * recovery restartpoints.
5716 CheckPointGuts(XLogRecPtr checkPointRedo)
5719 CheckPointSUBTRANS();
5720 CheckPointMultiXact();
5721 FlushBufferPool(); /* performs all required fsyncs */
5722 /* We deliberately delay 2PC checkpointing as long as possible */
5723 CheckPointTwoPhase(checkPointRedo);
5727 * Set a recovery restart point if appropriate
5729 * This is similar to CreateCheckpoint, but is used during WAL recovery
5730 * to establish a point from which recovery can roll forward without
5731 * replaying the entire recovery log. This function is called each time
5732 * a checkpoint record is read from XLOG; it must determine whether a
5733 * restartpoint is needed or not.
5736 RecoveryRestartPoint(const CheckPoint *checkPoint)
5742 * Do nothing if the elapsed time since the last restartpoint is less
5743 * than half of checkpoint_timeout. (We use a value less than
5744 * checkpoint_timeout so that variations in the timing of checkpoints on
5745 * the master, or speed of transmission of WAL segments to a slave, won't
5746 * make the slave skip a restartpoint once it's synced with the master.)
5747 * Checking true elapsed time keeps us from doing restartpoints too often
5748 * while rapidly scanning large amounts of WAL.
5750 elapsed_secs = time(NULL) - ControlFile->time;
5751 if (elapsed_secs < CheckPointTimeout / 2)
5755 * Is it safe to checkpoint? We must ask each of the resource managers
5756 * whether they have any partial state information that might prevent a
5757 * correct restart from this point. If so, we skip this opportunity, but
5758 * return at the next checkpoint record for another try.
5760 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5762 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5763 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5768 * OK, force data out to disk
5770 CheckPointGuts(checkPoint->redo);
5773 * Update pg_control so that any subsequent crash will restart from
5774 * this checkpoint. Note: ReadRecPtr gives the XLOG address of the
5775 * checkpoint record itself.
5777 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5778 ControlFile->checkPoint = ReadRecPtr;
5779 ControlFile->checkPointCopy = *checkPoint;
5780 ControlFile->time = time(NULL);
5781 UpdateControlFile();
5784 (errmsg("recovery restart point at %X/%X",
5785 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5789 * Write a NEXTOID log record
5792 XLogPutNextOid(Oid nextOid)
5796 rdata.data = (char *) (&nextOid);
5797 rdata.len = sizeof(Oid);
5798 rdata.buffer = InvalidBuffer;
5800 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5803 * We need not flush the NEXTOID record immediately, because any of the
5804 * just-allocated OIDs could only reach disk as part of a tuple insert or
5805 * update that would have its own XLOG record that must follow the NEXTOID
5806 * record. Therefore, the standard buffer LSN interlock applied to those
5807 * records will ensure no such OID reaches disk before the NEXTOID record
5813 * Write an XLOG SWITCH record.
5815 * Here we just blindly issue an XLogInsert request for the record.
5816 * All the magic happens inside XLogInsert.
5818 * The return value is either the end+1 address of the switch record,
5819 * or the end+1 address of the prior segment if we did not need to
5820 * write a switch record because we are already at segment start.
5823 RequestXLogSwitch(void)
5828 /* XLOG SWITCH, alone among xlog record types, has no data */
5829 rdata.buffer = InvalidBuffer;
5834 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5840 * XLOG resource manager's routines
5843 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5845 uint8 info = record->xl_info & ~XLR_INFO_MASK;
5847 if (info == XLOG_NEXTOID)
5851 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5852 if (ShmemVariableCache->nextOid < nextOid)
5854 ShmemVariableCache->nextOid = nextOid;
5855 ShmemVariableCache->oidCount = 0;
5858 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5860 CheckPoint checkPoint;
5862 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5863 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5864 ShmemVariableCache->nextXid = checkPoint.nextXid;
5865 ShmemVariableCache->nextOid = checkPoint.nextOid;
5866 ShmemVariableCache->oidCount = 0;
5867 MultiXactSetNextMXact(checkPoint.nextMulti,
5868 checkPoint.nextMultiOffset);
5870 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5871 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5872 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5875 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
5877 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5879 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5880 !list_member_int(expectedTLIs,
5881 (int) checkPoint.ThisTimeLineID))
5883 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5884 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5885 /* Following WAL records should be run with new TLI */
5886 ThisTimeLineID = checkPoint.ThisTimeLineID;
5889 RecoveryRestartPoint(&checkPoint);
5891 else if (info == XLOG_CHECKPOINT_ONLINE)
5893 CheckPoint checkPoint;
5895 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5896 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5897 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5898 checkPoint.nextXid))
5899 ShmemVariableCache->nextXid = checkPoint.nextXid;
5900 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5902 ShmemVariableCache->nextOid = checkPoint.nextOid;
5903 ShmemVariableCache->oidCount = 0;
5905 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
5906 checkPoint.nextMultiOffset);
5908 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
5909 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
5910 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
5912 /* TLI should not change in an on-line checkpoint */
5913 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5915 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5916 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5918 RecoveryRestartPoint(&checkPoint);
5920 else if (info == XLOG_SWITCH)
5922 /* nothing to do here */
5927 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
5929 uint8 info = xl_info & ~XLR_INFO_MASK;
5931 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5932 info == XLOG_CHECKPOINT_ONLINE)
5934 CheckPoint *checkpoint = (CheckPoint *) rec;
5936 appendStringInfo(buf, "checkpoint: redo %X/%X; undo %X/%X; "
5937 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
5938 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5939 checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
5940 checkpoint->ThisTimeLineID,
5941 checkpoint->nextXidEpoch, checkpoint->nextXid,
5942 checkpoint->nextOid,
5943 checkpoint->nextMulti,
5944 checkpoint->nextMultiOffset,
5945 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
5947 else if (info == XLOG_NEXTOID)
5951 memcpy(&nextOid, rec, sizeof(Oid));
5952 appendStringInfo(buf, "nextOid: %u", nextOid);
5954 else if (info == XLOG_SWITCH)
5956 appendStringInfo(buf, "xlog switch");
5959 appendStringInfo(buf, "UNKNOWN");
5965 xlog_outrec(StringInfo buf, XLogRecord *record)
5969 appendStringInfo(buf, "prev %X/%X; xid %u",
5970 record->xl_prev.xlogid, record->xl_prev.xrecoff,
5973 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
5975 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
5976 appendStringInfo(buf, "; bkpb%d", i+1);
5979 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
5981 #endif /* WAL_DEBUG */
5988 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
5990 int new_sync_method;
5993 if (pg_strcasecmp(method, "fsync") == 0)
5995 new_sync_method = SYNC_METHOD_FSYNC;
5998 #ifdef HAVE_FSYNC_WRITETHROUGH
5999 else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
6001 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
6005 #ifdef HAVE_FDATASYNC
6006 else if (pg_strcasecmp(method, "fdatasync") == 0)
6008 new_sync_method = SYNC_METHOD_FDATASYNC;
6012 #ifdef OPEN_SYNC_FLAG
6013 else if (pg_strcasecmp(method, "open_sync") == 0)
6015 new_sync_method = SYNC_METHOD_OPEN;
6016 new_sync_bit = OPEN_SYNC_FLAG;
6019 #ifdef OPEN_DATASYNC_FLAG
6020 else if (pg_strcasecmp(method, "open_datasync") == 0)
6022 new_sync_method = SYNC_METHOD_OPEN;
6023 new_sync_bit = OPEN_DATASYNC_FLAG;
6032 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
6035 * To ensure that no blocks escape unsynced, force an fsync on the
6036 * currently open log segment (if any). Also, if the open flag is
6037 * changing, close the log file so it will be reopened (with new flag
6040 if (openLogFile >= 0)
6042 if (pg_fsync(openLogFile) != 0)
6044 (errcode_for_file_access(),
6045 errmsg("could not fsync log file %u, segment %u: %m",
6046 openLogId, openLogSeg)));
6047 if (open_sync_bit != new_sync_bit)
6050 sync_method = new_sync_method;
6051 open_sync_bit = new_sync_bit;
6059 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6062 issue_xlog_fsync(void)
6064 switch (sync_method)
6066 case SYNC_METHOD_FSYNC:
6067 if (pg_fsync_no_writethrough(openLogFile) != 0)
6069 (errcode_for_file_access(),
6070 errmsg("could not fsync log file %u, segment %u: %m",
6071 openLogId, openLogSeg)));
6073 #ifdef HAVE_FSYNC_WRITETHROUGH
6074 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6075 if (pg_fsync_writethrough(openLogFile) != 0)
6077 (errcode_for_file_access(),
6078 errmsg("could not fsync write-through log file %u, segment %u: %m",
6079 openLogId, openLogSeg)));
6082 #ifdef HAVE_FDATASYNC
6083 case SYNC_METHOD_FDATASYNC:
6084 if (pg_fdatasync(openLogFile) != 0)
6086 (errcode_for_file_access(),
6087 errmsg("could not fdatasync log file %u, segment %u: %m",
6088 openLogId, openLogSeg)));
6091 case SYNC_METHOD_OPEN:
6092 /* write synced it already */
6095 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6102 * pg_start_backup: set up for taking an on-line backup dump
6104 * Essentially what this does is to create a backup label file in $PGDATA,
6105 * where it will be archived as part of the backup dump. The label file
6106 * contains the user-supplied label string (typically this would be used
6107 * to tell where the backup dump will be stored) and the starting time and
6108 * starting WAL location for the dump.
6111 pg_start_backup(PG_FUNCTION_ARGS)
6113 text *backupid = PG_GETARG_TEXT_P(0);
6116 XLogRecPtr checkpointloc;
6117 XLogRecPtr startpoint;
6120 char xlogfilename[MAXFNAMELEN];
6123 struct stat stat_buf;
6128 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6129 (errmsg("must be superuser to run a backup"))));
6131 if (!XLogArchivingActive())
6133 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6134 (errmsg("WAL archiving is not active"),
6135 (errhint("archive_command must be defined before "
6136 "online backups can be made safely.")))));
6138 backupidstr = DatumGetCString(DirectFunctionCall1(textout,
6139 PointerGetDatum(backupid)));
6142 * Mark backup active in shared memory. We must do full-page WAL writes
6143 * during an on-line backup even if not doing so at other times, because
6144 * it's quite possible for the backup dump to obtain a "torn" (partially
6145 * written) copy of a database page if it reads the page concurrently
6146 * with our write to the same page. This can be fixed as long as the
6147 * first write to the page in the WAL sequence is a full-page write.
6148 * Hence, we turn on forcePageWrites and then force a CHECKPOINT, to
6149 * ensure there are no dirty pages in shared memory that might get
6150 * dumped while the backup is in progress without having a corresponding
6151 * WAL record. (Once the backup is complete, we need not force full-page
6152 * writes anymore, since we expect that any pages not modified during
6153 * the backup interval must have been correctly captured by the backup.)
6155 * We must hold WALInsertLock to change the value of forcePageWrites,
6156 * to ensure adequate interlocking against XLogInsert().
6158 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6159 if (XLogCtl->Insert.forcePageWrites)
6161 LWLockRelease(WALInsertLock);
6163 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6164 errmsg("a backup is already in progress"),
6165 errhint("Run pg_stop_backup() and try again.")));
6167 XLogCtl->Insert.forcePageWrites = true;
6168 LWLockRelease(WALInsertLock);
6170 /* Use a TRY block to ensure we release forcePageWrites if fail below */
6174 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6175 * page problems, this guarantees that two successive backup runs will
6176 * have different checkpoint positions and hence different history
6177 * file names, even if nothing happened in between.
6179 RequestCheckpoint(true, false);
6182 * Now we need to fetch the checkpoint record location, and also its
6183 * REDO pointer. The oldest point in WAL that would be needed to
6184 * restore starting from the checkpoint is precisely the REDO pointer.
6186 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6187 checkpointloc = ControlFile->checkPoint;
6188 startpoint = ControlFile->checkPointCopy.redo;
6189 LWLockRelease(ControlFileLock);
6191 XLByteToSeg(startpoint, _logId, _logSeg);
6192 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6195 * We deliberately use strftime/localtime not the src/timezone
6196 * functions, so that backup labels will consistently be recorded in
6197 * the same timezone regardless of TimeZone setting. This matches
6198 * elog.c's practice.
6200 stamp_time = time(NULL);
6201 strftime(strfbuf, sizeof(strfbuf),
6202 "%Y-%m-%d %H:%M:%S %Z",
6203 localtime(&stamp_time));
6206 * Check for existing backup label --- implies a backup is already
6207 * running. (XXX given that we checked forcePageWrites above, maybe
6208 * it would be OK to just unlink any such label file?)
6210 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6212 if (errno != ENOENT)
6214 (errcode_for_file_access(),
6215 errmsg("could not stat file \"%s\": %m",
6216 BACKUP_LABEL_FILE)));
6220 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6221 errmsg("a backup is already in progress"),
6222 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6223 BACKUP_LABEL_FILE)));
6226 * Okay, write the file
6228 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6231 (errcode_for_file_access(),
6232 errmsg("could not create file \"%s\": %m",
6233 BACKUP_LABEL_FILE)));
6234 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6235 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6236 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6237 checkpointloc.xlogid, checkpointloc.xrecoff);
6238 fprintf(fp, "START TIME: %s\n", strfbuf);
6239 fprintf(fp, "LABEL: %s\n", backupidstr);
6240 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6242 (errcode_for_file_access(),
6243 errmsg("could not write file \"%s\": %m",
6244 BACKUP_LABEL_FILE)));
6248 /* Turn off forcePageWrites on failure */
6249 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6250 XLogCtl->Insert.forcePageWrites = false;
6251 LWLockRelease(WALInsertLock);
6258 * We're done. As a convenience, return the starting WAL location.
6260 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6261 startpoint.xlogid, startpoint.xrecoff);
6262 result = DatumGetTextP(DirectFunctionCall1(textin,
6263 CStringGetDatum(xlogfilename)));
6264 PG_RETURN_TEXT_P(result);
6268 * pg_stop_backup: finish taking an on-line backup dump
6270 * We remove the backup label file created by pg_start_backup, and instead
6271 * create a backup history file in pg_xlog (whence it will immediately be
6272 * archived). The backup history file contains the same info found in
6273 * the label file, plus the backup-end time and WAL location.
6276 pg_stop_backup(PG_FUNCTION_ARGS)
6279 XLogRecPtr startpoint;
6280 XLogRecPtr stoppoint;
6283 char histfilepath[MAXPGPATH];
6284 char startxlogfilename[MAXFNAMELEN];
6285 char stopxlogfilename[MAXFNAMELEN];
6295 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6296 (errmsg("must be superuser to run a backup"))));
6299 * OK to clear forcePageWrites
6301 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6302 XLogCtl->Insert.forcePageWrites = false;
6303 LWLockRelease(WALInsertLock);
6306 * Force a switch to a new xlog segment file, so that the backup
6307 * is valid as soon as archiver moves out the current segment file.
6308 * We'll report the end address of the XLOG SWITCH record as the backup
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,
6396 * this will post a .ready file for the newly created history file,
6397 * notifying 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
6540 * this 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);