1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/access/transam/xlog.c,v 1.275 2007/07/24 04:54:08 tgl Exp $
12 *-------------------------------------------------------------------------
26 #include "access/clog.h"
27 #include "access/heapam.h"
28 #include "access/multixact.h"
29 #include "access/subtrans.h"
30 #include "access/transam.h"
31 #include "access/tuptoaster.h"
32 #include "access/twophase.h"
33 #include "access/xact.h"
34 #include "access/xlog_internal.h"
35 #include "access/xlogdefs.h"
36 #include "access/xlogutils.h"
37 #include "catalog/catversion.h"
38 #include "catalog/pg_control.h"
39 #include "catalog/pg_type.h"
41 #include "miscadmin.h"
43 #include "postmaster/bgwriter.h"
44 #include "storage/bufpage.h"
45 #include "storage/fd.h"
46 #include "storage/pmsignal.h"
47 #include "storage/procarray.h"
48 #include "storage/spin.h"
49 #include "utils/builtins.h"
50 #include "utils/pg_locale.h"
54 /* File path names (all relative to $PGDATA) */
55 #define BACKUP_LABEL_FILE "backup_label"
56 #define BACKUP_LABEL_OLD "backup_label.old"
57 #define RECOVERY_COMMAND_FILE "recovery.conf"
58 #define RECOVERY_COMMAND_DONE "recovery.done"
61 /* User-settable parameters */
62 int CheckPointSegments = 3;
64 int XLogArchiveTimeout = 0;
65 char *XLogArchiveCommand = NULL;
66 char *XLOG_sync_method = NULL;
67 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
68 bool fullPageWrites = true;
69 bool log_checkpoints = false;
72 bool XLOG_DEBUG = false;
76 * XLOGfileslop is the maximum number of preallocated future XLOG segments.
77 * When we are done with an old XLOG segment file, we will recycle it as a
78 * future XLOG segment as long as there aren't already XLOGfileslop future
79 * segments; else we'll delete it. This could be made a separate GUC
80 * variable, but at present I think it's sufficient to hardwire it as
81 * 2*CheckPointSegments+1. Under normal conditions, a checkpoint will free
82 * no more than 2*CheckPointSegments log segments, and we want to recycle all
83 * of them; the +1 allows boundary cases to happen without wasting a
84 * delete/create-segment cycle.
86 #define XLOGfileslop (2*CheckPointSegments + 1)
89 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
90 int sync_method = DEFAULT_SYNC_METHOD;
91 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
93 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
97 * Statistics for current checkpoint are collected in this global struct.
98 * Because only the background writer or a stand-alone backend can perform
99 * checkpoints, this will be unused in normal backends.
101 CheckpointStatsData CheckpointStats;
104 * ThisTimeLineID will be same in all backends --- it identifies current
105 * WAL timeline for the database system.
107 TimeLineID ThisTimeLineID = 0;
109 /* Are we doing recovery from XLOG? */
110 bool InRecovery = false;
112 /* Are we recovering using offline XLOG archives? */
113 static bool InArchiveRecovery = false;
115 /* Was the last xlog file restored from archive, or local? */
116 static bool restoredFromArchive = false;
118 /* options taken from recovery.conf */
119 static char *recoveryRestoreCommand = NULL;
120 static bool recoveryTarget = false;
121 static bool recoveryTargetExact = false;
122 static bool recoveryTargetInclusive = true;
123 static TransactionId recoveryTargetXid;
124 static TimestampTz recoveryTargetTime;
126 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
127 static TransactionId recoveryStopXid;
128 static TimestampTz recoveryStopTime;
129 static bool recoveryStopAfter;
132 * During normal operation, the only timeline we care about is ThisTimeLineID.
133 * During recovery, however, things are more complicated. To simplify life
134 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
135 * scan through the WAL history (that is, it is the line that was active when
136 * the currently-scanned WAL record was generated). We also need these
139 * recoveryTargetTLI: the desired timeline that we want to end in.
141 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
142 * its known parents, newest first (so recoveryTargetTLI is always the
143 * first list member). Only these TLIs are expected to be seen in the WAL
144 * segments we read, and indeed only these TLIs will be considered as
145 * candidate WAL files to open at all.
147 * curFileTLI: the TLI appearing in the name of the current input WAL file.
148 * (This is not necessarily the same as ThisTimeLineID, because we could
149 * be scanning data that was copied from an ancestor timeline when the current
150 * file was created.) During a sequential scan we do not allow this value
153 static TimeLineID recoveryTargetTLI;
154 static List *expectedTLIs;
155 static TimeLineID curFileTLI;
158 * MyLastRecPtr points to the start of the last XLOG record inserted by the
159 * current transaction. If MyLastRecPtr.xrecoff == 0, then the current
160 * xact hasn't yet inserted any transaction-controlled XLOG records.
162 * Note that XLOG records inserted outside transaction control are not
163 * reflected into MyLastRecPtr. They do, however, cause MyXactMadeXLogEntry
164 * to be set true. The latter can be used to test whether the current xact
165 * made any loggable changes (including out-of-xact changes, such as
168 * When we insert/update/delete a tuple in a temporary relation, we do not
169 * make any XLOG record, since we don't care about recovering the state of
170 * the temp rel after a crash. However, we will still need to remember
171 * whether our transaction committed or aborted in that case. So, we must
172 * set MyXactMadeTempRelUpdate true to indicate that the XID will be of
175 XLogRecPtr MyLastRecPtr = {0, 0};
177 bool MyXactMadeXLogEntry = false;
179 bool MyXactMadeTempRelUpdate = false;
182 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
183 * current backend. It is updated for all inserts, transaction-controlled
184 * or not. ProcLastRecEnd is similar but points to end+1 of last record.
186 static XLogRecPtr ProcLastRecPtr = {0, 0};
188 XLogRecPtr ProcLastRecEnd = {0, 0};
191 * RedoRecPtr is this backend's local copy of the REDO record pointer
192 * (which is almost but not quite the same as a pointer to the most recent
193 * CHECKPOINT record). We update this from the shared-memory copy,
194 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
195 * hold the Insert lock). See XLogInsert for details. We are also allowed
196 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
197 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
200 static XLogRecPtr RedoRecPtr;
203 * Shared-memory data structures for XLOG control
205 * LogwrtRqst indicates a byte position that we need to write and/or fsync
206 * the log up to (all records before that point must be written or fsynced).
207 * LogwrtResult indicates the byte positions we have already written/fsynced.
208 * These structs are identical but are declared separately to indicate their
209 * slightly different functions.
211 * We do a lot of pushups to minimize the amount of access to lockable
212 * shared memory values. There are actually three shared-memory copies of
213 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
214 * XLogCtl->LogwrtResult is protected by info_lck
215 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
216 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
217 * One must hold the associated lock to read or write any of these, but
218 * of course no lock is needed to read/write the unshared LogwrtResult.
220 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
221 * right", since both are updated by a write or flush operation before
222 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
223 * is that it can be examined/modified by code that already holds WALWriteLock
224 * without needing to grab info_lck as well.
226 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
227 * but is updated when convenient. Again, it exists for the convenience of
228 * code that is already holding WALInsertLock but not the other locks.
230 * The unshared LogwrtResult may lag behind any or all of these, and again
231 * is updated when convenient.
233 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
234 * (protected by info_lck), but we don't need to cache any copies of it.
236 * Note that this all works because the request and result positions can only
237 * advance forward, never back up, and so we can easily determine which of two
238 * values is "more up to date".
240 * info_lck is only held long enough to read/update the protected variables,
241 * so it's a plain spinlock. The other locks are held longer (potentially
242 * over I/O operations), so we use LWLocks for them. These locks are:
244 * WALInsertLock: must be held to insert a record into the WAL buffers.
246 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
249 * ControlFileLock: must be held to read/update control file or create
252 * CheckpointLock: must be held to do a checkpoint (ensures only one
253 * checkpointer at a time; currently, with all checkpoints done by the
254 * bgwriter, this is just pro forma).
259 typedef struct XLogwrtRqst
261 XLogRecPtr Write; /* last byte + 1 to write out */
262 XLogRecPtr Flush; /* last byte + 1 to flush */
265 typedef struct XLogwrtResult
267 XLogRecPtr Write; /* last byte + 1 written out */
268 XLogRecPtr Flush; /* last byte + 1 flushed */
272 * Shared state data for XLogInsert.
274 typedef struct XLogCtlInsert
276 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
277 XLogRecPtr PrevRecord; /* start of previously-inserted record */
278 int curridx; /* current block index in cache */
279 XLogPageHeader currpage; /* points to header of block in cache */
280 char *currpos; /* current insertion point in cache */
281 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
282 bool forcePageWrites; /* forcing full-page writes for PITR? */
286 * Shared state data for XLogWrite/XLogFlush.
288 typedef struct XLogCtlWrite
290 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
291 int curridx; /* cache index of next block to write */
292 time_t lastSegSwitchTime; /* time of last xlog segment switch */
296 * Total shared-memory state for XLOG.
298 typedef struct XLogCtlData
300 /* Protected by WALInsertLock: */
301 XLogCtlInsert Insert;
303 /* Protected by info_lck: */
304 XLogwrtRqst LogwrtRqst;
305 XLogwrtResult LogwrtResult;
306 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
307 TransactionId ckptXid;
309 /* Protected by WALWriteLock: */
313 * These values do not change after startup, although the pointed-to pages
314 * and xlblocks values certainly do. Permission to read/write the pages
315 * and xlblocks values depends on WALInsertLock and WALWriteLock.
317 char *pages; /* buffers for unwritten XLOG pages */
318 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
319 Size XLogCacheByte; /* # bytes in xlog buffers */
320 int XLogCacheBlck; /* highest allocated xlog buffer index */
321 TimeLineID ThisTimeLineID;
323 slock_t info_lck; /* locks shared variables shown above */
326 static XLogCtlData *XLogCtl = NULL;
329 * We maintain an image of pg_control in shared memory.
331 static ControlFileData *ControlFile = NULL;
334 * Macros for managing XLogInsert state. In most cases, the calling routine
335 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
336 * so these are passed as parameters instead of being fetched via XLogCtl.
339 /* Free space remaining in the current xlog page buffer */
340 #define INSERT_FREESPACE(Insert) \
341 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
343 /* Construct XLogRecPtr value for current insertion point */
344 #define INSERT_RECPTR(recptr,Insert,curridx) \
346 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
348 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
351 #define PrevBufIdx(idx) \
352 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
354 #define NextBufIdx(idx) \
355 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
358 * Private, possibly out-of-date copy of shared LogwrtResult.
359 * See discussion above.
361 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
364 * openLogFile is -1 or a kernel FD for an open log file segment.
365 * When it's open, openLogOff is the current seek offset in the file.
366 * openLogId/openLogSeg identify the segment. These variables are only
367 * used to write the XLOG, and so will normally refer to the active segment.
369 static int openLogFile = -1;
370 static uint32 openLogId = 0;
371 static uint32 openLogSeg = 0;
372 static uint32 openLogOff = 0;
375 * These variables are used similarly to the ones above, but for reading
376 * the XLOG. Note, however, that readOff generally represents the offset
377 * of the page just read, not the seek position of the FD itself, which
378 * will be just past that page.
380 static int readFile = -1;
381 static uint32 readId = 0;
382 static uint32 readSeg = 0;
383 static uint32 readOff = 0;
385 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
386 static char *readBuf = NULL;
388 /* Buffer for current ReadRecord result (expandable) */
389 static char *readRecordBuf = NULL;
390 static uint32 readRecordBufSize = 0;
392 /* State information for XLOG reading */
393 static XLogRecPtr ReadRecPtr; /* start of last record read */
394 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
395 static XLogRecord *nextRecord = NULL;
396 static TimeLineID lastPageTLI = 0;
398 static bool InRedo = false;
401 static void XLogArchiveNotify(const char *xlog);
402 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
403 static bool XLogArchiveCheckDone(const char *xlog);
404 static void XLogArchiveCleanup(const char *xlog);
405 static void readRecoveryCommandFile(void);
406 static void exitArchiveRecovery(TimeLineID endTLI,
407 uint32 endLogId, uint32 endLogSeg);
408 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
409 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
411 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
412 XLogRecPtr *lsn, BkpBlock *bkpb);
413 static bool AdvanceXLInsertBuffer(bool new_segment);
414 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
415 static int XLogFileInit(uint32 log, uint32 seg,
416 bool *use_existent, bool use_lock);
417 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
418 bool find_free, int *max_advance,
420 static int XLogFileOpen(uint32 log, uint32 seg);
421 static int XLogFileRead(uint32 log, uint32 seg, int emode);
422 static void XLogFileClose(void);
423 static bool RestoreArchivedFile(char *path, const char *xlogfname,
424 const char *recovername, off_t expectedSize);
425 static void PreallocXlogFiles(XLogRecPtr endptr);
426 static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
427 static void CleanupBackupHistory(void);
428 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
429 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
430 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
431 static List *readTimeLineHistory(TimeLineID targetTLI);
432 static bool existsTimeLineHistory(TimeLineID probeTLI);
433 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
434 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
436 uint32 endLogId, uint32 endLogSeg);
437 static void WriteControlFile(void);
438 static void ReadControlFile(void);
439 static char *str_time(time_t tnow);
440 static void issue_xlog_fsync(void);
443 static void xlog_outrec(StringInfo buf, XLogRecord *record);
445 static bool read_backup_label(XLogRecPtr *checkPointLoc,
446 XLogRecPtr *minRecoveryLoc);
447 static void rm_redo_error_callback(void *arg);
451 * Insert an XLOG record having the specified RMID and info bytes,
452 * with the body of the record being the data chunk(s) described by
453 * the rdata chain (see xlog.h for notes about rdata).
455 * Returns XLOG pointer to end of record (beginning of next record).
456 * This can be used as LSN for data pages affected by the logged action.
457 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
458 * before the data page can be written out. This implements the basic
459 * WAL rule "write the log before the data".)
461 * NB: this routine feels free to scribble on the XLogRecData structs,
462 * though not on the data they reference. This is OK since the XLogRecData
463 * structs are always just temporaries in the calling code.
466 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
468 XLogCtlInsert *Insert = &XLogCtl->Insert;
470 XLogContRecord *contrecord;
472 XLogRecPtr WriteRqst;
476 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
477 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
478 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
479 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
480 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
481 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
482 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
489 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
490 bool no_tran = (rmid == RM_XLOG_ID);
492 if (info & XLR_INFO_MASK)
494 if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
495 elog(PANIC, "invalid xlog info mask %02X", (info & XLR_INFO_MASK));
497 info &= ~XLR_INFO_MASK;
501 * In bootstrap mode, we don't actually log anything but XLOG resources;
502 * return a phony record pointer.
504 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
507 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
512 * Here we scan the rdata chain, determine which buffers must be backed
513 * up, and compute the CRC values for the data. Note that the record
514 * header isn't added into the CRC initially since we don't know the final
515 * length or info bits quite yet. Thus, the CRC will represent the CRC of
516 * the whole record in the order "rdata, then backup blocks, then record
519 * We may have to loop back to here if a race condition is detected below.
520 * We could prevent the race by doing all this work while holding the
521 * insert lock, but it seems better to avoid doing CRC calculations while
522 * holding the lock. This means we have to be careful about modifying the
523 * rdata chain until we know we aren't going to loop back again. The only
524 * change we allow ourselves to make earlier is to set rdt->data = NULL in
525 * chain items we have decided we will have to back up the whole buffer
526 * for. This is OK because we will certainly decide the same thing again
527 * for those items if we do it over; doing it here saves an extra pass
528 * over the chain later.
531 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
533 dtbuf[i] = InvalidBuffer;
534 dtbuf_bkp[i] = false;
538 * Decide if we need to do full-page writes in this XLOG record: true if
539 * full_page_writes is on or we have a PITR request for it. Since we
540 * don't yet have the insert lock, forcePageWrites could change under us,
541 * but we'll recheck it once we have the lock.
543 doPageWrites = fullPageWrites || Insert->forcePageWrites;
545 INIT_CRC32(rdata_crc);
549 if (rdt->buffer == InvalidBuffer)
551 /* Simple data, just include it */
553 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
557 /* Find info for buffer */
558 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
560 if (rdt->buffer == dtbuf[i])
562 /* Buffer already referenced by earlier chain item */
568 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
572 if (dtbuf[i] == InvalidBuffer)
574 /* OK, put it in this slot */
575 dtbuf[i] = rdt->buffer;
576 if (XLogCheckBuffer(rdt, doPageWrites,
577 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
585 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
590 if (i >= XLR_MAX_BKP_BLOCKS)
591 elog(PANIC, "can backup at most %d blocks per xlog record",
594 /* Break out of loop when rdt points to last chain item */
595 if (rdt->next == NULL)
601 * Now add the backup block headers and data into the CRC
603 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
607 BkpBlock *bkpb = &(dtbuf_xlg[i]);
610 COMP_CRC32(rdata_crc,
613 page = (char *) BufferGetBlock(dtbuf[i]);
614 if (bkpb->hole_length == 0)
616 COMP_CRC32(rdata_crc,
622 /* must skip the hole */
623 COMP_CRC32(rdata_crc,
626 COMP_CRC32(rdata_crc,
627 page + (bkpb->hole_offset + bkpb->hole_length),
628 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
634 * NOTE: We disallow len == 0 because it provides a useful bit of extra
635 * error checking in ReadRecord. This means that all callers of
636 * XLogInsert must supply at least some not-in-a-buffer data. However, we
637 * make an exception for XLOG SWITCH records because we don't want them to
638 * ever cross a segment boundary.
640 if (len == 0 && !isLogSwitch)
641 elog(PANIC, "invalid xlog record length %u", len);
643 START_CRIT_SECTION();
645 /* Now wait to get insert lock */
646 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
649 * Check to see if my RedoRecPtr is out of date. If so, may have to go
650 * back and recompute everything. This can only happen just after a
651 * checkpoint, so it's better to be slow in this case and fast otherwise.
653 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
654 * affect the contents of the XLOG record, so we'll update our local copy
655 * but not force a recomputation.
657 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
659 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
660 RedoRecPtr = Insert->RedoRecPtr;
664 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
666 if (dtbuf[i] == InvalidBuffer)
668 if (dtbuf_bkp[i] == false &&
669 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
672 * Oops, this buffer now needs to be backed up, but we
673 * didn't think so above. Start over.
675 LWLockRelease(WALInsertLock);
684 * Also check to see if forcePageWrites was just turned on; if we weren't
685 * already doing full-page writes then go back and recompute. (If it was
686 * just turned off, we could recompute the record without full pages, but
687 * we choose not to bother.)
689 if (Insert->forcePageWrites && !doPageWrites)
691 /* Oops, must redo it with full-page data */
692 LWLockRelease(WALInsertLock);
698 * Make additional rdata chain entries for the backup blocks, so that we
699 * don't need to special-case them in the write loop. Note that we have
700 * now irrevocably changed the input rdata chain. At the exit of this
701 * loop, write_len includes the backup block data.
703 * Also set the appropriate info bits to show which buffers were backed
704 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
705 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
708 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
716 info |= XLR_SET_BKP_BLOCK(i);
718 bkpb = &(dtbuf_xlg[i]);
719 page = (char *) BufferGetBlock(dtbuf[i]);
721 rdt->next = &(dtbuf_rdt1[i]);
724 rdt->data = (char *) bkpb;
725 rdt->len = sizeof(BkpBlock);
726 write_len += sizeof(BkpBlock);
728 rdt->next = &(dtbuf_rdt2[i]);
731 if (bkpb->hole_length == 0)
740 /* must skip the hole */
742 rdt->len = bkpb->hole_offset;
743 write_len += bkpb->hole_offset;
745 rdt->next = &(dtbuf_rdt3[i]);
748 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
749 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
750 write_len += rdt->len;
756 * If we backed up any full blocks and online backup is not in progress,
757 * mark the backup blocks as removable. This allows the WAL archiver to
758 * know whether it is safe to compress archived WAL data by transforming
759 * full-block records into the non-full-block format.
761 * Note: we could just set the flag whenever !forcePageWrites, but
762 * defining it like this leaves the info bit free for some potential
763 * other use in records without any backup blocks.
765 if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
766 info |= XLR_BKP_REMOVABLE;
769 * If there isn't enough space on the current XLOG page for a record
770 * header, advance to the next page (leaving the unused space as zeroes).
773 freespace = INSERT_FREESPACE(Insert);
774 if (freespace < SizeOfXLogRecord)
776 updrqst = AdvanceXLInsertBuffer(false);
777 freespace = INSERT_FREESPACE(Insert);
780 /* Compute record's XLOG location */
781 curridx = Insert->curridx;
782 INSERT_RECPTR(RecPtr, Insert, curridx);
785 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
786 * segment, we need not insert it (and don't want to because we'd like
787 * consecutive switch requests to be no-ops). Instead, make sure
788 * everything is written and flushed through the end of the prior segment,
789 * and return the prior segment's end address.
792 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
794 /* We can release insert lock immediately */
795 LWLockRelease(WALInsertLock);
797 RecPtr.xrecoff -= SizeOfXLogLongPHD;
798 if (RecPtr.xrecoff == 0)
800 /* crossing a logid boundary */
802 RecPtr.xrecoff = XLogFileSize;
805 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
806 LogwrtResult = XLogCtl->Write.LogwrtResult;
807 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
809 XLogwrtRqst FlushRqst;
811 FlushRqst.Write = RecPtr;
812 FlushRqst.Flush = RecPtr;
813 XLogWrite(FlushRqst, false, false);
815 LWLockRelease(WALWriteLock);
822 /* Insert record header */
824 record = (XLogRecord *) Insert->currpos;
825 record->xl_prev = Insert->PrevRecord;
826 record->xl_xid = GetCurrentTransactionIdIfAny();
827 record->xl_tot_len = SizeOfXLogRecord + write_len;
828 record->xl_len = len; /* doesn't include backup blocks */
829 record->xl_info = info;
830 record->xl_rmid = rmid;
832 /* Now we can finish computing the record's CRC */
833 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
834 SizeOfXLogRecord - sizeof(pg_crc32));
835 FIN_CRC32(rdata_crc);
836 record->xl_crc = rdata_crc;
843 initStringInfo(&buf);
844 appendStringInfo(&buf, "INSERT @ %X/%X: ",
845 RecPtr.xlogid, RecPtr.xrecoff);
846 xlog_outrec(&buf, record);
847 if (rdata->data != NULL)
849 appendStringInfo(&buf, " - ");
850 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
852 elog(LOG, "%s", buf.data);
857 /* Record begin of record in appropriate places */
859 MyLastRecPtr = RecPtr;
860 ProcLastRecPtr = RecPtr;
861 Insert->PrevRecord = RecPtr;
862 MyXactMadeXLogEntry = true;
864 Insert->currpos += SizeOfXLogRecord;
865 freespace -= SizeOfXLogRecord;
868 * Append the data, including backup blocks if any
872 while (rdata->data == NULL)
877 if (rdata->len > freespace)
879 memcpy(Insert->currpos, rdata->data, freespace);
880 rdata->data += freespace;
881 rdata->len -= freespace;
882 write_len -= freespace;
886 memcpy(Insert->currpos, rdata->data, rdata->len);
887 freespace -= rdata->len;
888 write_len -= rdata->len;
889 Insert->currpos += rdata->len;
895 /* Use next buffer */
896 updrqst = AdvanceXLInsertBuffer(false);
897 curridx = Insert->curridx;
898 /* Insert cont-record header */
899 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
900 contrecord = (XLogContRecord *) Insert->currpos;
901 contrecord->xl_rem_len = write_len;
902 Insert->currpos += SizeOfXLogContRecord;
903 freespace = INSERT_FREESPACE(Insert);
906 /* Ensure next record will be properly aligned */
907 Insert->currpos = (char *) Insert->currpage +
908 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
909 freespace = INSERT_FREESPACE(Insert);
912 * The recptr I return is the beginning of the *next* record. This will be
913 * stored as LSN for changed data pages...
915 INSERT_RECPTR(RecPtr, Insert, curridx);
918 * If the record is an XLOG_SWITCH, we must now write and flush all the
919 * existing data, and then forcibly advance to the start of the next
920 * segment. It's not good to do this I/O while holding the insert lock,
921 * but there seems too much risk of confusion if we try to release the
922 * lock sooner. Fortunately xlog switch needn't be a high-performance
923 * operation anyway...
927 XLogCtlWrite *Write = &XLogCtl->Write;
928 XLogwrtRqst FlushRqst;
929 XLogRecPtr OldSegEnd;
931 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
934 * Flush through the end of the page containing XLOG_SWITCH, and
935 * perform end-of-segment actions (eg, notifying archiver).
937 WriteRqst = XLogCtl->xlblocks[curridx];
938 FlushRqst.Write = WriteRqst;
939 FlushRqst.Flush = WriteRqst;
940 XLogWrite(FlushRqst, false, true);
942 /* Set up the next buffer as first page of next segment */
943 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
944 (void) AdvanceXLInsertBuffer(true);
946 /* There should be no unwritten data */
947 curridx = Insert->curridx;
948 Assert(curridx == Write->curridx);
950 /* Compute end address of old segment */
951 OldSegEnd = XLogCtl->xlblocks[curridx];
952 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
953 if (OldSegEnd.xrecoff == 0)
955 /* crossing a logid boundary */
956 OldSegEnd.xlogid -= 1;
957 OldSegEnd.xrecoff = XLogFileSize;
960 /* Make it look like we've written and synced all of old segment */
961 LogwrtResult.Write = OldSegEnd;
962 LogwrtResult.Flush = OldSegEnd;
965 * Update shared-memory status --- this code should match XLogWrite
968 /* use volatile pointer to prevent code rearrangement */
969 volatile XLogCtlData *xlogctl = XLogCtl;
971 SpinLockAcquire(&xlogctl->info_lck);
972 xlogctl->LogwrtResult = LogwrtResult;
973 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
974 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
975 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
976 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
977 SpinLockRelease(&xlogctl->info_lck);
980 Write->LogwrtResult = LogwrtResult;
982 LWLockRelease(WALWriteLock);
984 updrqst = false; /* done already */
988 /* normal case, ie not xlog switch */
990 /* Need to update shared LogwrtRqst if some block was filled up */
991 if (freespace < SizeOfXLogRecord)
993 /* curridx is filled and available for writing out */
998 /* if updrqst already set, write through end of previous buf */
999 curridx = PrevBufIdx(curridx);
1001 WriteRqst = XLogCtl->xlblocks[curridx];
1004 LWLockRelease(WALInsertLock);
1008 /* use volatile pointer to prevent code rearrangement */
1009 volatile XLogCtlData *xlogctl = XLogCtl;
1011 SpinLockAcquire(&xlogctl->info_lck);
1012 /* advance global request to include new block(s) */
1013 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
1014 xlogctl->LogwrtRqst.Write = WriteRqst;
1015 /* update local result copy while I have the chance */
1016 LogwrtResult = xlogctl->LogwrtResult;
1017 SpinLockRelease(&xlogctl->info_lck);
1020 ProcLastRecEnd = RecPtr;
1028 * Determine whether the buffer referenced by an XLogRecData item has to
1029 * be backed up, and if so fill a BkpBlock struct for it. In any case
1030 * save the buffer's LSN at *lsn.
1033 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1034 XLogRecPtr *lsn, BkpBlock *bkpb)
1038 page = (PageHeader) BufferGetBlock(rdata->buffer);
1041 * XXX We assume page LSN is first data on *every* page that can be passed
1042 * to XLogInsert, whether it otherwise has the standard page layout or
1045 *lsn = page->pd_lsn;
1048 XLByteLE(page->pd_lsn, RedoRecPtr))
1051 * The page needs to be backed up, so set up *bkpb
1053 bkpb->node = BufferGetFileNode(rdata->buffer);
1054 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1056 if (rdata->buffer_std)
1058 /* Assume we can omit data between pd_lower and pd_upper */
1059 uint16 lower = page->pd_lower;
1060 uint16 upper = page->pd_upper;
1062 if (lower >= SizeOfPageHeaderData &&
1066 bkpb->hole_offset = lower;
1067 bkpb->hole_length = upper - lower;
1071 /* No "hole" to compress out */
1072 bkpb->hole_offset = 0;
1073 bkpb->hole_length = 0;
1078 /* Not a standard page header, don't try to eliminate "hole" */
1079 bkpb->hole_offset = 0;
1080 bkpb->hole_length = 0;
1083 return true; /* buffer requires backup */
1086 return false; /* buffer does not need to be backed up */
1092 * Create an archive notification file
1094 * The name of the notification file is the message that will be picked up
1095 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1096 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1097 * then when complete, rename it to 0000000100000001000000C6.done
1100 XLogArchiveNotify(const char *xlog)
1102 char archiveStatusPath[MAXPGPATH];
1105 /* insert an otherwise empty file called <XLOG>.ready */
1106 StatusFilePath(archiveStatusPath, xlog, ".ready");
1107 fd = AllocateFile(archiveStatusPath, "w");
1111 (errcode_for_file_access(),
1112 errmsg("could not create archive status file \"%s\": %m",
1113 archiveStatusPath)));
1119 (errcode_for_file_access(),
1120 errmsg("could not write archive status file \"%s\": %m",
1121 archiveStatusPath)));
1125 /* Notify archiver that it's got something to do */
1126 if (IsUnderPostmaster)
1127 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1131 * Convenience routine to notify using log/seg representation of filename
1134 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1136 char xlog[MAXFNAMELEN];
1138 XLogFileName(xlog, ThisTimeLineID, log, seg);
1139 XLogArchiveNotify(xlog);
1143 * XLogArchiveCheckDone
1145 * This is called when we are ready to delete or recycle an old XLOG segment
1146 * file or backup history file. If it is okay to delete it then return true.
1147 * If it is not time to delete it, make sure a .ready file exists, and return
1150 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1151 * then return false; else create <XLOG>.ready and return false.
1153 * The reason we do things this way is so that if the original attempt to
1154 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1157 XLogArchiveCheckDone(const char *xlog)
1159 char archiveStatusPath[MAXPGPATH];
1160 struct stat stat_buf;
1162 /* Always deletable if archiving is off */
1163 if (!XLogArchivingActive())
1166 /* First check for .done --- this means archiver is done with it */
1167 StatusFilePath(archiveStatusPath, xlog, ".done");
1168 if (stat(archiveStatusPath, &stat_buf) == 0)
1171 /* check for .ready --- this means archiver is still busy with it */
1172 StatusFilePath(archiveStatusPath, xlog, ".ready");
1173 if (stat(archiveStatusPath, &stat_buf) == 0)
1176 /* Race condition --- maybe archiver just finished, so recheck */
1177 StatusFilePath(archiveStatusPath, xlog, ".done");
1178 if (stat(archiveStatusPath, &stat_buf) == 0)
1181 /* Retry creation of the .ready file */
1182 XLogArchiveNotify(xlog);
1187 * XLogArchiveCleanup
1189 * Cleanup archive notification file(s) for a particular xlog segment
1192 XLogArchiveCleanup(const char *xlog)
1194 char archiveStatusPath[MAXPGPATH];
1196 /* Remove the .done file */
1197 StatusFilePath(archiveStatusPath, xlog, ".done");
1198 unlink(archiveStatusPath);
1199 /* should we complain about failure? */
1201 /* Remove the .ready file if present --- normally it shouldn't be */
1202 StatusFilePath(archiveStatusPath, xlog, ".ready");
1203 unlink(archiveStatusPath);
1204 /* should we complain about failure? */
1208 * Advance the Insert state to the next buffer page, writing out the next
1209 * buffer if it still contains unwritten data.
1211 * If new_segment is TRUE then we set up the next buffer page as the first
1212 * page of the next xlog segment file, possibly but not usually the next
1213 * consecutive file page.
1215 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1216 * just-filled page. If we can do this for free (without an extra lock),
1217 * we do so here. Otherwise the caller must do it. We return TRUE if the
1218 * request update still needs to be done, FALSE if we did it internally.
1220 * Must be called with WALInsertLock held.
1223 AdvanceXLInsertBuffer(bool new_segment)
1225 XLogCtlInsert *Insert = &XLogCtl->Insert;
1226 XLogCtlWrite *Write = &XLogCtl->Write;
1227 int nextidx = NextBufIdx(Insert->curridx);
1228 bool update_needed = true;
1229 XLogRecPtr OldPageRqstPtr;
1230 XLogwrtRqst WriteRqst;
1231 XLogRecPtr NewPageEndPtr;
1232 XLogPageHeader NewPage;
1234 /* Use Insert->LogwrtResult copy if it's more fresh */
1235 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1236 LogwrtResult = Insert->LogwrtResult;
1239 * Get ending-offset of the buffer page we need to replace (this may be
1240 * zero if the buffer hasn't been used yet). Fall through if it's already
1243 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1244 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1246 /* nope, got work to do... */
1247 XLogRecPtr FinishedPageRqstPtr;
1249 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1251 /* Before waiting, get info_lck and update LogwrtResult */
1253 /* use volatile pointer to prevent code rearrangement */
1254 volatile XLogCtlData *xlogctl = XLogCtl;
1256 SpinLockAcquire(&xlogctl->info_lck);
1257 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1258 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1259 LogwrtResult = xlogctl->LogwrtResult;
1260 SpinLockRelease(&xlogctl->info_lck);
1263 update_needed = false; /* Did the shared-request update */
1265 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1267 /* OK, someone wrote it already */
1268 Insert->LogwrtResult = LogwrtResult;
1272 /* Must acquire write lock */
1273 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1274 LogwrtResult = Write->LogwrtResult;
1275 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1277 /* OK, someone wrote it already */
1278 LWLockRelease(WALWriteLock);
1279 Insert->LogwrtResult = LogwrtResult;
1284 * Have to write buffers while holding insert lock. This is
1285 * not good, so only write as much as we absolutely must.
1287 WriteRqst.Write = OldPageRqstPtr;
1288 WriteRqst.Flush.xlogid = 0;
1289 WriteRqst.Flush.xrecoff = 0;
1290 XLogWrite(WriteRqst, false, false);
1291 LWLockRelease(WALWriteLock);
1292 Insert->LogwrtResult = LogwrtResult;
1298 * Now the next buffer slot is free and we can set it up to be the next
1301 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1305 /* force it to a segment start point */
1306 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1307 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1310 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1312 /* crossing a logid boundary */
1313 NewPageEndPtr.xlogid += 1;
1314 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1317 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1318 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1319 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1321 Insert->curridx = nextidx;
1322 Insert->currpage = NewPage;
1324 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1327 * Be sure to re-zero the buffer so that bytes beyond what we've written
1328 * will look like zeroes and not valid XLOG records...
1330 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1333 * Fill the new page's header
1335 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1337 /* NewPage->xlp_info = 0; */ /* done by memset */
1338 NewPage ->xlp_tli = ThisTimeLineID;
1339 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1340 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1343 * If first page of an XLOG segment file, make it a long header.
1345 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1347 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1349 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1350 NewLongPage->xlp_seg_size = XLogSegSize;
1351 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1352 NewPage ->xlp_info |= XLP_LONG_HEADER;
1354 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1357 return update_needed;
1361 * Write and/or fsync the log at least as far as WriteRqst indicates.
1363 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1364 * may stop at any convenient boundary (such as a cache or logfile boundary).
1365 * This option allows us to avoid uselessly issuing multiple writes when a
1366 * single one would do.
1368 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1369 * perform end-of-segment actions after writing the last page, even if
1370 * it's not physically the end of its segment. (NB: this will work properly
1371 * only if caller specifies WriteRqst == page-end and flexible == false,
1372 * and there is some data to write.)
1374 * Must be called with WALWriteLock held.
1377 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1379 XLogCtlWrite *Write = &XLogCtl->Write;
1381 bool last_iteration;
1389 /* We should always be inside a critical section here */
1390 Assert(CritSectionCount > 0);
1393 * Update local LogwrtResult (caller probably did this already, but...)
1395 LogwrtResult = Write->LogwrtResult;
1398 * Since successive pages in the xlog cache are consecutively allocated,
1399 * we can usually gather multiple pages together and issue just one
1400 * write() call. npages is the number of pages we have determined can be
1401 * written together; startidx is the cache block index of the first one,
1402 * and startoffset is the file offset at which it should go. The latter
1403 * two variables are only valid when npages > 0, but we must initialize
1404 * all of them to keep the compiler quiet.
1411 * Within the loop, curridx is the cache block index of the page to
1412 * consider writing. We advance Write->curridx only after successfully
1413 * writing pages. (Right now, this refinement is useless since we are
1414 * going to PANIC if any error occurs anyway; but someday it may come in
1417 curridx = Write->curridx;
1419 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1422 * Make sure we're not ahead of the insert process. This could happen
1423 * if we're passed a bogus WriteRqst.Write that is past the end of the
1424 * last page that's been initialized by AdvanceXLInsertBuffer.
1426 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1427 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1428 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1429 XLogCtl->xlblocks[curridx].xlogid,
1430 XLogCtl->xlblocks[curridx].xrecoff);
1432 /* Advance LogwrtResult.Write to end of current buffer page */
1433 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1434 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1436 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1439 * Switch to new logfile segment. We cannot have any pending
1440 * pages here (since we dump what we have at segment end).
1442 Assert(npages == 0);
1443 if (openLogFile >= 0)
1445 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1447 /* create/use new log file */
1448 use_existent = true;
1449 openLogFile = XLogFileInit(openLogId, openLogSeg,
1450 &use_existent, true);
1454 /* Make sure we have the current logfile open */
1455 if (openLogFile < 0)
1457 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1458 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1462 /* Add current page to the set of pending pages-to-dump */
1465 /* first of group */
1467 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1472 * Dump the set if this will be the last loop iteration, or if we are
1473 * at the last page of the cache area (since the next page won't be
1474 * contiguous in memory), or if we are at the end of the logfile
1477 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1479 finishing_seg = !ispartialpage &&
1480 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1482 if (last_iteration ||
1483 curridx == XLogCtl->XLogCacheBlck ||
1489 /* Need to seek in the file? */
1490 if (openLogOff != startoffset)
1492 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1494 (errcode_for_file_access(),
1495 errmsg("could not seek in log file %u, "
1496 "segment %u to offset %u: %m",
1497 openLogId, openLogSeg, startoffset)));
1498 openLogOff = startoffset;
1501 /* OK to write the page(s) */
1502 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1503 nbytes = npages * (Size) XLOG_BLCKSZ;
1505 if (write(openLogFile, from, nbytes) != nbytes)
1507 /* if write didn't set errno, assume no disk space */
1511 (errcode_for_file_access(),
1512 errmsg("could not write to log file %u, segment %u "
1513 "at offset %u, length %lu: %m",
1514 openLogId, openLogSeg,
1515 openLogOff, (unsigned long) nbytes)));
1518 /* Update state for write */
1519 openLogOff += nbytes;
1520 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1524 * If we just wrote the whole last page of a logfile segment,
1525 * fsync the segment immediately. This avoids having to go back
1526 * and re-open prior segments when an fsync request comes along
1527 * later. Doing it here ensures that one and only one backend will
1528 * perform this fsync.
1530 * We also do this if this is the last page written for an xlog
1533 * This is also the right place to notify the Archiver that the
1534 * segment is ready to copy to archival storage, and to update the
1535 * timer for archive_timeout, and to signal for a checkpoint if
1536 * too many logfile segments have been used since the last
1539 if (finishing_seg || (xlog_switch && last_iteration))
1542 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1544 if (XLogArchivingActive())
1545 XLogArchiveNotifySeg(openLogId, openLogSeg);
1547 Write->lastSegSwitchTime = time(NULL);
1550 * Signal bgwriter to start a checkpoint if we've consumed too
1551 * much xlog since the last one. (We look at local copy of
1552 * RedoRecPtr which might be a little out of date, but should
1553 * be close enough for this purpose.)
1555 * A straight computation of segment number could overflow 32
1556 * bits. Rather than assuming we have working 64-bit
1557 * arithmetic, we compare the highest-order bits separately,
1558 * and force a checkpoint immediately when they change.
1560 if (IsUnderPostmaster)
1564 uint32 old_highbits,
1567 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1568 (RedoRecPtr.xrecoff / XLogSegSize);
1569 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1570 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile +
1572 new_highbits = openLogId / XLogSegSize;
1573 if (new_highbits != old_highbits ||
1574 new_segno >= old_segno + (uint32) (CheckPointSegments-1))
1575 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1582 /* Only asked to write a partial page */
1583 LogwrtResult.Write = WriteRqst.Write;
1586 curridx = NextBufIdx(curridx);
1588 /* If flexible, break out of loop as soon as we wrote something */
1589 if (flexible && npages == 0)
1593 Assert(npages == 0);
1594 Assert(curridx == Write->curridx);
1597 * If asked to flush, do so
1599 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1600 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1603 * Could get here without iterating above loop, in which case we might
1604 * have no open file or the wrong one. However, we do not need to
1605 * fsync more than one file.
1607 if (sync_method != SYNC_METHOD_OPEN)
1609 if (openLogFile >= 0 &&
1610 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1612 if (openLogFile < 0)
1614 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1615 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1620 LogwrtResult.Flush = LogwrtResult.Write;
1624 * Update shared-memory status
1626 * We make sure that the shared 'request' values do not fall behind the
1627 * 'result' values. This is not absolutely essential, but it saves some
1628 * code in a couple of places.
1631 /* use volatile pointer to prevent code rearrangement */
1632 volatile XLogCtlData *xlogctl = XLogCtl;
1634 SpinLockAcquire(&xlogctl->info_lck);
1635 xlogctl->LogwrtResult = LogwrtResult;
1636 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1637 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1638 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1639 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1640 SpinLockRelease(&xlogctl->info_lck);
1643 Write->LogwrtResult = LogwrtResult;
1647 * Ensure that all XLOG data through the given position is flushed to disk.
1649 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1650 * already held, and we try to avoid acquiring it if possible.
1653 XLogFlush(XLogRecPtr record)
1655 XLogRecPtr WriteRqstPtr;
1656 XLogwrtRqst WriteRqst;
1658 /* Disabled during REDO */
1662 /* Quick exit if already known flushed */
1663 if (XLByteLE(record, LogwrtResult.Flush))
1668 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1669 record.xlogid, record.xrecoff,
1670 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1671 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1674 START_CRIT_SECTION();
1677 * Since fsync is usually a horribly expensive operation, we try to
1678 * piggyback as much data as we can on each fsync: if we see any more data
1679 * entered into the xlog buffer, we'll write and fsync that too, so that
1680 * the final value of LogwrtResult.Flush is as large as possible. This
1681 * gives us some chance of avoiding another fsync immediately after.
1684 /* initialize to given target; may increase below */
1685 WriteRqstPtr = record;
1687 /* read LogwrtResult and update local state */
1689 /* use volatile pointer to prevent code rearrangement */
1690 volatile XLogCtlData *xlogctl = XLogCtl;
1692 SpinLockAcquire(&xlogctl->info_lck);
1693 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1694 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1695 LogwrtResult = xlogctl->LogwrtResult;
1696 SpinLockRelease(&xlogctl->info_lck);
1700 if (!XLByteLE(record, LogwrtResult.Flush))
1702 /* now wait for the write lock */
1703 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1704 LogwrtResult = XLogCtl->Write.LogwrtResult;
1705 if (!XLByteLE(record, LogwrtResult.Flush))
1707 /* try to write/flush later additions to XLOG as well */
1708 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1710 XLogCtlInsert *Insert = &XLogCtl->Insert;
1711 uint32 freespace = INSERT_FREESPACE(Insert);
1713 if (freespace < SizeOfXLogRecord) /* buffer is full */
1714 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1717 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1718 WriteRqstPtr.xrecoff -= freespace;
1720 LWLockRelease(WALInsertLock);
1721 WriteRqst.Write = WriteRqstPtr;
1722 WriteRqst.Flush = WriteRqstPtr;
1726 WriteRqst.Write = WriteRqstPtr;
1727 WriteRqst.Flush = record;
1729 XLogWrite(WriteRqst, false, false);
1731 LWLockRelease(WALWriteLock);
1737 * If we still haven't flushed to the request point then we have a
1738 * problem; most likely, the requested flush point is past end of XLOG.
1739 * This has been seen to occur when a disk page has a corrupted LSN.
1741 * Formerly we treated this as a PANIC condition, but that hurts the
1742 * system's robustness rather than helping it: we do not want to take down
1743 * the whole system due to corruption on one data page. In particular, if
1744 * the bad page is encountered again during recovery then we would be
1745 * unable to restart the database at all! (This scenario has actually
1746 * happened in the field several times with 7.1 releases. Note that we
1747 * cannot get here while InRedo is true, but if the bad page is brought in
1748 * and marked dirty during recovery then CreateCheckPoint will try to
1749 * flush it at the end of recovery.)
1751 * The current approach is to ERROR under normal conditions, but only
1752 * WARNING during recovery, so that the system can be brought up even if
1753 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1754 * be promoted to PANIC since xact.c calls this routine inside a critical
1755 * section. However, calls from bufmgr.c are not within critical sections
1756 * and so we will not force a restart for a bad LSN on a data page.
1758 if (XLByteLT(LogwrtResult.Flush, record))
1759 elog(InRecovery ? WARNING : ERROR,
1760 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1761 record.xlogid, record.xrecoff,
1762 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1766 * Flush xlog, but without specifying exactly where to flush to.
1768 * We normally flush only completed blocks; but if there is nothing to do on
1769 * that basis, we check for unflushed async commits in the current incomplete
1770 * block, and flush through the latest one of those. Thus, if async commits
1771 * are not being used, we will flush complete blocks only. We can guarantee
1772 * that async commits reach disk after at most three cycles; normally only
1773 * one or two. (We allow XLogWrite to write "flexibly", meaning it can stop
1774 * at the end of the buffer ring; this makes a difference only with very high
1775 * load or long wal_writer_delay, but imposes one extra cycle for the worst
1776 * case for async commits.)
1778 * This routine is invoked periodically by the background walwriter process.
1781 XLogBackgroundFlush(void)
1783 XLogRecPtr WriteRqstPtr;
1784 bool flexible = true;
1786 /* read LogwrtResult and update local state */
1788 /* use volatile pointer to prevent code rearrangement */
1789 volatile XLogCtlData *xlogctl = XLogCtl;
1791 SpinLockAcquire(&xlogctl->info_lck);
1792 LogwrtResult = xlogctl->LogwrtResult;
1793 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1794 SpinLockRelease(&xlogctl->info_lck);
1797 /* back off to last completed page boundary */
1798 WriteRqstPtr.xrecoff -= WriteRqstPtr.xrecoff % XLOG_BLCKSZ;
1800 #ifdef NOT_YET /* async commit patch is still to come */
1801 /* if we have already flushed that far, consider async commit records */
1802 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1804 /* use volatile pointer to prevent code rearrangement */
1805 volatile XLogCtlData *xlogctl = XLogCtl;
1807 SpinLockAcquire(&xlogctl->async_commit_lck);
1808 WriteRqstPtr = xlogctl->asyncCommitLSN;
1809 SpinLockRelease(&xlogctl->async_commit_lck);
1810 flexible = false; /* ensure it all gets written */
1814 /* Done if already known flushed */
1815 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1820 elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
1821 WriteRqstPtr.xlogid, WriteRqstPtr.xrecoff,
1822 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1823 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1826 START_CRIT_SECTION();
1828 /* now wait for the write lock */
1829 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1830 LogwrtResult = XLogCtl->Write.LogwrtResult;
1831 if (!XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1833 XLogwrtRqst WriteRqst;
1835 WriteRqst.Write = WriteRqstPtr;
1836 WriteRqst.Flush = WriteRqstPtr;
1837 XLogWrite(WriteRqst, flexible, false);
1839 LWLockRelease(WALWriteLock);
1845 * Test whether XLOG data has been flushed up to (at least) the given position.
1847 * Returns true if a flush is still needed. (It may be that someone else
1848 * is already in process of flushing that far, however.)
1851 XLogNeedsFlush(XLogRecPtr record)
1853 /* Quick exit if already known flushed */
1854 if (XLByteLE(record, LogwrtResult.Flush))
1857 /* read LogwrtResult and update local state */
1859 /* use volatile pointer to prevent code rearrangement */
1860 volatile XLogCtlData *xlogctl = XLogCtl;
1862 SpinLockAcquire(&xlogctl->info_lck);
1863 LogwrtResult = xlogctl->LogwrtResult;
1864 SpinLockRelease(&xlogctl->info_lck);
1868 if (XLByteLE(record, LogwrtResult.Flush))
1875 * Create a new XLOG file segment, or open a pre-existing one.
1877 * log, seg: identify segment to be created/opened.
1879 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1880 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1883 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1884 * place. This should be TRUE except during bootstrap log creation. The
1885 * caller must *not* hold the lock at call.
1887 * Returns FD of opened file.
1889 * Note: errors here are ERROR not PANIC because we might or might not be
1890 * inside a critical section (eg, during checkpoint there is no reason to
1891 * take down the system on failure). They will promote to PANIC if we are
1892 * in a critical section.
1895 XLogFileInit(uint32 log, uint32 seg,
1896 bool *use_existent, bool use_lock)
1898 char path[MAXPGPATH];
1899 char tmppath[MAXPGPATH];
1901 uint32 installed_log;
1902 uint32 installed_seg;
1907 XLogFilePath(path, ThisTimeLineID, log, seg);
1910 * Try to use existent file (checkpoint maker may have created it already)
1914 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1918 if (errno != ENOENT)
1920 (errcode_for_file_access(),
1921 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1929 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
1930 * another process is doing the same thing. If so, we will end up
1931 * pre-creating an extra log segment. That seems OK, and better than
1932 * holding the lock throughout this lengthy process.
1934 elog(DEBUG2, "creating and filling new WAL file");
1936 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1940 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1941 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1945 (errcode_for_file_access(),
1946 errmsg("could not create file \"%s\": %m", tmppath)));
1949 * Zero-fill the file. We have to do this the hard way to ensure that all
1950 * the file space has really been allocated --- on platforms that allow
1951 * "holes" in files, just seeking to the end doesn't allocate intermediate
1952 * space. This way, we know that we have all the space and (after the
1953 * fsync below) that all the indirect blocks are down on disk. Therefore,
1954 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
1957 * Note: palloc zbuffer, instead of just using a local char array, to
1958 * ensure it is reasonably well-aligned; this may save a few cycles
1959 * transferring data to the kernel.
1961 zbuffer = (char *) palloc0(XLOG_BLCKSZ);
1962 for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
1965 if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
1967 int save_errno = errno;
1970 * If we fail to make the file, delete it to release disk space
1973 /* if write didn't set errno, assume problem is no disk space */
1974 errno = save_errno ? save_errno : ENOSPC;
1977 (errcode_for_file_access(),
1978 errmsg("could not write to file \"%s\": %m", tmppath)));
1983 if (pg_fsync(fd) != 0)
1985 (errcode_for_file_access(),
1986 errmsg("could not fsync file \"%s\": %m", tmppath)));
1990 (errcode_for_file_access(),
1991 errmsg("could not close file \"%s\": %m", tmppath)));
1994 * Now move the segment into place with its final name.
1996 * If caller didn't want to use a pre-existing file, get rid of any
1997 * pre-existing file. Otherwise, cope with possibility that someone else
1998 * has created the file while we were filling ours: if so, use ours to
1999 * pre-create a future log segment.
2001 installed_log = log;
2002 installed_seg = seg;
2003 max_advance = XLOGfileslop;
2004 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
2005 *use_existent, &max_advance,
2008 /* No need for any more future segments... */
2012 elog(DEBUG2, "done creating and filling new WAL file");
2014 /* Set flag to tell caller there was no existent file */
2015 *use_existent = false;
2017 /* Now open original target segment (might not be file I just made) */
2018 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2022 (errcode_for_file_access(),
2023 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2030 * Create a new XLOG file segment by copying a pre-existing one.
2032 * log, seg: identify segment to be created.
2034 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
2035 * a different timeline)
2037 * Currently this is only used during recovery, and so there are no locking
2038 * considerations. But we should be just as tense as XLogFileInit to avoid
2039 * emplacing a bogus file.
2042 XLogFileCopy(uint32 log, uint32 seg,
2043 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
2045 char path[MAXPGPATH];
2046 char tmppath[MAXPGPATH];
2047 char buffer[XLOG_BLCKSZ];
2053 * Open the source file
2055 XLogFilePath(path, srcTLI, srclog, srcseg);
2056 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2059 (errcode_for_file_access(),
2060 errmsg("could not open file \"%s\": %m", path)));
2063 * Copy into a temp file name.
2065 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2069 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2070 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2074 (errcode_for_file_access(),
2075 errmsg("could not create file \"%s\": %m", tmppath)));
2078 * Do the data copying.
2080 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2083 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2087 (errcode_for_file_access(),
2088 errmsg("could not read file \"%s\": %m", path)));
2091 (errmsg("not enough data in file \"%s\"", path)));
2094 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2096 int save_errno = errno;
2099 * If we fail to make the file, delete it to release disk space
2102 /* if write didn't set errno, assume problem is no disk space */
2103 errno = save_errno ? save_errno : ENOSPC;
2106 (errcode_for_file_access(),
2107 errmsg("could not write to file \"%s\": %m", tmppath)));
2111 if (pg_fsync(fd) != 0)
2113 (errcode_for_file_access(),
2114 errmsg("could not fsync file \"%s\": %m", tmppath)));
2118 (errcode_for_file_access(),
2119 errmsg("could not close file \"%s\": %m", tmppath)));
2124 * Now move the segment into place with its final name.
2126 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2127 elog(ERROR, "InstallXLogFileSegment should not have failed");
2131 * Install a new XLOG segment file as a current or future log segment.
2133 * This is used both to install a newly-created segment (which has a temp
2134 * filename while it's being created) and to recycle an old segment.
2136 * *log, *seg: identify segment to install as (or first possible target).
2137 * When find_free is TRUE, these are modified on return to indicate the
2138 * actual installation location or last segment searched.
2140 * tmppath: initial name of file to install. It will be renamed into place.
2142 * find_free: if TRUE, install the new segment at the first empty log/seg
2143 * number at or after the passed numbers. If FALSE, install the new segment
2144 * exactly where specified, deleting any existing segment file there.
2146 * *max_advance: maximum number of log/seg slots to advance past the starting
2147 * point. Fail if no free slot is found in this range. On return, reduced
2148 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2149 * when find_free is FALSE.)
2151 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2152 * place. This should be TRUE except during bootstrap log creation. The
2153 * caller must *not* hold the lock at call.
2155 * Returns TRUE if file installed, FALSE if not installed because of
2156 * exceeding max_advance limit. On Windows, we also return FALSE if we
2157 * can't rename the file into place because someone's got it open.
2158 * (Any other kind of failure causes ereport().)
2161 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2162 bool find_free, int *max_advance,
2165 char path[MAXPGPATH];
2166 struct stat stat_buf;
2168 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2171 * We want to be sure that only one process does this at a time.
2174 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2178 /* Force installation: get rid of any pre-existing segment file */
2183 /* Find a free slot to put it in */
2184 while (stat(path, &stat_buf) == 0)
2186 if (*max_advance <= 0)
2188 /* Failed to find a free slot within specified range */
2190 LWLockRelease(ControlFileLock);
2193 NextLogSeg(*log, *seg);
2195 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2200 * Prefer link() to rename() here just to be really sure that we don't
2201 * overwrite an existing logfile. However, there shouldn't be one, so
2202 * rename() is an acceptable substitute except for the truly paranoid.
2204 #if HAVE_WORKING_LINK
2205 if (link(tmppath, path) < 0)
2207 (errcode_for_file_access(),
2208 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2209 tmppath, path, *log, *seg)));
2212 if (rename(tmppath, path) < 0)
2215 #if !defined(__CYGWIN__)
2216 if (GetLastError() == ERROR_ACCESS_DENIED)
2218 if (errno == EACCES)
2222 LWLockRelease(ControlFileLock);
2228 (errcode_for_file_access(),
2229 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2230 tmppath, path, *log, *seg)));
2235 LWLockRelease(ControlFileLock);
2241 * Open a pre-existing logfile segment for writing.
2244 XLogFileOpen(uint32 log, uint32 seg)
2246 char path[MAXPGPATH];
2249 XLogFilePath(path, ThisTimeLineID, log, seg);
2251 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2255 (errcode_for_file_access(),
2256 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2263 * Open a logfile segment for reading (during recovery).
2266 XLogFileRead(uint32 log, uint32 seg, int emode)
2268 char path[MAXPGPATH];
2269 char xlogfname[MAXFNAMELEN];
2274 * Loop looking for a suitable timeline ID: we might need to read any of
2275 * the timelines listed in expectedTLIs.
2277 * We expect curFileTLI on entry to be the TLI of the preceding file in
2278 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2279 * to go backwards; this prevents us from picking up the wrong file when a
2280 * parent timeline extends to higher segment numbers than the child we
2283 foreach(cell, expectedTLIs)
2285 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2287 if (tli < curFileTLI)
2288 break; /* don't bother looking at too-old TLIs */
2290 if (InArchiveRecovery)
2292 XLogFileName(xlogfname, tli, log, seg);
2293 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2298 XLogFilePath(path, tli, log, seg);
2300 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2307 if (errno != ENOENT) /* unexpected failure? */
2309 (errcode_for_file_access(),
2310 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2314 /* Couldn't find it. For simplicity, complain about front timeline */
2315 XLogFilePath(path, recoveryTargetTLI, log, seg);
2318 (errcode_for_file_access(),
2319 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2325 * Close the current logfile segment for writing.
2330 Assert(openLogFile >= 0);
2333 * posix_fadvise is problematic on many platforms: on older x86 Linux it
2334 * just dumps core, and there are reports of problems on PPC platforms as
2335 * well. The following is therefore disabled for the time being. We could
2336 * consider some kind of configure test to see if it's safe to use, but
2337 * since we lack hard evidence that there's any useful performance gain to
2338 * be had, spending time on that seems unprofitable for now.
2343 * WAL segment files will not be re-read in normal operation, so we advise
2344 * OS to release any cached pages. But do not do so if WAL archiving is
2345 * active, because archiver process could use the cache to read the WAL
2348 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
2349 * O_SYNC, and some platforms only have posix_fadvise().
2351 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2352 if (!XLogArchivingActive())
2353 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2355 #endif /* NOT_USED */
2357 if (close(openLogFile))
2359 (errcode_for_file_access(),
2360 errmsg("could not close log file %u, segment %u: %m",
2361 openLogId, openLogSeg)));
2366 * Attempt to retrieve the specified file from off-line archival storage.
2367 * If successful, fill "path" with its complete path (note that this will be
2368 * a temp file name that doesn't follow the normal naming convention), and
2371 * If not successful, fill "path" with the name of the normal on-line file
2372 * (which may or may not actually exist, but we'll try to use it), and return
2375 * For fixed-size files, the caller may pass the expected size as an
2376 * additional crosscheck on successful recovery. If the file size is not
2377 * known, set expectedSize = 0.
2380 RestoreArchivedFile(char *path, const char *xlogfname,
2381 const char *recovername, off_t expectedSize)
2383 char xlogpath[MAXPGPATH];
2384 char xlogRestoreCmd[MAXPGPATH];
2390 struct stat stat_buf;
2393 * When doing archive recovery, we always prefer an archived log file even
2394 * if a file of the same name exists in XLOGDIR. The reason is that the
2395 * file in XLOGDIR could be an old, un-filled or partly-filled version
2396 * that was copied and restored as part of backing up $PGDATA.
2398 * We could try to optimize this slightly by checking the local copy
2399 * lastchange timestamp against the archived copy, but we have no API to
2400 * do this, nor can we guarantee that the lastchange timestamp was
2401 * preserved correctly when we copied to archive. Our aim is robustness,
2402 * so we elect not to do this.
2404 * If we cannot obtain the log file from the archive, however, we will try
2405 * to use the XLOGDIR file if it exists. This is so that we can make use
2406 * of log segments that weren't yet transferred to the archive.
2408 * Notice that we don't actually overwrite any files when we copy back
2409 * from archive because the recoveryRestoreCommand may inadvertently
2410 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2411 * fallback to the segments remaining in current XLOGDIR later. The
2412 * copy-from-archive filename is always the same, ensuring that we don't
2413 * run out of disk space on long recoveries.
2415 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2418 * Make sure there is no existing file named recovername.
2420 if (stat(xlogpath, &stat_buf) != 0)
2422 if (errno != ENOENT)
2424 (errcode_for_file_access(),
2425 errmsg("could not stat file \"%s\": %m",
2430 if (unlink(xlogpath) != 0)
2432 (errcode_for_file_access(),
2433 errmsg("could not remove file \"%s\": %m",
2438 * construct the command to be executed
2440 dp = xlogRestoreCmd;
2441 endp = xlogRestoreCmd + MAXPGPATH - 1;
2444 for (sp = recoveryRestoreCommand; *sp; sp++)
2451 /* %p: relative path of target file */
2453 StrNCpy(dp, xlogpath, endp - dp);
2454 make_native_path(dp);
2458 /* %f: filename of desired file */
2460 StrNCpy(dp, xlogfname, endp - dp);
2464 /* convert %% to a single % */
2470 /* otherwise treat the % as not special */
2485 (errmsg_internal("executing restore command \"%s\"",
2489 * Copy xlog from archival storage to XLOGDIR
2491 rc = system(xlogRestoreCmd);
2495 * command apparently succeeded, but let's make sure the file is
2496 * really there now and has the correct size.
2498 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2499 * it, but is that too strong? We could try to plow ahead with a
2500 * local copy of the file ... but the problem is that there probably
2501 * isn't one, and we'd incorrectly conclude we've reached the end of
2502 * WAL and we're done recovering ...
2504 if (stat(xlogpath, &stat_buf) == 0)
2506 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2508 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2510 (unsigned long) stat_buf.st_size,
2511 (unsigned long) expectedSize)));
2515 (errmsg("restored log file \"%s\" from archive",
2517 strcpy(path, xlogpath);
2524 if (errno != ENOENT)
2526 (errcode_for_file_access(),
2527 errmsg("could not stat file \"%s\": %m",
2533 * Remember, we rollforward UNTIL the restore fails so failure here is
2534 * just part of the process... that makes it difficult to determine
2535 * whether the restore failed because there isn't an archive to restore,
2536 * or because the administrator has specified the restore program
2537 * incorrectly. We have to assume the former.
2539 * However, if the failure was due to any sort of signal, it's best to
2540 * punt and abort recovery. (If we "return false" here, upper levels
2541 * will assume that recovery is complete and start up the database!)
2542 * It's essential to abort on child SIGINT and SIGQUIT, because per spec
2543 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2544 * those it's a good bet we should have gotten it too. Aborting on other
2545 * signals such as SIGTERM seems a good idea as well.
2547 * Per the Single Unix Spec, shells report exit status > 128 when
2548 * a called command died on a signal. Also, 126 and 127 are used to
2549 * report problems such as an unfindable command; treat those as fatal
2552 signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;
2554 ereport(signaled ? FATAL : DEBUG2,
2555 (errmsg("could not restore file \"%s\" from archive: return code %d",
2559 * if an archived file is not available, there might still be a version of
2560 * this file in XLOGDIR, so return that as the filename to open.
2562 * In many recovery scenarios we expect this to fail also, but if so that
2563 * just means we've reached the end of WAL.
2565 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2570 * Preallocate log files beyond the specified log endpoint.
2572 * XXX this is currently extremely conservative, since it forces only one
2573 * future log segment to exist, and even that only if we are 75% done with
2574 * the current one. This is only appropriate for very low-WAL-volume systems.
2575 * High-volume systems will be OK once they've built up a sufficient set of
2576 * recycled log segments, but the startup transient is likely to include
2577 * a lot of segment creations by foreground processes, which is not so good.
2580 PreallocXlogFiles(XLogRecPtr endptr)
2587 XLByteToPrevSeg(endptr, _logId, _logSeg);
2588 if ((endptr.xrecoff - 1) % XLogSegSize >=
2589 (uint32) (0.75 * XLogSegSize))
2591 NextLogSeg(_logId, _logSeg);
2592 use_existent = true;
2593 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2596 CheckpointStats.ckpt_segs_added++;
2601 * Recycle or remove all log files older or equal to passed log/seg#
2603 * endptr is current (or recent) end of xlog; this is used to determine
2604 * whether we want to recycle rather than delete no-longer-wanted log files.
2607 RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
2613 struct dirent *xlde;
2614 char lastoff[MAXFNAMELEN];
2615 char path[MAXPGPATH];
2618 * Initialize info about where to try to recycle to. We allow recycling
2619 * segments up to XLOGfileslop segments beyond the current XLOG location.
2621 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2622 max_advance = XLOGfileslop;
2624 xldir = AllocateDir(XLOGDIR);
2627 (errcode_for_file_access(),
2628 errmsg("could not open transaction log directory \"%s\": %m",
2631 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2633 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2636 * We ignore the timeline part of the XLOG segment identifiers in
2637 * deciding whether a segment is still needed. This ensures that we
2638 * won't prematurely remove a segment from a parent timeline. We could
2639 * probably be a little more proactive about removing segments of
2640 * non-parent timelines, but that would be a whole lot more
2643 * We use the alphanumeric sorting property of the filenames to decide
2644 * which ones are earlier than the lastoff segment.
2646 if (strlen(xlde->d_name) == 24 &&
2647 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2648 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2650 if (XLogArchiveCheckDone(xlde->d_name))
2652 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2655 * Before deleting the file, see if it can be recycled as a
2656 * future log segment.
2658 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2663 (errmsg("recycled transaction log file \"%s\"",
2665 CheckpointStats.ckpt_segs_recycled++;
2666 /* Needn't recheck that slot on future iterations */
2667 if (max_advance > 0)
2669 NextLogSeg(endlogId, endlogSeg);
2675 /* No need for any more future segments... */
2677 (errmsg("removing transaction log file \"%s\"",
2680 CheckpointStats.ckpt_segs_removed++;
2683 XLogArchiveCleanup(xlde->d_name);
2692 * Remove previous backup history files. This also retries creation of
2693 * .ready files for any backup history files for which XLogArchiveNotify
2697 CleanupBackupHistory(void)
2700 struct dirent *xlde;
2701 char path[MAXPGPATH];
2703 xldir = AllocateDir(XLOGDIR);
2706 (errcode_for_file_access(),
2707 errmsg("could not open transaction log directory \"%s\": %m",
2710 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2712 if (strlen(xlde->d_name) > 24 &&
2713 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2714 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2717 if (XLogArchiveCheckDone(xlde->d_name))
2720 (errmsg("removing transaction log backup history file \"%s\"",
2722 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2724 XLogArchiveCleanup(xlde->d_name);
2733 * Restore the backup blocks present in an XLOG record, if any.
2735 * We assume all of the record has been read into memory at *record.
2737 * Note: when a backup block is available in XLOG, we restore it
2738 * unconditionally, even if the page in the database appears newer.
2739 * This is to protect ourselves against database pages that were partially
2740 * or incorrectly written during a crash. We assume that the XLOG data
2741 * must be good because it has passed a CRC check, while the database
2742 * page might not be. This will force us to replay all subsequent
2743 * modifications of the page that appear in XLOG, rather than possibly
2744 * ignoring them as already applied, but that's not a huge drawback.
2747 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2756 blk = (char *) XLogRecGetData(record) + record->xl_len;
2757 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2759 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2762 memcpy(&bkpb, blk, sizeof(BkpBlock));
2763 blk += sizeof(BkpBlock);
2765 reln = XLogOpenRelation(bkpb.node);
2766 buffer = XLogReadBuffer(reln, bkpb.block, true);
2767 Assert(BufferIsValid(buffer));
2768 page = (Page) BufferGetPage(buffer);
2770 if (bkpb.hole_length == 0)
2772 memcpy((char *) page, blk, BLCKSZ);
2776 /* must zero-fill the hole */
2777 MemSet((char *) page, 0, BLCKSZ);
2778 memcpy((char *) page, blk, bkpb.hole_offset);
2779 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2780 blk + bkpb.hole_offset,
2781 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2784 PageSetLSN(page, lsn);
2785 PageSetTLI(page, ThisTimeLineID);
2786 MarkBufferDirty(buffer);
2787 UnlockReleaseBuffer(buffer);
2789 blk += BLCKSZ - bkpb.hole_length;
2794 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2795 * record (other than to the minimal extent of computing the amount of
2796 * data to read in) until we've checked the CRCs.
2798 * We assume all of the record has been read into memory at *record.
2801 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2805 uint32 len = record->xl_len;
2809 /* First the rmgr data */
2811 COMP_CRC32(crc, XLogRecGetData(record), len);
2813 /* Add in the backup blocks, if any */
2814 blk = (char *) XLogRecGetData(record) + len;
2815 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2819 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2822 memcpy(&bkpb, blk, sizeof(BkpBlock));
2823 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2826 (errmsg("incorrect hole size in record at %X/%X",
2827 recptr.xlogid, recptr.xrecoff)));
2830 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2831 COMP_CRC32(crc, blk, blen);
2835 /* Check that xl_tot_len agrees with our calculation */
2836 if (blk != (char *) record + record->xl_tot_len)
2839 (errmsg("incorrect total length in record at %X/%X",
2840 recptr.xlogid, recptr.xrecoff)));
2844 /* Finally include the record header */
2845 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2846 SizeOfXLogRecord - sizeof(pg_crc32));
2849 if (!EQ_CRC32(record->xl_crc, crc))
2852 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2853 recptr.xlogid, recptr.xrecoff)));
2861 * Attempt to read an XLOG record.
2863 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2864 * try to read a record just after the last one previously read.
2866 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2867 * (emode must be either PANIC or LOG.)
2869 * The record is copied into readRecordBuf, so that on successful return,
2870 * the returned record pointer always points there.
2873 ReadRecord(XLogRecPtr *RecPtr, int emode)
2877 XLogRecPtr tmpRecPtr = EndRecPtr;
2878 bool randAccess = false;
2881 uint32 targetPageOff;
2882 uint32 targetRecOff;
2883 uint32 pageHeaderSize;
2885 if (readBuf == NULL)
2888 * First time through, permanently allocate readBuf. We do it this
2889 * way, rather than just making a static array, for two reasons: (1)
2890 * no need to waste the storage in most instantiations of the backend;
2891 * (2) a static char array isn't guaranteed to have any particular
2892 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2894 readBuf = (char *) malloc(XLOG_BLCKSZ);
2895 Assert(readBuf != NULL);
2900 RecPtr = &tmpRecPtr;
2901 /* fast case if next record is on same page */
2902 if (nextRecord != NULL)
2904 record = nextRecord;
2907 /* align old recptr to next page */
2908 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2909 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2910 if (tmpRecPtr.xrecoff >= XLogFileSize)
2912 (tmpRecPtr.xlogid)++;
2913 tmpRecPtr.xrecoff = 0;
2915 /* We will account for page header size below */
2919 if (!XRecOffIsValid(RecPtr->xrecoff))
2921 (errmsg("invalid record offset at %X/%X",
2922 RecPtr->xlogid, RecPtr->xrecoff)));
2925 * Since we are going to a random position in WAL, forget any prior
2926 * state about what timeline we were in, and allow it to be any
2927 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
2928 * to go backwards (but we can't reset that variable right here, since
2929 * we might not change files at all).
2931 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2932 randAccess = true; /* allow curFileTLI to go backwards too */
2935 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2940 XLByteToSeg(*RecPtr, readId, readSeg);
2943 /* Now it's okay to reset curFileTLI if random fetch */
2947 readFile = XLogFileRead(readId, readSeg, emode);
2949 goto next_record_is_invalid;
2952 * Whenever switching to a new WAL segment, we read the first page of
2953 * the file and validate its header, even if that's not where the
2954 * target record is. This is so that we can check the additional
2955 * identification info that is present in the first page's "long"
2959 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2962 (errcode_for_file_access(),
2963 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2964 readId, readSeg, readOff)));
2965 goto next_record_is_invalid;
2967 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2968 goto next_record_is_invalid;
2971 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2972 if (readOff != targetPageOff)
2974 readOff = targetPageOff;
2975 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2978 (errcode_for_file_access(),
2979 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2980 readId, readSeg, readOff)));
2981 goto next_record_is_invalid;
2983 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2986 (errcode_for_file_access(),
2987 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2988 readId, readSeg, readOff)));
2989 goto next_record_is_invalid;
2991 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2992 goto next_record_is_invalid;
2994 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2995 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
2996 if (targetRecOff == 0)
2999 * Can only get here in the continuing-from-prev-page case, because
3000 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
3001 * to skip over the new page's header.
3003 tmpRecPtr.xrecoff += pageHeaderSize;
3004 targetRecOff = pageHeaderSize;
3006 else if (targetRecOff < pageHeaderSize)
3009 (errmsg("invalid record offset at %X/%X",
3010 RecPtr->xlogid, RecPtr->xrecoff)));
3011 goto next_record_is_invalid;
3013 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3014 targetRecOff == pageHeaderSize)
3017 (errmsg("contrecord is requested by %X/%X",
3018 RecPtr->xlogid, RecPtr->xrecoff)));
3019 goto next_record_is_invalid;
3021 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3026 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
3029 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3031 if (record->xl_len != 0)
3034 (errmsg("invalid xlog switch record at %X/%X",
3035 RecPtr->xlogid, RecPtr->xrecoff)));
3036 goto next_record_is_invalid;
3039 else if (record->xl_len == 0)
3042 (errmsg("record with zero length at %X/%X",
3043 RecPtr->xlogid, RecPtr->xrecoff)));
3044 goto next_record_is_invalid;
3046 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3047 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3048 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3051 (errmsg("invalid record length at %X/%X",
3052 RecPtr->xlogid, RecPtr->xrecoff)));
3053 goto next_record_is_invalid;
3055 if (record->xl_rmid > RM_MAX_ID)
3058 (errmsg("invalid resource manager ID %u at %X/%X",
3059 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3060 goto next_record_is_invalid;
3065 * We can't exactly verify the prev-link, but surely it should be less
3066 * than the record's own address.
3068 if (!XLByteLT(record->xl_prev, *RecPtr))
3071 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3072 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3073 RecPtr->xlogid, RecPtr->xrecoff)));
3074 goto next_record_is_invalid;
3080 * Record's prev-link should exactly match our previous location. This
3081 * check guards against torn WAL pages where a stale but valid-looking
3082 * WAL record starts on a sector boundary.
3084 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3087 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3088 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3089 RecPtr->xlogid, RecPtr->xrecoff)));
3090 goto next_record_is_invalid;
3095 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3096 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3097 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3098 * enough for all "normal" records, but very large commit or abort records
3099 * might need more space.)
3101 total_len = record->xl_tot_len;
3102 if (total_len > readRecordBufSize)
3104 uint32 newSize = total_len;
3106 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3107 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3109 free(readRecordBuf);
3110 readRecordBuf = (char *) malloc(newSize);
3113 readRecordBufSize = 0;
3114 /* We treat this as a "bogus data" condition */
3116 (errmsg("record length %u at %X/%X too long",
3117 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3118 goto next_record_is_invalid;
3120 readRecordBufSize = newSize;
3123 buffer = readRecordBuf;
3125 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3126 if (total_len > len)
3128 /* Need to reassemble record */
3129 XLogContRecord *contrecord;
3130 uint32 gotlen = len;
3132 memcpy(buffer, record, len);
3133 record = (XLogRecord *) buffer;
3137 readOff += XLOG_BLCKSZ;
3138 if (readOff >= XLogSegSize)
3142 NextLogSeg(readId, readSeg);
3143 readFile = XLogFileRead(readId, readSeg, emode);
3145 goto next_record_is_invalid;
3148 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3151 (errcode_for_file_access(),
3152 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3153 readId, readSeg, readOff)));
3154 goto next_record_is_invalid;
3156 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3157 goto next_record_is_invalid;
3158 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3161 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3162 readId, readSeg, readOff)));
3163 goto next_record_is_invalid;
3165 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3166 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3167 if (contrecord->xl_rem_len == 0 ||
3168 total_len != (contrecord->xl_rem_len + gotlen))
3171 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3172 contrecord->xl_rem_len,
3173 readId, readSeg, readOff)));
3174 goto next_record_is_invalid;
3176 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3177 if (contrecord->xl_rem_len > len)
3179 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3184 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3185 contrecord->xl_rem_len);
3188 if (!RecordIsValid(record, *RecPtr, emode))
3189 goto next_record_is_invalid;
3190 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3191 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3192 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3194 nextRecord = (XLogRecord *) ((char *) contrecord +
3195 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3197 EndRecPtr.xlogid = readId;
3198 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3200 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3201 ReadRecPtr = *RecPtr;
3202 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3206 /* Record does not cross a page boundary */
3207 if (!RecordIsValid(record, *RecPtr, emode))
3208 goto next_record_is_invalid;
3209 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3210 MAXALIGN(total_len))
3211 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3212 EndRecPtr.xlogid = RecPtr->xlogid;
3213 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3214 ReadRecPtr = *RecPtr;
3215 memcpy(buffer, record, total_len);
3218 * Special processing if it's an XLOG SWITCH record
3220 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3222 /* Pretend it extends to end of segment */
3223 EndRecPtr.xrecoff += XLogSegSize - 1;
3224 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3225 nextRecord = NULL; /* definitely not on same page */
3228 * Pretend that readBuf contains the last page of the segment. This is
3229 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3232 readOff = XLogSegSize - XLOG_BLCKSZ;
3234 return (XLogRecord *) buffer;
3236 next_record_is_invalid:;
3244 * Check whether the xlog header of a page just read in looks valid.
3246 * This is just a convenience subroutine to avoid duplicated code in
3247 * ReadRecord. It's not intended for use from anywhere else.
3250 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3254 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3257 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3258 hdr->xlp_magic, readId, readSeg, readOff)));
3261 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3264 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3265 hdr->xlp_info, readId, readSeg, readOff)));
3268 if (hdr->xlp_info & XLP_LONG_HEADER)
3270 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3272 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3274 char fhdrident_str[32];
3275 char sysident_str[32];
3278 * Format sysids separately to keep platform-dependent format code
3279 * out of the translatable message string.
3281 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3282 longhdr->xlp_sysid);
3283 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3284 ControlFile->system_identifier);
3286 (errmsg("WAL file is from different system"),
3287 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3288 fhdrident_str, sysident_str)));
3291 if (longhdr->xlp_seg_size != XLogSegSize)
3294 (errmsg("WAL file is from different system"),
3295 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3298 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3301 (errmsg("WAL file is from different system"),
3302 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3306 else if (readOff == 0)
3308 /* hmm, first page of file doesn't have a long header? */
3310 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3311 hdr->xlp_info, readId, readSeg, readOff)));
3315 recaddr.xlogid = readId;
3316 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3317 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3320 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3321 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3322 readId, readSeg, readOff)));
3327 * Check page TLI is one of the expected values.
3329 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3332 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3334 readId, readSeg, readOff)));
3339 * Since child timelines are always assigned a TLI greater than their
3340 * immediate parent's TLI, we should never see TLI go backwards across
3341 * successive pages of a consistent WAL sequence.
3343 * Of course this check should only be applied when advancing sequentially
3344 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3345 * going to a random page.
3347 if (hdr->xlp_tli < lastPageTLI)
3350 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3351 hdr->xlp_tli, lastPageTLI,
3352 readId, readSeg, readOff)));
3355 lastPageTLI = hdr->xlp_tli;
3360 * Try to read a timeline's history file.
3362 * If successful, return the list of component TLIs (the given TLI followed by
3363 * its ancestor TLIs). If we can't find the history file, assume that the
3364 * timeline has no parents, and return a list of just the specified timeline
3368 readTimeLineHistory(TimeLineID targetTLI)
3371 char path[MAXPGPATH];
3372 char histfname[MAXFNAMELEN];
3373 char fline[MAXPGPATH];
3376 if (InArchiveRecovery)
3378 TLHistoryFileName(histfname, targetTLI);
3379 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3382 TLHistoryFilePath(path, targetTLI);
3384 fd = AllocateFile(path, "r");
3387 if (errno != ENOENT)
3389 (errcode_for_file_access(),
3390 errmsg("could not open file \"%s\": %m", path)));
3391 /* Not there, so assume no parents */
3392 return list_make1_int((int) targetTLI);
3400 while (fgets(fline, sizeof(fline), fd) != NULL)
3402 /* skip leading whitespace and check for # comment */
3407 for (ptr = fline; *ptr; ptr++)
3409 if (!isspace((unsigned char) *ptr))
3412 if (*ptr == '\0' || *ptr == '#')
3415 /* expect a numeric timeline ID as first field of line */
3416 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3419 (errmsg("syntax error in history file: %s", fline),
3420 errhint("Expected a numeric timeline ID.")));
3423 tli <= (TimeLineID) linitial_int(result))
3425 (errmsg("invalid data in history file: %s", fline),
3426 errhint("Timeline IDs must be in increasing sequence.")));
3428 /* Build list with newest item first */
3429 result = lcons_int((int) tli, result);
3431 /* we ignore the remainder of each line */
3437 targetTLI <= (TimeLineID) linitial_int(result))
3439 (errmsg("invalid data in history file \"%s\"", path),
3440 errhint("Timeline IDs must be less than child timeline's ID.")));
3442 result = lcons_int((int) targetTLI, result);
3445 (errmsg_internal("history of timeline %u is %s",
3446 targetTLI, nodeToString(result))));
3452 * Probe whether a timeline history file exists for the given timeline ID
3455 existsTimeLineHistory(TimeLineID probeTLI)
3457 char path[MAXPGPATH];
3458 char histfname[MAXFNAMELEN];
3461 if (InArchiveRecovery)
3463 TLHistoryFileName(histfname, probeTLI);
3464 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3467 TLHistoryFilePath(path, probeTLI);
3469 fd = AllocateFile(path, "r");
3477 if (errno != ENOENT)
3479 (errcode_for_file_access(),
3480 errmsg("could not open file \"%s\": %m", path)));
3486 * Find the newest existing timeline, assuming that startTLI exists.
3488 * Note: while this is somewhat heuristic, it does positively guarantee
3489 * that (result + 1) is not a known timeline, and therefore it should
3490 * be safe to assign that ID to a new timeline.
3493 findNewestTimeLine(TimeLineID startTLI)
3495 TimeLineID newestTLI;
3496 TimeLineID probeTLI;
3499 * The algorithm is just to probe for the existence of timeline history
3500 * files. XXX is it useful to allow gaps in the sequence?
3502 newestTLI = startTLI;
3504 for (probeTLI = startTLI + 1;; probeTLI++)
3506 if (existsTimeLineHistory(probeTLI))
3508 newestTLI = probeTLI; /* probeTLI exists */
3512 /* doesn't exist, assume we're done */
3521 * Create a new timeline history file.
3523 * newTLI: ID of the new timeline
3524 * parentTLI: ID of its immediate parent
3525 * endTLI et al: ID of the last used WAL file, for annotation purposes
3527 * Currently this is only used during recovery, and so there are no locking
3528 * considerations. But we should be just as tense as XLogFileInit to avoid
3529 * emplacing a bogus file.
3532 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3533 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3535 char path[MAXPGPATH];
3536 char tmppath[MAXPGPATH];
3537 char histfname[MAXFNAMELEN];
3538 char xlogfname[MAXFNAMELEN];
3539 char buffer[BLCKSZ];
3544 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3547 * Write into a temp file name.
3549 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3553 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3554 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3558 (errcode_for_file_access(),
3559 errmsg("could not create file \"%s\": %m", tmppath)));
3562 * If a history file exists for the parent, copy it verbatim
3564 if (InArchiveRecovery)
3566 TLHistoryFileName(histfname, parentTLI);
3567 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3570 TLHistoryFilePath(path, parentTLI);
3572 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3575 if (errno != ENOENT)
3577 (errcode_for_file_access(),
3578 errmsg("could not open file \"%s\": %m", path)));
3579 /* Not there, so assume parent has no parents */
3586 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3587 if (nbytes < 0 || errno != 0)
3589 (errcode_for_file_access(),
3590 errmsg("could not read file \"%s\": %m", path)));
3594 if ((int) write(fd, buffer, nbytes) != nbytes)
3596 int save_errno = errno;
3599 * If we fail to make the file, delete it to release disk
3605 * if write didn't set errno, assume problem is no disk space
3607 errno = save_errno ? save_errno : ENOSPC;
3610 (errcode_for_file_access(),
3611 errmsg("could not write to file \"%s\": %m", tmppath)));
3618 * Append one line with the details of this timeline split.
3620 * If we did have a parent file, insert an extra newline just in case the
3621 * parent file failed to end with one.
3623 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3625 snprintf(buffer, sizeof(buffer),
3626 "%s%u\t%s\t%s transaction %u at %s\n",
3627 (srcfd < 0) ? "" : "\n",
3630 recoveryStopAfter ? "after" : "before",
3632 timestamptz_to_str(recoveryStopTime));
3634 nbytes = strlen(buffer);
3636 if ((int) write(fd, buffer, nbytes) != nbytes)
3638 int save_errno = errno;
3641 * If we fail to make the file, delete it to release disk space
3644 /* if write didn't set errno, assume problem is no disk space */
3645 errno = save_errno ? save_errno : ENOSPC;
3648 (errcode_for_file_access(),
3649 errmsg("could not write to file \"%s\": %m", tmppath)));
3652 if (pg_fsync(fd) != 0)
3654 (errcode_for_file_access(),
3655 errmsg("could not fsync file \"%s\": %m", tmppath)));
3659 (errcode_for_file_access(),
3660 errmsg("could not close file \"%s\": %m", tmppath)));
3664 * Now move the completed history file into place with its final name.
3666 TLHistoryFilePath(path, newTLI);
3669 * Prefer link() to rename() here just to be really sure that we don't
3670 * overwrite an existing logfile. However, there shouldn't be one, so
3671 * rename() is an acceptable substitute except for the truly paranoid.
3673 #if HAVE_WORKING_LINK
3674 if (link(tmppath, path) < 0)
3676 (errcode_for_file_access(),
3677 errmsg("could not link file \"%s\" to \"%s\": %m",
3681 if (rename(tmppath, path) < 0)
3683 (errcode_for_file_access(),
3684 errmsg("could not rename file \"%s\" to \"%s\": %m",
3688 /* The history file can be archived immediately. */
3689 TLHistoryFileName(histfname, newTLI);
3690 XLogArchiveNotify(histfname);
3694 * I/O routines for pg_control
3696 * *ControlFile is a buffer in shared memory that holds an image of the
3697 * contents of pg_control. WriteControlFile() initializes pg_control
3698 * given a preloaded buffer, ReadControlFile() loads the buffer from
3699 * the pg_control file (during postmaster or standalone-backend startup),
3700 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3702 * For simplicity, WriteControlFile() initializes the fields of pg_control
3703 * that are related to checking backend/database compatibility, and
3704 * ReadControlFile() verifies they are correct. We could split out the
3705 * I/O and compatibility-check functions, but there seems no need currently.
3708 WriteControlFile(void)
3711 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3715 * Initialize version and compatibility-check fields
3717 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3718 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3720 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3721 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3723 ControlFile->blcksz = BLCKSZ;
3724 ControlFile->relseg_size = RELSEG_SIZE;
3725 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3726 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3728 ControlFile->nameDataLen = NAMEDATALEN;
3729 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3731 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
3733 #ifdef HAVE_INT64_TIMESTAMP
3734 ControlFile->enableIntTimes = TRUE;
3736 ControlFile->enableIntTimes = FALSE;
3739 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3740 localeptr = setlocale(LC_COLLATE, NULL);
3743 (errmsg("invalid LC_COLLATE setting")));
3744 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3745 localeptr = setlocale(LC_CTYPE, NULL);
3748 (errmsg("invalid LC_CTYPE setting")));
3749 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3751 /* Contents are protected with a CRC */
3752 INIT_CRC32(ControlFile->crc);
3753 COMP_CRC32(ControlFile->crc,
3754 (char *) ControlFile,
3755 offsetof(ControlFileData, crc));
3756 FIN_CRC32(ControlFile->crc);
3759 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3760 * excess over sizeof(ControlFileData). This reduces the odds of
3761 * premature-EOF errors when reading pg_control. We'll still fail when we
3762 * check the contents of the file, but hopefully with a more specific
3763 * error than "couldn't read pg_control".
3765 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3766 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3768 memset(buffer, 0, PG_CONTROL_SIZE);
3769 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3771 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3772 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3776 (errcode_for_file_access(),
3777 errmsg("could not create control file \"%s\": %m",
3778 XLOG_CONTROL_FILE)));
3781 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3783 /* if write didn't set errno, assume problem is no disk space */
3787 (errcode_for_file_access(),
3788 errmsg("could not write to control file: %m")));
3791 if (pg_fsync(fd) != 0)
3793 (errcode_for_file_access(),
3794 errmsg("could not fsync control file: %m")));
3798 (errcode_for_file_access(),
3799 errmsg("could not close control file: %m")));
3803 ReadControlFile(void)
3811 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3816 (errcode_for_file_access(),
3817 errmsg("could not open control file \"%s\": %m",
3818 XLOG_CONTROL_FILE)));
3820 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3822 (errcode_for_file_access(),
3823 errmsg("could not read from control file: %m")));
3828 * Check for expected pg_control format version. If this is wrong, the
3829 * CRC check will likely fail because we'll be checking the wrong number
3830 * of bytes. Complaining about wrong version will probably be more
3831 * enlightening than complaining about wrong CRC.
3833 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3835 (errmsg("database files are incompatible with server"),
3836 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3837 " but the server was compiled with PG_CONTROL_VERSION %d.",
3838 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3839 errhint("It looks like you need to initdb.")));
3840 /* Now check the CRC. */
3843 (char *) ControlFile,
3844 offsetof(ControlFileData, crc));
3847 if (!EQ_CRC32(crc, ControlFile->crc))
3849 (errmsg("incorrect checksum in control file")));
3852 * Do compatibility checking immediately. We do this here for 2 reasons:
3854 * (1) if the database isn't compatible with the backend executable, we
3855 * want to abort before we can possibly do any damage;
3857 * (2) this code is executed in the postmaster, so the setlocale() will
3858 * propagate to forked backends, which aren't going to read this file for
3859 * themselves. (These locale settings are considered critical
3860 * compatibility items because they can affect sort order of indexes.)
3862 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3864 (errmsg("database files are incompatible with server"),
3865 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3866 " but the server was compiled with CATALOG_VERSION_NO %d.",
3867 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3868 errhint("It looks like you need to initdb.")));
3869 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3871 (errmsg("database files are incompatible with server"),
3872 errdetail("The database cluster was initialized with MAXALIGN %d,"
3873 " but the server was compiled with MAXALIGN %d.",
3874 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3875 errhint("It looks like you need to initdb.")));
3876 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3878 (errmsg("database files are incompatible with server"),
3879 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3880 errhint("It looks like you need to initdb.")));
3881 if (ControlFile->blcksz != BLCKSZ)
3883 (errmsg("database files are incompatible with server"),
3884 errdetail("The database cluster was initialized with BLCKSZ %d,"
3885 " but the server was compiled with BLCKSZ %d.",
3886 ControlFile->blcksz, BLCKSZ),
3887 errhint("It looks like you need to recompile or initdb.")));
3888 if (ControlFile->relseg_size != RELSEG_SIZE)
3890 (errmsg("database files are incompatible with server"),
3891 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3892 " but the server was compiled with RELSEG_SIZE %d.",
3893 ControlFile->relseg_size, RELSEG_SIZE),
3894 errhint("It looks like you need to recompile or initdb.")));
3895 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3897 (errmsg("database files are incompatible with server"),
3898 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3899 " but the server was compiled with XLOG_BLCKSZ %d.",
3900 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3901 errhint("It looks like you need to recompile or initdb.")));
3902 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3904 (errmsg("database files are incompatible with server"),
3905 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3906 " but the server was compiled with XLOG_SEG_SIZE %d.",
3907 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3908 errhint("It looks like you need to recompile or initdb.")));
3909 if (ControlFile->nameDataLen != NAMEDATALEN)
3911 (errmsg("database files are incompatible with server"),
3912 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3913 " but the server was compiled with NAMEDATALEN %d.",
3914 ControlFile->nameDataLen, NAMEDATALEN),
3915 errhint("It looks like you need to recompile or initdb.")));
3916 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3918 (errmsg("database files are incompatible with server"),
3919 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3920 " but the server was compiled with INDEX_MAX_KEYS %d.",
3921 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3922 errhint("It looks like you need to recompile or initdb.")));
3923 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
3925 (errmsg("database files are incompatible with server"),
3926 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
3927 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
3928 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
3929 errhint("It looks like you need to recompile or initdb.")));
3931 #ifdef HAVE_INT64_TIMESTAMP
3932 if (ControlFile->enableIntTimes != TRUE)
3934 (errmsg("database files are incompatible with server"),
3935 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3936 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3937 errhint("It looks like you need to recompile or initdb.")));
3939 if (ControlFile->enableIntTimes != FALSE)
3941 (errmsg("database files are incompatible with server"),
3942 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3943 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3944 errhint("It looks like you need to recompile or initdb.")));
3947 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3949 (errmsg("database files are incompatible with server"),
3950 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3951 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3952 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3953 errhint("It looks like you need to recompile or initdb.")));
3954 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3956 (errmsg("database files are incompatible with operating system"),
3957 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3958 " which is not recognized by setlocale().",
3959 ControlFile->lc_collate),
3960 errhint("It looks like you need to initdb or install locale support.")));
3961 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3963 (errmsg("database files are incompatible with operating system"),
3964 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3965 " which is not recognized by setlocale().",
3966 ControlFile->lc_ctype),
3967 errhint("It looks like you need to initdb or install locale support.")));
3969 /* Make the fixed locale settings visible as GUC variables, too */
3970 SetConfigOption("lc_collate", ControlFile->lc_collate,
3971 PGC_INTERNAL, PGC_S_OVERRIDE);
3972 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3973 PGC_INTERNAL, PGC_S_OVERRIDE);
3977 UpdateControlFile(void)
3981 INIT_CRC32(ControlFile->crc);
3982 COMP_CRC32(ControlFile->crc,
3983 (char *) ControlFile,
3984 offsetof(ControlFileData, crc));
3985 FIN_CRC32(ControlFile->crc);
3987 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3992 (errcode_for_file_access(),
3993 errmsg("could not open control file \"%s\": %m",
3994 XLOG_CONTROL_FILE)));
3997 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3999 /* if write didn't set errno, assume problem is no disk space */
4003 (errcode_for_file_access(),
4004 errmsg("could not write to control file: %m")));
4007 if (pg_fsync(fd) != 0)
4009 (errcode_for_file_access(),
4010 errmsg("could not fsync control file: %m")));
4014 (errcode_for_file_access(),
4015 errmsg("could not close control file: %m")));
4019 * Initialization of shared memory for XLOG
4027 size = sizeof(XLogCtlData);
4028 /* xlblocks array */
4029 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
4030 /* extra alignment padding for XLOG I/O buffers */
4031 size = add_size(size, ALIGNOF_XLOG_BUFFER);
4032 /* and the buffers themselves */
4033 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4036 * Note: we don't count ControlFileData, it comes out of the "slop factor"
4037 * added by CreateSharedMemoryAndSemaphores. This lets us use this
4038 * routine again below to compute the actual allocation size.
4051 ControlFile = (ControlFileData *)
4052 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4053 XLogCtl = (XLogCtlData *)
4054 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4056 if (foundCFile || foundXLog)
4058 /* both should be present or neither */
4059 Assert(foundCFile && foundXLog);
4063 memset(XLogCtl, 0, sizeof(XLogCtlData));
4066 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4067 * multiple of the alignment for same, so no extra alignment padding is
4070 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4071 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4072 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4073 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4076 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4078 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4079 XLogCtl->pages = allocptr;
4080 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4083 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4084 * in additional info.)
4086 XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
4088 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4089 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4090 SpinLockInit(&XLogCtl->info_lck);
4093 * If we are not in bootstrap mode, pg_control should already exist. Read
4094 * and validate it immediately (see comments in ReadControlFile() for the
4097 if (!IsBootstrapProcessingMode())
4102 * This func must be called ONCE on system install. It creates pg_control
4103 * and the initial XLOG segment.
4108 CheckPoint checkPoint;
4110 XLogPageHeader page;
4111 XLogLongPageHeader longpage;
4114 uint64 sysidentifier;
4119 * Select a hopefully-unique system identifier code for this installation.
4120 * We use the result of gettimeofday(), including the fractional seconds
4121 * field, as being about as unique as we can easily get. (Think not to
4122 * use random(), since it hasn't been seeded and there's no portable way
4123 * to seed it other than the system clock value...) The upper half of the
4124 * uint64 value is just the tv_sec part, while the lower half is the XOR
4125 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4126 * unnecessarily if "uint64" is really only 32 bits wide. A person
4127 * knowing this encoding can determine the initialization time of the
4128 * installation, which could perhaps be useful sometimes.
4130 gettimeofday(&tv, NULL);
4131 sysidentifier = ((uint64) tv.tv_sec) << 32;
4132 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4134 /* First timeline ID is always 1 */
4137 /* page buffer must be aligned suitably for O_DIRECT */
4138 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4139 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4140 memset(page, 0, XLOG_BLCKSZ);
4142 /* Set up information for the initial checkpoint record */
4143 checkPoint.redo.xlogid = 0;
4144 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4145 checkPoint.ThisTimeLineID = ThisTimeLineID;
4146 checkPoint.nextXidEpoch = 0;
4147 checkPoint.nextXid = FirstNormalTransactionId;
4148 checkPoint.nextOid = FirstBootstrapObjectId;
4149 checkPoint.nextMulti = FirstMultiXactId;
4150 checkPoint.nextMultiOffset = 0;
4151 checkPoint.time = time(NULL);
4153 ShmemVariableCache->nextXid = checkPoint.nextXid;
4154 ShmemVariableCache->nextOid = checkPoint.nextOid;
4155 ShmemVariableCache->oidCount = 0;
4156 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4158 /* Set up the XLOG page header */
4159 page->xlp_magic = XLOG_PAGE_MAGIC;
4160 page->xlp_info = XLP_LONG_HEADER;
4161 page->xlp_tli = ThisTimeLineID;
4162 page->xlp_pageaddr.xlogid = 0;
4163 page->xlp_pageaddr.xrecoff = 0;
4164 longpage = (XLogLongPageHeader) page;
4165 longpage->xlp_sysid = sysidentifier;
4166 longpage->xlp_seg_size = XLogSegSize;
4167 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4169 /* Insert the initial checkpoint record */
4170 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4171 record->xl_prev.xlogid = 0;
4172 record->xl_prev.xrecoff = 0;
4173 record->xl_xid = InvalidTransactionId;
4174 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4175 record->xl_len = sizeof(checkPoint);
4176 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4177 record->xl_rmid = RM_XLOG_ID;
4178 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4181 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4182 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4183 SizeOfXLogRecord - sizeof(pg_crc32));
4185 record->xl_crc = crc;
4187 /* Create first XLOG segment file */
4188 use_existent = false;
4189 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4191 /* Write the first page with the initial record */
4193 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4195 /* if write didn't set errno, assume problem is no disk space */
4199 (errcode_for_file_access(),
4200 errmsg("could not write bootstrap transaction log file: %m")));
4203 if (pg_fsync(openLogFile) != 0)
4205 (errcode_for_file_access(),
4206 errmsg("could not fsync bootstrap transaction log file: %m")));
4208 if (close(openLogFile))
4210 (errcode_for_file_access(),
4211 errmsg("could not close bootstrap transaction log file: %m")));
4215 /* Now create pg_control */
4217 memset(ControlFile, 0, sizeof(ControlFileData));
4218 /* Initialize pg_control status fields */
4219 ControlFile->system_identifier = sysidentifier;
4220 ControlFile->state = DB_SHUTDOWNED;
4221 ControlFile->time = checkPoint.time;
4222 ControlFile->checkPoint = checkPoint.redo;
4223 ControlFile->checkPointCopy = checkPoint;
4224 /* some additional ControlFile fields are set in WriteControlFile() */
4228 /* Bootstrap the commit log, too */
4230 BootStrapSUBTRANS();
4231 BootStrapMultiXact();
4237 str_time(time_t tnow)
4239 static char buf[128];
4241 strftime(buf, sizeof(buf),
4242 "%Y-%m-%d %H:%M:%S %Z",
4249 * See if there is a recovery command file (recovery.conf), and if so
4250 * read in parameters for archive recovery.
4252 * XXX longer term intention is to expand this to
4253 * cater for additional parameters and controls
4254 * possibly use a flex lexer similar to the GUC one
4257 readRecoveryCommandFile(void)
4260 char cmdline[MAXPGPATH];
4261 TimeLineID rtli = 0;
4262 bool rtliGiven = false;
4263 bool syntaxError = false;
4265 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4268 if (errno == ENOENT)
4269 return; /* not there, so no archive recovery */
4271 (errcode_for_file_access(),
4272 errmsg("could not open recovery command file \"%s\": %m",
4273 RECOVERY_COMMAND_FILE)));
4277 (errmsg("starting archive recovery")));
4282 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4284 /* skip leading whitespace and check for # comment */
4289 for (ptr = cmdline; *ptr; ptr++)
4291 if (!isspace((unsigned char) *ptr))
4294 if (*ptr == '\0' || *ptr == '#')
4297 /* identify the quoted parameter value */
4298 tok1 = strtok(ptr, "'");
4304 tok2 = strtok(NULL, "'");
4310 /* reparse to get just the parameter name */
4311 tok1 = strtok(ptr, " \t=");
4318 if (strcmp(tok1, "restore_command") == 0)
4320 recoveryRestoreCommand = pstrdup(tok2);
4322 (errmsg("restore_command = \"%s\"",
4323 recoveryRestoreCommand)));
4325 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4328 if (strcmp(tok2, "latest") == 0)
4333 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4334 if (errno == EINVAL || errno == ERANGE)
4336 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4341 (errmsg("recovery_target_timeline = %u", rtli)));
4344 (errmsg("recovery_target_timeline = latest")));
4346 else if (strcmp(tok1, "recovery_target_xid") == 0)
4349 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4350 if (errno == EINVAL || errno == ERANGE)
4352 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4355 (errmsg("recovery_target_xid = %u",
4356 recoveryTargetXid)));
4357 recoveryTarget = true;
4358 recoveryTargetExact = true;
4360 else if (strcmp(tok1, "recovery_target_time") == 0)
4363 * if recovery_target_xid specified, then this overrides
4364 * recovery_target_time
4366 if (recoveryTargetExact)
4368 recoveryTarget = true;
4369 recoveryTargetExact = false;
4372 * Convert the time string given by the user to TimestampTz form.
4374 recoveryTargetTime =
4375 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
4376 CStringGetDatum(tok2),
4377 ObjectIdGetDatum(InvalidOid),
4378 Int32GetDatum(-1)));
4380 (errmsg("recovery_target_time = %s",
4381 timestamptz_to_str(recoveryTargetTime))));
4383 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4386 * does nothing if a recovery_target is not also set
4388 if (strcmp(tok2, "true") == 0)
4389 recoveryTargetInclusive = true;
4392 recoveryTargetInclusive = false;
4396 (errmsg("recovery_target_inclusive = %s", tok2)));
4400 (errmsg("unrecognized recovery parameter \"%s\"",
4408 (errmsg("syntax error in recovery command file: %s",
4410 errhint("Lines should have the format parameter = 'value'.")));
4412 /* Check that required parameters were supplied */
4413 if (recoveryRestoreCommand == NULL)
4415 (errmsg("recovery command file \"%s\" did not specify restore_command",
4416 RECOVERY_COMMAND_FILE)));
4418 /* Enable fetching from archive recovery area */
4419 InArchiveRecovery = true;
4422 * If user specified recovery_target_timeline, validate it or compute the
4423 * "latest" value. We can't do this until after we've gotten the restore
4424 * command and set InArchiveRecovery, because we need to fetch timeline
4425 * history files from the archive.
4431 /* Timeline 1 does not have a history file, all else should */
4432 if (rtli != 1 && !existsTimeLineHistory(rtli))
4434 (errmsg("recovery_target_timeline %u does not exist",
4436 recoveryTargetTLI = rtli;
4440 /* We start the "latest" search from pg_control's timeline */
4441 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4447 * Exit archive-recovery state
4450 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4452 char recoveryPath[MAXPGPATH];
4453 char xlogpath[MAXPGPATH];
4456 * We are no longer in archive recovery state.
4458 InArchiveRecovery = false;
4461 * We should have the ending log segment currently open. Verify, and then
4462 * close it (to avoid problems on Windows with trying to rename or delete
4465 Assert(readFile >= 0);
4466 Assert(readId == endLogId);
4467 Assert(readSeg == endLogSeg);
4473 * If the segment was fetched from archival storage, we want to replace
4474 * the existing xlog segment (if any) with the archival version. This is
4475 * because whatever is in XLOGDIR is very possibly older than what we have
4476 * from the archives, since it could have come from restoring a PGDATA
4477 * backup. In any case, the archival version certainly is more
4478 * descriptive of what our current database state is, because that is what
4481 * Note that if we are establishing a new timeline, ThisTimeLineID is
4482 * already set to the new value, and so we will create a new file instead
4483 * of overwriting any existing file.
4485 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4486 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4488 if (restoredFromArchive)
4491 (errmsg_internal("moving last restored xlog to \"%s\"",
4493 unlink(xlogpath); /* might or might not exist */
4494 if (rename(recoveryPath, xlogpath) != 0)
4496 (errcode_for_file_access(),
4497 errmsg("could not rename file \"%s\" to \"%s\": %m",
4498 recoveryPath, xlogpath)));
4499 /* XXX might we need to fix permissions on the file? */
4504 * If the latest segment is not archival, but there's still a
4505 * RECOVERYXLOG laying about, get rid of it.
4507 unlink(recoveryPath); /* ignore any error */
4510 * If we are establishing a new timeline, we have to copy data from
4511 * the last WAL segment of the old timeline to create a starting WAL
4512 * segment for the new timeline.
4514 if (endTLI != ThisTimeLineID)
4515 XLogFileCopy(endLogId, endLogSeg,
4516 endTLI, endLogId, endLogSeg);
4520 * Let's just make real sure there are not .ready or .done flags posted
4521 * for the new segment.
4523 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4524 XLogArchiveCleanup(xlogpath);
4526 /* Get rid of any remaining recovered timeline-history file, too */
4527 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4528 unlink(recoveryPath); /* ignore any error */
4531 * Rename the config file out of the way, so that we don't accidentally
4532 * re-enter archive recovery mode in a subsequent crash.
4534 unlink(RECOVERY_COMMAND_DONE);
4535 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4537 (errcode_for_file_access(),
4538 errmsg("could not rename file \"%s\" to \"%s\": %m",
4539 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4542 (errmsg("archive recovery complete")));
4546 * For point-in-time recovery, this function decides whether we want to
4547 * stop applying the XLOG at or after the current record.
4549 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4550 * *includeThis is set TRUE if we should apply this record before stopping.
4551 * Also, some information is saved in recoveryStopXid et al for use in
4552 * annotating the new timeline's history file.
4555 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4559 TimestampTz recordXtime;
4561 /* Do we have a PITR target at all? */
4562 if (!recoveryTarget)
4565 /* We only consider stopping at COMMIT or ABORT records */
4566 if (record->xl_rmid != RM_XACT_ID)
4568 record_info = record->xl_info & ~XLR_INFO_MASK;
4569 if (record_info == XLOG_XACT_COMMIT)
4571 xl_xact_commit *recordXactCommitData;
4573 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4574 recordXtime = recordXactCommitData->xact_time;
4576 else if (record_info == XLOG_XACT_ABORT)
4578 xl_xact_abort *recordXactAbortData;
4580 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4581 recordXtime = recordXactAbortData->xact_time;
4586 if (recoveryTargetExact)
4589 * there can be only one transaction end record with this exact
4592 * when testing for an xid, we MUST test for equality only, since
4593 * transactions are numbered in the order they start, not the order
4594 * they complete. A higher numbered xid will complete before you about
4595 * 50% of the time...
4597 stopsHere = (record->xl_xid == recoveryTargetXid);
4599 *includeThis = recoveryTargetInclusive;
4604 * there can be many transactions that share the same commit time, so
4605 * we stop after the last one, if we are inclusive, or stop at the
4606 * first one if we are exclusive
4608 if (recoveryTargetInclusive)
4609 stopsHere = (recordXtime > recoveryTargetTime);
4611 stopsHere = (recordXtime >= recoveryTargetTime);
4613 *includeThis = false;
4618 recoveryStopXid = record->xl_xid;
4619 recoveryStopTime = recordXtime;
4620 recoveryStopAfter = *includeThis;
4622 if (record_info == XLOG_XACT_COMMIT)
4624 if (recoveryStopAfter)
4626 (errmsg("recovery stopping after commit of transaction %u, time %s",
4628 timestamptz_to_str(recoveryStopTime))));
4631 (errmsg("recovery stopping before commit of transaction %u, time %s",
4633 timestamptz_to_str(recoveryStopTime))));
4637 if (recoveryStopAfter)
4639 (errmsg("recovery stopping after abort of transaction %u, time %s",
4641 timestamptz_to_str(recoveryStopTime))));
4644 (errmsg("recovery stopping before abort of transaction %u, time %s",
4646 timestamptz_to_str(recoveryStopTime))));
4654 * This must be called ONCE during postmaster or standalone-backend startup
4659 XLogCtlInsert *Insert;
4660 CheckPoint checkPoint;
4662 bool needNewTimeLine = false;
4663 bool haveBackupLabel = false;
4673 TransactionId oldestActiveXID;
4676 * Read control file and check XLOG status looks valid.
4678 * Note: in most control paths, *ControlFile is already valid and we need
4679 * not do ReadControlFile() here, but might as well do it to be sure.
4683 if (ControlFile->state < DB_SHUTDOWNED ||
4684 ControlFile->state > DB_IN_PRODUCTION ||
4685 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4687 (errmsg("control file contains invalid data")));
4689 if (ControlFile->state == DB_SHUTDOWNED)
4691 (errmsg("database system was shut down at %s",
4692 str_time(ControlFile->time))));
4693 else if (ControlFile->state == DB_SHUTDOWNING)
4695 (errmsg("database system shutdown was interrupted; last known up at %s",
4696 str_time(ControlFile->time))));
4697 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4699 (errmsg("database system was interrupted while in recovery at %s",
4700 str_time(ControlFile->time)),
4701 errhint("This probably means that some data is corrupted and"
4702 " you will have to use the last backup for recovery.")));
4703 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4705 (errmsg("database system was interrupted while in recovery at log time %s",
4706 str_time(ControlFile->checkPointCopy.time)),
4707 errhint("If this has occurred more than once some data might be corrupted"
4708 " and you might need to choose an earlier recovery target.")));
4709 else if (ControlFile->state == DB_IN_PRODUCTION)
4711 (errmsg("database system was interrupted; last known up at %s",
4712 str_time(ControlFile->time))));
4714 /* This is just to allow attaching to startup process with a debugger */
4715 #ifdef XLOG_REPLAY_DELAY
4716 if (ControlFile->state != DB_SHUTDOWNED)
4717 pg_usleep(60000000L);
4721 * Initialize on the assumption we want to recover to the same timeline
4722 * that's active according to pg_control.
4724 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4727 * Check for recovery control file, and if so set up state for offline
4730 readRecoveryCommandFile();
4732 /* Now we can determine the list of expected TLIs */
4733 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4736 * If pg_control's timeline is not in expectedTLIs, then we cannot
4737 * proceed: the backup is not part of the history of the requested
4740 if (!list_member_int(expectedTLIs,
4741 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4743 (errmsg("requested timeline %u is not a child of database system timeline %u",
4745 ControlFile->checkPointCopy.ThisTimeLineID)));
4747 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4750 * When a backup_label file is present, we want to roll forward from
4751 * the checkpoint it identifies, rather than using pg_control.
4753 record = ReadCheckpointRecord(checkPointLoc, 0);
4757 (errmsg("checkpoint record is at %X/%X",
4758 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4759 InRecovery = true; /* force recovery even if SHUTDOWNED */
4764 (errmsg("could not locate required checkpoint record"),
4765 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4767 /* set flag to delete it later */
4768 haveBackupLabel = true;
4773 * Get the last valid checkpoint record. If the latest one according
4774 * to pg_control is broken, try the next-to-last one.
4776 checkPointLoc = ControlFile->checkPoint;
4777 record = ReadCheckpointRecord(checkPointLoc, 1);
4781 (errmsg("checkpoint record is at %X/%X",
4782 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4786 checkPointLoc = ControlFile->prevCheckPoint;
4787 record = ReadCheckpointRecord(checkPointLoc, 2);
4791 (errmsg("using previous checkpoint record at %X/%X",
4792 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4793 InRecovery = true; /* force recovery even if SHUTDOWNED */
4797 (errmsg("could not locate a valid checkpoint record")));
4801 LastRec = RecPtr = checkPointLoc;
4802 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4803 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4806 (errmsg("redo record is at %X/%X; shutdown %s",
4807 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4808 wasShutdown ? "TRUE" : "FALSE")));
4810 (errmsg("next transaction ID: %u/%u; next OID: %u",
4811 checkPoint.nextXidEpoch, checkPoint.nextXid,
4812 checkPoint.nextOid)));
4814 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4815 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4816 if (!TransactionIdIsNormal(checkPoint.nextXid))
4818 (errmsg("invalid next transaction ID")));
4820 ShmemVariableCache->nextXid = checkPoint.nextXid;
4821 ShmemVariableCache->nextOid = checkPoint.nextOid;
4822 ShmemVariableCache->oidCount = 0;
4823 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4826 * We must replay WAL entries using the same TimeLineID they were created
4827 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4828 * also xlog_redo()).
4830 ThisTimeLineID = checkPoint.ThisTimeLineID;
4832 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4834 if (XLByteLT(RecPtr, checkPoint.redo))
4836 (errmsg("invalid redo in checkpoint record")));
4839 * Check whether we need to force recovery from WAL. If it appears to
4840 * have been a clean shutdown and we did not have a recovery.conf file,
4841 * then assume no recovery needed.
4843 if (XLByteLT(checkPoint.redo, RecPtr))
4847 (errmsg("invalid redo record in shutdown checkpoint")));
4850 else if (ControlFile->state != DB_SHUTDOWNED)
4852 else if (InArchiveRecovery)
4854 /* force recovery due to presence of recovery.conf */
4864 * Update pg_control to show that we are recovering and to show the
4865 * selected checkpoint as the place we are starting from. We also mark
4866 * pg_control with any minimum recovery stop point obtained from a
4867 * backup history file.
4869 if (InArchiveRecovery)
4872 (errmsg("automatic recovery in progress")));
4873 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4878 (errmsg("database system was not properly shut down; "
4879 "automatic recovery in progress")));
4880 ControlFile->state = DB_IN_CRASH_RECOVERY;
4882 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4883 ControlFile->checkPoint = checkPointLoc;
4884 ControlFile->checkPointCopy = checkPoint;
4885 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4886 ControlFile->minRecoveryPoint = minRecoveryLoc;
4887 ControlFile->time = time(NULL);
4888 UpdateControlFile();
4891 * If there was a backup label file, it's done its job and the info
4892 * has now been propagated into pg_control. We must get rid of the
4893 * label file so that if we crash during recovery, we'll pick up at
4894 * the latest recovery restartpoint instead of going all the way back
4895 * to the backup start point. It seems prudent though to just rename
4896 * the file out of the way rather than delete it completely.
4898 if (haveBackupLabel)
4900 unlink(BACKUP_LABEL_OLD);
4901 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4903 (errcode_for_file_access(),
4904 errmsg("could not rename file \"%s\" to \"%s\": %m",
4905 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4908 /* Start up the recovery environment */
4909 XLogInitRelationCache();
4911 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4913 if (RmgrTable[rmid].rm_startup != NULL)
4914 RmgrTable[rmid].rm_startup();
4918 * Find the first record that logically follows the checkpoint --- it
4919 * might physically precede it, though.
4921 if (XLByteLT(checkPoint.redo, RecPtr))
4923 /* back up to find the record */
4924 record = ReadRecord(&(checkPoint.redo), PANIC);
4928 /* just have to read next record after CheckPoint */
4929 record = ReadRecord(NULL, LOG);
4934 bool recoveryContinue = true;
4935 bool recoveryApply = true;
4936 ErrorContextCallback errcontext;
4940 (errmsg("redo starts at %X/%X",
4941 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4944 * main redo apply loop
4953 initStringInfo(&buf);
4954 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4955 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4956 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4957 xlog_outrec(&buf, record);
4958 appendStringInfo(&buf, " - ");
4959 RmgrTable[record->xl_rmid].rm_desc(&buf,
4961 XLogRecGetData(record));
4962 elog(LOG, "%s", buf.data);
4968 * Have we reached our recovery target?
4970 if (recoveryStopsHere(record, &recoveryApply))
4972 needNewTimeLine = true; /* see below */
4973 recoveryContinue = false;
4978 /* Setup error traceback support for ereport() */
4979 errcontext.callback = rm_redo_error_callback;
4980 errcontext.arg = (void *) record;
4981 errcontext.previous = error_context_stack;
4982 error_context_stack = &errcontext;
4984 /* nextXid must be beyond record's xid */
4985 if (TransactionIdFollowsOrEquals(record->xl_xid,
4986 ShmemVariableCache->nextXid))
4988 ShmemVariableCache->nextXid = record->xl_xid;
4989 TransactionIdAdvance(ShmemVariableCache->nextXid);
4992 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4993 RestoreBkpBlocks(record, EndRecPtr);
4995 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4997 /* Pop the error context stack */
4998 error_context_stack = errcontext.previous;
5000 LastRec = ReadRecPtr;
5002 record = ReadRecord(NULL, LOG);
5003 } while (record != NULL && recoveryContinue);
5006 * end of main redo apply loop
5010 (errmsg("redo done at %X/%X",
5011 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5016 /* there are no WAL records following the checkpoint */
5018 (errmsg("redo is not required")));
5023 * Re-fetch the last valid or last applied record, so we can identify the
5024 * exact endpoint of what we consider the valid portion of WAL.
5026 record = ReadRecord(&LastRec, PANIC);
5027 EndOfLog = EndRecPtr;
5028 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
5031 * Complain if we did not roll forward far enough to render the backup
5034 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
5036 if (needNewTimeLine) /* stopped because of stop request */
5038 (errmsg("requested recovery stop point is before end time of backup dump")));
5040 /* ran off end of WAL */
5042 (errmsg("WAL ends before end time of backup dump")));
5046 * Consider whether we need to assign a new timeline ID.
5048 * If we stopped short of the end of WAL during recovery, then we are
5049 * generating a new timeline and must assign it a unique new ID.
5050 * Otherwise, we can just extend the timeline we were in when we ran out
5053 if (needNewTimeLine)
5055 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5057 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5058 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5059 curFileTLI, endLogId, endLogSeg);
5062 /* Save the selected TimeLineID in shared memory, too */
5063 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5066 * We are now done reading the old WAL. Turn off archive fetching if it
5067 * was active, and make a writable copy of the last WAL segment. (Note
5068 * that we also have a copy of the last block of the old WAL in readBuf;
5069 * we will use that below.)
5071 if (InArchiveRecovery)
5072 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5075 * Prepare to write WAL starting at EndOfLog position, and init xlog
5076 * buffer cache using the block containing the last record from the
5077 * previous incarnation.
5079 openLogId = endLogId;
5080 openLogSeg = endLogSeg;
5081 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5083 Insert = &XLogCtl->Insert;
5084 Insert->PrevRecord = LastRec;
5085 XLogCtl->xlblocks[0].xlogid = openLogId;
5086 XLogCtl->xlblocks[0].xrecoff =
5087 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5090 * Tricky point here: readBuf contains the *last* block that the LastRec
5091 * record spans, not the one it starts in. The last block is indeed the
5092 * one we want to use.
5094 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5095 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5096 Insert->currpos = (char *) Insert->currpage +
5097 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5099 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5101 XLogCtl->Write.LogwrtResult = LogwrtResult;
5102 Insert->LogwrtResult = LogwrtResult;
5103 XLogCtl->LogwrtResult = LogwrtResult;
5105 XLogCtl->LogwrtRqst.Write = EndOfLog;
5106 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5108 freespace = INSERT_FREESPACE(Insert);
5111 /* Make sure rest of page is zero */
5112 MemSet(Insert->currpos, 0, freespace);
5113 XLogCtl->Write.curridx = 0;
5118 * Whenever Write.LogwrtResult points to exactly the end of a page,
5119 * Write.curridx must point to the *next* page (see XLogWrite()).
5121 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5122 * this is sufficient. The first actual attempt to insert a log
5123 * record will advance the insert state.
5125 XLogCtl->Write.curridx = NextBufIdx(0);
5128 /* Pre-scan prepared transactions to find out the range of XIDs present */
5129 oldestActiveXID = PrescanPreparedTransactions();
5136 * Allow resource managers to do any required cleanup.
5138 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5140 if (RmgrTable[rmid].rm_cleanup != NULL)
5141 RmgrTable[rmid].rm_cleanup();
5145 * Check to see if the XLOG sequence contained any unresolved
5146 * references to uninitialized pages.
5148 XLogCheckInvalidPages();
5151 * Reset pgstat data, because it may be invalid after recovery.
5156 * Perform a checkpoint to update all our recovery activity to disk.
5158 * Note that we write a shutdown checkpoint rather than an on-line
5159 * one. This is not particularly critical, but since we may be
5160 * assigning a new TLI, using a shutdown checkpoint allows us to have
5161 * the rule that TLI only changes in shutdown checkpoints, which
5162 * allows some extra error checking in xlog_redo.
5164 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5167 * Close down recovery environment
5169 XLogCloseRelationCache();
5173 * Preallocate additional log files, if wanted.
5175 PreallocXlogFiles(EndOfLog);
5178 * Okay, we're officially UP.
5182 ControlFile->state = DB_IN_PRODUCTION;
5183 ControlFile->time = time(NULL);
5184 UpdateControlFile();
5186 /* start the archive_timeout timer running */
5187 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5189 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5190 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5191 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5193 /* Start up the commit log and related stuff, too */
5195 StartupSUBTRANS(oldestActiveXID);
5198 /* Reload shared-memory state for prepared transactions */
5199 RecoverPreparedTransactions();
5201 /* Shut down readFile facility, free space */
5214 free(readRecordBuf);
5215 readRecordBuf = NULL;
5216 readRecordBufSize = 0;
5221 * Subroutine to try to fetch and validate a prior checkpoint record.
5223 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5224 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5227 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5231 if (!XRecOffIsValid(RecPtr.xrecoff))
5237 (errmsg("invalid primary checkpoint link in control file")));
5241 (errmsg("invalid secondary checkpoint link in control file")));
5245 (errmsg("invalid checkpoint link in backup_label file")));
5251 record = ReadRecord(&RecPtr, LOG);
5259 (errmsg("invalid primary checkpoint record")));
5263 (errmsg("invalid secondary checkpoint record")));
5267 (errmsg("invalid checkpoint record")));
5272 if (record->xl_rmid != RM_XLOG_ID)
5278 (errmsg("invalid resource manager ID in primary checkpoint record")));
5282 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5286 (errmsg("invalid resource manager ID in checkpoint record")));
5291 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5292 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5298 (errmsg("invalid xl_info in primary checkpoint record")));
5302 (errmsg("invalid xl_info in secondary checkpoint record")));
5306 (errmsg("invalid xl_info in checkpoint record")));
5311 if (record->xl_len != sizeof(CheckPoint) ||
5312 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5318 (errmsg("invalid length of primary checkpoint record")));
5322 (errmsg("invalid length of secondary checkpoint record")));
5326 (errmsg("invalid length of checkpoint record")));
5335 * This must be called during startup of a backend process, except that
5336 * it need not be called in a standalone backend (which does StartupXLOG
5337 * instead). We need to initialize the local copies of ThisTimeLineID and
5340 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5341 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5342 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5345 InitXLOGAccess(void)
5347 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5348 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5349 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5350 (void) GetRedoRecPtr();
5354 * Once spawned, a backend may update its local RedoRecPtr from
5355 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5356 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5361 /* use volatile pointer to prevent code rearrangement */
5362 volatile XLogCtlData *xlogctl = XLogCtl;
5364 SpinLockAcquire(&xlogctl->info_lck);
5365 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5366 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5367 SpinLockRelease(&xlogctl->info_lck);
5373 * GetInsertRecPtr -- Returns the current insert position.
5375 * NOTE: The value *actually* returned is the position of the last full
5376 * xlog page. It lags behind the real insert position by at most 1 page.
5377 * For that, we don't need to acquire WALInsertLock which can be quite
5378 * heavily contended, and an approximation is enough for the current
5379 * usage of this function.
5382 GetInsertRecPtr(void)
5384 /* use volatile pointer to prevent code rearrangement */
5385 volatile XLogCtlData *xlogctl = XLogCtl;
5388 SpinLockAcquire(&xlogctl->info_lck);
5389 recptr = xlogctl->LogwrtRqst.Write;
5390 SpinLockRelease(&xlogctl->info_lck);
5396 * Get the time of the last xlog segment switch
5399 GetLastSegSwitchTime(void)
5403 /* Need WALWriteLock, but shared lock is sufficient */
5404 LWLockAcquire(WALWriteLock, LW_SHARED);
5405 result = XLogCtl->Write.lastSegSwitchTime;
5406 LWLockRelease(WALWriteLock);
5412 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5414 * This is exported for use by code that would like to have 64-bit XIDs.
5415 * We don't really support such things, but all XIDs within the system
5416 * can be presumed "close to" the result, and thus the epoch associated
5417 * with them can be determined.
5420 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5422 uint32 ckptXidEpoch;
5423 TransactionId ckptXid;
5424 TransactionId nextXid;
5426 /* Must read checkpoint info first, else have race condition */
5428 /* use volatile pointer to prevent code rearrangement */
5429 volatile XLogCtlData *xlogctl = XLogCtl;
5431 SpinLockAcquire(&xlogctl->info_lck);
5432 ckptXidEpoch = xlogctl->ckptXidEpoch;
5433 ckptXid = xlogctl->ckptXid;
5434 SpinLockRelease(&xlogctl->info_lck);
5437 /* Now fetch current nextXid */
5438 nextXid = ReadNewTransactionId();
5441 * nextXid is certainly logically later than ckptXid. So if it's
5442 * numerically less, it must have wrapped into the next epoch.
5444 if (nextXid < ckptXid)
5448 *epoch = ckptXidEpoch;
5452 * This must be called ONCE during postmaster or standalone-backend shutdown
5455 ShutdownXLOG(int code, Datum arg)
5458 (errmsg("shutting down")));
5460 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5463 ShutdownMultiXact();
5466 (errmsg("database system is shut down")));
5470 * Log start of a checkpoint.
5473 LogCheckpointStart(int flags)
5475 elog(LOG, "checkpoint starting:%s%s%s%s%s%s",
5476 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
5477 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
5478 (flags & CHECKPOINT_FORCE) ? " force" : "",
5479 (flags & CHECKPOINT_WAIT) ? " wait" : "",
5480 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
5481 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
5485 * Log end of a checkpoint.
5488 LogCheckpointEnd(void)
5490 long write_secs, sync_secs, total_secs;
5491 int write_usecs, sync_usecs, total_usecs;
5493 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
5495 TimestampDifference(CheckpointStats.ckpt_start_t,
5496 CheckpointStats.ckpt_end_t,
5497 &total_secs, &total_usecs);
5499 TimestampDifference(CheckpointStats.ckpt_write_t,
5500 CheckpointStats.ckpt_sync_t,
5501 &write_secs, &write_usecs);
5503 TimestampDifference(CheckpointStats.ckpt_sync_t,
5504 CheckpointStats.ckpt_sync_end_t,
5505 &sync_secs, &sync_usecs);
5507 elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
5508 "%d transaction log file(s) added, %d removed, %d recycled; "
5509 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
5510 CheckpointStats.ckpt_bufs_written,
5511 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
5512 CheckpointStats.ckpt_segs_added,
5513 CheckpointStats.ckpt_segs_removed,
5514 CheckpointStats.ckpt_segs_recycled,
5515 write_secs, write_usecs/1000,
5516 sync_secs, sync_usecs/1000,
5517 total_secs, total_usecs/1000);
5521 * Perform a checkpoint --- either during shutdown, or on-the-fly
5523 * flags is a bitwise OR of the following:
5524 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
5525 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
5526 * ignoring checkpoint_completion_target parameter.
5527 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
5528 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
5530 * Note: flags contains other bits, of interest here only for logging purposes.
5531 * In particular note that this routine is synchronous and does not pay
5532 * attention to CHECKPOINT_WAIT.
5535 CreateCheckPoint(int flags)
5537 bool shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
5538 CheckPoint checkPoint;
5540 XLogCtlInsert *Insert = &XLogCtl->Insert;
5545 TransactionId *inCommitXids;
5549 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5550 * (This is just pro forma, since in the present system structure there is
5551 * only one process that is allowed to issue checkpoints at any given
5554 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5557 * Prepare to accumulate statistics.
5559 * Note: because it is possible for log_checkpoints to change while a
5560 * checkpoint proceeds, we always accumulate stats, even if
5561 * log_checkpoints is currently off.
5563 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
5564 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
5567 * Use a critical section to force system panic if we have trouble.
5569 START_CRIT_SECTION();
5573 ControlFile->state = DB_SHUTDOWNING;
5574 ControlFile->time = time(NULL);
5575 UpdateControlFile();
5578 MemSet(&checkPoint, 0, sizeof(checkPoint));
5579 checkPoint.ThisTimeLineID = ThisTimeLineID;
5580 checkPoint.time = time(NULL);
5583 * We must hold WALInsertLock while examining insert state to determine
5584 * the checkpoint REDO pointer.
5586 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5589 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5590 * any XLOG records since the start of the last checkpoint, skip the
5591 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5592 * when the system is idle. That wastes log space, and more importantly it
5593 * exposes us to possible loss of both current and previous checkpoint
5594 * records if the machine crashes just as we're writing the update.
5595 * (Perhaps it'd make even more sense to checkpoint only when the previous
5596 * checkpoint record is in a different xlog page?)
5598 * We have to make two tests to determine that nothing has happened since
5599 * the start of the last checkpoint: current insertion point must match
5600 * the end of the last checkpoint record, and its redo pointer must point
5603 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
5605 XLogRecPtr curInsert;
5607 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5608 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5609 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5610 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5611 ControlFile->checkPoint.xlogid ==
5612 ControlFile->checkPointCopy.redo.xlogid &&
5613 ControlFile->checkPoint.xrecoff ==
5614 ControlFile->checkPointCopy.redo.xrecoff)
5616 LWLockRelease(WALInsertLock);
5617 LWLockRelease(CheckpointLock);
5624 * Compute new REDO record ptr = location of next XLOG record.
5626 * NB: this is NOT necessarily where the checkpoint record itself will be,
5627 * since other backends may insert more XLOG records while we're off doing
5628 * the buffer flush work. Those XLOG records are logically after the
5629 * checkpoint, even though physically before it. Got that?
5631 freespace = INSERT_FREESPACE(Insert);
5632 if (freespace < SizeOfXLogRecord)
5634 (void) AdvanceXLInsertBuffer(false);
5635 /* OK to ignore update return flag, since we will do flush anyway */
5636 freespace = INSERT_FREESPACE(Insert);
5638 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5641 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5642 * must be done while holding the insert lock AND the info_lck.
5644 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5645 * pointing past where it really needs to point. This is okay; the only
5646 * consequence is that XLogInsert might back up whole buffers that it
5647 * didn't really need to. We can't postpone advancing RedoRecPtr because
5648 * XLogInserts that happen while we are dumping buffers must assume that
5649 * their buffer changes are not included in the checkpoint.
5652 /* use volatile pointer to prevent code rearrangement */
5653 volatile XLogCtlData *xlogctl = XLogCtl;
5655 SpinLockAcquire(&xlogctl->info_lck);
5656 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5657 SpinLockRelease(&xlogctl->info_lck);
5661 * Now we can release WAL insert lock, allowing other xacts to proceed
5662 * while we are flushing disk buffers.
5664 LWLockRelease(WALInsertLock);
5667 * If enabled, log checkpoint start. We postpone this until now
5668 * so as not to log anything if we decided to skip the checkpoint.
5670 if (log_checkpoints)
5671 LogCheckpointStart(flags);
5674 * Before flushing data, we must wait for any transactions that are
5675 * currently in their commit critical sections. If an xact inserted its
5676 * commit record into XLOG just before the REDO point, then a crash
5677 * restart from the REDO point would not replay that record, which means
5678 * that our flushing had better include the xact's update of pg_clog. So
5679 * we wait till he's out of his commit critical section before proceeding.
5680 * See notes in RecordTransactionCommit().
5682 * Because we've already released WALInsertLock, this test is a bit fuzzy:
5683 * it is possible that we will wait for xacts we didn't really need to
5684 * wait for. But the delay should be short and it seems better to make
5685 * checkpoint take a bit longer than to hold locks longer than necessary.
5686 * (In fact, the whole reason we have this issue is that xact.c does
5687 * commit record XLOG insertion and clog update as two separate steps
5688 * protected by different locks, but again that seems best on grounds
5689 * of minimizing lock contention.)
5691 * A transaction that has not yet set inCommit when we look cannot be
5692 * at risk, since he's not inserted his commit record yet; and one that's
5693 * already cleared it is not at risk either, since he's done fixing clog
5694 * and we will correctly flush the update below. So we cannot miss any
5695 * xacts we need to wait for.
5697 nInCommit = GetTransactionsInCommit(&inCommitXids);
5701 pg_usleep(10000L); /* wait for 10 msec */
5702 } while (HaveTransactionsInCommit(inCommitXids, nInCommit));
5704 pfree(inCommitXids);
5707 * Get the other info we need for the checkpoint record.
5709 LWLockAcquire(XidGenLock, LW_SHARED);
5710 checkPoint.nextXid = ShmemVariableCache->nextXid;
5711 LWLockRelease(XidGenLock);
5713 /* Increase XID epoch if we've wrapped around since last checkpoint */
5714 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5715 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5716 checkPoint.nextXidEpoch++;
5718 LWLockAcquire(OidGenLock, LW_SHARED);
5719 checkPoint.nextOid = ShmemVariableCache->nextOid;
5721 checkPoint.nextOid += ShmemVariableCache->oidCount;
5722 LWLockRelease(OidGenLock);
5724 MultiXactGetCheckptMulti(shutdown,
5725 &checkPoint.nextMulti,
5726 &checkPoint.nextMultiOffset);
5729 * Having constructed the checkpoint record, ensure all shmem disk buffers
5730 * and commit-log buffers are flushed to disk.
5732 * This I/O could fail for various reasons. If so, we will fail to
5733 * complete the checkpoint, but there is no reason to force a system
5734 * panic. Accordingly, exit critical section while doing it.
5738 CheckPointGuts(checkPoint.redo, flags);
5740 START_CRIT_SECTION();
5743 * Now insert the checkpoint record into XLOG.
5745 rdata.data = (char *) (&checkPoint);
5746 rdata.len = sizeof(checkPoint);
5747 rdata.buffer = InvalidBuffer;
5750 recptr = XLogInsert(RM_XLOG_ID,
5751 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5752 XLOG_CHECKPOINT_ONLINE,
5758 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5759 * = end of actual checkpoint record.
5761 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5763 (errmsg("concurrent transaction log activity while database system is shutting down")));
5766 * Select point at which we can truncate the log, which we base on the
5767 * prior checkpoint's earliest info.
5769 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5772 * Update the control file.
5774 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5776 ControlFile->state = DB_SHUTDOWNED;
5777 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5778 ControlFile->checkPoint = ProcLastRecPtr;
5779 ControlFile->checkPointCopy = checkPoint;
5780 ControlFile->time = time(NULL);
5781 UpdateControlFile();
5782 LWLockRelease(ControlFileLock);
5784 /* Update shared-memory copy of checkpoint XID/epoch */
5786 /* use volatile pointer to prevent code rearrangement */
5787 volatile XLogCtlData *xlogctl = XLogCtl;
5789 SpinLockAcquire(&xlogctl->info_lck);
5790 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5791 xlogctl->ckptXid = checkPoint.nextXid;
5792 SpinLockRelease(&xlogctl->info_lck);
5796 * We are now done with critical updates; no need for system panic if we
5797 * have trouble while fooling with old log segments.
5802 * Delete old log files (those no longer needed even for previous
5805 if (_logId || _logSeg)
5807 PrevLogSeg(_logId, _logSeg);
5808 RemoveOldXlogFiles(_logId, _logSeg, recptr);
5812 * Make more log segments if needed. (Do this after recycling old log
5813 * segments, since that may supply some of the needed files.)
5816 PreallocXlogFiles(recptr);
5819 * Truncate pg_subtrans if possible. We can throw away all data before
5820 * the oldest XMIN of any running transaction. No future transaction will
5821 * attempt to reference any pg_subtrans entry older than that (see Asserts
5822 * in subtrans.c). During recovery, though, we mustn't do this because
5823 * StartupSUBTRANS hasn't been called yet.
5826 TruncateSUBTRANS(GetOldestXmin(true, false));
5828 /* All real work is done, but log before releasing lock. */
5829 if (log_checkpoints)
5832 LWLockRelease(CheckpointLock);
5836 * Flush all data in shared memory to disk, and fsync
5838 * This is the common code shared between regular checkpoints and
5839 * recovery restartpoints.
5842 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
5845 CheckPointSUBTRANS();
5846 CheckPointMultiXact();
5847 CheckPointBuffers(flags); /* performs all required fsyncs */
5848 /* We deliberately delay 2PC checkpointing as long as possible */
5849 CheckPointTwoPhase(checkPointRedo);
5853 * Set a recovery restart point if appropriate
5855 * This is similar to CreateCheckPoint, but is used during WAL recovery
5856 * to establish a point from which recovery can roll forward without
5857 * replaying the entire recovery log. This function is called each time
5858 * a checkpoint record is read from XLOG; it must determine whether a
5859 * restartpoint is needed or not.
5862 RecoveryRestartPoint(const CheckPoint *checkPoint)
5868 * Do nothing if the elapsed time since the last restartpoint is less than
5869 * half of checkpoint_timeout. (We use a value less than
5870 * checkpoint_timeout so that variations in the timing of checkpoints on
5871 * the master, or speed of transmission of WAL segments to a slave, won't
5872 * make the slave skip a restartpoint once it's synced with the master.)
5873 * Checking true elapsed time keeps us from doing restartpoints too often
5874 * while rapidly scanning large amounts of WAL.
5876 elapsed_secs = time(NULL) - ControlFile->time;
5877 if (elapsed_secs < CheckPointTimeout / 2)
5881 * Is it safe to checkpoint? We must ask each of the resource managers
5882 * whether they have any partial state information that might prevent a
5883 * correct restart from this point. If so, we skip this opportunity, but
5884 * return at the next checkpoint record for another try.
5886 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5888 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5889 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5894 * OK, force data out to disk
5896 CheckPointGuts(checkPoint->redo, CHECKPOINT_IMMEDIATE);
5899 * Update pg_control so that any subsequent crash will restart from this
5900 * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
5903 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5904 ControlFile->checkPoint = ReadRecPtr;
5905 ControlFile->checkPointCopy = *checkPoint;
5906 ControlFile->time = time(NULL);
5907 UpdateControlFile();
5910 (errmsg("recovery restart point at %X/%X",
5911 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5915 * Write a NEXTOID log record
5918 XLogPutNextOid(Oid nextOid)
5922 rdata.data = (char *) (&nextOid);
5923 rdata.len = sizeof(Oid);
5924 rdata.buffer = InvalidBuffer;
5926 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5929 * We need not flush the NEXTOID record immediately, because any of the
5930 * just-allocated OIDs could only reach disk as part of a tuple insert or
5931 * update that would have its own XLOG record that must follow the NEXTOID
5932 * record. Therefore, the standard buffer LSN interlock applied to those
5933 * records will ensure no such OID reaches disk before the NEXTOID record
5936 * Note, however, that the above statement only covers state "within" the
5937 * database. When we use a generated OID as a file or directory name,
5938 * we are in a sense violating the basic WAL rule, because that filesystem
5939 * change may reach disk before the NEXTOID WAL record does. The impact
5940 * of this is that if a database crash occurs immediately afterward,
5941 * we might after restart re-generate the same OID and find that it
5942 * conflicts with the leftover file or directory. But since for safety's
5943 * sake we always loop until finding a nonconflicting filename, this poses
5944 * no real problem in practice. See pgsql-hackers discussion 27-Sep-2006.
5949 * Write an XLOG SWITCH record.
5951 * Here we just blindly issue an XLogInsert request for the record.
5952 * All the magic happens inside XLogInsert.
5954 * The return value is either the end+1 address of the switch record,
5955 * or the end+1 address of the prior segment if we did not need to
5956 * write a switch record because we are already at segment start.
5959 RequestXLogSwitch(void)
5964 /* XLOG SWITCH, alone among xlog record types, has no data */
5965 rdata.buffer = InvalidBuffer;
5970 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5976 * XLOG resource manager's routines
5979 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5981 uint8 info = record->xl_info & ~XLR_INFO_MASK;
5983 if (info == XLOG_NEXTOID)
5987 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
5988 if (ShmemVariableCache->nextOid < nextOid)
5990 ShmemVariableCache->nextOid = nextOid;
5991 ShmemVariableCache->oidCount = 0;
5994 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
5996 CheckPoint checkPoint;
5998 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5999 /* In a SHUTDOWN checkpoint, believe the counters exactly */
6000 ShmemVariableCache->nextXid = checkPoint.nextXid;
6001 ShmemVariableCache->nextOid = checkPoint.nextOid;
6002 ShmemVariableCache->oidCount = 0;
6003 MultiXactSetNextMXact(checkPoint.nextMulti,
6004 checkPoint.nextMultiOffset);
6006 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6007 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6008 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6011 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
6013 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6015 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
6016 !list_member_int(expectedTLIs,
6017 (int) checkPoint.ThisTimeLineID))
6019 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
6020 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6021 /* Following WAL records should be run with new TLI */
6022 ThisTimeLineID = checkPoint.ThisTimeLineID;
6025 RecoveryRestartPoint(&checkPoint);
6027 else if (info == XLOG_CHECKPOINT_ONLINE)
6029 CheckPoint checkPoint;
6031 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6032 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
6033 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
6034 checkPoint.nextXid))
6035 ShmemVariableCache->nextXid = checkPoint.nextXid;
6036 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
6038 ShmemVariableCache->nextOid = checkPoint.nextOid;
6039 ShmemVariableCache->oidCount = 0;
6041 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
6042 checkPoint.nextMultiOffset);
6044 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6045 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6046 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6048 /* TLI should not change in an on-line checkpoint */
6049 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6051 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
6052 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6054 RecoveryRestartPoint(&checkPoint);
6056 else if (info == XLOG_NOOP)
6058 /* nothing to do here */
6060 else if (info == XLOG_SWITCH)
6062 /* nothing to do here */
6067 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
6069 uint8 info = xl_info & ~XLR_INFO_MASK;
6071 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
6072 info == XLOG_CHECKPOINT_ONLINE)
6074 CheckPoint *checkpoint = (CheckPoint *) rec;
6076 appendStringInfo(buf, "checkpoint: redo %X/%X; "
6077 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
6078 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
6079 checkpoint->ThisTimeLineID,
6080 checkpoint->nextXidEpoch, checkpoint->nextXid,
6081 checkpoint->nextOid,
6082 checkpoint->nextMulti,
6083 checkpoint->nextMultiOffset,
6084 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
6086 else if (info == XLOG_NOOP)
6088 appendStringInfo(buf, "xlog no-op");
6090 else if (info == XLOG_NEXTOID)
6094 memcpy(&nextOid, rec, sizeof(Oid));
6095 appendStringInfo(buf, "nextOid: %u", nextOid);
6097 else if (info == XLOG_SWITCH)
6099 appendStringInfo(buf, "xlog switch");
6102 appendStringInfo(buf, "UNKNOWN");
6108 xlog_outrec(StringInfo buf, XLogRecord *record)
6112 appendStringInfo(buf, "prev %X/%X; xid %u",
6113 record->xl_prev.xlogid, record->xl_prev.xrecoff,
6116 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
6118 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
6119 appendStringInfo(buf, "; bkpb%d", i + 1);
6122 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
6124 #endif /* WAL_DEBUG */
6131 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
6133 int new_sync_method;
6136 if (pg_strcasecmp(method, "fsync") == 0)
6138 new_sync_method = SYNC_METHOD_FSYNC;
6141 #ifdef HAVE_FSYNC_WRITETHROUGH
6142 else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
6144 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
6148 #ifdef HAVE_FDATASYNC
6149 else if (pg_strcasecmp(method, "fdatasync") == 0)
6151 new_sync_method = SYNC_METHOD_FDATASYNC;
6155 #ifdef OPEN_SYNC_FLAG
6156 else if (pg_strcasecmp(method, "open_sync") == 0)
6158 new_sync_method = SYNC_METHOD_OPEN;
6159 new_sync_bit = OPEN_SYNC_FLAG;
6162 #ifdef OPEN_DATASYNC_FLAG
6163 else if (pg_strcasecmp(method, "open_datasync") == 0)
6165 new_sync_method = SYNC_METHOD_OPEN;
6166 new_sync_bit = OPEN_DATASYNC_FLAG;
6175 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
6178 * To ensure that no blocks escape unsynced, force an fsync on the
6179 * currently open log segment (if any). Also, if the open flag is
6180 * changing, close the log file so it will be reopened (with new flag
6183 if (openLogFile >= 0)
6185 if (pg_fsync(openLogFile) != 0)
6187 (errcode_for_file_access(),
6188 errmsg("could not fsync log file %u, segment %u: %m",
6189 openLogId, openLogSeg)));
6190 if (open_sync_bit != new_sync_bit)
6193 sync_method = new_sync_method;
6194 open_sync_bit = new_sync_bit;
6202 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6205 issue_xlog_fsync(void)
6207 switch (sync_method)
6209 case SYNC_METHOD_FSYNC:
6210 if (pg_fsync_no_writethrough(openLogFile) != 0)
6212 (errcode_for_file_access(),
6213 errmsg("could not fsync log file %u, segment %u: %m",
6214 openLogId, openLogSeg)));
6216 #ifdef HAVE_FSYNC_WRITETHROUGH
6217 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6218 if (pg_fsync_writethrough(openLogFile) != 0)
6220 (errcode_for_file_access(),
6221 errmsg("could not fsync write-through log file %u, segment %u: %m",
6222 openLogId, openLogSeg)));
6225 #ifdef HAVE_FDATASYNC
6226 case SYNC_METHOD_FDATASYNC:
6227 if (pg_fdatasync(openLogFile) != 0)
6229 (errcode_for_file_access(),
6230 errmsg("could not fdatasync log file %u, segment %u: %m",
6231 openLogId, openLogSeg)));
6234 case SYNC_METHOD_OPEN:
6235 /* write synced it already */
6238 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6245 * pg_start_backup: set up for taking an on-line backup dump
6247 * Essentially what this does is to create a backup label file in $PGDATA,
6248 * where it will be archived as part of the backup dump. The label file
6249 * contains the user-supplied label string (typically this would be used
6250 * to tell where the backup dump will be stored) and the starting time and
6251 * starting WAL location for the dump.
6254 pg_start_backup(PG_FUNCTION_ARGS)
6256 text *backupid = PG_GETARG_TEXT_P(0);
6259 XLogRecPtr checkpointloc;
6260 XLogRecPtr startpoint;
6263 char xlogfilename[MAXFNAMELEN];
6266 struct stat stat_buf;
6271 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6272 (errmsg("must be superuser to run a backup"))));
6274 if (!XLogArchivingActive())
6276 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6277 (errmsg("WAL archiving is not active"),
6278 (errhint("archive_command must be defined before "
6279 "online backups can be made safely.")))));
6281 backupidstr = DatumGetCString(DirectFunctionCall1(textout,
6282 PointerGetDatum(backupid)));
6285 * Mark backup active in shared memory. We must do full-page WAL writes
6286 * during an on-line backup even if not doing so at other times, because
6287 * it's quite possible for the backup dump to obtain a "torn" (partially
6288 * written) copy of a database page if it reads the page concurrently with
6289 * our write to the same page. This can be fixed as long as the first
6290 * write to the page in the WAL sequence is a full-page write. Hence, we
6291 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6292 * are no dirty pages in shared memory that might get dumped while the
6293 * backup is in progress without having a corresponding WAL record. (Once
6294 * the backup is complete, we need not force full-page writes anymore,
6295 * since we expect that any pages not modified during the backup interval
6296 * must have been correctly captured by the backup.)
6298 * We must hold WALInsertLock to change the value of forcePageWrites, to
6299 * ensure adequate interlocking against XLogInsert().
6301 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6302 if (XLogCtl->Insert.forcePageWrites)
6304 LWLockRelease(WALInsertLock);
6306 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6307 errmsg("a backup is already in progress"),
6308 errhint("Run pg_stop_backup() and try again.")));
6310 XLogCtl->Insert.forcePageWrites = true;
6311 LWLockRelease(WALInsertLock);
6313 /* Use a TRY block to ensure we release forcePageWrites if fail below */
6317 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6318 * page problems, this guarantees that two successive backup runs will
6319 * have different checkpoint positions and hence different history
6320 * file names, even if nothing happened in between.
6322 * We don't use CHECKPOINT_IMMEDIATE, hence this can take awhile.
6324 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT);
6327 * Now we need to fetch the checkpoint record location, and also its
6328 * REDO pointer. The oldest point in WAL that would be needed to
6329 * restore starting from the checkpoint is precisely the REDO pointer.
6331 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6332 checkpointloc = ControlFile->checkPoint;
6333 startpoint = ControlFile->checkPointCopy.redo;
6334 LWLockRelease(ControlFileLock);
6336 XLByteToSeg(startpoint, _logId, _logSeg);
6337 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6340 * We deliberately use strftime/localtime not the src/timezone
6341 * functions, so that backup labels will consistently be recorded in
6342 * the same timezone regardless of TimeZone setting. This matches
6343 * elog.c's practice.
6345 stamp_time = time(NULL);
6346 strftime(strfbuf, sizeof(strfbuf),
6347 "%Y-%m-%d %H:%M:%S %Z",
6348 localtime(&stamp_time));
6351 * Check for existing backup label --- implies a backup is already
6352 * running. (XXX given that we checked forcePageWrites above, maybe
6353 * it would be OK to just unlink any such label file?)
6355 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6357 if (errno != ENOENT)
6359 (errcode_for_file_access(),
6360 errmsg("could not stat file \"%s\": %m",
6361 BACKUP_LABEL_FILE)));
6365 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6366 errmsg("a backup is already in progress"),
6367 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6368 BACKUP_LABEL_FILE)));
6371 * Okay, write the file
6373 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6376 (errcode_for_file_access(),
6377 errmsg("could not create file \"%s\": %m",
6378 BACKUP_LABEL_FILE)));
6379 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6380 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6381 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6382 checkpointloc.xlogid, checkpointloc.xrecoff);
6383 fprintf(fp, "START TIME: %s\n", strfbuf);
6384 fprintf(fp, "LABEL: %s\n", backupidstr);
6385 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6387 (errcode_for_file_access(),
6388 errmsg("could not write file \"%s\": %m",
6389 BACKUP_LABEL_FILE)));
6393 /* Turn off forcePageWrites on failure */
6394 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6395 XLogCtl->Insert.forcePageWrites = false;
6396 LWLockRelease(WALInsertLock);
6403 * We're done. As a convenience, return the starting WAL location.
6405 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6406 startpoint.xlogid, startpoint.xrecoff);
6407 result = DatumGetTextP(DirectFunctionCall1(textin,
6408 CStringGetDatum(xlogfilename)));
6409 PG_RETURN_TEXT_P(result);
6413 * pg_stop_backup: finish taking an on-line backup dump
6415 * We remove the backup label file created by pg_start_backup, and instead
6416 * create a backup history file in pg_xlog (whence it will immediately be
6417 * archived). The backup history file contains the same info found in
6418 * the label file, plus the backup-end time and WAL location.
6421 pg_stop_backup(PG_FUNCTION_ARGS)
6424 XLogRecPtr startpoint;
6425 XLogRecPtr stoppoint;
6428 char histfilepath[MAXPGPATH];
6429 char startxlogfilename[MAXFNAMELEN];
6430 char stopxlogfilename[MAXFNAMELEN];
6440 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6441 (errmsg("must be superuser to run a backup"))));
6444 * OK to clear forcePageWrites
6446 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6447 XLogCtl->Insert.forcePageWrites = false;
6448 LWLockRelease(WALInsertLock);
6451 * Force a switch to a new xlog segment file, so that the backup is valid
6452 * as soon as archiver moves out the current segment file. We'll report
6453 * the end address of the XLOG SWITCH record as the backup stopping point.
6455 stoppoint = RequestXLogSwitch();
6457 XLByteToSeg(stoppoint, _logId, _logSeg);
6458 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
6461 * We deliberately use strftime/localtime not the src/timezone functions,
6462 * so that backup labels will consistently be recorded in the same
6463 * timezone regardless of TimeZone setting. This matches elog.c's
6466 stamp_time = time(NULL);
6467 strftime(strfbuf, sizeof(strfbuf),
6468 "%Y-%m-%d %H:%M:%S %Z",
6469 localtime(&stamp_time));
6472 * Open the existing label file
6474 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6477 if (errno != ENOENT)
6479 (errcode_for_file_access(),
6480 errmsg("could not read file \"%s\": %m",
6481 BACKUP_LABEL_FILE)));
6483 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6484 errmsg("a backup is not in progress")));
6488 * Read and parse the START WAL LOCATION line (this code is pretty crude,
6489 * but we are not expecting any variability in the file format).
6491 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
6492 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6493 &ch) != 4 || ch != '\n')
6495 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6496 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6499 * Write the backup history file
6501 XLByteToSeg(startpoint, _logId, _logSeg);
6502 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6503 startpoint.xrecoff % XLogSegSize);
6504 fp = AllocateFile(histfilepath, "w");
6507 (errcode_for_file_access(),
6508 errmsg("could not create file \"%s\": %m",
6510 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6511 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
6512 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
6513 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
6514 /* transfer remaining lines from label to history file */
6515 while ((ich = fgetc(lfp)) != EOF)
6517 fprintf(fp, "STOP TIME: %s\n", strfbuf);
6518 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6520 (errcode_for_file_access(),
6521 errmsg("could not write file \"%s\": %m",
6525 * Close and remove the backup label file
6527 if (ferror(lfp) || FreeFile(lfp))
6529 (errcode_for_file_access(),
6530 errmsg("could not read file \"%s\": %m",
6531 BACKUP_LABEL_FILE)));
6532 if (unlink(BACKUP_LABEL_FILE) != 0)
6534 (errcode_for_file_access(),
6535 errmsg("could not remove file \"%s\": %m",
6536 BACKUP_LABEL_FILE)));
6539 * Clean out any no-longer-needed history files. As a side effect, this
6540 * will post a .ready file for the newly created history file, notifying
6541 * the archiver that history file may be archived immediately.
6543 CleanupBackupHistory();
6546 * We're done. As a convenience, return the ending WAL location.
6548 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
6549 stoppoint.xlogid, stoppoint.xrecoff);
6550 result = DatumGetTextP(DirectFunctionCall1(textin,
6551 CStringGetDatum(stopxlogfilename)));
6552 PG_RETURN_TEXT_P(result);
6556 * pg_switch_xlog: switch to next xlog file
6559 pg_switch_xlog(PG_FUNCTION_ARGS)
6562 XLogRecPtr switchpoint;
6563 char location[MAXFNAMELEN];
6567 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6568 (errmsg("must be superuser to switch transaction log files"))));
6570 switchpoint = RequestXLogSwitch();
6573 * As a convenience, return the WAL location of the switch record
6575 snprintf(location, sizeof(location), "%X/%X",
6576 switchpoint.xlogid, switchpoint.xrecoff);
6577 result = DatumGetTextP(DirectFunctionCall1(textin,
6578 CStringGetDatum(location)));
6579 PG_RETURN_TEXT_P(result);
6583 * Report the current WAL write location (same format as pg_start_backup etc)
6585 * This is useful for determining how much of WAL is visible to an external
6586 * archiving process. Note that the data before this point is written out
6587 * to the kernel, but is not necessarily synced to disk.
6590 pg_current_xlog_location(PG_FUNCTION_ARGS)
6593 char location[MAXFNAMELEN];
6595 /* Make sure we have an up-to-date local LogwrtResult */
6597 /* use volatile pointer to prevent code rearrangement */
6598 volatile XLogCtlData *xlogctl = XLogCtl;
6600 SpinLockAcquire(&xlogctl->info_lck);
6601 LogwrtResult = xlogctl->LogwrtResult;
6602 SpinLockRelease(&xlogctl->info_lck);
6605 snprintf(location, sizeof(location), "%X/%X",
6606 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
6608 result = DatumGetTextP(DirectFunctionCall1(textin,
6609 CStringGetDatum(location)));
6610 PG_RETURN_TEXT_P(result);
6614 * Report the current WAL insert location (same format as pg_start_backup etc)
6616 * This function is mostly for debugging purposes.
6619 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
6622 XLogCtlInsert *Insert = &XLogCtl->Insert;
6623 XLogRecPtr current_recptr;
6624 char location[MAXFNAMELEN];
6627 * Get the current end-of-WAL position ... shared lock is sufficient
6629 LWLockAcquire(WALInsertLock, LW_SHARED);
6630 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
6631 LWLockRelease(WALInsertLock);
6633 snprintf(location, sizeof(location), "%X/%X",
6634 current_recptr.xlogid, current_recptr.xrecoff);
6636 result = DatumGetTextP(DirectFunctionCall1(textin,
6637 CStringGetDatum(location)));
6638 PG_RETURN_TEXT_P(result);
6642 * Compute an xlog file name and decimal byte offset given a WAL location,
6643 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6645 * Note that a location exactly at a segment boundary is taken to be in
6646 * the previous segment. This is usually the right thing, since the
6647 * expected usage is to determine which xlog file(s) are ready to archive.
6650 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
6652 text *location = PG_GETARG_TEXT_P(0);
6654 unsigned int uxlogid;
6655 unsigned int uxrecoff;
6659 XLogRecPtr locationpoint;
6660 char xlogfilename[MAXFNAMELEN];
6663 TupleDesc resultTupleDesc;
6664 HeapTuple resultHeapTuple;
6668 * Read input and parse
6670 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6671 PointerGetDatum(location)));
6673 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6675 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6676 errmsg("could not parse transaction log location \"%s\"",
6679 locationpoint.xlogid = uxlogid;
6680 locationpoint.xrecoff = uxrecoff;
6683 * Construct a tuple descriptor for the result row. This must match this
6684 * function's pg_proc entry!
6686 resultTupleDesc = CreateTemplateTupleDesc(2, false);
6687 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
6689 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
6692 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
6697 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6698 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6700 values[0] = DirectFunctionCall1(textin,
6701 CStringGetDatum(xlogfilename));
6707 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
6709 values[1] = UInt32GetDatum(xrecoff);
6713 * Tuple jam: Having first prepared your Datums, then squash together
6715 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
6717 result = HeapTupleGetDatum(resultHeapTuple);
6719 PG_RETURN_DATUM(result);
6723 * Compute an xlog file name given a WAL location,
6724 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6727 pg_xlogfile_name(PG_FUNCTION_ARGS)
6729 text *location = PG_GETARG_TEXT_P(0);
6732 unsigned int uxlogid;
6733 unsigned int uxrecoff;
6736 XLogRecPtr locationpoint;
6737 char xlogfilename[MAXFNAMELEN];
6739 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6740 PointerGetDatum(location)));
6742 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6744 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6745 errmsg("could not parse transaction log location \"%s\"",
6748 locationpoint.xlogid = uxlogid;
6749 locationpoint.xrecoff = uxrecoff;
6751 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6752 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6754 result = DatumGetTextP(DirectFunctionCall1(textin,
6755 CStringGetDatum(xlogfilename)));
6756 PG_RETURN_TEXT_P(result);
6760 * read_backup_label: check to see if a backup_label file is present
6762 * If we see a backup_label during recovery, we assume that we are recovering
6763 * from a backup dump file, and we therefore roll forward from the checkpoint
6764 * identified by the label file, NOT what pg_control says. This avoids the
6765 * problem that pg_control might have been archived one or more checkpoints
6766 * later than the start of the dump, and so if we rely on it as the start
6767 * point, we will fail to restore a consistent database state.
6769 * We also attempt to retrieve the corresponding backup history file.
6770 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6773 * Returns TRUE if a backup_label was found (and fills the checkpoint
6774 * location into *checkPointLoc); returns FALSE if not.
6777 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6779 XLogRecPtr startpoint;
6780 XLogRecPtr stoppoint;
6781 char histfilename[MAXFNAMELEN];
6782 char histfilepath[MAXPGPATH];
6783 char startxlogfilename[MAXFNAMELEN];
6784 char stopxlogfilename[MAXFNAMELEN];
6792 /* Default is to not constrain recovery stop point */
6793 minRecoveryLoc->xlogid = 0;
6794 minRecoveryLoc->xrecoff = 0;
6797 * See if label file is present
6799 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6802 if (errno != ENOENT)
6804 (errcode_for_file_access(),
6805 errmsg("could not read file \"%s\": %m",
6806 BACKUP_LABEL_FILE)));
6807 return false; /* it's not there, all is fine */
6811 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
6812 * is pretty crude, but we are not expecting any variability in the file
6815 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
6816 &startpoint.xlogid, &startpoint.xrecoff, &tli,
6817 startxlogfilename, &ch) != 5 || ch != '\n')
6819 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6820 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6821 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
6822 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
6823 &ch) != 3 || ch != '\n')
6825 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6826 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6827 if (ferror(lfp) || FreeFile(lfp))
6829 (errcode_for_file_access(),
6830 errmsg("could not read file \"%s\": %m",
6831 BACKUP_LABEL_FILE)));
6834 * Try to retrieve the backup history file (no error if we can't)
6836 XLByteToSeg(startpoint, _logId, _logSeg);
6837 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
6838 startpoint.xrecoff % XLogSegSize);
6840 if (InArchiveRecovery)
6841 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
6843 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
6844 startpoint.xrecoff % XLogSegSize);
6846 fp = AllocateFile(histfilepath, "r");
6850 * Parse history file to identify stop point.
6852 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
6853 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6854 &ch) != 4 || ch != '\n')
6856 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6857 errmsg("invalid data in file \"%s\"", histfilename)));
6858 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
6859 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6860 &ch) != 4 || ch != '\n')
6862 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6863 errmsg("invalid data in file \"%s\"", histfilename)));
6864 *minRecoveryLoc = stoppoint;
6865 if (ferror(fp) || FreeFile(fp))
6867 (errcode_for_file_access(),
6868 errmsg("could not read file \"%s\": %m",
6876 * Error context callback for errors occurring during rm_redo().
6879 rm_redo_error_callback(void *arg)
6881 XLogRecord *record = (XLogRecord *) arg;
6884 initStringInfo(&buf);
6885 RmgrTable[record->xl_rmid].rm_desc(&buf,
6887 XLogRecGetData(record));
6889 /* don't bother emitting empty description */
6891 errcontext("xlog redo %s", buf.data);