1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2008, 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.297 2008/04/16 23:59:40 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/ipc.h"
47 #include "storage/pmsignal.h"
48 #include "storage/procarray.h"
49 #include "storage/smgr.h"
50 #include "storage/spin.h"
51 #include "utils/builtins.h"
52 #include "utils/pg_locale.h"
53 #include "utils/ps_status.h"
56 /* File path names (all relative to $PGDATA) */
57 #define BACKUP_LABEL_FILE "backup_label"
58 #define BACKUP_LABEL_OLD "backup_label.old"
59 #define RECOVERY_COMMAND_FILE "recovery.conf"
60 #define RECOVERY_COMMAND_DONE "recovery.done"
63 /* User-settable parameters */
64 int CheckPointSegments = 3;
66 int XLogArchiveTimeout = 0;
67 bool XLogArchiveMode = false;
68 char *XLogArchiveCommand = NULL;
69 char *XLOG_sync_method = NULL;
70 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
71 bool fullPageWrites = true;
72 bool log_checkpoints = false;
75 bool XLOG_DEBUG = false;
79 * XLOGfileslop is the maximum number of preallocated future XLOG segments.
80 * When we are done with an old XLOG segment file, we will recycle it as a
81 * future XLOG segment as long as there aren't already XLOGfileslop future
82 * segments; else we'll delete it. This could be made a separate GUC
83 * variable, but at present I think it's sufficient to hardwire it as
84 * 2*CheckPointSegments+1. Under normal conditions, a checkpoint will free
85 * no more than 2*CheckPointSegments log segments, and we want to recycle all
86 * of them; the +1 allows boundary cases to happen without wasting a
87 * delete/create-segment cycle.
89 #define XLOGfileslop (2*CheckPointSegments + 1)
92 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
93 int sync_method = DEFAULT_SYNC_METHOD;
94 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
96 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
100 * Statistics for current checkpoint are collected in this global struct.
101 * Because only the background writer or a stand-alone backend can perform
102 * checkpoints, this will be unused in normal backends.
104 CheckpointStatsData CheckpointStats;
107 * ThisTimeLineID will be same in all backends --- it identifies current
108 * WAL timeline for the database system.
110 TimeLineID ThisTimeLineID = 0;
112 /* Are we doing recovery from XLOG? */
113 bool InRecovery = false;
115 /* Are we recovering using offline XLOG archives? */
116 static bool InArchiveRecovery = false;
118 /* Was the last xlog file restored from archive, or local? */
119 static bool restoredFromArchive = false;
121 /* options taken from recovery.conf */
122 static char *recoveryRestoreCommand = NULL;
123 static bool recoveryTarget = false;
124 static bool recoveryTargetExact = false;
125 static bool recoveryTargetInclusive = true;
126 static bool recoveryLogRestartpoints = false;
127 static TransactionId recoveryTargetXid;
128 static TimestampTz recoveryTargetTime;
129 static TimestampTz recoveryLastXTime = 0;
131 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
132 static TransactionId recoveryStopXid;
133 static TimestampTz recoveryStopTime;
134 static bool recoveryStopAfter;
137 * During normal operation, the only timeline we care about is ThisTimeLineID.
138 * During recovery, however, things are more complicated. To simplify life
139 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
140 * scan through the WAL history (that is, it is the line that was active when
141 * the currently-scanned WAL record was generated). We also need these
144 * recoveryTargetTLI: the desired timeline that we want to end in.
146 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
147 * its known parents, newest first (so recoveryTargetTLI is always the
148 * first list member). Only these TLIs are expected to be seen in the WAL
149 * segments we read, and indeed only these TLIs will be considered as
150 * candidate WAL files to open at all.
152 * curFileTLI: the TLI appearing in the name of the current input WAL file.
153 * (This is not necessarily the same as ThisTimeLineID, because we could
154 * be scanning data that was copied from an ancestor timeline when the current
155 * file was created.) During a sequential scan we do not allow this value
158 static TimeLineID recoveryTargetTLI;
159 static List *expectedTLIs;
160 static TimeLineID curFileTLI;
163 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
164 * current backend. It is updated for all inserts. XactLastRecEnd points to
165 * end+1 of the last record, and is reset when we end a top-level transaction,
166 * or start a new one; so it can be used to tell if the current transaction has
167 * created any XLOG records.
169 static XLogRecPtr ProcLastRecPtr = {0, 0};
171 XLogRecPtr XactLastRecEnd = {0, 0};
174 * RedoRecPtr is this backend's local copy of the REDO record pointer
175 * (which is almost but not quite the same as a pointer to the most recent
176 * CHECKPOINT record). We update this from the shared-memory copy,
177 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
178 * hold the Insert lock). See XLogInsert for details. We are also allowed
179 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
180 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
183 static XLogRecPtr RedoRecPtr;
186 * Shared-memory data structures for XLOG control
188 * LogwrtRqst indicates a byte position that we need to write and/or fsync
189 * the log up to (all records before that point must be written or fsynced).
190 * LogwrtResult indicates the byte positions we have already written/fsynced.
191 * These structs are identical but are declared separately to indicate their
192 * slightly different functions.
194 * We do a lot of pushups to minimize the amount of access to lockable
195 * shared memory values. There are actually three shared-memory copies of
196 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
197 * XLogCtl->LogwrtResult is protected by info_lck
198 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
199 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
200 * One must hold the associated lock to read or write any of these, but
201 * of course no lock is needed to read/write the unshared LogwrtResult.
203 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
204 * right", since both are updated by a write or flush operation before
205 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
206 * is that it can be examined/modified by code that already holds WALWriteLock
207 * without needing to grab info_lck as well.
209 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
210 * but is updated when convenient. Again, it exists for the convenience of
211 * code that is already holding WALInsertLock but not the other locks.
213 * The unshared LogwrtResult may lag behind any or all of these, and again
214 * is updated when convenient.
216 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
217 * (protected by info_lck), but we don't need to cache any copies of it.
219 * Note that this all works because the request and result positions can only
220 * advance forward, never back up, and so we can easily determine which of two
221 * values is "more up to date".
223 * info_lck is only held long enough to read/update the protected variables,
224 * so it's a plain spinlock. The other locks are held longer (potentially
225 * over I/O operations), so we use LWLocks for them. These locks are:
227 * WALInsertLock: must be held to insert a record into the WAL buffers.
229 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
232 * ControlFileLock: must be held to read/update control file or create
235 * CheckpointLock: must be held to do a checkpoint (ensures only one
236 * checkpointer at a time; currently, with all checkpoints done by the
237 * bgwriter, this is just pro forma).
242 typedef struct XLogwrtRqst
244 XLogRecPtr Write; /* last byte + 1 to write out */
245 XLogRecPtr Flush; /* last byte + 1 to flush */
248 typedef struct XLogwrtResult
250 XLogRecPtr Write; /* last byte + 1 written out */
251 XLogRecPtr Flush; /* last byte + 1 flushed */
255 * Shared state data for XLogInsert.
257 typedef struct XLogCtlInsert
259 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
260 XLogRecPtr PrevRecord; /* start of previously-inserted record */
261 int curridx; /* current block index in cache */
262 XLogPageHeader currpage; /* points to header of block in cache */
263 char *currpos; /* current insertion point in cache */
264 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
265 bool forcePageWrites; /* forcing full-page writes for PITR? */
269 * Shared state data for XLogWrite/XLogFlush.
271 typedef struct XLogCtlWrite
273 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
274 int curridx; /* cache index of next block to write */
275 pg_time_t lastSegSwitchTime; /* time of last xlog segment switch */
279 * Total shared-memory state for XLOG.
281 typedef struct XLogCtlData
283 /* Protected by WALInsertLock: */
284 XLogCtlInsert Insert;
286 /* Protected by info_lck: */
287 XLogwrtRqst LogwrtRqst;
288 XLogwrtResult LogwrtResult;
289 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
290 TransactionId ckptXid;
291 XLogRecPtr asyncCommitLSN; /* LSN of newest async commit */
293 /* Protected by WALWriteLock: */
297 * These values do not change after startup, although the pointed-to pages
298 * and xlblocks values certainly do. Permission to read/write the pages
299 * and xlblocks values depends on WALInsertLock and WALWriteLock.
301 char *pages; /* buffers for unwritten XLOG pages */
302 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
303 int XLogCacheBlck; /* highest allocated xlog buffer index */
304 TimeLineID ThisTimeLineID;
306 slock_t info_lck; /* locks shared variables shown above */
309 static XLogCtlData *XLogCtl = NULL;
312 * We maintain an image of pg_control in shared memory.
314 static ControlFileData *ControlFile = NULL;
317 * Macros for managing XLogInsert state. In most cases, the calling routine
318 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
319 * so these are passed as parameters instead of being fetched via XLogCtl.
322 /* Free space remaining in the current xlog page buffer */
323 #define INSERT_FREESPACE(Insert) \
324 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
326 /* Construct XLogRecPtr value for current insertion point */
327 #define INSERT_RECPTR(recptr,Insert,curridx) \
329 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
331 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
334 #define PrevBufIdx(idx) \
335 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
337 #define NextBufIdx(idx) \
338 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
341 * Private, possibly out-of-date copy of shared LogwrtResult.
342 * See discussion above.
344 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
347 * openLogFile is -1 or a kernel FD for an open log file segment.
348 * When it's open, openLogOff is the current seek offset in the file.
349 * openLogId/openLogSeg identify the segment. These variables are only
350 * used to write the XLOG, and so will normally refer to the active segment.
352 static int openLogFile = -1;
353 static uint32 openLogId = 0;
354 static uint32 openLogSeg = 0;
355 static uint32 openLogOff = 0;
358 * These variables are used similarly to the ones above, but for reading
359 * the XLOG. Note, however, that readOff generally represents the offset
360 * of the page just read, not the seek position of the FD itself, which
361 * will be just past that page.
363 static int readFile = -1;
364 static uint32 readId = 0;
365 static uint32 readSeg = 0;
366 static uint32 readOff = 0;
368 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
369 static char *readBuf = NULL;
371 /* Buffer for current ReadRecord result (expandable) */
372 static char *readRecordBuf = NULL;
373 static uint32 readRecordBufSize = 0;
375 /* State information for XLOG reading */
376 static XLogRecPtr ReadRecPtr; /* start of last record read */
377 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
378 static XLogRecord *nextRecord = NULL;
379 static TimeLineID lastPageTLI = 0;
381 static bool InRedo = false;
384 static void XLogArchiveNotify(const char *xlog);
385 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
386 static bool XLogArchiveCheckDone(const char *xlog, bool create_if_missing);
387 static void XLogArchiveCleanup(const char *xlog);
388 static void readRecoveryCommandFile(void);
389 static void exitArchiveRecovery(TimeLineID endTLI,
390 uint32 endLogId, uint32 endLogSeg);
391 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
392 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
394 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
395 XLogRecPtr *lsn, BkpBlock *bkpb);
396 static bool AdvanceXLInsertBuffer(bool new_segment);
397 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
398 static int XLogFileInit(uint32 log, uint32 seg,
399 bool *use_existent, bool use_lock);
400 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
401 bool find_free, int *max_advance,
403 static int XLogFileOpen(uint32 log, uint32 seg);
404 static int XLogFileRead(uint32 log, uint32 seg, int emode);
405 static void XLogFileClose(void);
406 static bool RestoreArchivedFile(char *path, const char *xlogfname,
407 const char *recovername, off_t expectedSize);
408 static void PreallocXlogFiles(XLogRecPtr endptr);
409 static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
410 static void CleanupBackupHistory(void);
411 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
412 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
413 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
414 static List *readTimeLineHistory(TimeLineID targetTLI);
415 static bool existsTimeLineHistory(TimeLineID probeTLI);
416 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
417 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
419 uint32 endLogId, uint32 endLogSeg);
420 static void WriteControlFile(void);
421 static void ReadControlFile(void);
422 static char *str_time(pg_time_t tnow);
424 static void xlog_outrec(StringInfo buf, XLogRecord *record);
426 static void issue_xlog_fsync(void);
427 static void pg_start_backup_callback(int code, Datum arg);
428 static bool read_backup_label(XLogRecPtr *checkPointLoc,
429 XLogRecPtr *minRecoveryLoc);
430 static void rm_redo_error_callback(void *arg);
434 * Insert an XLOG record having the specified RMID and info bytes,
435 * with the body of the record being the data chunk(s) described by
436 * the rdata chain (see xlog.h for notes about rdata).
438 * Returns XLOG pointer to end of record (beginning of next record).
439 * This can be used as LSN for data pages affected by the logged action.
440 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
441 * before the data page can be written out. This implements the basic
442 * WAL rule "write the log before the data".)
444 * NB: this routine feels free to scribble on the XLogRecData structs,
445 * though not on the data they reference. This is OK since the XLogRecData
446 * structs are always just temporaries in the calling code.
449 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
451 XLogCtlInsert *Insert = &XLogCtl->Insert;
453 XLogContRecord *contrecord;
455 XLogRecPtr WriteRqst;
459 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
460 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
461 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
462 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
463 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
464 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
465 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
472 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
474 /* info's high bits are reserved for use by me */
475 if (info & XLR_INFO_MASK)
476 elog(PANIC, "invalid xlog info mask %02X", info);
479 * In bootstrap mode, we don't actually log anything but XLOG resources;
480 * return a phony record pointer.
482 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
485 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
490 * Here we scan the rdata chain, determine which buffers must be backed
491 * up, and compute the CRC values for the data. Note that the record
492 * header isn't added into the CRC initially since we don't know the final
493 * length or info bits quite yet. Thus, the CRC will represent the CRC of
494 * the whole record in the order "rdata, then backup blocks, then record
497 * We may have to loop back to here if a race condition is detected below.
498 * We could prevent the race by doing all this work while holding the
499 * insert lock, but it seems better to avoid doing CRC calculations while
500 * holding the lock. This means we have to be careful about modifying the
501 * rdata chain until we know we aren't going to loop back again. The only
502 * change we allow ourselves to make earlier is to set rdt->data = NULL in
503 * chain items we have decided we will have to back up the whole buffer
504 * for. This is OK because we will certainly decide the same thing again
505 * for those items if we do it over; doing it here saves an extra pass
506 * over the chain later.
509 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
511 dtbuf[i] = InvalidBuffer;
512 dtbuf_bkp[i] = false;
516 * Decide if we need to do full-page writes in this XLOG record: true if
517 * full_page_writes is on or we have a PITR request for it. Since we
518 * don't yet have the insert lock, forcePageWrites could change under us,
519 * but we'll recheck it once we have the lock.
521 doPageWrites = fullPageWrites || Insert->forcePageWrites;
523 INIT_CRC32(rdata_crc);
527 if (rdt->buffer == InvalidBuffer)
529 /* Simple data, just include it */
531 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
535 /* Find info for buffer */
536 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
538 if (rdt->buffer == dtbuf[i])
540 /* Buffer already referenced by earlier chain item */
546 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
550 if (dtbuf[i] == InvalidBuffer)
552 /* OK, put it in this slot */
553 dtbuf[i] = rdt->buffer;
554 if (XLogCheckBuffer(rdt, doPageWrites,
555 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
563 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
568 if (i >= XLR_MAX_BKP_BLOCKS)
569 elog(PANIC, "can backup at most %d blocks per xlog record",
572 /* Break out of loop when rdt points to last chain item */
573 if (rdt->next == NULL)
579 * Now add the backup block headers and data into the CRC
581 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
585 BkpBlock *bkpb = &(dtbuf_xlg[i]);
588 COMP_CRC32(rdata_crc,
591 page = (char *) BufferGetBlock(dtbuf[i]);
592 if (bkpb->hole_length == 0)
594 COMP_CRC32(rdata_crc,
600 /* must skip the hole */
601 COMP_CRC32(rdata_crc,
604 COMP_CRC32(rdata_crc,
605 page + (bkpb->hole_offset + bkpb->hole_length),
606 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
612 * NOTE: We disallow len == 0 because it provides a useful bit of extra
613 * error checking in ReadRecord. This means that all callers of
614 * XLogInsert must supply at least some not-in-a-buffer data. However, we
615 * make an exception for XLOG SWITCH records because we don't want them to
616 * ever cross a segment boundary.
618 if (len == 0 && !isLogSwitch)
619 elog(PANIC, "invalid xlog record length %u", len);
621 START_CRIT_SECTION();
623 /* Now wait to get insert lock */
624 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
627 * Check to see if my RedoRecPtr is out of date. If so, may have to go
628 * back and recompute everything. This can only happen just after a
629 * checkpoint, so it's better to be slow in this case and fast otherwise.
631 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
632 * affect the contents of the XLOG record, so we'll update our local copy
633 * but not force a recomputation.
635 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
637 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
638 RedoRecPtr = Insert->RedoRecPtr;
642 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
644 if (dtbuf[i] == InvalidBuffer)
646 if (dtbuf_bkp[i] == false &&
647 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
650 * Oops, this buffer now needs to be backed up, but we
651 * didn't think so above. Start over.
653 LWLockRelease(WALInsertLock);
662 * Also check to see if forcePageWrites was just turned on; if we weren't
663 * already doing full-page writes then go back and recompute. (If it was
664 * just turned off, we could recompute the record without full pages, but
665 * we choose not to bother.)
667 if (Insert->forcePageWrites && !doPageWrites)
669 /* Oops, must redo it with full-page data */
670 LWLockRelease(WALInsertLock);
676 * Make additional rdata chain entries for the backup blocks, so that we
677 * don't need to special-case them in the write loop. Note that we have
678 * now irrevocably changed the input rdata chain. At the exit of this
679 * loop, write_len includes the backup block data.
681 * Also set the appropriate info bits to show which buffers were backed
682 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
683 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
686 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
694 info |= XLR_SET_BKP_BLOCK(i);
696 bkpb = &(dtbuf_xlg[i]);
697 page = (char *) BufferGetBlock(dtbuf[i]);
699 rdt->next = &(dtbuf_rdt1[i]);
702 rdt->data = (char *) bkpb;
703 rdt->len = sizeof(BkpBlock);
704 write_len += sizeof(BkpBlock);
706 rdt->next = &(dtbuf_rdt2[i]);
709 if (bkpb->hole_length == 0)
718 /* must skip the hole */
720 rdt->len = bkpb->hole_offset;
721 write_len += bkpb->hole_offset;
723 rdt->next = &(dtbuf_rdt3[i]);
726 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
727 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
728 write_len += rdt->len;
734 * If we backed up any full blocks and online backup is not in progress,
735 * mark the backup blocks as removable. This allows the WAL archiver to
736 * know whether it is safe to compress archived WAL data by transforming
737 * full-block records into the non-full-block format.
739 * Note: we could just set the flag whenever !forcePageWrites, but
740 * defining it like this leaves the info bit free for some potential other
741 * use in records without any backup blocks.
743 if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
744 info |= XLR_BKP_REMOVABLE;
747 * If there isn't enough space on the current XLOG page for a record
748 * header, advance to the next page (leaving the unused space as zeroes).
751 freespace = INSERT_FREESPACE(Insert);
752 if (freespace < SizeOfXLogRecord)
754 updrqst = AdvanceXLInsertBuffer(false);
755 freespace = INSERT_FREESPACE(Insert);
758 /* Compute record's XLOG location */
759 curridx = Insert->curridx;
760 INSERT_RECPTR(RecPtr, Insert, curridx);
763 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
764 * segment, we need not insert it (and don't want to because we'd like
765 * consecutive switch requests to be no-ops). Instead, make sure
766 * everything is written and flushed through the end of the prior segment,
767 * and return the prior segment's end address.
770 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
772 /* We can release insert lock immediately */
773 LWLockRelease(WALInsertLock);
775 RecPtr.xrecoff -= SizeOfXLogLongPHD;
776 if (RecPtr.xrecoff == 0)
778 /* crossing a logid boundary */
780 RecPtr.xrecoff = XLogFileSize;
783 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
784 LogwrtResult = XLogCtl->Write.LogwrtResult;
785 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
787 XLogwrtRqst FlushRqst;
789 FlushRqst.Write = RecPtr;
790 FlushRqst.Flush = RecPtr;
791 XLogWrite(FlushRqst, false, false);
793 LWLockRelease(WALWriteLock);
800 /* Insert record header */
802 record = (XLogRecord *) Insert->currpos;
803 record->xl_prev = Insert->PrevRecord;
804 record->xl_xid = GetCurrentTransactionIdIfAny();
805 record->xl_tot_len = SizeOfXLogRecord + write_len;
806 record->xl_len = len; /* doesn't include backup blocks */
807 record->xl_info = info;
808 record->xl_rmid = rmid;
810 /* Now we can finish computing the record's CRC */
811 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
812 SizeOfXLogRecord - sizeof(pg_crc32));
813 FIN_CRC32(rdata_crc);
814 record->xl_crc = rdata_crc;
821 initStringInfo(&buf);
822 appendStringInfo(&buf, "INSERT @ %X/%X: ",
823 RecPtr.xlogid, RecPtr.xrecoff);
824 xlog_outrec(&buf, record);
825 if (rdata->data != NULL)
827 appendStringInfo(&buf, " - ");
828 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
830 elog(LOG, "%s", buf.data);
835 /* Record begin of record in appropriate places */
836 ProcLastRecPtr = RecPtr;
837 Insert->PrevRecord = RecPtr;
839 Insert->currpos += SizeOfXLogRecord;
840 freespace -= SizeOfXLogRecord;
843 * Append the data, including backup blocks if any
847 while (rdata->data == NULL)
852 if (rdata->len > freespace)
854 memcpy(Insert->currpos, rdata->data, freespace);
855 rdata->data += freespace;
856 rdata->len -= freespace;
857 write_len -= freespace;
861 memcpy(Insert->currpos, rdata->data, rdata->len);
862 freespace -= rdata->len;
863 write_len -= rdata->len;
864 Insert->currpos += rdata->len;
870 /* Use next buffer */
871 updrqst = AdvanceXLInsertBuffer(false);
872 curridx = Insert->curridx;
873 /* Insert cont-record header */
874 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
875 contrecord = (XLogContRecord *) Insert->currpos;
876 contrecord->xl_rem_len = write_len;
877 Insert->currpos += SizeOfXLogContRecord;
878 freespace = INSERT_FREESPACE(Insert);
881 /* Ensure next record will be properly aligned */
882 Insert->currpos = (char *) Insert->currpage +
883 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
884 freespace = INSERT_FREESPACE(Insert);
887 * The recptr I return is the beginning of the *next* record. This will be
888 * stored as LSN for changed data pages...
890 INSERT_RECPTR(RecPtr, Insert, curridx);
893 * If the record is an XLOG_SWITCH, we must now write and flush all the
894 * existing data, and then forcibly advance to the start of the next
895 * segment. It's not good to do this I/O while holding the insert lock,
896 * but there seems too much risk of confusion if we try to release the
897 * lock sooner. Fortunately xlog switch needn't be a high-performance
898 * operation anyway...
902 XLogCtlWrite *Write = &XLogCtl->Write;
903 XLogwrtRqst FlushRqst;
904 XLogRecPtr OldSegEnd;
906 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
909 * Flush through the end of the page containing XLOG_SWITCH, and
910 * perform end-of-segment actions (eg, notifying archiver).
912 WriteRqst = XLogCtl->xlblocks[curridx];
913 FlushRqst.Write = WriteRqst;
914 FlushRqst.Flush = WriteRqst;
915 XLogWrite(FlushRqst, false, true);
917 /* Set up the next buffer as first page of next segment */
918 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
919 (void) AdvanceXLInsertBuffer(true);
921 /* There should be no unwritten data */
922 curridx = Insert->curridx;
923 Assert(curridx == Write->curridx);
925 /* Compute end address of old segment */
926 OldSegEnd = XLogCtl->xlblocks[curridx];
927 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
928 if (OldSegEnd.xrecoff == 0)
930 /* crossing a logid boundary */
931 OldSegEnd.xlogid -= 1;
932 OldSegEnd.xrecoff = XLogFileSize;
935 /* Make it look like we've written and synced all of old segment */
936 LogwrtResult.Write = OldSegEnd;
937 LogwrtResult.Flush = OldSegEnd;
940 * Update shared-memory status --- this code should match XLogWrite
943 /* use volatile pointer to prevent code rearrangement */
944 volatile XLogCtlData *xlogctl = XLogCtl;
946 SpinLockAcquire(&xlogctl->info_lck);
947 xlogctl->LogwrtResult = LogwrtResult;
948 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
949 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
950 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
951 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
952 SpinLockRelease(&xlogctl->info_lck);
955 Write->LogwrtResult = LogwrtResult;
957 LWLockRelease(WALWriteLock);
959 updrqst = false; /* done already */
963 /* normal case, ie not xlog switch */
965 /* Need to update shared LogwrtRqst if some block was filled up */
966 if (freespace < SizeOfXLogRecord)
968 /* curridx is filled and available for writing out */
973 /* if updrqst already set, write through end of previous buf */
974 curridx = PrevBufIdx(curridx);
976 WriteRqst = XLogCtl->xlblocks[curridx];
979 LWLockRelease(WALInsertLock);
983 /* use volatile pointer to prevent code rearrangement */
984 volatile XLogCtlData *xlogctl = XLogCtl;
986 SpinLockAcquire(&xlogctl->info_lck);
987 /* advance global request to include new block(s) */
988 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
989 xlogctl->LogwrtRqst.Write = WriteRqst;
990 /* update local result copy while I have the chance */
991 LogwrtResult = xlogctl->LogwrtResult;
992 SpinLockRelease(&xlogctl->info_lck);
995 XactLastRecEnd = RecPtr;
1003 * Determine whether the buffer referenced by an XLogRecData item has to
1004 * be backed up, and if so fill a BkpBlock struct for it. In any case
1005 * save the buffer's LSN at *lsn.
1008 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1009 XLogRecPtr *lsn, BkpBlock *bkpb)
1013 page = (PageHeader) BufferGetBlock(rdata->buffer);
1016 * XXX We assume page LSN is first data on *every* page that can be passed
1017 * to XLogInsert, whether it otherwise has the standard page layout or
1020 *lsn = page->pd_lsn;
1023 XLByteLE(page->pd_lsn, RedoRecPtr))
1026 * The page needs to be backed up, so set up *bkpb
1028 bkpb->node = BufferGetFileNode(rdata->buffer);
1029 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1031 if (rdata->buffer_std)
1033 /* Assume we can omit data between pd_lower and pd_upper */
1034 uint16 lower = page->pd_lower;
1035 uint16 upper = page->pd_upper;
1037 if (lower >= SizeOfPageHeaderData &&
1041 bkpb->hole_offset = lower;
1042 bkpb->hole_length = upper - lower;
1046 /* No "hole" to compress out */
1047 bkpb->hole_offset = 0;
1048 bkpb->hole_length = 0;
1053 /* Not a standard page header, don't try to eliminate "hole" */
1054 bkpb->hole_offset = 0;
1055 bkpb->hole_length = 0;
1058 return true; /* buffer requires backup */
1061 return false; /* buffer does not need to be backed up */
1067 * Create an archive notification file
1069 * The name of the notification file is the message that will be picked up
1070 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1071 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1072 * then when complete, rename it to 0000000100000001000000C6.done
1075 XLogArchiveNotify(const char *xlog)
1077 char archiveStatusPath[MAXPGPATH];
1080 /* insert an otherwise empty file called <XLOG>.ready */
1081 StatusFilePath(archiveStatusPath, xlog, ".ready");
1082 fd = AllocateFile(archiveStatusPath, "w");
1086 (errcode_for_file_access(),
1087 errmsg("could not create archive status file \"%s\": %m",
1088 archiveStatusPath)));
1094 (errcode_for_file_access(),
1095 errmsg("could not write archive status file \"%s\": %m",
1096 archiveStatusPath)));
1100 /* Notify archiver that it's got something to do */
1101 if (IsUnderPostmaster)
1102 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1106 * Convenience routine to notify using log/seg representation of filename
1109 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1111 char xlog[MAXFNAMELEN];
1113 XLogFileName(xlog, ThisTimeLineID, log, seg);
1114 XLogArchiveNotify(xlog);
1118 * XLogArchiveCheckDone
1120 * This is called when we are ready to delete or recycle an old XLOG segment
1121 * file or backup history file. If it is okay to delete it then return true.
1122 * If it is not time to delete it, make sure a .ready file exists, and return
1125 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1126 * then return false; else create <XLOG>.ready and return false.
1128 * The reason we do things this way is so that if the original attempt to
1129 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1132 XLogArchiveCheckDone(const char *xlog, bool create_if_missing)
1134 char archiveStatusPath[MAXPGPATH];
1135 struct stat stat_buf;
1137 /* Always deletable if archiving is off */
1138 if (!XLogArchivingActive())
1141 /* First check for .done --- this means archiver is done with it */
1142 StatusFilePath(archiveStatusPath, xlog, ".done");
1143 if (stat(archiveStatusPath, &stat_buf) == 0)
1146 /* check for .ready --- this means archiver is still busy with it */
1147 StatusFilePath(archiveStatusPath, xlog, ".ready");
1148 if (stat(archiveStatusPath, &stat_buf) == 0)
1151 /* Race condition --- maybe archiver just finished, so recheck */
1152 StatusFilePath(archiveStatusPath, xlog, ".done");
1153 if (stat(archiveStatusPath, &stat_buf) == 0)
1156 /* Retry creation of the .ready file */
1157 if (create_if_missing)
1158 XLogArchiveNotify(xlog);
1164 * XLogArchiveCleanup
1166 * Cleanup archive notification file(s) for a particular xlog segment
1169 XLogArchiveCleanup(const char *xlog)
1171 char archiveStatusPath[MAXPGPATH];
1173 /* Remove the .done file */
1174 StatusFilePath(archiveStatusPath, xlog, ".done");
1175 unlink(archiveStatusPath);
1176 /* should we complain about failure? */
1178 /* Remove the .ready file if present --- normally it shouldn't be */
1179 StatusFilePath(archiveStatusPath, xlog, ".ready");
1180 unlink(archiveStatusPath);
1181 /* should we complain about failure? */
1185 * Advance the Insert state to the next buffer page, writing out the next
1186 * buffer if it still contains unwritten data.
1188 * If new_segment is TRUE then we set up the next buffer page as the first
1189 * page of the next xlog segment file, possibly but not usually the next
1190 * consecutive file page.
1192 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1193 * just-filled page. If we can do this for free (without an extra lock),
1194 * we do so here. Otherwise the caller must do it. We return TRUE if the
1195 * request update still needs to be done, FALSE if we did it internally.
1197 * Must be called with WALInsertLock held.
1200 AdvanceXLInsertBuffer(bool new_segment)
1202 XLogCtlInsert *Insert = &XLogCtl->Insert;
1203 XLogCtlWrite *Write = &XLogCtl->Write;
1204 int nextidx = NextBufIdx(Insert->curridx);
1205 bool update_needed = true;
1206 XLogRecPtr OldPageRqstPtr;
1207 XLogwrtRqst WriteRqst;
1208 XLogRecPtr NewPageEndPtr;
1209 XLogPageHeader NewPage;
1211 /* Use Insert->LogwrtResult copy if it's more fresh */
1212 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1213 LogwrtResult = Insert->LogwrtResult;
1216 * Get ending-offset of the buffer page we need to replace (this may be
1217 * zero if the buffer hasn't been used yet). Fall through if it's already
1220 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1221 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1223 /* nope, got work to do... */
1224 XLogRecPtr FinishedPageRqstPtr;
1226 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1228 /* Before waiting, get info_lck and update LogwrtResult */
1230 /* use volatile pointer to prevent code rearrangement */
1231 volatile XLogCtlData *xlogctl = XLogCtl;
1233 SpinLockAcquire(&xlogctl->info_lck);
1234 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1235 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1236 LogwrtResult = xlogctl->LogwrtResult;
1237 SpinLockRelease(&xlogctl->info_lck);
1240 update_needed = false; /* Did the shared-request update */
1242 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1244 /* OK, someone wrote it already */
1245 Insert->LogwrtResult = LogwrtResult;
1249 /* Must acquire write lock */
1250 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1251 LogwrtResult = Write->LogwrtResult;
1252 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1254 /* OK, someone wrote it already */
1255 LWLockRelease(WALWriteLock);
1256 Insert->LogwrtResult = LogwrtResult;
1261 * Have to write buffers while holding insert lock. This is
1262 * not good, so only write as much as we absolutely must.
1264 WriteRqst.Write = OldPageRqstPtr;
1265 WriteRqst.Flush.xlogid = 0;
1266 WriteRqst.Flush.xrecoff = 0;
1267 XLogWrite(WriteRqst, false, false);
1268 LWLockRelease(WALWriteLock);
1269 Insert->LogwrtResult = LogwrtResult;
1275 * Now the next buffer slot is free and we can set it up to be the next
1278 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1282 /* force it to a segment start point */
1283 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1284 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1287 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1289 /* crossing a logid boundary */
1290 NewPageEndPtr.xlogid += 1;
1291 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1294 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1295 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1296 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1298 Insert->curridx = nextidx;
1299 Insert->currpage = NewPage;
1301 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1304 * Be sure to re-zero the buffer so that bytes beyond what we've written
1305 * will look like zeroes and not valid XLOG records...
1307 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1310 * Fill the new page's header
1312 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1314 /* NewPage->xlp_info = 0; */ /* done by memset */
1315 NewPage ->xlp_tli = ThisTimeLineID;
1316 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1317 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1320 * If first page of an XLOG segment file, make it a long header.
1322 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1324 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1326 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1327 NewLongPage->xlp_seg_size = XLogSegSize;
1328 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1329 NewPage ->xlp_info |= XLP_LONG_HEADER;
1331 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1334 return update_needed;
1338 * Check whether we've consumed enough xlog space that a checkpoint is needed.
1340 * Caller must have just finished filling the open log file (so that
1341 * openLogId/openLogSeg are valid). We measure the distance from RedoRecPtr
1342 * to the open log file and see if that exceeds CheckPointSegments.
1344 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
1347 XLogCheckpointNeeded(void)
1350 * A straight computation of segment number could overflow 32 bits. Rather
1351 * than assuming we have working 64-bit arithmetic, we compare the
1352 * highest-order bits separately, and force a checkpoint immediately when
1357 uint32 old_highbits,
1360 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1361 (RedoRecPtr.xrecoff / XLogSegSize);
1362 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1363 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile + openLogSeg;
1364 new_highbits = openLogId / XLogSegSize;
1365 if (new_highbits != old_highbits ||
1366 new_segno >= old_segno + (uint32) (CheckPointSegments - 1))
1372 * Write and/or fsync the log at least as far as WriteRqst indicates.
1374 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1375 * may stop at any convenient boundary (such as a cache or logfile boundary).
1376 * This option allows us to avoid uselessly issuing multiple writes when a
1377 * single one would do.
1379 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1380 * perform end-of-segment actions after writing the last page, even if
1381 * it's not physically the end of its segment. (NB: this will work properly
1382 * only if caller specifies WriteRqst == page-end and flexible == false,
1383 * and there is some data to write.)
1385 * Must be called with WALWriteLock held.
1388 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1390 XLogCtlWrite *Write = &XLogCtl->Write;
1392 bool last_iteration;
1400 /* We should always be inside a critical section here */
1401 Assert(CritSectionCount > 0);
1404 * Update local LogwrtResult (caller probably did this already, but...)
1406 LogwrtResult = Write->LogwrtResult;
1409 * Since successive pages in the xlog cache are consecutively allocated,
1410 * we can usually gather multiple pages together and issue just one
1411 * write() call. npages is the number of pages we have determined can be
1412 * written together; startidx is the cache block index of the first one,
1413 * and startoffset is the file offset at which it should go. The latter
1414 * two variables are only valid when npages > 0, but we must initialize
1415 * all of them to keep the compiler quiet.
1422 * Within the loop, curridx is the cache block index of the page to
1423 * consider writing. We advance Write->curridx only after successfully
1424 * writing pages. (Right now, this refinement is useless since we are
1425 * going to PANIC if any error occurs anyway; but someday it may come in
1428 curridx = Write->curridx;
1430 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1433 * Make sure we're not ahead of the insert process. This could happen
1434 * if we're passed a bogus WriteRqst.Write that is past the end of the
1435 * last page that's been initialized by AdvanceXLInsertBuffer.
1437 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1438 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1439 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1440 XLogCtl->xlblocks[curridx].xlogid,
1441 XLogCtl->xlblocks[curridx].xrecoff);
1443 /* Advance LogwrtResult.Write to end of current buffer page */
1444 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1445 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1447 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1450 * Switch to new logfile segment. We cannot have any pending
1451 * pages here (since we dump what we have at segment end).
1453 Assert(npages == 0);
1454 if (openLogFile >= 0)
1456 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1458 /* create/use new log file */
1459 use_existent = true;
1460 openLogFile = XLogFileInit(openLogId, openLogSeg,
1461 &use_existent, true);
1465 /* Make sure we have the current logfile open */
1466 if (openLogFile < 0)
1468 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1469 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1473 /* Add current page to the set of pending pages-to-dump */
1476 /* first of group */
1478 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1483 * Dump the set if this will be the last loop iteration, or if we are
1484 * at the last page of the cache area (since the next page won't be
1485 * contiguous in memory), or if we are at the end of the logfile
1488 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1490 finishing_seg = !ispartialpage &&
1491 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1493 if (last_iteration ||
1494 curridx == XLogCtl->XLogCacheBlck ||
1500 /* Need to seek in the file? */
1501 if (openLogOff != startoffset)
1503 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1505 (errcode_for_file_access(),
1506 errmsg("could not seek in log file %u, "
1507 "segment %u to offset %u: %m",
1508 openLogId, openLogSeg, startoffset)));
1509 openLogOff = startoffset;
1512 /* OK to write the page(s) */
1513 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1514 nbytes = npages * (Size) XLOG_BLCKSZ;
1516 if (write(openLogFile, from, nbytes) != nbytes)
1518 /* if write didn't set errno, assume no disk space */
1522 (errcode_for_file_access(),
1523 errmsg("could not write to log file %u, segment %u "
1524 "at offset %u, length %lu: %m",
1525 openLogId, openLogSeg,
1526 openLogOff, (unsigned long) nbytes)));
1529 /* Update state for write */
1530 openLogOff += nbytes;
1531 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1535 * If we just wrote the whole last page of a logfile segment,
1536 * fsync the segment immediately. This avoids having to go back
1537 * and re-open prior segments when an fsync request comes along
1538 * later. Doing it here ensures that one and only one backend will
1539 * perform this fsync.
1541 * We also do this if this is the last page written for an xlog
1544 * This is also the right place to notify the Archiver that the
1545 * segment is ready to copy to archival storage, and to update the
1546 * timer for archive_timeout, and to signal for a checkpoint if
1547 * too many logfile segments have been used since the last
1550 if (finishing_seg || (xlog_switch && last_iteration))
1553 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1555 if (XLogArchivingActive())
1556 XLogArchiveNotifySeg(openLogId, openLogSeg);
1558 Write->lastSegSwitchTime = (pg_time_t) time(NULL);
1561 * Signal bgwriter to start a checkpoint if we've consumed too
1562 * much xlog since the last one. For speed, we first check
1563 * using the local copy of RedoRecPtr, which might be out of
1564 * date; if it looks like a checkpoint is needed, forcibly
1565 * update RedoRecPtr and recheck.
1567 if (IsUnderPostmaster &&
1568 XLogCheckpointNeeded())
1570 (void) GetRedoRecPtr();
1571 if (XLogCheckpointNeeded())
1572 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1579 /* Only asked to write a partial page */
1580 LogwrtResult.Write = WriteRqst.Write;
1583 curridx = NextBufIdx(curridx);
1585 /* If flexible, break out of loop as soon as we wrote something */
1586 if (flexible && npages == 0)
1590 Assert(npages == 0);
1591 Assert(curridx == Write->curridx);
1594 * If asked to flush, do so
1596 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1597 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1600 * Could get here without iterating above loop, in which case we might
1601 * have no open file or the wrong one. However, we do not need to
1602 * fsync more than one file.
1604 if (sync_method != SYNC_METHOD_OPEN)
1606 if (openLogFile >= 0 &&
1607 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1609 if (openLogFile < 0)
1611 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1612 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1617 LogwrtResult.Flush = LogwrtResult.Write;
1621 * Update shared-memory status
1623 * We make sure that the shared 'request' values do not fall behind the
1624 * 'result' values. This is not absolutely essential, but it saves some
1625 * code in a couple of places.
1628 /* use volatile pointer to prevent code rearrangement */
1629 volatile XLogCtlData *xlogctl = XLogCtl;
1631 SpinLockAcquire(&xlogctl->info_lck);
1632 xlogctl->LogwrtResult = LogwrtResult;
1633 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1634 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1635 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1636 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1637 SpinLockRelease(&xlogctl->info_lck);
1640 Write->LogwrtResult = LogwrtResult;
1644 * Record the LSN for an asynchronous transaction commit.
1645 * (This should not be called for aborts, nor for synchronous commits.)
1648 XLogSetAsyncCommitLSN(XLogRecPtr asyncCommitLSN)
1650 /* use volatile pointer to prevent code rearrangement */
1651 volatile XLogCtlData *xlogctl = XLogCtl;
1653 SpinLockAcquire(&xlogctl->info_lck);
1654 if (XLByteLT(xlogctl->asyncCommitLSN, asyncCommitLSN))
1655 xlogctl->asyncCommitLSN = asyncCommitLSN;
1656 SpinLockRelease(&xlogctl->info_lck);
1660 * Ensure that all XLOG data through the given position is flushed to disk.
1662 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1663 * already held, and we try to avoid acquiring it if possible.
1666 XLogFlush(XLogRecPtr record)
1668 XLogRecPtr WriteRqstPtr;
1669 XLogwrtRqst WriteRqst;
1671 /* Disabled during REDO */
1675 /* Quick exit if already known flushed */
1676 if (XLByteLE(record, LogwrtResult.Flush))
1681 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1682 record.xlogid, record.xrecoff,
1683 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1684 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1687 START_CRIT_SECTION();
1690 * Since fsync is usually a horribly expensive operation, we try to
1691 * piggyback as much data as we can on each fsync: if we see any more data
1692 * entered into the xlog buffer, we'll write and fsync that too, so that
1693 * the final value of LogwrtResult.Flush is as large as possible. This
1694 * gives us some chance of avoiding another fsync immediately after.
1697 /* initialize to given target; may increase below */
1698 WriteRqstPtr = record;
1700 /* read LogwrtResult and update local state */
1702 /* use volatile pointer to prevent code rearrangement */
1703 volatile XLogCtlData *xlogctl = XLogCtl;
1705 SpinLockAcquire(&xlogctl->info_lck);
1706 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1707 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1708 LogwrtResult = xlogctl->LogwrtResult;
1709 SpinLockRelease(&xlogctl->info_lck);
1713 if (!XLByteLE(record, LogwrtResult.Flush))
1715 /* now wait for the write lock */
1716 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1717 LogwrtResult = XLogCtl->Write.LogwrtResult;
1718 if (!XLByteLE(record, LogwrtResult.Flush))
1720 /* try to write/flush later additions to XLOG as well */
1721 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1723 XLogCtlInsert *Insert = &XLogCtl->Insert;
1724 uint32 freespace = INSERT_FREESPACE(Insert);
1726 if (freespace < SizeOfXLogRecord) /* buffer is full */
1727 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1730 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1731 WriteRqstPtr.xrecoff -= freespace;
1733 LWLockRelease(WALInsertLock);
1734 WriteRqst.Write = WriteRqstPtr;
1735 WriteRqst.Flush = WriteRqstPtr;
1739 WriteRqst.Write = WriteRqstPtr;
1740 WriteRqst.Flush = record;
1742 XLogWrite(WriteRqst, false, false);
1744 LWLockRelease(WALWriteLock);
1750 * If we still haven't flushed to the request point then we have a
1751 * problem; most likely, the requested flush point is past end of XLOG.
1752 * This has been seen to occur when a disk page has a corrupted LSN.
1754 * Formerly we treated this as a PANIC condition, but that hurts the
1755 * system's robustness rather than helping it: we do not want to take down
1756 * the whole system due to corruption on one data page. In particular, if
1757 * the bad page is encountered again during recovery then we would be
1758 * unable to restart the database at all! (This scenario has actually
1759 * happened in the field several times with 7.1 releases. Note that we
1760 * cannot get here while InRedo is true, but if the bad page is brought in
1761 * and marked dirty during recovery then CreateCheckPoint will try to
1762 * flush it at the end of recovery.)
1764 * The current approach is to ERROR under normal conditions, but only
1765 * WARNING during recovery, so that the system can be brought up even if
1766 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1767 * be promoted to PANIC since xact.c calls this routine inside a critical
1768 * section. However, calls from bufmgr.c are not within critical sections
1769 * and so we will not force a restart for a bad LSN on a data page.
1771 if (XLByteLT(LogwrtResult.Flush, record))
1772 elog(InRecovery ? WARNING : ERROR,
1773 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1774 record.xlogid, record.xrecoff,
1775 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1779 * Flush xlog, but without specifying exactly where to flush to.
1781 * We normally flush only completed blocks; but if there is nothing to do on
1782 * that basis, we check for unflushed async commits in the current incomplete
1783 * block, and flush through the latest one of those. Thus, if async commits
1784 * are not being used, we will flush complete blocks only. We can guarantee
1785 * that async commits reach disk after at most three cycles; normally only
1786 * one or two. (We allow XLogWrite to write "flexibly", meaning it can stop
1787 * at the end of the buffer ring; this makes a difference only with very high
1788 * load or long wal_writer_delay, but imposes one extra cycle for the worst
1789 * case for async commits.)
1791 * This routine is invoked periodically by the background walwriter process.
1794 XLogBackgroundFlush(void)
1796 XLogRecPtr WriteRqstPtr;
1797 bool flexible = true;
1799 /* read LogwrtResult and update local state */
1801 /* use volatile pointer to prevent code rearrangement */
1802 volatile XLogCtlData *xlogctl = XLogCtl;
1804 SpinLockAcquire(&xlogctl->info_lck);
1805 LogwrtResult = xlogctl->LogwrtResult;
1806 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1807 SpinLockRelease(&xlogctl->info_lck);
1810 /* back off to last completed page boundary */
1811 WriteRqstPtr.xrecoff -= WriteRqstPtr.xrecoff % XLOG_BLCKSZ;
1813 /* if we have already flushed that far, consider async commit records */
1814 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1816 /* use volatile pointer to prevent code rearrangement */
1817 volatile XLogCtlData *xlogctl = XLogCtl;
1819 SpinLockAcquire(&xlogctl->info_lck);
1820 WriteRqstPtr = xlogctl->asyncCommitLSN;
1821 SpinLockRelease(&xlogctl->info_lck);
1822 flexible = false; /* ensure it all gets written */
1825 /* Done if already known flushed */
1826 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1831 elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
1832 WriteRqstPtr.xlogid, WriteRqstPtr.xrecoff,
1833 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1834 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1837 START_CRIT_SECTION();
1839 /* now wait for the write lock */
1840 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1841 LogwrtResult = XLogCtl->Write.LogwrtResult;
1842 if (!XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1844 XLogwrtRqst WriteRqst;
1846 WriteRqst.Write = WriteRqstPtr;
1847 WriteRqst.Flush = WriteRqstPtr;
1848 XLogWrite(WriteRqst, flexible, false);
1850 LWLockRelease(WALWriteLock);
1856 * Flush any previous asynchronously-committed transactions' commit records.
1858 * NOTE: it is unwise to assume that this provides any strong guarantees.
1859 * In particular, because of the inexact LSN bookkeeping used by clog.c,
1860 * we cannot assume that hint bits will be settable for these transactions.
1863 XLogAsyncCommitFlush(void)
1865 XLogRecPtr WriteRqstPtr;
1867 /* use volatile pointer to prevent code rearrangement */
1868 volatile XLogCtlData *xlogctl = XLogCtl;
1870 SpinLockAcquire(&xlogctl->info_lck);
1871 WriteRqstPtr = xlogctl->asyncCommitLSN;
1872 SpinLockRelease(&xlogctl->info_lck);
1874 XLogFlush(WriteRqstPtr);
1878 * Test whether XLOG data has been flushed up to (at least) the given position.
1880 * Returns true if a flush is still needed. (It may be that someone else
1881 * is already in process of flushing that far, however.)
1884 XLogNeedsFlush(XLogRecPtr record)
1886 /* Quick exit if already known flushed */
1887 if (XLByteLE(record, LogwrtResult.Flush))
1890 /* read LogwrtResult and update local state */
1892 /* use volatile pointer to prevent code rearrangement */
1893 volatile XLogCtlData *xlogctl = XLogCtl;
1895 SpinLockAcquire(&xlogctl->info_lck);
1896 LogwrtResult = xlogctl->LogwrtResult;
1897 SpinLockRelease(&xlogctl->info_lck);
1901 if (XLByteLE(record, LogwrtResult.Flush))
1908 * Create a new XLOG file segment, or open a pre-existing one.
1910 * log, seg: identify segment to be created/opened.
1912 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1913 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1916 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1917 * place. This should be TRUE except during bootstrap log creation. The
1918 * caller must *not* hold the lock at call.
1920 * Returns FD of opened file.
1922 * Note: errors here are ERROR not PANIC because we might or might not be
1923 * inside a critical section (eg, during checkpoint there is no reason to
1924 * take down the system on failure). They will promote to PANIC if we are
1925 * in a critical section.
1928 XLogFileInit(uint32 log, uint32 seg,
1929 bool *use_existent, bool use_lock)
1931 char path[MAXPGPATH];
1932 char tmppath[MAXPGPATH];
1934 uint32 installed_log;
1935 uint32 installed_seg;
1940 XLogFilePath(path, ThisTimeLineID, log, seg);
1943 * Try to use existent file (checkpoint maker may have created it already)
1947 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1951 if (errno != ENOENT)
1953 (errcode_for_file_access(),
1954 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1962 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
1963 * another process is doing the same thing. If so, we will end up
1964 * pre-creating an extra log segment. That seems OK, and better than
1965 * holding the lock throughout this lengthy process.
1967 elog(DEBUG2, "creating and filling new WAL file");
1969 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1973 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1974 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1978 (errcode_for_file_access(),
1979 errmsg("could not create file \"%s\": %m", tmppath)));
1982 * Zero-fill the file. We have to do this the hard way to ensure that all
1983 * the file space has really been allocated --- on platforms that allow
1984 * "holes" in files, just seeking to the end doesn't allocate intermediate
1985 * space. This way, we know that we have all the space and (after the
1986 * fsync below) that all the indirect blocks are down on disk. Therefore,
1987 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
1990 * Note: palloc zbuffer, instead of just using a local char array, to
1991 * ensure it is reasonably well-aligned; this may save a few cycles
1992 * transferring data to the kernel.
1994 zbuffer = (char *) palloc0(XLOG_BLCKSZ);
1995 for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
1998 if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
2000 int save_errno = errno;
2003 * If we fail to make the file, delete it to release disk space
2006 /* if write didn't set errno, assume problem is no disk space */
2007 errno = save_errno ? save_errno : ENOSPC;
2010 (errcode_for_file_access(),
2011 errmsg("could not write to file \"%s\": %m", tmppath)));
2016 if (pg_fsync(fd) != 0)
2018 (errcode_for_file_access(),
2019 errmsg("could not fsync file \"%s\": %m", tmppath)));
2023 (errcode_for_file_access(),
2024 errmsg("could not close file \"%s\": %m", tmppath)));
2027 * Now move the segment into place with its final name.
2029 * If caller didn't want to use a pre-existing file, get rid of any
2030 * pre-existing file. Otherwise, cope with possibility that someone else
2031 * has created the file while we were filling ours: if so, use ours to
2032 * pre-create a future log segment.
2034 installed_log = log;
2035 installed_seg = seg;
2036 max_advance = XLOGfileslop;
2037 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
2038 *use_existent, &max_advance,
2041 /* No need for any more future segments... */
2045 elog(DEBUG2, "done creating and filling new WAL file");
2047 /* Set flag to tell caller there was no existent file */
2048 *use_existent = false;
2050 /* Now open original target segment (might not be file I just made) */
2051 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2055 (errcode_for_file_access(),
2056 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2063 * Create a new XLOG file segment by copying a pre-existing one.
2065 * log, seg: identify segment to be created.
2067 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
2068 * a different timeline)
2070 * Currently this is only used during recovery, and so there are no locking
2071 * considerations. But we should be just as tense as XLogFileInit to avoid
2072 * emplacing a bogus file.
2075 XLogFileCopy(uint32 log, uint32 seg,
2076 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
2078 char path[MAXPGPATH];
2079 char tmppath[MAXPGPATH];
2080 char buffer[XLOG_BLCKSZ];
2086 * Open the source file
2088 XLogFilePath(path, srcTLI, srclog, srcseg);
2089 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2092 (errcode_for_file_access(),
2093 errmsg("could not open file \"%s\": %m", path)));
2096 * Copy into a temp file name.
2098 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2102 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2103 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2107 (errcode_for_file_access(),
2108 errmsg("could not create file \"%s\": %m", tmppath)));
2111 * Do the data copying.
2113 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2116 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2120 (errcode_for_file_access(),
2121 errmsg("could not read file \"%s\": %m", path)));
2124 (errmsg("not enough data in file \"%s\"", path)));
2127 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2129 int save_errno = errno;
2132 * If we fail to make the file, delete it to release disk space
2135 /* if write didn't set errno, assume problem is no disk space */
2136 errno = save_errno ? save_errno : ENOSPC;
2139 (errcode_for_file_access(),
2140 errmsg("could not write to file \"%s\": %m", tmppath)));
2144 if (pg_fsync(fd) != 0)
2146 (errcode_for_file_access(),
2147 errmsg("could not fsync file \"%s\": %m", tmppath)));
2151 (errcode_for_file_access(),
2152 errmsg("could not close file \"%s\": %m", tmppath)));
2157 * Now move the segment into place with its final name.
2159 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2160 elog(ERROR, "InstallXLogFileSegment should not have failed");
2164 * Install a new XLOG segment file as a current or future log segment.
2166 * This is used both to install a newly-created segment (which has a temp
2167 * filename while it's being created) and to recycle an old segment.
2169 * *log, *seg: identify segment to install as (or first possible target).
2170 * When find_free is TRUE, these are modified on return to indicate the
2171 * actual installation location or last segment searched.
2173 * tmppath: initial name of file to install. It will be renamed into place.
2175 * find_free: if TRUE, install the new segment at the first empty log/seg
2176 * number at or after the passed numbers. If FALSE, install the new segment
2177 * exactly where specified, deleting any existing segment file there.
2179 * *max_advance: maximum number of log/seg slots to advance past the starting
2180 * point. Fail if no free slot is found in this range. On return, reduced
2181 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2182 * when find_free is FALSE.)
2184 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2185 * place. This should be TRUE except during bootstrap log creation. The
2186 * caller must *not* hold the lock at call.
2188 * Returns TRUE if file installed, FALSE if not installed because of
2189 * exceeding max_advance limit. On Windows, we also return FALSE if we
2190 * can't rename the file into place because someone's got it open.
2191 * (Any other kind of failure causes ereport().)
2194 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2195 bool find_free, int *max_advance,
2198 char path[MAXPGPATH];
2199 struct stat stat_buf;
2201 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2204 * We want to be sure that only one process does this at a time.
2207 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2211 /* Force installation: get rid of any pre-existing segment file */
2216 /* Find a free slot to put it in */
2217 while (stat(path, &stat_buf) == 0)
2219 if (*max_advance <= 0)
2221 /* Failed to find a free slot within specified range */
2223 LWLockRelease(ControlFileLock);
2226 NextLogSeg(*log, *seg);
2228 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2233 * Prefer link() to rename() here just to be really sure that we don't
2234 * overwrite an existing logfile. However, there shouldn't be one, so
2235 * rename() is an acceptable substitute except for the truly paranoid.
2237 #if HAVE_WORKING_LINK
2238 if (link(tmppath, path) < 0)
2240 (errcode_for_file_access(),
2241 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2242 tmppath, path, *log, *seg)));
2245 if (rename(tmppath, path) < 0)
2248 #if !defined(__CYGWIN__)
2249 if (GetLastError() == ERROR_ACCESS_DENIED)
2251 if (errno == EACCES)
2255 LWLockRelease(ControlFileLock);
2261 (errcode_for_file_access(),
2262 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2263 tmppath, path, *log, *seg)));
2268 LWLockRelease(ControlFileLock);
2274 * Open a pre-existing logfile segment for writing.
2277 XLogFileOpen(uint32 log, uint32 seg)
2279 char path[MAXPGPATH];
2282 XLogFilePath(path, ThisTimeLineID, log, seg);
2284 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2288 (errcode_for_file_access(),
2289 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2296 * Open a logfile segment for reading (during recovery).
2299 XLogFileRead(uint32 log, uint32 seg, int emode)
2301 char path[MAXPGPATH];
2302 char xlogfname[MAXFNAMELEN];
2303 char activitymsg[MAXFNAMELEN + 16];
2308 * Loop looking for a suitable timeline ID: we might need to read any of
2309 * the timelines listed in expectedTLIs.
2311 * We expect curFileTLI on entry to be the TLI of the preceding file in
2312 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2313 * to go backwards; this prevents us from picking up the wrong file when a
2314 * parent timeline extends to higher segment numbers than the child we
2317 foreach(cell, expectedTLIs)
2319 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2321 if (tli < curFileTLI)
2322 break; /* don't bother looking at too-old TLIs */
2324 XLogFileName(xlogfname, tli, log, seg);
2326 if (InArchiveRecovery)
2328 /* Report recovery progress in PS display */
2329 snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
2331 set_ps_display(activitymsg, false);
2333 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2338 XLogFilePath(path, tli, log, seg);
2340 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2346 /* Report recovery progress in PS display */
2347 snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
2349 set_ps_display(activitymsg, false);
2353 if (errno != ENOENT) /* unexpected failure? */
2355 (errcode_for_file_access(),
2356 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2360 /* Couldn't find it. For simplicity, complain about front timeline */
2361 XLogFilePath(path, recoveryTargetTLI, log, seg);
2364 (errcode_for_file_access(),
2365 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2371 * Close the current logfile segment for writing.
2376 Assert(openLogFile >= 0);
2379 * posix_fadvise is problematic on many platforms: on older x86 Linux it
2380 * just dumps core, and there are reports of problems on PPC platforms as
2381 * well. The following is therefore disabled for the time being. We could
2382 * consider some kind of configure test to see if it's safe to use, but
2383 * since we lack hard evidence that there's any useful performance gain to
2384 * be had, spending time on that seems unprofitable for now.
2389 * WAL segment files will not be re-read in normal operation, so we advise
2390 * OS to release any cached pages. But do not do so if WAL archiving is
2391 * active, because archiver process could use the cache to read the WAL
2394 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
2395 * O_SYNC, and some platforms only have posix_fadvise().
2397 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2398 if (!XLogArchivingActive())
2399 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2401 #endif /* NOT_USED */
2403 if (close(openLogFile))
2405 (errcode_for_file_access(),
2406 errmsg("could not close log file %u, segment %u: %m",
2407 openLogId, openLogSeg)));
2412 * Attempt to retrieve the specified file from off-line archival storage.
2413 * If successful, fill "path" with its complete path (note that this will be
2414 * a temp file name that doesn't follow the normal naming convention), and
2417 * If not successful, fill "path" with the name of the normal on-line file
2418 * (which may or may not actually exist, but we'll try to use it), and return
2421 * For fixed-size files, the caller may pass the expected size as an
2422 * additional crosscheck on successful recovery. If the file size is not
2423 * known, set expectedSize = 0.
2426 RestoreArchivedFile(char *path, const char *xlogfname,
2427 const char *recovername, off_t expectedSize)
2429 char xlogpath[MAXPGPATH];
2430 char xlogRestoreCmd[MAXPGPATH];
2431 char lastRestartPointFname[MAXPGPATH];
2437 struct stat stat_buf;
2442 * When doing archive recovery, we always prefer an archived log file even
2443 * if a file of the same name exists in XLOGDIR. The reason is that the
2444 * file in XLOGDIR could be an old, un-filled or partly-filled version
2445 * that was copied and restored as part of backing up $PGDATA.
2447 * We could try to optimize this slightly by checking the local copy
2448 * lastchange timestamp against the archived copy, but we have no API to
2449 * do this, nor can we guarantee that the lastchange timestamp was
2450 * preserved correctly when we copied to archive. Our aim is robustness,
2451 * so we elect not to do this.
2453 * If we cannot obtain the log file from the archive, however, we will try
2454 * to use the XLOGDIR file if it exists. This is so that we can make use
2455 * of log segments that weren't yet transferred to the archive.
2457 * Notice that we don't actually overwrite any files when we copy back
2458 * from archive because the recoveryRestoreCommand may inadvertently
2459 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2460 * fallback to the segments remaining in current XLOGDIR later. The
2461 * copy-from-archive filename is always the same, ensuring that we don't
2462 * run out of disk space on long recoveries.
2464 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2467 * Make sure there is no existing file named recovername.
2469 if (stat(xlogpath, &stat_buf) != 0)
2471 if (errno != ENOENT)
2473 (errcode_for_file_access(),
2474 errmsg("could not stat file \"%s\": %m",
2479 if (unlink(xlogpath) != 0)
2481 (errcode_for_file_access(),
2482 errmsg("could not remove file \"%s\": %m",
2487 * construct the command to be executed
2489 dp = xlogRestoreCmd;
2490 endp = xlogRestoreCmd + MAXPGPATH - 1;
2493 for (sp = recoveryRestoreCommand; *sp; sp++)
2500 /* %p: relative path of target file */
2502 StrNCpy(dp, xlogpath, endp - dp);
2503 make_native_path(dp);
2507 /* %f: filename of desired file */
2509 StrNCpy(dp, xlogfname, endp - dp);
2513 /* %r: filename of last restartpoint */
2515 XLByteToSeg(ControlFile->checkPointCopy.redo,
2516 restartLog, restartSeg);
2517 XLogFileName(lastRestartPointFname,
2518 ControlFile->checkPointCopy.ThisTimeLineID,
2519 restartLog, restartSeg);
2520 StrNCpy(dp, lastRestartPointFname, endp - dp);
2524 /* convert %% to a single % */
2530 /* otherwise treat the % as not special */
2545 (errmsg_internal("executing restore command \"%s\"",
2549 * Copy xlog from archival storage to XLOGDIR
2551 rc = system(xlogRestoreCmd);
2555 * command apparently succeeded, but let's make sure the file is
2556 * really there now and has the correct size.
2558 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2559 * it, but is that too strong? We could try to plow ahead with a
2560 * local copy of the file ... but the problem is that there probably
2561 * isn't one, and we'd incorrectly conclude we've reached the end of
2562 * WAL and we're done recovering ...
2564 if (stat(xlogpath, &stat_buf) == 0)
2566 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2568 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2570 (unsigned long) stat_buf.st_size,
2571 (unsigned long) expectedSize)));
2575 (errmsg("restored log file \"%s\" from archive",
2577 strcpy(path, xlogpath);
2584 if (errno != ENOENT)
2586 (errcode_for_file_access(),
2587 errmsg("could not stat file \"%s\": %m",
2593 * Remember, we rollforward UNTIL the restore fails so failure here is
2594 * just part of the process... that makes it difficult to determine
2595 * whether the restore failed because there isn't an archive to restore,
2596 * or because the administrator has specified the restore program
2597 * incorrectly. We have to assume the former.
2599 * However, if the failure was due to any sort of signal, it's best to
2600 * punt and abort recovery. (If we "return false" here, upper levels will
2601 * assume that recovery is complete and start up the database!) It's
2602 * essential to abort on child SIGINT and SIGQUIT, because per spec
2603 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2604 * those it's a good bet we should have gotten it too. Aborting on other
2605 * signals such as SIGTERM seems a good idea as well.
2607 * Per the Single Unix Spec, shells report exit status > 128 when a called
2608 * command died on a signal. Also, 126 and 127 are used to report
2609 * problems such as an unfindable command; treat those as fatal errors
2612 signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;
2614 ereport(signaled ? FATAL : DEBUG2,
2615 (errmsg("could not restore file \"%s\" from archive: return code %d",
2619 * if an archived file is not available, there might still be a version of
2620 * this file in XLOGDIR, so return that as the filename to open.
2622 * In many recovery scenarios we expect this to fail also, but if so that
2623 * just means we've reached the end of WAL.
2625 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2630 * Preallocate log files beyond the specified log endpoint.
2632 * XXX this is currently extremely conservative, since it forces only one
2633 * future log segment to exist, and even that only if we are 75% done with
2634 * the current one. This is only appropriate for very low-WAL-volume systems.
2635 * High-volume systems will be OK once they've built up a sufficient set of
2636 * recycled log segments, but the startup transient is likely to include
2637 * a lot of segment creations by foreground processes, which is not so good.
2640 PreallocXlogFiles(XLogRecPtr endptr)
2647 XLByteToPrevSeg(endptr, _logId, _logSeg);
2648 if ((endptr.xrecoff - 1) % XLogSegSize >=
2649 (uint32) (0.75 * XLogSegSize))
2651 NextLogSeg(_logId, _logSeg);
2652 use_existent = true;
2653 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2656 CheckpointStats.ckpt_segs_added++;
2661 * Recycle or remove all log files older or equal to passed log/seg#
2663 * endptr is current (or recent) end of xlog; this is used to determine
2664 * whether we want to recycle rather than delete no-longer-wanted log files.
2667 RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
2673 struct dirent *xlde;
2674 char lastoff[MAXFNAMELEN];
2675 char path[MAXPGPATH];
2678 * Initialize info about where to try to recycle to. We allow recycling
2679 * segments up to XLOGfileslop segments beyond the current XLOG location.
2681 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2682 max_advance = XLOGfileslop;
2684 xldir = AllocateDir(XLOGDIR);
2687 (errcode_for_file_access(),
2688 errmsg("could not open transaction log directory \"%s\": %m",
2691 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2693 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2696 * We ignore the timeline part of the XLOG segment identifiers in
2697 * deciding whether a segment is still needed. This ensures that we
2698 * won't prematurely remove a segment from a parent timeline. We could
2699 * probably be a little more proactive about removing segments of
2700 * non-parent timelines, but that would be a whole lot more
2703 * We use the alphanumeric sorting property of the filenames to decide
2704 * which ones are earlier than the lastoff segment.
2706 if (strlen(xlde->d_name) == 24 &&
2707 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2708 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2710 if (XLogArchiveCheckDone(xlde->d_name, true))
2712 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2715 * Before deleting the file, see if it can be recycled as a
2716 * future log segment.
2718 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2723 (errmsg("recycled transaction log file \"%s\"",
2725 CheckpointStats.ckpt_segs_recycled++;
2726 /* Needn't recheck that slot on future iterations */
2727 if (max_advance > 0)
2729 NextLogSeg(endlogId, endlogSeg);
2735 /* No need for any more future segments... */
2737 (errmsg("removing transaction log file \"%s\"",
2740 CheckpointStats.ckpt_segs_removed++;
2743 XLogArchiveCleanup(xlde->d_name);
2752 * Remove previous backup history files. This also retries creation of
2753 * .ready files for any backup history files for which XLogArchiveNotify
2757 CleanupBackupHistory(void)
2760 struct dirent *xlde;
2761 char path[MAXPGPATH];
2763 xldir = AllocateDir(XLOGDIR);
2766 (errcode_for_file_access(),
2767 errmsg("could not open transaction log directory \"%s\": %m",
2770 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2772 if (strlen(xlde->d_name) > 24 &&
2773 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2774 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2777 if (XLogArchiveCheckDone(xlde->d_name, true))
2780 (errmsg("removing transaction log backup history file \"%s\"",
2782 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2784 XLogArchiveCleanup(xlde->d_name);
2793 * Restore the backup blocks present in an XLOG record, if any.
2795 * We assume all of the record has been read into memory at *record.
2797 * Note: when a backup block is available in XLOG, we restore it
2798 * unconditionally, even if the page in the database appears newer.
2799 * This is to protect ourselves against database pages that were partially
2800 * or incorrectly written during a crash. We assume that the XLOG data
2801 * must be good because it has passed a CRC check, while the database
2802 * page might not be. This will force us to replay all subsequent
2803 * modifications of the page that appear in XLOG, rather than possibly
2804 * ignoring them as already applied, but that's not a huge drawback.
2807 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2816 blk = (char *) XLogRecGetData(record) + record->xl_len;
2817 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 blk += sizeof(BkpBlock);
2825 reln = XLogOpenRelation(bkpb.node);
2826 buffer = XLogReadBuffer(reln, bkpb.block, true);
2827 Assert(BufferIsValid(buffer));
2828 page = (Page) BufferGetPage(buffer);
2830 if (bkpb.hole_length == 0)
2832 memcpy((char *) page, blk, BLCKSZ);
2836 /* must zero-fill the hole */
2837 MemSet((char *) page, 0, BLCKSZ);
2838 memcpy((char *) page, blk, bkpb.hole_offset);
2839 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2840 blk + bkpb.hole_offset,
2841 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2844 PageSetLSN(page, lsn);
2845 PageSetTLI(page, ThisTimeLineID);
2846 MarkBufferDirty(buffer);
2847 UnlockReleaseBuffer(buffer);
2849 blk += BLCKSZ - bkpb.hole_length;
2854 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2855 * record (other than to the minimal extent of computing the amount of
2856 * data to read in) until we've checked the CRCs.
2858 * We assume all of the record has been read into memory at *record.
2861 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2865 uint32 len = record->xl_len;
2869 /* First the rmgr data */
2871 COMP_CRC32(crc, XLogRecGetData(record), len);
2873 /* Add in the backup blocks, if any */
2874 blk = (char *) XLogRecGetData(record) + len;
2875 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2879 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2882 memcpy(&bkpb, blk, sizeof(BkpBlock));
2883 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2886 (errmsg("incorrect hole size in record at %X/%X",
2887 recptr.xlogid, recptr.xrecoff)));
2890 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2891 COMP_CRC32(crc, blk, blen);
2895 /* Check that xl_tot_len agrees with our calculation */
2896 if (blk != (char *) record + record->xl_tot_len)
2899 (errmsg("incorrect total length in record at %X/%X",
2900 recptr.xlogid, recptr.xrecoff)));
2904 /* Finally include the record header */
2905 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2906 SizeOfXLogRecord - sizeof(pg_crc32));
2909 if (!EQ_CRC32(record->xl_crc, crc))
2912 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2913 recptr.xlogid, recptr.xrecoff)));
2921 * Attempt to read an XLOG record.
2923 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2924 * try to read a record just after the last one previously read.
2926 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2927 * (emode must be either PANIC or LOG.)
2929 * The record is copied into readRecordBuf, so that on successful return,
2930 * the returned record pointer always points there.
2933 ReadRecord(XLogRecPtr *RecPtr, int emode)
2937 XLogRecPtr tmpRecPtr = EndRecPtr;
2938 bool randAccess = false;
2941 uint32 targetPageOff;
2942 uint32 targetRecOff;
2943 uint32 pageHeaderSize;
2945 if (readBuf == NULL)
2948 * First time through, permanently allocate readBuf. We do it this
2949 * way, rather than just making a static array, for two reasons: (1)
2950 * no need to waste the storage in most instantiations of the backend;
2951 * (2) a static char array isn't guaranteed to have any particular
2952 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2954 readBuf = (char *) malloc(XLOG_BLCKSZ);
2955 Assert(readBuf != NULL);
2960 RecPtr = &tmpRecPtr;
2961 /* fast case if next record is on same page */
2962 if (nextRecord != NULL)
2964 record = nextRecord;
2967 /* align old recptr to next page */
2968 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2969 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2970 if (tmpRecPtr.xrecoff >= XLogFileSize)
2972 (tmpRecPtr.xlogid)++;
2973 tmpRecPtr.xrecoff = 0;
2975 /* We will account for page header size below */
2979 if (!XRecOffIsValid(RecPtr->xrecoff))
2981 (errmsg("invalid record offset at %X/%X",
2982 RecPtr->xlogid, RecPtr->xrecoff)));
2985 * Since we are going to a random position in WAL, forget any prior
2986 * state about what timeline we were in, and allow it to be any
2987 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
2988 * to go backwards (but we can't reset that variable right here, since
2989 * we might not change files at all).
2991 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2992 randAccess = true; /* allow curFileTLI to go backwards too */
2995 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
3000 XLByteToSeg(*RecPtr, readId, readSeg);
3003 /* Now it's okay to reset curFileTLI if random fetch */
3007 readFile = XLogFileRead(readId, readSeg, emode);
3009 goto next_record_is_invalid;
3012 * Whenever switching to a new WAL segment, we read the first page of
3013 * the file and validate its header, even if that's not where the
3014 * target record is. This is so that we can check the additional
3015 * identification info that is present in the first page's "long"
3019 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3022 (errcode_for_file_access(),
3023 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3024 readId, readSeg, readOff)));
3025 goto next_record_is_invalid;
3027 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3028 goto next_record_is_invalid;
3031 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
3032 if (readOff != targetPageOff)
3034 readOff = targetPageOff;
3035 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
3038 (errcode_for_file_access(),
3039 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
3040 readId, readSeg, readOff)));
3041 goto next_record_is_invalid;
3043 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3046 (errcode_for_file_access(),
3047 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3048 readId, readSeg, readOff)));
3049 goto next_record_is_invalid;
3051 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3052 goto next_record_is_invalid;
3054 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3055 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
3056 if (targetRecOff == 0)
3059 * Can only get here in the continuing-from-prev-page case, because
3060 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
3061 * to skip over the new page's header.
3063 tmpRecPtr.xrecoff += pageHeaderSize;
3064 targetRecOff = pageHeaderSize;
3066 else if (targetRecOff < pageHeaderSize)
3069 (errmsg("invalid record offset at %X/%X",
3070 RecPtr->xlogid, RecPtr->xrecoff)));
3071 goto next_record_is_invalid;
3073 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3074 targetRecOff == pageHeaderSize)
3077 (errmsg("contrecord is requested by %X/%X",
3078 RecPtr->xlogid, RecPtr->xrecoff)));
3079 goto next_record_is_invalid;
3081 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3086 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
3089 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3091 if (record->xl_len != 0)
3094 (errmsg("invalid xlog switch record at %X/%X",
3095 RecPtr->xlogid, RecPtr->xrecoff)));
3096 goto next_record_is_invalid;
3099 else if (record->xl_len == 0)
3102 (errmsg("record with zero length at %X/%X",
3103 RecPtr->xlogid, RecPtr->xrecoff)));
3104 goto next_record_is_invalid;
3106 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3107 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3108 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3111 (errmsg("invalid record length at %X/%X",
3112 RecPtr->xlogid, RecPtr->xrecoff)));
3113 goto next_record_is_invalid;
3115 if (record->xl_rmid > RM_MAX_ID)
3118 (errmsg("invalid resource manager ID %u at %X/%X",
3119 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3120 goto next_record_is_invalid;
3125 * We can't exactly verify the prev-link, but surely it should be less
3126 * than the record's own address.
3128 if (!XLByteLT(record->xl_prev, *RecPtr))
3131 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3132 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3133 RecPtr->xlogid, RecPtr->xrecoff)));
3134 goto next_record_is_invalid;
3140 * Record's prev-link should exactly match our previous location. This
3141 * check guards against torn WAL pages where a stale but valid-looking
3142 * WAL record starts on a sector boundary.
3144 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3147 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3148 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3149 RecPtr->xlogid, RecPtr->xrecoff)));
3150 goto next_record_is_invalid;
3155 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3156 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3157 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3158 * enough for all "normal" records, but very large commit or abort records
3159 * might need more space.)
3161 total_len = record->xl_tot_len;
3162 if (total_len > readRecordBufSize)
3164 uint32 newSize = total_len;
3166 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3167 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3169 free(readRecordBuf);
3170 readRecordBuf = (char *) malloc(newSize);
3173 readRecordBufSize = 0;
3174 /* We treat this as a "bogus data" condition */
3176 (errmsg("record length %u at %X/%X too long",
3177 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3178 goto next_record_is_invalid;
3180 readRecordBufSize = newSize;
3183 buffer = readRecordBuf;
3185 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3186 if (total_len > len)
3188 /* Need to reassemble record */
3189 XLogContRecord *contrecord;
3190 uint32 gotlen = len;
3192 memcpy(buffer, record, len);
3193 record = (XLogRecord *) buffer;
3197 readOff += XLOG_BLCKSZ;
3198 if (readOff >= XLogSegSize)
3202 NextLogSeg(readId, readSeg);
3203 readFile = XLogFileRead(readId, readSeg, emode);
3205 goto next_record_is_invalid;
3208 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3211 (errcode_for_file_access(),
3212 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3213 readId, readSeg, readOff)));
3214 goto next_record_is_invalid;
3216 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3217 goto next_record_is_invalid;
3218 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3221 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3222 readId, readSeg, readOff)));
3223 goto next_record_is_invalid;
3225 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3226 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3227 if (contrecord->xl_rem_len == 0 ||
3228 total_len != (contrecord->xl_rem_len + gotlen))
3231 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3232 contrecord->xl_rem_len,
3233 readId, readSeg, readOff)));
3234 goto next_record_is_invalid;
3236 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3237 if (contrecord->xl_rem_len > len)
3239 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3244 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3245 contrecord->xl_rem_len);
3248 if (!RecordIsValid(record, *RecPtr, emode))
3249 goto next_record_is_invalid;
3250 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3251 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3252 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3254 nextRecord = (XLogRecord *) ((char *) contrecord +
3255 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3257 EndRecPtr.xlogid = readId;
3258 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3260 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3261 ReadRecPtr = *RecPtr;
3262 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3266 /* Record does not cross a page boundary */
3267 if (!RecordIsValid(record, *RecPtr, emode))
3268 goto next_record_is_invalid;
3269 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3270 MAXALIGN(total_len))
3271 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3272 EndRecPtr.xlogid = RecPtr->xlogid;
3273 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3274 ReadRecPtr = *RecPtr;
3275 memcpy(buffer, record, total_len);
3278 * Special processing if it's an XLOG SWITCH record
3280 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3282 /* Pretend it extends to end of segment */
3283 EndRecPtr.xrecoff += XLogSegSize - 1;
3284 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3285 nextRecord = NULL; /* definitely not on same page */
3288 * Pretend that readBuf contains the last page of the segment. This is
3289 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3292 readOff = XLogSegSize - XLOG_BLCKSZ;
3294 return (XLogRecord *) buffer;
3296 next_record_is_invalid:;
3304 * Check whether the xlog header of a page just read in looks valid.
3306 * This is just a convenience subroutine to avoid duplicated code in
3307 * ReadRecord. It's not intended for use from anywhere else.
3310 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3314 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3317 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3318 hdr->xlp_magic, readId, readSeg, readOff)));
3321 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3324 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3325 hdr->xlp_info, readId, readSeg, readOff)));
3328 if (hdr->xlp_info & XLP_LONG_HEADER)
3330 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3332 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3334 char fhdrident_str[32];
3335 char sysident_str[32];
3338 * Format sysids separately to keep platform-dependent format code
3339 * out of the translatable message string.
3341 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3342 longhdr->xlp_sysid);
3343 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3344 ControlFile->system_identifier);
3346 (errmsg("WAL file is from different system"),
3347 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3348 fhdrident_str, sysident_str)));
3351 if (longhdr->xlp_seg_size != XLogSegSize)
3354 (errmsg("WAL file is from different system"),
3355 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3358 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3361 (errmsg("WAL file is from different system"),
3362 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3366 else if (readOff == 0)
3368 /* hmm, first page of file doesn't have a long header? */
3370 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3371 hdr->xlp_info, readId, readSeg, readOff)));
3375 recaddr.xlogid = readId;
3376 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3377 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3380 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3381 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3382 readId, readSeg, readOff)));
3387 * Check page TLI is one of the expected values.
3389 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3392 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3394 readId, readSeg, readOff)));
3399 * Since child timelines are always assigned a TLI greater than their
3400 * immediate parent's TLI, we should never see TLI go backwards across
3401 * successive pages of a consistent WAL sequence.
3403 * Of course this check should only be applied when advancing sequentially
3404 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3405 * going to a random page.
3407 if (hdr->xlp_tli < lastPageTLI)
3410 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3411 hdr->xlp_tli, lastPageTLI,
3412 readId, readSeg, readOff)));
3415 lastPageTLI = hdr->xlp_tli;
3420 * Try to read a timeline's history file.
3422 * If successful, return the list of component TLIs (the given TLI followed by
3423 * its ancestor TLIs). If we can't find the history file, assume that the
3424 * timeline has no parents, and return a list of just the specified timeline
3428 readTimeLineHistory(TimeLineID targetTLI)
3431 char path[MAXPGPATH];
3432 char histfname[MAXFNAMELEN];
3433 char fline[MAXPGPATH];
3436 if (InArchiveRecovery)
3438 TLHistoryFileName(histfname, targetTLI);
3439 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3442 TLHistoryFilePath(path, targetTLI);
3444 fd = AllocateFile(path, "r");
3447 if (errno != ENOENT)
3449 (errcode_for_file_access(),
3450 errmsg("could not open file \"%s\": %m", path)));
3451 /* Not there, so assume no parents */
3452 return list_make1_int((int) targetTLI);
3460 while (fgets(fline, sizeof(fline), fd) != NULL)
3462 /* skip leading whitespace and check for # comment */
3467 for (ptr = fline; *ptr; ptr++)
3469 if (!isspace((unsigned char) *ptr))
3472 if (*ptr == '\0' || *ptr == '#')
3475 /* expect a numeric timeline ID as first field of line */
3476 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3479 (errmsg("syntax error in history file: %s", fline),
3480 errhint("Expected a numeric timeline ID.")));
3483 tli <= (TimeLineID) linitial_int(result))
3485 (errmsg("invalid data in history file: %s", fline),
3486 errhint("Timeline IDs must be in increasing sequence.")));
3488 /* Build list with newest item first */
3489 result = lcons_int((int) tli, result);
3491 /* we ignore the remainder of each line */
3497 targetTLI <= (TimeLineID) linitial_int(result))
3499 (errmsg("invalid data in history file \"%s\"", path),
3500 errhint("Timeline IDs must be less than child timeline's ID.")));
3502 result = lcons_int((int) targetTLI, result);
3505 (errmsg_internal("history of timeline %u is %s",
3506 targetTLI, nodeToString(result))));
3512 * Probe whether a timeline history file exists for the given timeline ID
3515 existsTimeLineHistory(TimeLineID probeTLI)
3517 char path[MAXPGPATH];
3518 char histfname[MAXFNAMELEN];
3521 if (InArchiveRecovery)
3523 TLHistoryFileName(histfname, probeTLI);
3524 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3527 TLHistoryFilePath(path, probeTLI);
3529 fd = AllocateFile(path, "r");
3537 if (errno != ENOENT)
3539 (errcode_for_file_access(),
3540 errmsg("could not open file \"%s\": %m", path)));
3546 * Find the newest existing timeline, assuming that startTLI exists.
3548 * Note: while this is somewhat heuristic, it does positively guarantee
3549 * that (result + 1) is not a known timeline, and therefore it should
3550 * be safe to assign that ID to a new timeline.
3553 findNewestTimeLine(TimeLineID startTLI)
3555 TimeLineID newestTLI;
3556 TimeLineID probeTLI;
3559 * The algorithm is just to probe for the existence of timeline history
3560 * files. XXX is it useful to allow gaps in the sequence?
3562 newestTLI = startTLI;
3564 for (probeTLI = startTLI + 1;; probeTLI++)
3566 if (existsTimeLineHistory(probeTLI))
3568 newestTLI = probeTLI; /* probeTLI exists */
3572 /* doesn't exist, assume we're done */
3581 * Create a new timeline history file.
3583 * newTLI: ID of the new timeline
3584 * parentTLI: ID of its immediate parent
3585 * endTLI et al: ID of the last used WAL file, for annotation purposes
3587 * Currently this is only used during recovery, and so there are no locking
3588 * considerations. But we should be just as tense as XLogFileInit to avoid
3589 * emplacing a bogus file.
3592 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3593 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3595 char path[MAXPGPATH];
3596 char tmppath[MAXPGPATH];
3597 char histfname[MAXFNAMELEN];
3598 char xlogfname[MAXFNAMELEN];
3599 char buffer[BLCKSZ];
3604 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3607 * Write into a temp file name.
3609 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3613 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3614 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3618 (errcode_for_file_access(),
3619 errmsg("could not create file \"%s\": %m", tmppath)));
3622 * If a history file exists for the parent, copy it verbatim
3624 if (InArchiveRecovery)
3626 TLHistoryFileName(histfname, parentTLI);
3627 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3630 TLHistoryFilePath(path, parentTLI);
3632 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3635 if (errno != ENOENT)
3637 (errcode_for_file_access(),
3638 errmsg("could not open file \"%s\": %m", path)));
3639 /* Not there, so assume parent has no parents */
3646 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3647 if (nbytes < 0 || errno != 0)
3649 (errcode_for_file_access(),
3650 errmsg("could not read file \"%s\": %m", path)));
3654 if ((int) write(fd, buffer, nbytes) != nbytes)
3656 int save_errno = errno;
3659 * If we fail to make the file, delete it to release disk
3665 * if write didn't set errno, assume problem is no disk space
3667 errno = save_errno ? save_errno : ENOSPC;
3670 (errcode_for_file_access(),
3671 errmsg("could not write to file \"%s\": %m", tmppath)));
3678 * Append one line with the details of this timeline split.
3680 * If we did have a parent file, insert an extra newline just in case the
3681 * parent file failed to end with one.
3683 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3685 snprintf(buffer, sizeof(buffer),
3686 "%s%u\t%s\t%s transaction %u at %s\n",
3687 (srcfd < 0) ? "" : "\n",
3690 recoveryStopAfter ? "after" : "before",
3692 timestamptz_to_str(recoveryStopTime));
3694 nbytes = strlen(buffer);
3696 if ((int) write(fd, buffer, nbytes) != nbytes)
3698 int save_errno = errno;
3701 * If we fail to make the file, delete it to release disk space
3704 /* if write didn't set errno, assume problem is no disk space */
3705 errno = save_errno ? save_errno : ENOSPC;
3708 (errcode_for_file_access(),
3709 errmsg("could not write to file \"%s\": %m", tmppath)));
3712 if (pg_fsync(fd) != 0)
3714 (errcode_for_file_access(),
3715 errmsg("could not fsync file \"%s\": %m", tmppath)));
3719 (errcode_for_file_access(),
3720 errmsg("could not close file \"%s\": %m", tmppath)));
3724 * Now move the completed history file into place with its final name.
3726 TLHistoryFilePath(path, newTLI);
3729 * Prefer link() to rename() here just to be really sure that we don't
3730 * overwrite an existing logfile. However, there shouldn't be one, so
3731 * rename() is an acceptable substitute except for the truly paranoid.
3733 #if HAVE_WORKING_LINK
3734 if (link(tmppath, path) < 0)
3736 (errcode_for_file_access(),
3737 errmsg("could not link file \"%s\" to \"%s\": %m",
3741 if (rename(tmppath, path) < 0)
3743 (errcode_for_file_access(),
3744 errmsg("could not rename file \"%s\" to \"%s\": %m",
3748 /* The history file can be archived immediately. */
3749 TLHistoryFileName(histfname, newTLI);
3750 XLogArchiveNotify(histfname);
3754 * I/O routines for pg_control
3756 * *ControlFile is a buffer in shared memory that holds an image of the
3757 * contents of pg_control. WriteControlFile() initializes pg_control
3758 * given a preloaded buffer, ReadControlFile() loads the buffer from
3759 * the pg_control file (during postmaster or standalone-backend startup),
3760 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3762 * For simplicity, WriteControlFile() initializes the fields of pg_control
3763 * that are related to checking backend/database compatibility, and
3764 * ReadControlFile() verifies they are correct. We could split out the
3765 * I/O and compatibility-check functions, but there seems no need currently.
3768 WriteControlFile(void)
3771 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3775 * Initialize version and compatibility-check fields
3777 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3778 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3780 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3781 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3783 ControlFile->blcksz = BLCKSZ;
3784 ControlFile->relseg_size = RELSEG_SIZE;
3785 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3786 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3788 ControlFile->nameDataLen = NAMEDATALEN;
3789 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3791 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
3793 #ifdef HAVE_INT64_TIMESTAMP
3794 ControlFile->enableIntTimes = TRUE;
3796 ControlFile->enableIntTimes = FALSE;
3799 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3800 localeptr = setlocale(LC_COLLATE, NULL);
3803 (errmsg("invalid LC_COLLATE setting")));
3804 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3805 localeptr = setlocale(LC_CTYPE, NULL);
3808 (errmsg("invalid LC_CTYPE setting")));
3809 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3811 /* Contents are protected with a CRC */
3812 INIT_CRC32(ControlFile->crc);
3813 COMP_CRC32(ControlFile->crc,
3814 (char *) ControlFile,
3815 offsetof(ControlFileData, crc));
3816 FIN_CRC32(ControlFile->crc);
3819 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3820 * excess over sizeof(ControlFileData). This reduces the odds of
3821 * premature-EOF errors when reading pg_control. We'll still fail when we
3822 * check the contents of the file, but hopefully with a more specific
3823 * error than "couldn't read pg_control".
3825 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3826 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3828 memset(buffer, 0, PG_CONTROL_SIZE);
3829 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3831 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3832 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3836 (errcode_for_file_access(),
3837 errmsg("could not create control file \"%s\": %m",
3838 XLOG_CONTROL_FILE)));
3841 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3843 /* if write didn't set errno, assume problem is no disk space */
3847 (errcode_for_file_access(),
3848 errmsg("could not write to control file: %m")));
3851 if (pg_fsync(fd) != 0)
3853 (errcode_for_file_access(),
3854 errmsg("could not fsync control file: %m")));
3858 (errcode_for_file_access(),
3859 errmsg("could not close control file: %m")));
3863 ReadControlFile(void)
3871 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3876 (errcode_for_file_access(),
3877 errmsg("could not open control file \"%s\": %m",
3878 XLOG_CONTROL_FILE)));
3880 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3882 (errcode_for_file_access(),
3883 errmsg("could not read from control file: %m")));
3888 * Check for expected pg_control format version. If this is wrong, the
3889 * CRC check will likely fail because we'll be checking the wrong number
3890 * of bytes. Complaining about wrong version will probably be more
3891 * enlightening than complaining about wrong CRC.
3894 if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
3896 (errmsg("database files are incompatible with server"),
3897 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
3898 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
3899 ControlFile->pg_control_version, ControlFile->pg_control_version,
3900 PG_CONTROL_VERSION, PG_CONTROL_VERSION),
3901 errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
3903 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3905 (errmsg("database files are incompatible with server"),
3906 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3907 " but the server was compiled with PG_CONTROL_VERSION %d.",
3908 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3909 errhint("It looks like you need to initdb.")));
3911 /* Now check the CRC. */
3914 (char *) ControlFile,
3915 offsetof(ControlFileData, crc));
3918 if (!EQ_CRC32(crc, ControlFile->crc))
3920 (errmsg("incorrect checksum in control file")));
3923 * Do compatibility checking immediately. We do this here for 2 reasons:
3925 * (1) if the database isn't compatible with the backend executable, we
3926 * want to abort before we can possibly do any damage;
3928 * (2) this code is executed in the postmaster, so the setlocale() will
3929 * propagate to forked backends, which aren't going to read this file for
3930 * themselves. (These locale settings are considered critical
3931 * compatibility items because they can affect sort order of indexes.)
3933 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3935 (errmsg("database files are incompatible with server"),
3936 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3937 " but the server was compiled with CATALOG_VERSION_NO %d.",
3938 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3939 errhint("It looks like you need to initdb.")));
3940 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3942 (errmsg("database files are incompatible with server"),
3943 errdetail("The database cluster was initialized with MAXALIGN %d,"
3944 " but the server was compiled with MAXALIGN %d.",
3945 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3946 errhint("It looks like you need to initdb.")));
3947 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3949 (errmsg("database files are incompatible with server"),
3950 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3951 errhint("It looks like you need to initdb.")));
3952 if (ControlFile->blcksz != BLCKSZ)
3954 (errmsg("database files are incompatible with server"),
3955 errdetail("The database cluster was initialized with BLCKSZ %d,"
3956 " but the server was compiled with BLCKSZ %d.",
3957 ControlFile->blcksz, BLCKSZ),
3958 errhint("It looks like you need to recompile or initdb.")));
3959 if (ControlFile->relseg_size != RELSEG_SIZE)
3961 (errmsg("database files are incompatible with server"),
3962 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3963 " but the server was compiled with RELSEG_SIZE %d.",
3964 ControlFile->relseg_size, RELSEG_SIZE),
3965 errhint("It looks like you need to recompile or initdb.")));
3966 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3968 (errmsg("database files are incompatible with server"),
3969 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3970 " but the server was compiled with XLOG_BLCKSZ %d.",
3971 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3972 errhint("It looks like you need to recompile or initdb.")));
3973 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3975 (errmsg("database files are incompatible with server"),
3976 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3977 " but the server was compiled with XLOG_SEG_SIZE %d.",
3978 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3979 errhint("It looks like you need to recompile or initdb.")));
3980 if (ControlFile->nameDataLen != NAMEDATALEN)
3982 (errmsg("database files are incompatible with server"),
3983 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3984 " but the server was compiled with NAMEDATALEN %d.",
3985 ControlFile->nameDataLen, NAMEDATALEN),
3986 errhint("It looks like you need to recompile or initdb.")));
3987 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3989 (errmsg("database files are incompatible with server"),
3990 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3991 " but the server was compiled with INDEX_MAX_KEYS %d.",
3992 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3993 errhint("It looks like you need to recompile or initdb.")));
3994 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
3996 (errmsg("database files are incompatible with server"),
3997 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
3998 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
3999 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4000 errhint("It looks like you need to recompile or initdb.")));
4002 #ifdef HAVE_INT64_TIMESTAMP
4003 if (ControlFile->enableIntTimes != TRUE)
4005 (errmsg("database files are incompatible with server"),
4006 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
4007 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
4008 errhint("It looks like you need to recompile or initdb.")));
4010 if (ControlFile->enableIntTimes != FALSE)
4012 (errmsg("database files are incompatible with server"),
4013 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
4014 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
4015 errhint("It looks like you need to recompile or initdb.")));
4018 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
4020 (errmsg("database files are incompatible with server"),
4021 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
4022 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
4023 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
4024 errhint("It looks like you need to recompile or initdb.")));
4025 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
4027 (errmsg("database files are incompatible with operating system"),
4028 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
4029 " which is not recognized by setlocale().",
4030 ControlFile->lc_collate),
4031 errhint("It looks like you need to initdb or install locale support.")));
4032 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
4034 (errmsg("database files are incompatible with operating system"),
4035 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
4036 " which is not recognized by setlocale().",
4037 ControlFile->lc_ctype),
4038 errhint("It looks like you need to initdb or install locale support.")));
4040 /* Make the fixed locale settings visible as GUC variables, too */
4041 SetConfigOption("lc_collate", ControlFile->lc_collate,
4042 PGC_INTERNAL, PGC_S_OVERRIDE);
4043 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
4044 PGC_INTERNAL, PGC_S_OVERRIDE);
4048 UpdateControlFile(void)
4052 INIT_CRC32(ControlFile->crc);
4053 COMP_CRC32(ControlFile->crc,
4054 (char *) ControlFile,
4055 offsetof(ControlFileData, crc));
4056 FIN_CRC32(ControlFile->crc);
4058 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4063 (errcode_for_file_access(),
4064 errmsg("could not open control file \"%s\": %m",
4065 XLOG_CONTROL_FILE)));
4068 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4070 /* if write didn't set errno, assume problem is no disk space */
4074 (errcode_for_file_access(),
4075 errmsg("could not write to control file: %m")));
4078 if (pg_fsync(fd) != 0)
4080 (errcode_for_file_access(),
4081 errmsg("could not fsync control file: %m")));
4085 (errcode_for_file_access(),
4086 errmsg("could not close control file: %m")));
4090 * Initialization of shared memory for XLOG
4098 size = sizeof(XLogCtlData);
4099 /* xlblocks array */
4100 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
4101 /* extra alignment padding for XLOG I/O buffers */
4102 size = add_size(size, ALIGNOF_XLOG_BUFFER);
4103 /* and the buffers themselves */
4104 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4107 * Note: we don't count ControlFileData, it comes out of the "slop factor"
4108 * added by CreateSharedMemoryAndSemaphores. This lets us use this
4109 * routine again below to compute the actual allocation size.
4122 ControlFile = (ControlFileData *)
4123 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4124 XLogCtl = (XLogCtlData *)
4125 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4127 if (foundCFile || foundXLog)
4129 /* both should be present or neither */
4130 Assert(foundCFile && foundXLog);
4134 memset(XLogCtl, 0, sizeof(XLogCtlData));
4137 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4138 * multiple of the alignment for same, so no extra alignment padding is
4141 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4142 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4143 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4144 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4147 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4149 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4150 XLogCtl->pages = allocptr;
4151 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4154 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4155 * in additional info.)
4157 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4158 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4159 SpinLockInit(&XLogCtl->info_lck);
4162 * If we are not in bootstrap mode, pg_control should already exist. Read
4163 * and validate it immediately (see comments in ReadControlFile() for the
4166 if (!IsBootstrapProcessingMode())
4171 * This func must be called ONCE on system install. It creates pg_control
4172 * and the initial XLOG segment.
4177 CheckPoint checkPoint;
4179 XLogPageHeader page;
4180 XLogLongPageHeader longpage;
4183 uint64 sysidentifier;
4188 * Select a hopefully-unique system identifier code for this installation.
4189 * We use the result of gettimeofday(), including the fractional seconds
4190 * field, as being about as unique as we can easily get. (Think not to
4191 * use random(), since it hasn't been seeded and there's no portable way
4192 * to seed it other than the system clock value...) The upper half of the
4193 * uint64 value is just the tv_sec part, while the lower half is the XOR
4194 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4195 * unnecessarily if "uint64" is really only 32 bits wide. A person
4196 * knowing this encoding can determine the initialization time of the
4197 * installation, which could perhaps be useful sometimes.
4199 gettimeofday(&tv, NULL);
4200 sysidentifier = ((uint64) tv.tv_sec) << 32;
4201 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4203 /* First timeline ID is always 1 */
4206 /* page buffer must be aligned suitably for O_DIRECT */
4207 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4208 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4209 memset(page, 0, XLOG_BLCKSZ);
4211 /* Set up information for the initial checkpoint record */
4212 checkPoint.redo.xlogid = 0;
4213 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4214 checkPoint.ThisTimeLineID = ThisTimeLineID;
4215 checkPoint.nextXidEpoch = 0;
4216 checkPoint.nextXid = FirstNormalTransactionId;
4217 checkPoint.nextOid = FirstBootstrapObjectId;
4218 checkPoint.nextMulti = FirstMultiXactId;
4219 checkPoint.nextMultiOffset = 0;
4220 checkPoint.time = (pg_time_t) time(NULL);
4222 ShmemVariableCache->nextXid = checkPoint.nextXid;
4223 ShmemVariableCache->nextOid = checkPoint.nextOid;
4224 ShmemVariableCache->oidCount = 0;
4225 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4227 /* Set up the XLOG page header */
4228 page->xlp_magic = XLOG_PAGE_MAGIC;
4229 page->xlp_info = XLP_LONG_HEADER;
4230 page->xlp_tli = ThisTimeLineID;
4231 page->xlp_pageaddr.xlogid = 0;
4232 page->xlp_pageaddr.xrecoff = 0;
4233 longpage = (XLogLongPageHeader) page;
4234 longpage->xlp_sysid = sysidentifier;
4235 longpage->xlp_seg_size = XLogSegSize;
4236 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4238 /* Insert the initial checkpoint record */
4239 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4240 record->xl_prev.xlogid = 0;
4241 record->xl_prev.xrecoff = 0;
4242 record->xl_xid = InvalidTransactionId;
4243 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4244 record->xl_len = sizeof(checkPoint);
4245 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4246 record->xl_rmid = RM_XLOG_ID;
4247 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4250 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4251 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4252 SizeOfXLogRecord - sizeof(pg_crc32));
4254 record->xl_crc = crc;
4256 /* Create first XLOG segment file */
4257 use_existent = false;
4258 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4260 /* Write the first page with the initial record */
4262 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4264 /* if write didn't set errno, assume problem is no disk space */
4268 (errcode_for_file_access(),
4269 errmsg("could not write bootstrap transaction log file: %m")));
4272 if (pg_fsync(openLogFile) != 0)
4274 (errcode_for_file_access(),
4275 errmsg("could not fsync bootstrap transaction log file: %m")));
4277 if (close(openLogFile))
4279 (errcode_for_file_access(),
4280 errmsg("could not close bootstrap transaction log file: %m")));
4284 /* Now create pg_control */
4286 memset(ControlFile, 0, sizeof(ControlFileData));
4287 /* Initialize pg_control status fields */
4288 ControlFile->system_identifier = sysidentifier;
4289 ControlFile->state = DB_SHUTDOWNED;
4290 ControlFile->time = checkPoint.time;
4291 ControlFile->checkPoint = checkPoint.redo;
4292 ControlFile->checkPointCopy = checkPoint;
4293 /* some additional ControlFile fields are set in WriteControlFile() */
4297 /* Bootstrap the commit log, too */
4299 BootStrapSUBTRANS();
4300 BootStrapMultiXact();
4306 str_time(pg_time_t tnow)
4308 static char buf[128];
4310 pg_strftime(buf, sizeof(buf),
4311 "%Y-%m-%d %H:%M:%S %Z",
4312 pg_localtime(&tnow, log_timezone));
4318 * See if there is a recovery command file (recovery.conf), and if so
4319 * read in parameters for archive recovery.
4321 * XXX longer term intention is to expand this to
4322 * cater for additional parameters and controls
4323 * possibly use a flex lexer similar to the GUC one
4326 readRecoveryCommandFile(void)
4329 char cmdline[MAXPGPATH];
4330 TimeLineID rtli = 0;
4331 bool rtliGiven = false;
4332 bool syntaxError = false;
4334 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4337 if (errno == ENOENT)
4338 return; /* not there, so no archive recovery */
4340 (errcode_for_file_access(),
4341 errmsg("could not open recovery command file \"%s\": %m",
4342 RECOVERY_COMMAND_FILE)));
4346 (errmsg("starting archive recovery")));
4351 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4353 /* skip leading whitespace and check for # comment */
4358 for (ptr = cmdline; *ptr; ptr++)
4360 if (!isspace((unsigned char) *ptr))
4363 if (*ptr == '\0' || *ptr == '#')
4366 /* identify the quoted parameter value */
4367 tok1 = strtok(ptr, "'");
4373 tok2 = strtok(NULL, "'");
4379 /* reparse to get just the parameter name */
4380 tok1 = strtok(ptr, " \t=");
4387 if (strcmp(tok1, "restore_command") == 0)
4389 recoveryRestoreCommand = pstrdup(tok2);
4391 (errmsg("restore_command = '%s'",
4392 recoveryRestoreCommand)));
4394 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4397 if (strcmp(tok2, "latest") == 0)
4402 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4403 if (errno == EINVAL || errno == ERANGE)
4405 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4410 (errmsg("recovery_target_timeline = %u", rtli)));
4413 (errmsg("recovery_target_timeline = latest")));
4415 else if (strcmp(tok1, "recovery_target_xid") == 0)
4418 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4419 if (errno == EINVAL || errno == ERANGE)
4421 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4424 (errmsg("recovery_target_xid = %u",
4425 recoveryTargetXid)));
4426 recoveryTarget = true;
4427 recoveryTargetExact = true;
4429 else if (strcmp(tok1, "recovery_target_time") == 0)
4432 * if recovery_target_xid specified, then this overrides
4433 * recovery_target_time
4435 if (recoveryTargetExact)
4437 recoveryTarget = true;
4438 recoveryTargetExact = false;
4441 * Convert the time string given by the user to TimestampTz form.
4443 recoveryTargetTime =
4444 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
4445 CStringGetDatum(tok2),
4446 ObjectIdGetDatum(InvalidOid),
4447 Int32GetDatum(-1)));
4449 (errmsg("recovery_target_time = '%s'",
4450 timestamptz_to_str(recoveryTargetTime))));
4452 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4455 * does nothing if a recovery_target is not also set
4457 if (strcmp(tok2, "true") == 0)
4458 recoveryTargetInclusive = true;
4461 recoveryTargetInclusive = false;
4465 (errmsg("recovery_target_inclusive = %s", tok2)));
4467 else if (strcmp(tok1, "log_restartpoints") == 0)
4470 * does nothing if a recovery_target is not also set
4472 if (strcmp(tok2, "true") == 0)
4473 recoveryLogRestartpoints = true;
4476 recoveryLogRestartpoints = false;
4480 (errmsg("log_restartpoints = %s", tok2)));
4484 (errmsg("unrecognized recovery parameter \"%s\"",
4492 (errmsg("syntax error in recovery command file: %s",
4494 errhint("Lines should have the format parameter = 'value'.")));
4496 /* Check that required parameters were supplied */
4497 if (recoveryRestoreCommand == NULL)
4499 (errmsg("recovery command file \"%s\" did not specify restore_command",
4500 RECOVERY_COMMAND_FILE)));
4502 /* Enable fetching from archive recovery area */
4503 InArchiveRecovery = true;
4506 * If user specified recovery_target_timeline, validate it or compute the
4507 * "latest" value. We can't do this until after we've gotten the restore
4508 * command and set InArchiveRecovery, because we need to fetch timeline
4509 * history files from the archive.
4515 /* Timeline 1 does not have a history file, all else should */
4516 if (rtli != 1 && !existsTimeLineHistory(rtli))
4518 (errmsg("recovery target timeline %u does not exist",
4520 recoveryTargetTLI = rtli;
4524 /* We start the "latest" search from pg_control's timeline */
4525 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4531 * Exit archive-recovery state
4534 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4536 char recoveryPath[MAXPGPATH];
4537 char xlogpath[MAXPGPATH];
4540 * We are no longer in archive recovery state.
4542 InArchiveRecovery = false;
4545 * We should have the ending log segment currently open. Verify, and then
4546 * close it (to avoid problems on Windows with trying to rename or delete
4549 Assert(readFile >= 0);
4550 Assert(readId == endLogId);
4551 Assert(readSeg == endLogSeg);
4557 * If the segment was fetched from archival storage, we want to replace
4558 * the existing xlog segment (if any) with the archival version. This is
4559 * because whatever is in XLOGDIR is very possibly older than what we have
4560 * from the archives, since it could have come from restoring a PGDATA
4561 * backup. In any case, the archival version certainly is more
4562 * descriptive of what our current database state is, because that is what
4565 * Note that if we are establishing a new timeline, ThisTimeLineID is
4566 * already set to the new value, and so we will create a new file instead
4567 * of overwriting any existing file. (This is, in fact, always the case
4570 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4571 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4573 if (restoredFromArchive)
4576 (errmsg_internal("moving last restored xlog to \"%s\"",
4578 unlink(xlogpath); /* might or might not exist */
4579 if (rename(recoveryPath, xlogpath) != 0)
4581 (errcode_for_file_access(),
4582 errmsg("could not rename file \"%s\" to \"%s\": %m",
4583 recoveryPath, xlogpath)));
4584 /* XXX might we need to fix permissions on the file? */
4589 * If the latest segment is not archival, but there's still a
4590 * RECOVERYXLOG laying about, get rid of it.
4592 unlink(recoveryPath); /* ignore any error */
4595 * If we are establishing a new timeline, we have to copy data from
4596 * the last WAL segment of the old timeline to create a starting WAL
4597 * segment for the new timeline.
4599 if (endTLI != ThisTimeLineID)
4600 XLogFileCopy(endLogId, endLogSeg,
4601 endTLI, endLogId, endLogSeg);
4605 * Let's just make real sure there are not .ready or .done flags posted
4606 * for the new segment.
4608 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4609 XLogArchiveCleanup(xlogpath);
4611 /* Get rid of any remaining recovered timeline-history file, too */
4612 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4613 unlink(recoveryPath); /* ignore any error */
4616 * Rename the config file out of the way, so that we don't accidentally
4617 * re-enter archive recovery mode in a subsequent crash.
4619 unlink(RECOVERY_COMMAND_DONE);
4620 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4622 (errcode_for_file_access(),
4623 errmsg("could not rename file \"%s\" to \"%s\": %m",
4624 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4627 (errmsg("archive recovery complete")));
4631 * For point-in-time recovery, this function decides whether we want to
4632 * stop applying the XLOG at or after the current record.
4634 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4635 * *includeThis is set TRUE if we should apply this record before stopping.
4636 * Also, some information is saved in recoveryStopXid et al for use in
4637 * annotating the new timeline's history file.
4640 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4644 TimestampTz recordXtime;
4646 /* We only consider stopping at COMMIT or ABORT records */
4647 if (record->xl_rmid != RM_XACT_ID)
4649 record_info = record->xl_info & ~XLR_INFO_MASK;
4650 if (record_info == XLOG_XACT_COMMIT)
4652 xl_xact_commit *recordXactCommitData;
4654 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4655 recordXtime = recordXactCommitData->xact_time;
4657 else if (record_info == XLOG_XACT_ABORT)
4659 xl_xact_abort *recordXactAbortData;
4661 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4662 recordXtime = recordXactAbortData->xact_time;
4667 /* Remember the most recent COMMIT/ABORT time for logging purposes */
4668 recoveryLastXTime = recordXtime;
4670 /* Do we have a PITR target at all? */
4671 if (!recoveryTarget)
4674 if (recoveryTargetExact)
4677 * there can be only one transaction end record with this exact
4680 * when testing for an xid, we MUST test for equality only, since
4681 * transactions are numbered in the order they start, not the order
4682 * they complete. A higher numbered xid will complete before you about
4683 * 50% of the time...
4685 stopsHere = (record->xl_xid == recoveryTargetXid);
4687 *includeThis = recoveryTargetInclusive;
4692 * there can be many transactions that share the same commit time, so
4693 * we stop after the last one, if we are inclusive, or stop at the
4694 * first one if we are exclusive
4696 if (recoveryTargetInclusive)
4697 stopsHere = (recordXtime > recoveryTargetTime);
4699 stopsHere = (recordXtime >= recoveryTargetTime);
4701 *includeThis = false;
4706 recoveryStopXid = record->xl_xid;
4707 recoveryStopTime = recordXtime;
4708 recoveryStopAfter = *includeThis;
4710 if (record_info == XLOG_XACT_COMMIT)
4712 if (recoveryStopAfter)
4714 (errmsg("recovery stopping after commit of transaction %u, time %s",
4716 timestamptz_to_str(recoveryStopTime))));
4719 (errmsg("recovery stopping before commit of transaction %u, time %s",
4721 timestamptz_to_str(recoveryStopTime))));
4725 if (recoveryStopAfter)
4727 (errmsg("recovery stopping after abort of transaction %u, time %s",
4729 timestamptz_to_str(recoveryStopTime))));
4732 (errmsg("recovery stopping before abort of transaction %u, time %s",
4734 timestamptz_to_str(recoveryStopTime))));
4742 * This must be called ONCE during postmaster or standalone-backend startup
4747 XLogCtlInsert *Insert;
4748 CheckPoint checkPoint;
4750 bool reachedStopPoint = false;
4751 bool haveBackupLabel = false;
4761 TransactionId oldestActiveXID;
4764 * Read control file and check XLOG status looks valid.
4766 * Note: in most control paths, *ControlFile is already valid and we need
4767 * not do ReadControlFile() here, but might as well do it to be sure.
4771 if (ControlFile->state < DB_SHUTDOWNED ||
4772 ControlFile->state > DB_IN_PRODUCTION ||
4773 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4775 (errmsg("control file contains invalid data")));
4777 if (ControlFile->state == DB_SHUTDOWNED)
4779 (errmsg("database system was shut down at %s",
4780 str_time(ControlFile->time))));
4781 else if (ControlFile->state == DB_SHUTDOWNING)
4783 (errmsg("database system shutdown was interrupted; last known up at %s",
4784 str_time(ControlFile->time))));
4785 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4787 (errmsg("database system was interrupted while in recovery at %s",
4788 str_time(ControlFile->time)),
4789 errhint("This probably means that some data is corrupted and"
4790 " you will have to use the last backup for recovery.")));
4791 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4793 (errmsg("database system was interrupted while in recovery at log time %s",
4794 str_time(ControlFile->checkPointCopy.time)),
4795 errhint("If this has occurred more than once some data might be corrupted"
4796 " and you might need to choose an earlier recovery target.")));
4797 else if (ControlFile->state == DB_IN_PRODUCTION)
4799 (errmsg("database system was interrupted; last known up at %s",
4800 str_time(ControlFile->time))));
4802 /* This is just to allow attaching to startup process with a debugger */
4803 #ifdef XLOG_REPLAY_DELAY
4804 if (ControlFile->state != DB_SHUTDOWNED)
4805 pg_usleep(60000000L);
4809 * Initialize on the assumption we want to recover to the same timeline
4810 * that's active according to pg_control.
4812 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4815 * Check for recovery control file, and if so set up state for offline
4818 readRecoveryCommandFile();
4820 /* Now we can determine the list of expected TLIs */
4821 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4824 * If pg_control's timeline is not in expectedTLIs, then we cannot
4825 * proceed: the backup is not part of the history of the requested
4828 if (!list_member_int(expectedTLIs,
4829 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4831 (errmsg("requested timeline %u is not a child of database system timeline %u",
4833 ControlFile->checkPointCopy.ThisTimeLineID)));
4835 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4838 * When a backup_label file is present, we want to roll forward from
4839 * the checkpoint it identifies, rather than using pg_control.
4841 record = ReadCheckpointRecord(checkPointLoc, 0);
4845 (errmsg("checkpoint record is at %X/%X",
4846 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4847 InRecovery = true; /* force recovery even if SHUTDOWNED */
4852 (errmsg("could not locate required checkpoint record"),
4853 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4855 /* set flag to delete it later */
4856 haveBackupLabel = true;
4861 * Get the last valid checkpoint record. If the latest one according
4862 * to pg_control is broken, try the next-to-last one.
4864 checkPointLoc = ControlFile->checkPoint;
4865 record = ReadCheckpointRecord(checkPointLoc, 1);
4869 (errmsg("checkpoint record is at %X/%X",
4870 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4874 checkPointLoc = ControlFile->prevCheckPoint;
4875 record = ReadCheckpointRecord(checkPointLoc, 2);
4879 (errmsg("using previous checkpoint record at %X/%X",
4880 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4881 InRecovery = true; /* force recovery even if SHUTDOWNED */
4885 (errmsg("could not locate a valid checkpoint record")));
4889 LastRec = RecPtr = checkPointLoc;
4890 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4891 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4894 (errmsg("redo record is at %X/%X; shutdown %s",
4895 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4896 wasShutdown ? "TRUE" : "FALSE")));
4898 (errmsg("next transaction ID: %u/%u; next OID: %u",
4899 checkPoint.nextXidEpoch, checkPoint.nextXid,
4900 checkPoint.nextOid)));
4902 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4903 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4904 if (!TransactionIdIsNormal(checkPoint.nextXid))
4906 (errmsg("invalid next transaction ID")));
4908 ShmemVariableCache->nextXid = checkPoint.nextXid;
4909 ShmemVariableCache->nextOid = checkPoint.nextOid;
4910 ShmemVariableCache->oidCount = 0;
4911 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4914 * We must replay WAL entries using the same TimeLineID they were created
4915 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4916 * also xlog_redo()).
4918 ThisTimeLineID = checkPoint.ThisTimeLineID;
4920 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4922 if (XLByteLT(RecPtr, checkPoint.redo))
4924 (errmsg("invalid redo in checkpoint record")));
4927 * Check whether we need to force recovery from WAL. If it appears to
4928 * have been a clean shutdown and we did not have a recovery.conf file,
4929 * then assume no recovery needed.
4931 if (XLByteLT(checkPoint.redo, RecPtr))
4935 (errmsg("invalid redo record in shutdown checkpoint")));
4938 else if (ControlFile->state != DB_SHUTDOWNED)
4940 else if (InArchiveRecovery)
4942 /* force recovery due to presence of recovery.conf */
4952 * Update pg_control to show that we are recovering and to show the
4953 * selected checkpoint as the place we are starting from. We also mark
4954 * pg_control with any minimum recovery stop point obtained from a
4955 * backup history file.
4957 if (InArchiveRecovery)
4960 (errmsg("automatic recovery in progress")));
4961 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4966 (errmsg("database system was not properly shut down; "
4967 "automatic recovery in progress")));
4968 ControlFile->state = DB_IN_CRASH_RECOVERY;
4970 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4971 ControlFile->checkPoint = checkPointLoc;
4972 ControlFile->checkPointCopy = checkPoint;
4973 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4974 ControlFile->minRecoveryPoint = minRecoveryLoc;
4975 ControlFile->time = (pg_time_t) time(NULL);
4976 UpdateControlFile();
4979 * If there was a backup label file, it's done its job and the info
4980 * has now been propagated into pg_control. We must get rid of the
4981 * label file so that if we crash during recovery, we'll pick up at
4982 * the latest recovery restartpoint instead of going all the way back
4983 * to the backup start point. It seems prudent though to just rename
4984 * the file out of the way rather than delete it completely.
4986 if (haveBackupLabel)
4988 unlink(BACKUP_LABEL_OLD);
4989 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4991 (errcode_for_file_access(),
4992 errmsg("could not rename file \"%s\" to \"%s\": %m",
4993 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4996 /* Start up the recovery environment */
4997 XLogInitRelationCache();
4999 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5001 if (RmgrTable[rmid].rm_startup != NULL)
5002 RmgrTable[rmid].rm_startup();
5006 * Find the first record that logically follows the checkpoint --- it
5007 * might physically precede it, though.
5009 if (XLByteLT(checkPoint.redo, RecPtr))
5011 /* back up to find the record */
5012 record = ReadRecord(&(checkPoint.redo), PANIC);
5016 /* just have to read next record after CheckPoint */
5017 record = ReadRecord(NULL, LOG);
5022 bool recoveryContinue = true;
5023 bool recoveryApply = true;
5024 ErrorContextCallback errcontext;
5028 (errmsg("redo starts at %X/%X",
5029 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5032 * main redo apply loop
5041 initStringInfo(&buf);
5042 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
5043 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
5044 EndRecPtr.xlogid, EndRecPtr.xrecoff);
5045 xlog_outrec(&buf, record);
5046 appendStringInfo(&buf, " - ");
5047 RmgrTable[record->xl_rmid].rm_desc(&buf,
5049 XLogRecGetData(record));
5050 elog(LOG, "%s", buf.data);
5056 * Have we reached our recovery target?
5058 if (recoveryStopsHere(record, &recoveryApply))
5060 reachedStopPoint = true; /* see below */
5061 recoveryContinue = false;
5066 /* Setup error traceback support for ereport() */
5067 errcontext.callback = rm_redo_error_callback;
5068 errcontext.arg = (void *) record;
5069 errcontext.previous = error_context_stack;
5070 error_context_stack = &errcontext;
5072 /* nextXid must be beyond record's xid */
5073 if (TransactionIdFollowsOrEquals(record->xl_xid,
5074 ShmemVariableCache->nextXid))
5076 ShmemVariableCache->nextXid = record->xl_xid;
5077 TransactionIdAdvance(ShmemVariableCache->nextXid);
5080 if (record->xl_info & XLR_BKP_BLOCK_MASK)
5081 RestoreBkpBlocks(record, EndRecPtr);
5083 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
5085 /* Pop the error context stack */
5086 error_context_stack = errcontext.previous;
5088 LastRec = ReadRecPtr;
5090 record = ReadRecord(NULL, LOG);
5091 } while (record != NULL && recoveryContinue);
5094 * end of main redo apply loop
5098 (errmsg("redo done at %X/%X",
5099 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5100 if (recoveryLastXTime)
5102 (errmsg("last completed transaction was at log time %s",
5103 timestamptz_to_str(recoveryLastXTime))));
5108 /* there are no WAL records following the checkpoint */
5110 (errmsg("redo is not required")));
5115 * Re-fetch the last valid or last applied record, so we can identify the
5116 * exact endpoint of what we consider the valid portion of WAL.
5118 record = ReadRecord(&LastRec, PANIC);
5119 EndOfLog = EndRecPtr;
5120 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
5123 * Complain if we did not roll forward far enough to render the backup
5126 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
5128 if (reachedStopPoint) /* stopped because of stop request */
5130 (errmsg("requested recovery stop point is before end time of backup dump")));
5131 else /* ran off end of WAL */
5133 (errmsg("WAL ends before end time of backup dump")));
5137 * Consider whether we need to assign a new timeline ID.
5139 * If we are doing an archive recovery, we always assign a new ID. This
5140 * handles a couple of issues. If we stopped short of the end of WAL
5141 * during recovery, then we are clearly generating a new timeline and must
5142 * assign it a unique new ID. Even if we ran to the end, modifying the
5143 * current last segment is problematic because it may result in trying to
5144 * overwrite an already-archived copy of that segment, and we encourage
5145 * DBAs to make their archive_commands reject that. We can dodge the
5146 * problem by making the new active segment have a new timeline ID.
5148 * In a normal crash recovery, we can just extend the timeline we were in.
5150 if (InArchiveRecovery)
5152 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5154 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5155 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5156 curFileTLI, endLogId, endLogSeg);
5159 /* Save the selected TimeLineID in shared memory, too */
5160 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5163 * We are now done reading the old WAL. Turn off archive fetching if it
5164 * was active, and make a writable copy of the last WAL segment. (Note
5165 * that we also have a copy of the last block of the old WAL in readBuf;
5166 * we will use that below.)
5168 if (InArchiveRecovery)
5169 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5172 * Prepare to write WAL starting at EndOfLog position, and init xlog
5173 * buffer cache using the block containing the last record from the
5174 * previous incarnation.
5176 openLogId = endLogId;
5177 openLogSeg = endLogSeg;
5178 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5180 Insert = &XLogCtl->Insert;
5181 Insert->PrevRecord = LastRec;
5182 XLogCtl->xlblocks[0].xlogid = openLogId;
5183 XLogCtl->xlblocks[0].xrecoff =
5184 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5187 * Tricky point here: readBuf contains the *last* block that the LastRec
5188 * record spans, not the one it starts in. The last block is indeed the
5189 * one we want to use.
5191 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5192 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5193 Insert->currpos = (char *) Insert->currpage +
5194 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5196 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5198 XLogCtl->Write.LogwrtResult = LogwrtResult;
5199 Insert->LogwrtResult = LogwrtResult;
5200 XLogCtl->LogwrtResult = LogwrtResult;
5202 XLogCtl->LogwrtRqst.Write = EndOfLog;
5203 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5205 freespace = INSERT_FREESPACE(Insert);
5208 /* Make sure rest of page is zero */
5209 MemSet(Insert->currpos, 0, freespace);
5210 XLogCtl->Write.curridx = 0;
5215 * Whenever Write.LogwrtResult points to exactly the end of a page,
5216 * Write.curridx must point to the *next* page (see XLogWrite()).
5218 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5219 * this is sufficient. The first actual attempt to insert a log
5220 * record will advance the insert state.
5222 XLogCtl->Write.curridx = NextBufIdx(0);
5225 /* Pre-scan prepared transactions to find out the range of XIDs present */
5226 oldestActiveXID = PrescanPreparedTransactions();
5233 * Allow resource managers to do any required cleanup.
5235 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5237 if (RmgrTable[rmid].rm_cleanup != NULL)
5238 RmgrTable[rmid].rm_cleanup();
5242 * Check to see if the XLOG sequence contained any unresolved
5243 * references to uninitialized pages.
5245 XLogCheckInvalidPages();
5248 * Reset pgstat data, because it may be invalid after recovery.
5253 * Perform a checkpoint to update all our recovery activity to disk.
5255 * Note that we write a shutdown checkpoint rather than an on-line
5256 * one. This is not particularly critical, but since we may be
5257 * assigning a new TLI, using a shutdown checkpoint allows us to have
5258 * the rule that TLI only changes in shutdown checkpoints, which
5259 * allows some extra error checking in xlog_redo.
5261 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5264 * Close down recovery environment
5266 XLogCloseRelationCache();
5270 * Preallocate additional log files, if wanted.
5272 PreallocXlogFiles(EndOfLog);
5275 * Okay, we're officially UP.
5279 ControlFile->state = DB_IN_PRODUCTION;
5280 ControlFile->time = (pg_time_t) time(NULL);
5281 UpdateControlFile();
5283 /* start the archive_timeout timer running */
5284 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5286 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5287 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5288 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5290 /* also initialize latestCompletedXid, to nextXid - 1 */
5291 ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
5292 TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);
5294 /* Start up the commit log and related stuff, too */
5296 StartupSUBTRANS(oldestActiveXID);
5299 /* Reload shared-memory state for prepared transactions */
5300 RecoverPreparedTransactions();
5302 /* Shut down readFile facility, free space */
5315 free(readRecordBuf);
5316 readRecordBuf = NULL;
5317 readRecordBufSize = 0;
5322 * Subroutine to try to fetch and validate a prior checkpoint record.
5324 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5325 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5328 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5332 if (!XRecOffIsValid(RecPtr.xrecoff))
5338 (errmsg("invalid primary checkpoint link in control file")));
5342 (errmsg("invalid secondary checkpoint link in control file")));
5346 (errmsg("invalid checkpoint link in backup_label file")));
5352 record = ReadRecord(&RecPtr, LOG);
5360 (errmsg("invalid primary checkpoint record")));
5364 (errmsg("invalid secondary checkpoint record")));
5368 (errmsg("invalid checkpoint record")));
5373 if (record->xl_rmid != RM_XLOG_ID)
5379 (errmsg("invalid resource manager ID in primary checkpoint record")));
5383 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5387 (errmsg("invalid resource manager ID in checkpoint record")));
5392 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5393 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5399 (errmsg("invalid xl_info in primary checkpoint record")));
5403 (errmsg("invalid xl_info in secondary checkpoint record")));
5407 (errmsg("invalid xl_info in checkpoint record")));
5412 if (record->xl_len != sizeof(CheckPoint) ||
5413 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5419 (errmsg("invalid length of primary checkpoint record")));
5423 (errmsg("invalid length of secondary checkpoint record")));
5427 (errmsg("invalid length of checkpoint record")));
5436 * This must be called during startup of a backend process, except that
5437 * it need not be called in a standalone backend (which does StartupXLOG
5438 * instead). We need to initialize the local copies of ThisTimeLineID and
5441 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5442 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5443 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5446 InitXLOGAccess(void)
5448 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5449 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5450 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5451 (void) GetRedoRecPtr();
5455 * Once spawned, a backend may update its local RedoRecPtr from
5456 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5457 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5462 /* use volatile pointer to prevent code rearrangement */
5463 volatile XLogCtlData *xlogctl = XLogCtl;
5465 SpinLockAcquire(&xlogctl->info_lck);
5466 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5467 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5468 SpinLockRelease(&xlogctl->info_lck);
5474 * GetInsertRecPtr -- Returns the current insert position.
5476 * NOTE: The value *actually* returned is the position of the last full
5477 * xlog page. It lags behind the real insert position by at most 1 page.
5478 * For that, we don't need to acquire WALInsertLock which can be quite
5479 * heavily contended, and an approximation is enough for the current
5480 * usage of this function.
5483 GetInsertRecPtr(void)
5485 /* use volatile pointer to prevent code rearrangement */
5486 volatile XLogCtlData *xlogctl = XLogCtl;
5489 SpinLockAcquire(&xlogctl->info_lck);
5490 recptr = xlogctl->LogwrtRqst.Write;
5491 SpinLockRelease(&xlogctl->info_lck);
5497 * Get the time of the last xlog segment switch
5500 GetLastSegSwitchTime(void)
5504 /* Need WALWriteLock, but shared lock is sufficient */
5505 LWLockAcquire(WALWriteLock, LW_SHARED);
5506 result = XLogCtl->Write.lastSegSwitchTime;
5507 LWLockRelease(WALWriteLock);
5513 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5515 * This is exported for use by code that would like to have 64-bit XIDs.
5516 * We don't really support such things, but all XIDs within the system
5517 * can be presumed "close to" the result, and thus the epoch associated
5518 * with them can be determined.
5521 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5523 uint32 ckptXidEpoch;
5524 TransactionId ckptXid;
5525 TransactionId nextXid;
5527 /* Must read checkpoint info first, else have race condition */
5529 /* use volatile pointer to prevent code rearrangement */
5530 volatile XLogCtlData *xlogctl = XLogCtl;
5532 SpinLockAcquire(&xlogctl->info_lck);
5533 ckptXidEpoch = xlogctl->ckptXidEpoch;
5534 ckptXid = xlogctl->ckptXid;
5535 SpinLockRelease(&xlogctl->info_lck);
5538 /* Now fetch current nextXid */
5539 nextXid = ReadNewTransactionId();
5542 * nextXid is certainly logically later than ckptXid. So if it's
5543 * numerically less, it must have wrapped into the next epoch.
5545 if (nextXid < ckptXid)
5549 *epoch = ckptXidEpoch;
5553 * This must be called ONCE during postmaster or standalone-backend shutdown
5556 ShutdownXLOG(int code, Datum arg)
5559 (errmsg("shutting down")));
5561 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5564 ShutdownMultiXact();
5567 (errmsg("database system is shut down")));
5571 * Log start of a checkpoint.
5574 LogCheckpointStart(int flags)
5576 elog(LOG, "checkpoint starting:%s%s%s%s%s%s",
5577 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
5578 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
5579 (flags & CHECKPOINT_FORCE) ? " force" : "",
5580 (flags & CHECKPOINT_WAIT) ? " wait" : "",
5581 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
5582 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
5586 * Log end of a checkpoint.
5589 LogCheckpointEnd(void)
5598 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
5600 TimestampDifference(CheckpointStats.ckpt_start_t,
5601 CheckpointStats.ckpt_end_t,
5602 &total_secs, &total_usecs);
5604 TimestampDifference(CheckpointStats.ckpt_write_t,
5605 CheckpointStats.ckpt_sync_t,
5606 &write_secs, &write_usecs);
5608 TimestampDifference(CheckpointStats.ckpt_sync_t,
5609 CheckpointStats.ckpt_sync_end_t,
5610 &sync_secs, &sync_usecs);
5612 elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
5613 "%d transaction log file(s) added, %d removed, %d recycled; "
5614 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
5615 CheckpointStats.ckpt_bufs_written,
5616 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
5617 CheckpointStats.ckpt_segs_added,
5618 CheckpointStats.ckpt_segs_removed,
5619 CheckpointStats.ckpt_segs_recycled,
5620 write_secs, write_usecs / 1000,
5621 sync_secs, sync_usecs / 1000,
5622 total_secs, total_usecs / 1000);
5626 * Perform a checkpoint --- either during shutdown, or on-the-fly
5628 * flags is a bitwise OR of the following:
5629 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
5630 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
5631 * ignoring checkpoint_completion_target parameter.
5632 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
5633 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
5635 * Note: flags contains other bits, of interest here only for logging purposes.
5636 * In particular note that this routine is synchronous and does not pay
5637 * attention to CHECKPOINT_WAIT.
5640 CreateCheckPoint(int flags)
5642 bool shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
5643 CheckPoint checkPoint;
5645 XLogCtlInsert *Insert = &XLogCtl->Insert;
5650 TransactionId *inCommitXids;
5654 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5655 * (This is just pro forma, since in the present system structure there is
5656 * only one process that is allowed to issue checkpoints at any given
5659 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5662 * Prepare to accumulate statistics.
5664 * Note: because it is possible for log_checkpoints to change while a
5665 * checkpoint proceeds, we always accumulate stats, even if
5666 * log_checkpoints is currently off.
5668 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
5669 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
5672 * Use a critical section to force system panic if we have trouble.
5674 START_CRIT_SECTION();
5678 ControlFile->state = DB_SHUTDOWNING;
5679 ControlFile->time = (pg_time_t) time(NULL);
5680 UpdateControlFile();
5684 * Let smgr prepare for checkpoint; this has to happen before we determine
5685 * the REDO pointer. Note that smgr must not do anything that'd have to
5686 * be undone if we decide no checkpoint is needed.
5690 /* Begin filling in the checkpoint WAL record */
5691 MemSet(&checkPoint, 0, sizeof(checkPoint));
5692 checkPoint.ThisTimeLineID = ThisTimeLineID;
5693 checkPoint.time = (pg_time_t) time(NULL);
5696 * We must hold WALInsertLock while examining insert state to determine
5697 * the checkpoint REDO pointer.
5699 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5702 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5703 * any XLOG records since the start of the last checkpoint, skip the
5704 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5705 * when the system is idle. That wastes log space, and more importantly it
5706 * exposes us to possible loss of both current and previous checkpoint
5707 * records if the machine crashes just as we're writing the update.
5708 * (Perhaps it'd make even more sense to checkpoint only when the previous
5709 * checkpoint record is in a different xlog page?)
5711 * We have to make two tests to determine that nothing has happened since
5712 * the start of the last checkpoint: current insertion point must match
5713 * the end of the last checkpoint record, and its redo pointer must point
5716 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
5718 XLogRecPtr curInsert;
5720 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5721 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5722 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5723 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5724 ControlFile->checkPoint.xlogid ==
5725 ControlFile->checkPointCopy.redo.xlogid &&
5726 ControlFile->checkPoint.xrecoff ==
5727 ControlFile->checkPointCopy.redo.xrecoff)
5729 LWLockRelease(WALInsertLock);
5730 LWLockRelease(CheckpointLock);
5737 * Compute new REDO record ptr = location of next XLOG record.
5739 * NB: this is NOT necessarily where the checkpoint record itself will be,
5740 * since other backends may insert more XLOG records while we're off doing
5741 * the buffer flush work. Those XLOG records are logically after the
5742 * checkpoint, even though physically before it. Got that?
5744 freespace = INSERT_FREESPACE(Insert);
5745 if (freespace < SizeOfXLogRecord)
5747 (void) AdvanceXLInsertBuffer(false);
5748 /* OK to ignore update return flag, since we will do flush anyway */
5749 freespace = INSERT_FREESPACE(Insert);
5751 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5754 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5755 * must be done while holding the insert lock AND the info_lck.
5757 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5758 * pointing past where it really needs to point. This is okay; the only
5759 * consequence is that XLogInsert might back up whole buffers that it
5760 * didn't really need to. We can't postpone advancing RedoRecPtr because
5761 * XLogInserts that happen while we are dumping buffers must assume that
5762 * their buffer changes are not included in the checkpoint.
5765 /* use volatile pointer to prevent code rearrangement */
5766 volatile XLogCtlData *xlogctl = XLogCtl;
5768 SpinLockAcquire(&xlogctl->info_lck);
5769 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5770 SpinLockRelease(&xlogctl->info_lck);
5774 * Now we can release WAL insert lock, allowing other xacts to proceed
5775 * while we are flushing disk buffers.
5777 LWLockRelease(WALInsertLock);
5780 * If enabled, log checkpoint start. We postpone this until now so as not
5781 * to log anything if we decided to skip the checkpoint.
5783 if (log_checkpoints)
5784 LogCheckpointStart(flags);
5787 * Before flushing data, we must wait for any transactions that are
5788 * currently in their commit critical sections. If an xact inserted its
5789 * commit record into XLOG just before the REDO point, then a crash
5790 * restart from the REDO point would not replay that record, which means
5791 * that our flushing had better include the xact's update of pg_clog. So
5792 * we wait till he's out of his commit critical section before proceeding.
5793 * See notes in RecordTransactionCommit().
5795 * Because we've already released WALInsertLock, this test is a bit fuzzy:
5796 * it is possible that we will wait for xacts we didn't really need to
5797 * wait for. But the delay should be short and it seems better to make
5798 * checkpoint take a bit longer than to hold locks longer than necessary.
5799 * (In fact, the whole reason we have this issue is that xact.c does
5800 * commit record XLOG insertion and clog update as two separate steps
5801 * protected by different locks, but again that seems best on grounds of
5802 * minimizing lock contention.)
5804 * A transaction that has not yet set inCommit when we look cannot be at
5805 * risk, since he's not inserted his commit record yet; and one that's
5806 * already cleared it is not at risk either, since he's done fixing clog
5807 * and we will correctly flush the update below. So we cannot miss any
5808 * xacts we need to wait for.
5810 nInCommit = GetTransactionsInCommit(&inCommitXids);
5815 pg_usleep(10000L); /* wait for 10 msec */
5816 } while (HaveTransactionsInCommit(inCommitXids, nInCommit));
5818 pfree(inCommitXids);
5821 * Get the other info we need for the checkpoint record.
5823 LWLockAcquire(XidGenLock, LW_SHARED);
5824 checkPoint.nextXid = ShmemVariableCache->nextXid;
5825 LWLockRelease(XidGenLock);
5827 /* Increase XID epoch if we've wrapped around since last checkpoint */
5828 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5829 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5830 checkPoint.nextXidEpoch++;
5832 LWLockAcquire(OidGenLock, LW_SHARED);
5833 checkPoint.nextOid = ShmemVariableCache->nextOid;
5835 checkPoint.nextOid += ShmemVariableCache->oidCount;
5836 LWLockRelease(OidGenLock);
5838 MultiXactGetCheckptMulti(shutdown,
5839 &checkPoint.nextMulti,
5840 &checkPoint.nextMultiOffset);
5843 * Having constructed the checkpoint record, ensure all shmem disk buffers
5844 * and commit-log buffers are flushed to disk.
5846 * This I/O could fail for various reasons. If so, we will fail to
5847 * complete the checkpoint, but there is no reason to force a system
5848 * panic. Accordingly, exit critical section while doing it.
5852 CheckPointGuts(checkPoint.redo, flags);
5854 START_CRIT_SECTION();
5857 * Now insert the checkpoint record into XLOG.
5859 rdata.data = (char *) (&checkPoint);
5860 rdata.len = sizeof(checkPoint);
5861 rdata.buffer = InvalidBuffer;
5864 recptr = XLogInsert(RM_XLOG_ID,
5865 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5866 XLOG_CHECKPOINT_ONLINE,
5872 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5873 * = end of actual checkpoint record.
5875 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5877 (errmsg("concurrent transaction log activity while database system is shutting down")));
5880 * Select point at which we can truncate the log, which we base on the
5881 * prior checkpoint's earliest info.
5883 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5886 * Update the control file.
5888 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5890 ControlFile->state = DB_SHUTDOWNED;
5891 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5892 ControlFile->checkPoint = ProcLastRecPtr;
5893 ControlFile->checkPointCopy = checkPoint;
5894 ControlFile->time = (pg_time_t) time(NULL);
5895 UpdateControlFile();
5896 LWLockRelease(ControlFileLock);
5898 /* Update shared-memory copy of checkpoint XID/epoch */
5900 /* use volatile pointer to prevent code rearrangement */
5901 volatile XLogCtlData *xlogctl = XLogCtl;
5903 SpinLockAcquire(&xlogctl->info_lck);
5904 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5905 xlogctl->ckptXid = checkPoint.nextXid;
5906 SpinLockRelease(&xlogctl->info_lck);
5910 * We are now done with critical updates; no need for system panic if we
5911 * have trouble while fooling with old log segments.
5916 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
5921 * Delete old log files (those no longer needed even for previous
5924 if (_logId || _logSeg)
5926 PrevLogSeg(_logId, _logSeg);
5927 RemoveOldXlogFiles(_logId, _logSeg, recptr);
5931 * Make more log segments if needed. (Do this after recycling old log
5932 * segments, since that may supply some of the needed files.)
5935 PreallocXlogFiles(recptr);
5938 * Truncate pg_subtrans if possible. We can throw away all data before
5939 * the oldest XMIN of any running transaction. No future transaction will
5940 * attempt to reference any pg_subtrans entry older than that (see Asserts
5941 * in subtrans.c). During recovery, though, we mustn't do this because
5942 * StartupSUBTRANS hasn't been called yet.
5945 TruncateSUBTRANS(GetOldestXmin(true, false));
5947 /* All real work is done, but log before releasing lock. */
5948 if (log_checkpoints)
5951 LWLockRelease(CheckpointLock);
5955 * Flush all data in shared memory to disk, and fsync
5957 * This is the common code shared between regular checkpoints and
5958 * recovery restartpoints.
5961 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
5964 CheckPointSUBTRANS();
5965 CheckPointMultiXact();
5966 CheckPointBuffers(flags); /* performs all required fsyncs */
5967 /* We deliberately delay 2PC checkpointing as long as possible */
5968 CheckPointTwoPhase(checkPointRedo);
5972 * Set a recovery restart point if appropriate
5974 * This is similar to CreateCheckPoint, but is used during WAL recovery
5975 * to establish a point from which recovery can roll forward without
5976 * replaying the entire recovery log. This function is called each time
5977 * a checkpoint record is read from XLOG; it must determine whether a
5978 * restartpoint is needed or not.
5981 RecoveryRestartPoint(const CheckPoint *checkPoint)
5987 * Do nothing if the elapsed time since the last restartpoint is less than
5988 * half of checkpoint_timeout. (We use a value less than
5989 * checkpoint_timeout so that variations in the timing of checkpoints on
5990 * the master, or speed of transmission of WAL segments to a slave, won't
5991 * make the slave skip a restartpoint once it's synced with the master.)
5992 * Checking true elapsed time keeps us from doing restartpoints too often
5993 * while rapidly scanning large amounts of WAL.
5995 elapsed_secs = (pg_time_t) time(NULL) - ControlFile->time;
5996 if (elapsed_secs < CheckPointTimeout / 2)
6000 * Is it safe to checkpoint? We must ask each of the resource managers
6001 * whether they have any partial state information that might prevent a
6002 * correct restart from this point. If so, we skip this opportunity, but
6003 * return at the next checkpoint record for another try.
6005 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
6007 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
6008 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
6010 elog(DEBUG2, "RM %d not safe to record restart point at %X/%X",
6012 checkPoint->redo.xlogid,
6013 checkPoint->redo.xrecoff);
6019 * OK, force data out to disk
6021 CheckPointGuts(checkPoint->redo, CHECKPOINT_IMMEDIATE);
6024 * Update pg_control so that any subsequent crash will restart from this
6025 * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
6028 ControlFile->prevCheckPoint = ControlFile->checkPoint;
6029 ControlFile->checkPoint = ReadRecPtr;
6030 ControlFile->checkPointCopy = *checkPoint;
6031 ControlFile->time = (pg_time_t) time(NULL);
6032 UpdateControlFile();
6034 ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
6035 (errmsg("recovery restart point at %X/%X",
6036 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
6037 if (recoveryLastXTime)
6038 ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
6039 (errmsg("last completed transaction was at log time %s",
6040 timestamptz_to_str(recoveryLastXTime))));
6044 * Write a NEXTOID log record
6047 XLogPutNextOid(Oid nextOid)
6051 rdata.data = (char *) (&nextOid);
6052 rdata.len = sizeof(Oid);
6053 rdata.buffer = InvalidBuffer;
6055 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
6058 * We need not flush the NEXTOID record immediately, because any of the
6059 * just-allocated OIDs could only reach disk as part of a tuple insert or
6060 * update that would have its own XLOG record that must follow the NEXTOID
6061 * record. Therefore, the standard buffer LSN interlock applied to those
6062 * records will ensure no such OID reaches disk before the NEXTOID record
6065 * Note, however, that the above statement only covers state "within" the
6066 * database. When we use a generated OID as a file or directory name, we
6067 * are in a sense violating the basic WAL rule, because that filesystem
6068 * change may reach disk before the NEXTOID WAL record does. The impact
6069 * of this is that if a database crash occurs immediately afterward, we
6070 * might after restart re-generate the same OID and find that it conflicts
6071 * with the leftover file or directory. But since for safety's sake we
6072 * always loop until finding a nonconflicting filename, this poses no real
6073 * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
6078 * Write an XLOG SWITCH record.
6080 * Here we just blindly issue an XLogInsert request for the record.
6081 * All the magic happens inside XLogInsert.
6083 * The return value is either the end+1 address of the switch record,
6084 * or the end+1 address of the prior segment if we did not need to
6085 * write a switch record because we are already at segment start.
6088 RequestXLogSwitch(void)
6093 /* XLOG SWITCH, alone among xlog record types, has no data */
6094 rdata.buffer = InvalidBuffer;
6099 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
6105 * XLOG resource manager's routines
6108 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
6110 uint8 info = record->xl_info & ~XLR_INFO_MASK;
6112 if (info == XLOG_NEXTOID)
6116 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
6117 if (ShmemVariableCache->nextOid < nextOid)
6119 ShmemVariableCache->nextOid = nextOid;
6120 ShmemVariableCache->oidCount = 0;
6123 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
6125 CheckPoint checkPoint;
6127 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6128 /* In a SHUTDOWN checkpoint, believe the counters exactly */
6129 ShmemVariableCache->nextXid = checkPoint.nextXid;
6130 ShmemVariableCache->nextOid = checkPoint.nextOid;
6131 ShmemVariableCache->oidCount = 0;
6132 MultiXactSetNextMXact(checkPoint.nextMulti,
6133 checkPoint.nextMultiOffset);
6135 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6136 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6137 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6140 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
6142 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6144 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
6145 !list_member_int(expectedTLIs,
6146 (int) checkPoint.ThisTimeLineID))
6148 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
6149 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6150 /* Following WAL records should be run with new TLI */
6151 ThisTimeLineID = checkPoint.ThisTimeLineID;
6154 RecoveryRestartPoint(&checkPoint);
6156 else if (info == XLOG_CHECKPOINT_ONLINE)
6158 CheckPoint checkPoint;
6160 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6161 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
6162 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
6163 checkPoint.nextXid))
6164 ShmemVariableCache->nextXid = checkPoint.nextXid;
6165 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
6167 ShmemVariableCache->nextOid = checkPoint.nextOid;
6168 ShmemVariableCache->oidCount = 0;
6170 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
6171 checkPoint.nextMultiOffset);
6173 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6174 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6175 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6177 /* TLI should not change in an on-line checkpoint */
6178 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6180 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
6181 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6183 RecoveryRestartPoint(&checkPoint);
6185 else if (info == XLOG_NOOP)
6187 /* nothing to do here */
6189 else if (info == XLOG_SWITCH)
6191 /* nothing to do here */
6196 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
6198 uint8 info = xl_info & ~XLR_INFO_MASK;
6200 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
6201 info == XLOG_CHECKPOINT_ONLINE)
6203 CheckPoint *checkpoint = (CheckPoint *) rec;
6205 appendStringInfo(buf, "checkpoint: redo %X/%X; "
6206 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
6207 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
6208 checkpoint->ThisTimeLineID,
6209 checkpoint->nextXidEpoch, checkpoint->nextXid,
6210 checkpoint->nextOid,
6211 checkpoint->nextMulti,
6212 checkpoint->nextMultiOffset,
6213 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
6215 else if (info == XLOG_NOOP)
6217 appendStringInfo(buf, "xlog no-op");
6219 else if (info == XLOG_NEXTOID)
6223 memcpy(&nextOid, rec, sizeof(Oid));
6224 appendStringInfo(buf, "nextOid: %u", nextOid);
6226 else if (info == XLOG_SWITCH)
6228 appendStringInfo(buf, "xlog switch");
6231 appendStringInfo(buf, "UNKNOWN");
6237 xlog_outrec(StringInfo buf, XLogRecord *record)
6241 appendStringInfo(buf, "prev %X/%X; xid %u",
6242 record->xl_prev.xlogid, record->xl_prev.xrecoff,
6245 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
6247 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
6248 appendStringInfo(buf, "; bkpb%d", i + 1);
6251 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
6253 #endif /* WAL_DEBUG */
6260 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
6262 int new_sync_method;
6265 if (pg_strcasecmp(method, "fsync") == 0)
6267 new_sync_method = SYNC_METHOD_FSYNC;
6270 #ifdef HAVE_FSYNC_WRITETHROUGH
6271 else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
6273 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
6277 #ifdef HAVE_FDATASYNC
6278 else if (pg_strcasecmp(method, "fdatasync") == 0)
6280 new_sync_method = SYNC_METHOD_FDATASYNC;
6284 #ifdef OPEN_SYNC_FLAG
6285 else if (pg_strcasecmp(method, "open_sync") == 0)
6287 new_sync_method = SYNC_METHOD_OPEN;
6288 new_sync_bit = OPEN_SYNC_FLAG;
6291 #ifdef OPEN_DATASYNC_FLAG
6292 else if (pg_strcasecmp(method, "open_datasync") == 0)
6294 new_sync_method = SYNC_METHOD_OPEN;
6295 new_sync_bit = OPEN_DATASYNC_FLAG;
6304 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
6307 * To ensure that no blocks escape unsynced, force an fsync on the
6308 * currently open log segment (if any). Also, if the open flag is
6309 * changing, close the log file so it will be reopened (with new flag
6312 if (openLogFile >= 0)
6314 if (pg_fsync(openLogFile) != 0)
6316 (errcode_for_file_access(),
6317 errmsg("could not fsync log file %u, segment %u: %m",
6318 openLogId, openLogSeg)));
6319 if (open_sync_bit != new_sync_bit)
6322 sync_method = new_sync_method;
6323 open_sync_bit = new_sync_bit;
6331 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6334 issue_xlog_fsync(void)
6336 switch (sync_method)
6338 case SYNC_METHOD_FSYNC:
6339 if (pg_fsync_no_writethrough(openLogFile) != 0)
6341 (errcode_for_file_access(),
6342 errmsg("could not fsync log file %u, segment %u: %m",
6343 openLogId, openLogSeg)));
6345 #ifdef HAVE_FSYNC_WRITETHROUGH
6346 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6347 if (pg_fsync_writethrough(openLogFile) != 0)
6349 (errcode_for_file_access(),
6350 errmsg("could not fsync write-through log file %u, segment %u: %m",
6351 openLogId, openLogSeg)));
6354 #ifdef HAVE_FDATASYNC
6355 case SYNC_METHOD_FDATASYNC:
6356 if (pg_fdatasync(openLogFile) != 0)
6358 (errcode_for_file_access(),
6359 errmsg("could not fdatasync log file %u, segment %u: %m",
6360 openLogId, openLogSeg)));
6363 case SYNC_METHOD_OPEN:
6364 /* write synced it already */
6367 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6374 * pg_start_backup: set up for taking an on-line backup dump
6376 * Essentially what this does is to create a backup label file in $PGDATA,
6377 * where it will be archived as part of the backup dump. The label file
6378 * contains the user-supplied label string (typically this would be used
6379 * to tell where the backup dump will be stored) and the starting time and
6380 * starting WAL location for the dump.
6383 pg_start_backup(PG_FUNCTION_ARGS)
6385 text *backupid = PG_GETARG_TEXT_P(0);
6387 XLogRecPtr checkpointloc;
6388 XLogRecPtr startpoint;
6389 pg_time_t stamp_time;
6391 char xlogfilename[MAXFNAMELEN];
6394 struct stat stat_buf;
6399 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6400 errmsg("must be superuser to run a backup")));
6402 if (!XLogArchivingActive())
6404 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6405 errmsg("WAL archiving is not active"),
6406 errhint("archive_mode must be enabled at server start.")));
6408 if (!XLogArchiveCommandSet())
6410 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6411 errmsg("WAL archiving is not active"),
6412 errhint("archive_command must be defined before "
6413 "online backups can be made safely.")));
6415 backupidstr = text_to_cstring(backupid);
6418 * Mark backup active in shared memory. We must do full-page WAL writes
6419 * during an on-line backup even if not doing so at other times, because
6420 * it's quite possible for the backup dump to obtain a "torn" (partially
6421 * written) copy of a database page if it reads the page concurrently with
6422 * our write to the same page. This can be fixed as long as the first
6423 * write to the page in the WAL sequence is a full-page write. Hence, we
6424 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6425 * are no dirty pages in shared memory that might get dumped while the
6426 * backup is in progress without having a corresponding WAL record. (Once
6427 * the backup is complete, we need not force full-page writes anymore,
6428 * since we expect that any pages not modified during the backup interval
6429 * must have been correctly captured by the backup.)
6431 * We must hold WALInsertLock to change the value of forcePageWrites, to
6432 * ensure adequate interlocking against XLogInsert().
6434 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6435 if (XLogCtl->Insert.forcePageWrites)
6437 LWLockRelease(WALInsertLock);
6439 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6440 errmsg("a backup is already in progress"),
6441 errhint("Run pg_stop_backup() and try again.")));
6443 XLogCtl->Insert.forcePageWrites = true;
6444 LWLockRelease(WALInsertLock);
6446 /* Ensure we release forcePageWrites if fail below */
6447 PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
6450 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6451 * page problems, this guarantees that two successive backup runs will
6452 * have different checkpoint positions and hence different history
6453 * file names, even if nothing happened in between.
6455 * We don't use CHECKPOINT_IMMEDIATE, hence this can take awhile.
6457 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT);
6460 * Now we need to fetch the checkpoint record location, and also its
6461 * REDO pointer. The oldest point in WAL that would be needed to
6462 * restore starting from the checkpoint is precisely the REDO pointer.
6464 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6465 checkpointloc = ControlFile->checkPoint;
6466 startpoint = ControlFile->checkPointCopy.redo;
6467 LWLockRelease(ControlFileLock);
6469 XLByteToSeg(startpoint, _logId, _logSeg);
6470 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6472 /* Use the log timezone here, not the session timezone */
6473 stamp_time = (pg_time_t) time(NULL);
6474 pg_strftime(strfbuf, sizeof(strfbuf),
6475 "%Y-%m-%d %H:%M:%S %Z",
6476 pg_localtime(&stamp_time, log_timezone));
6479 * Check for existing backup label --- implies a backup is already
6480 * running. (XXX given that we checked forcePageWrites above, maybe
6481 * it would be OK to just unlink any such label file?)
6483 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6485 if (errno != ENOENT)
6487 (errcode_for_file_access(),
6488 errmsg("could not stat file \"%s\": %m",
6489 BACKUP_LABEL_FILE)));
6493 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6494 errmsg("a backup is already in progress"),
6495 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6496 BACKUP_LABEL_FILE)));
6499 * Okay, write the file
6501 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6504 (errcode_for_file_access(),
6505 errmsg("could not create file \"%s\": %m",
6506 BACKUP_LABEL_FILE)));
6507 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6508 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6509 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6510 checkpointloc.xlogid, checkpointloc.xrecoff);
6511 fprintf(fp, "START TIME: %s\n", strfbuf);
6512 fprintf(fp, "LABEL: %s\n", backupidstr);
6513 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6515 (errcode_for_file_access(),
6516 errmsg("could not write file \"%s\": %m",
6517 BACKUP_LABEL_FILE)));
6519 PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
6522 * We're done. As a convenience, return the starting WAL location.
6524 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6525 startpoint.xlogid, startpoint.xrecoff);
6526 PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
6529 /* Error cleanup callback for pg_start_backup */
6531 pg_start_backup_callback(int code, Datum arg)
6533 /* Turn off forcePageWrites on failure */
6534 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6535 XLogCtl->Insert.forcePageWrites = false;
6536 LWLockRelease(WALInsertLock);
6540 * pg_stop_backup: finish taking an on-line backup dump
6542 * We remove the backup label file created by pg_start_backup, and instead
6543 * create a backup history file in pg_xlog (whence it will immediately be
6544 * archived). The backup history file contains the same info found in
6545 * the label file, plus the backup-end time and WAL location.
6548 pg_stop_backup(PG_FUNCTION_ARGS)
6550 XLogRecPtr startpoint;
6551 XLogRecPtr stoppoint;
6552 pg_time_t stamp_time;
6554 char histfilepath[MAXPGPATH];
6555 char startxlogfilename[MAXFNAMELEN];
6556 char stopxlogfilename[MAXFNAMELEN];
6563 int seconds_before_warning;
6568 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6569 (errmsg("must be superuser to run a backup"))));
6572 * OK to clear forcePageWrites
6574 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6575 XLogCtl->Insert.forcePageWrites = false;
6576 LWLockRelease(WALInsertLock);
6579 * Force a switch to a new xlog segment file, so that the backup is valid
6580 * as soon as archiver moves out the current segment file. We'll report
6581 * the end address of the XLOG SWITCH record as the backup stopping point.
6583 stoppoint = RequestXLogSwitch();
6585 XLByteToSeg(stoppoint, _logId, _logSeg);
6586 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
6588 /* Use the log timezone here, not the session timezone */
6589 stamp_time = (pg_time_t) time(NULL);
6590 pg_strftime(strfbuf, sizeof(strfbuf),
6591 "%Y-%m-%d %H:%M:%S %Z",
6592 pg_localtime(&stamp_time, log_timezone));
6595 * Open the existing label file
6597 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6600 if (errno != ENOENT)
6602 (errcode_for_file_access(),
6603 errmsg("could not read file \"%s\": %m",
6604 BACKUP_LABEL_FILE)));
6606 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6607 errmsg("a backup is not in progress")));
6611 * Read and parse the START WAL LOCATION line (this code is pretty crude,
6612 * but we are not expecting any variability in the file format).
6614 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
6615 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6616 &ch) != 4 || ch != '\n')
6618 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6619 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6622 * Write the backup history file
6624 XLByteToSeg(startpoint, _logId, _logSeg);
6625 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6626 startpoint.xrecoff % XLogSegSize);
6627 fp = AllocateFile(histfilepath, "w");
6630 (errcode_for_file_access(),
6631 errmsg("could not create file \"%s\": %m",
6633 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6634 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
6635 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
6636 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
6637 /* transfer remaining lines from label to history file */
6638 while ((ich = fgetc(lfp)) != EOF)
6640 fprintf(fp, "STOP TIME: %s\n", strfbuf);
6641 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6643 (errcode_for_file_access(),
6644 errmsg("could not write file \"%s\": %m",
6648 * Close and remove the backup label file
6650 if (ferror(lfp) || FreeFile(lfp))
6652 (errcode_for_file_access(),
6653 errmsg("could not read file \"%s\": %m",
6654 BACKUP_LABEL_FILE)));
6655 if (unlink(BACKUP_LABEL_FILE) != 0)
6657 (errcode_for_file_access(),
6658 errmsg("could not remove file \"%s\": %m",
6659 BACKUP_LABEL_FILE)));
6662 * Clean out any no-longer-needed history files. As a side effect, this
6663 * will post a .ready file for the newly created history file, notifying
6664 * the archiver that history file may be archived immediately.
6666 CleanupBackupHistory();
6669 * Wait until the history file has been archived. We assume that the
6670 * alphabetic sorting property of the WAL files ensures the last WAL
6671 * file is guaranteed archived by the time the history file is archived.
6673 * We wait forever, since archive_command is supposed to work and
6674 * we assume the admin wanted his backup to work completely. If you
6675 * don't wish to wait, you can SET statement_timeout = xx;
6677 * If the status file is missing, we assume that is because it was
6678 * set to .ready before we slept, then while asleep it has been set
6679 * to .done and then removed by a concurrent checkpoint.
6681 BackupHistoryFileName(histfilepath, ThisTimeLineID, _logId, _logSeg,
6682 startpoint.xrecoff % XLogSegSize);
6684 seconds_before_warning = 60;
6687 while (!XLogArchiveCheckDone(histfilepath, false))
6689 CHECK_FOR_INTERRUPTS();
6691 pg_usleep(1000000L);
6693 if (++waits >= seconds_before_warning)
6695 seconds_before_warning *= 2; /* This wraps in >10 years... */
6696 elog(WARNING, "pg_stop_backup() waiting for archive to complete "
6697 "(%d seconds delay)", waits);
6702 * We're done. As a convenience, return the ending WAL location.
6704 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
6705 stoppoint.xlogid, stoppoint.xrecoff);
6706 PG_RETURN_TEXT_P(cstring_to_text(stopxlogfilename));
6710 * pg_switch_xlog: switch to next xlog file
6713 pg_switch_xlog(PG_FUNCTION_ARGS)
6715 XLogRecPtr switchpoint;
6716 char location[MAXFNAMELEN];
6720 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6721 (errmsg("must be superuser to switch transaction log files"))));
6723 switchpoint = RequestXLogSwitch();
6726 * As a convenience, return the WAL location of the switch record
6728 snprintf(location, sizeof(location), "%X/%X",
6729 switchpoint.xlogid, switchpoint.xrecoff);
6730 PG_RETURN_TEXT_P(cstring_to_text(location));
6734 * Report the current WAL write location (same format as pg_start_backup etc)
6736 * This is useful for determining how much of WAL is visible to an external
6737 * archiving process. Note that the data before this point is written out
6738 * to the kernel, but is not necessarily synced to disk.
6741 pg_current_xlog_location(PG_FUNCTION_ARGS)
6743 char location[MAXFNAMELEN];
6745 /* Make sure we have an up-to-date local LogwrtResult */
6747 /* use volatile pointer to prevent code rearrangement */
6748 volatile XLogCtlData *xlogctl = XLogCtl;
6750 SpinLockAcquire(&xlogctl->info_lck);
6751 LogwrtResult = xlogctl->LogwrtResult;
6752 SpinLockRelease(&xlogctl->info_lck);
6755 snprintf(location, sizeof(location), "%X/%X",
6756 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
6757 PG_RETURN_TEXT_P(cstring_to_text(location));
6761 * Report the current WAL insert location (same format as pg_start_backup etc)
6763 * This function is mostly for debugging purposes.
6766 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
6768 XLogCtlInsert *Insert = &XLogCtl->Insert;
6769 XLogRecPtr current_recptr;
6770 char location[MAXFNAMELEN];
6773 * Get the current end-of-WAL position ... shared lock is sufficient
6775 LWLockAcquire(WALInsertLock, LW_SHARED);
6776 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
6777 LWLockRelease(WALInsertLock);
6779 snprintf(location, sizeof(location), "%X/%X",
6780 current_recptr.xlogid, current_recptr.xrecoff);
6781 PG_RETURN_TEXT_P(cstring_to_text(location));
6785 * Compute an xlog file name and decimal byte offset given a WAL location,
6786 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6788 * Note that a location exactly at a segment boundary is taken to be in
6789 * the previous segment. This is usually the right thing, since the
6790 * expected usage is to determine which xlog file(s) are ready to archive.
6793 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
6795 text *location = PG_GETARG_TEXT_P(0);
6797 unsigned int uxlogid;
6798 unsigned int uxrecoff;
6802 XLogRecPtr locationpoint;
6803 char xlogfilename[MAXFNAMELEN];
6806 TupleDesc resultTupleDesc;
6807 HeapTuple resultHeapTuple;
6811 * Read input and parse
6813 locationstr = text_to_cstring(location);
6815 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6817 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6818 errmsg("could not parse transaction log location \"%s\"",
6821 locationpoint.xlogid = uxlogid;
6822 locationpoint.xrecoff = uxrecoff;
6825 * Construct a tuple descriptor for the result row. This must match this
6826 * function's pg_proc entry!
6828 resultTupleDesc = CreateTemplateTupleDesc(2, false);
6829 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
6831 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
6834 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
6839 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6840 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6842 values[0] = CStringGetTextDatum(xlogfilename);
6848 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
6850 values[1] = UInt32GetDatum(xrecoff);
6854 * Tuple jam: Having first prepared your Datums, then squash together
6856 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
6858 result = HeapTupleGetDatum(resultHeapTuple);
6860 PG_RETURN_DATUM(result);
6864 * Compute an xlog file name given a WAL location,
6865 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6868 pg_xlogfile_name(PG_FUNCTION_ARGS)
6870 text *location = PG_GETARG_TEXT_P(0);
6872 unsigned int uxlogid;
6873 unsigned int uxrecoff;
6876 XLogRecPtr locationpoint;
6877 char xlogfilename[MAXFNAMELEN];
6879 locationstr = text_to_cstring(location);
6881 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6883 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6884 errmsg("could not parse transaction log location \"%s\"",
6887 locationpoint.xlogid = uxlogid;
6888 locationpoint.xrecoff = uxrecoff;
6890 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6891 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6893 PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
6897 * read_backup_label: check to see if a backup_label file is present
6899 * If we see a backup_label during recovery, we assume that we are recovering
6900 * from a backup dump file, and we therefore roll forward from the checkpoint
6901 * identified by the label file, NOT what pg_control says. This avoids the
6902 * problem that pg_control might have been archived one or more checkpoints
6903 * later than the start of the dump, and so if we rely on it as the start
6904 * point, we will fail to restore a consistent database state.
6906 * We also attempt to retrieve the corresponding backup history file.
6907 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6910 * Returns TRUE if a backup_label was found (and fills the checkpoint
6911 * location into *checkPointLoc); returns FALSE if not.
6914 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6916 XLogRecPtr startpoint;
6917 XLogRecPtr stoppoint;
6918 char histfilename[MAXFNAMELEN];
6919 char histfilepath[MAXPGPATH];
6920 char startxlogfilename[MAXFNAMELEN];
6921 char stopxlogfilename[MAXFNAMELEN];
6929 /* Default is to not constrain recovery stop point */
6930 minRecoveryLoc->xlogid = 0;
6931 minRecoveryLoc->xrecoff = 0;
6934 * See if label file is present
6936 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6939 if (errno != ENOENT)
6941 (errcode_for_file_access(),
6942 errmsg("could not read file \"%s\": %m",
6943 BACKUP_LABEL_FILE)));
6944 return false; /* it's not there, all is fine */
6948 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
6949 * is pretty crude, but we are not expecting any variability in the file
6952 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
6953 &startpoint.xlogid, &startpoint.xrecoff, &tli,
6954 startxlogfilename, &ch) != 5 || ch != '\n')
6956 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6957 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6958 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
6959 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
6960 &ch) != 3 || ch != '\n')
6962 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6963 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6964 if (ferror(lfp) || FreeFile(lfp))
6966 (errcode_for_file_access(),
6967 errmsg("could not read file \"%s\": %m",
6968 BACKUP_LABEL_FILE)));
6971 * Try to retrieve the backup history file (no error if we can't)
6973 XLByteToSeg(startpoint, _logId, _logSeg);
6974 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
6975 startpoint.xrecoff % XLogSegSize);
6977 if (InArchiveRecovery)
6978 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
6980 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
6981 startpoint.xrecoff % XLogSegSize);
6983 fp = AllocateFile(histfilepath, "r");
6987 * Parse history file to identify stop point.
6989 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
6990 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6991 &ch) != 4 || ch != '\n')
6993 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6994 errmsg("invalid data in file \"%s\"", histfilename)));
6995 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
6996 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6997 &ch) != 4 || ch != '\n')
6999 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7000 errmsg("invalid data in file \"%s\"", histfilename)));
7001 *minRecoveryLoc = stoppoint;
7002 if (ferror(fp) || FreeFile(fp))
7004 (errcode_for_file_access(),
7005 errmsg("could not read file \"%s\": %m",
7013 * Error context callback for errors occurring during rm_redo().
7016 rm_redo_error_callback(void *arg)
7018 XLogRecord *record = (XLogRecord *) arg;
7021 initStringInfo(&buf);
7022 RmgrTable[record->xl_rmid].rm_desc(&buf,
7024 XLogRecGetData(record));
7026 /* don't bother emitting empty description */
7028 errcontext("xlog redo %s", buf.data);