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.307 2008/05/12 19:45:23 mha Exp $
12 *-------------------------------------------------------------------------
26 #include "access/clog.h"
27 #include "access/multixact.h"
28 #include "access/subtrans.h"
29 #include "access/transam.h"
30 #include "access/tuptoaster.h"
31 #include "access/twophase.h"
32 #include "access/xact.h"
33 #include "access/xlog_internal.h"
34 #include "access/xlogdefs.h"
35 #include "access/xlogutils.h"
36 #include "catalog/catversion.h"
37 #include "catalog/pg_control.h"
38 #include "catalog/pg_type.h"
40 #include "miscadmin.h"
42 #include "postmaster/bgwriter.h"
43 #include "storage/bufpage.h"
44 #include "storage/fd.h"
45 #include "storage/ipc.h"
46 #include "storage/pmsignal.h"
47 #include "storage/procarray.h"
48 #include "storage/smgr.h"
49 #include "storage/spin.h"
50 #include "utils/builtins.h"
51 #include "utils/pg_locale.h"
52 #include "utils/ps_status.h"
55 /* File path names (all relative to $PGDATA) */
56 #define BACKUP_LABEL_FILE "backup_label"
57 #define BACKUP_LABEL_OLD "backup_label.old"
58 #define RECOVERY_COMMAND_FILE "recovery.conf"
59 #define RECOVERY_COMMAND_DONE "recovery.done"
62 /* User-settable parameters */
63 int CheckPointSegments = 3;
65 int XLogArchiveTimeout = 0;
66 bool XLogArchiveMode = false;
67 char *XLogArchiveCommand = NULL;
68 bool fullPageWrites = true;
69 bool log_checkpoints = false;
72 bool XLOG_DEBUG = false;
76 * XLOGfileslop is the maximum number of preallocated future XLOG segments.
77 * When we are done with an old XLOG segment file, we will recycle it as a
78 * future XLOG segment as long as there aren't already XLOGfileslop future
79 * segments; else we'll delete it. This could be made a separate GUC
80 * variable, but at present I think it's sufficient to hardwire it as
81 * 2*CheckPointSegments+1. Under normal conditions, a checkpoint will free
82 * no more than 2*CheckPointSegments log segments, and we want to recycle all
83 * of them; the +1 allows boundary cases to happen without wasting a
84 * delete/create-segment cycle.
86 #define XLOGfileslop (2*CheckPointSegments + 1)
89 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
90 int sync_method = DEFAULT_SYNC_METHOD;
91 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
93 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
98 const struct config_enum_entry sync_method_options[] = {
99 {"fsync", SYNC_METHOD_FSYNC},
100 #ifdef HAVE_FSYNC_WRITETHROUGH
101 {"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH},
103 #ifdef HAVE_FDATASYNC
104 {"fdatasync", SYNC_METHOD_FDATASYNC},
106 #ifdef OPEN_SYNC_FLAG
107 {"open_sync", SYNC_METHOD_OPEN},
109 #ifdef OPEN_DATASYNC_FLAG
110 {"open_datasync", SYNC_METHOD_OPEN_DSYNC},
116 * Statistics for current checkpoint are collected in this global struct.
117 * Because only the background writer or a stand-alone backend can perform
118 * checkpoints, this will be unused in normal backends.
120 CheckpointStatsData CheckpointStats;
123 * ThisTimeLineID will be same in all backends --- it identifies current
124 * WAL timeline for the database system.
126 TimeLineID ThisTimeLineID = 0;
128 /* Are we doing recovery from XLOG? */
129 bool InRecovery = false;
131 /* Are we recovering using offline XLOG archives? */
132 static bool InArchiveRecovery = false;
134 /* Was the last xlog file restored from archive, or local? */
135 static bool restoredFromArchive = false;
137 /* options taken from recovery.conf */
138 static char *recoveryRestoreCommand = NULL;
139 static bool recoveryTarget = false;
140 static bool recoveryTargetExact = false;
141 static bool recoveryTargetInclusive = true;
142 static bool recoveryLogRestartpoints = false;
143 static TransactionId recoveryTargetXid;
144 static TimestampTz recoveryTargetTime;
145 static TimestampTz recoveryLastXTime = 0;
147 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
148 static TransactionId recoveryStopXid;
149 static TimestampTz recoveryStopTime;
150 static bool recoveryStopAfter;
153 * During normal operation, the only timeline we care about is ThisTimeLineID.
154 * During recovery, however, things are more complicated. To simplify life
155 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
156 * scan through the WAL history (that is, it is the line that was active when
157 * the currently-scanned WAL record was generated). We also need these
160 * recoveryTargetTLI: the desired timeline that we want to end in.
162 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
163 * its known parents, newest first (so recoveryTargetTLI is always the
164 * first list member). Only these TLIs are expected to be seen in the WAL
165 * segments we read, and indeed only these TLIs will be considered as
166 * candidate WAL files to open at all.
168 * curFileTLI: the TLI appearing in the name of the current input WAL file.
169 * (This is not necessarily the same as ThisTimeLineID, because we could
170 * be scanning data that was copied from an ancestor timeline when the current
171 * file was created.) During a sequential scan we do not allow this value
174 static TimeLineID recoveryTargetTLI;
175 static List *expectedTLIs;
176 static TimeLineID curFileTLI;
179 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
180 * current backend. It is updated for all inserts. XactLastRecEnd points to
181 * end+1 of the last record, and is reset when we end a top-level transaction,
182 * or start a new one; so it can be used to tell if the current transaction has
183 * created any XLOG records.
185 static XLogRecPtr ProcLastRecPtr = {0, 0};
187 XLogRecPtr XactLastRecEnd = {0, 0};
190 * RedoRecPtr is this backend's local copy of the REDO record pointer
191 * (which is almost but not quite the same as a pointer to the most recent
192 * CHECKPOINT record). We update this from the shared-memory copy,
193 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
194 * hold the Insert lock). See XLogInsert for details. We are also allowed
195 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
196 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
199 static XLogRecPtr RedoRecPtr;
202 * Shared-memory data structures for XLOG control
204 * LogwrtRqst indicates a byte position that we need to write and/or fsync
205 * the log up to (all records before that point must be written or fsynced).
206 * LogwrtResult indicates the byte positions we have already written/fsynced.
207 * These structs are identical but are declared separately to indicate their
208 * slightly different functions.
210 * We do a lot of pushups to minimize the amount of access to lockable
211 * shared memory values. There are actually three shared-memory copies of
212 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
213 * XLogCtl->LogwrtResult is protected by info_lck
214 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
215 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
216 * One must hold the associated lock to read or write any of these, but
217 * of course no lock is needed to read/write the unshared LogwrtResult.
219 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
220 * right", since both are updated by a write or flush operation before
221 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
222 * is that it can be examined/modified by code that already holds WALWriteLock
223 * without needing to grab info_lck as well.
225 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
226 * but is updated when convenient. Again, it exists for the convenience of
227 * code that is already holding WALInsertLock but not the other locks.
229 * The unshared LogwrtResult may lag behind any or all of these, and again
230 * is updated when convenient.
232 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
233 * (protected by info_lck), but we don't need to cache any copies of it.
235 * Note that this all works because the request and result positions can only
236 * advance forward, never back up, and so we can easily determine which of two
237 * values is "more up to date".
239 * info_lck is only held long enough to read/update the protected variables,
240 * so it's a plain spinlock. The other locks are held longer (potentially
241 * over I/O operations), so we use LWLocks for them. These locks are:
243 * WALInsertLock: must be held to insert a record into the WAL buffers.
245 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
248 * ControlFileLock: must be held to read/update control file or create
251 * CheckpointLock: must be held to do a checkpoint (ensures only one
252 * checkpointer at a time; currently, with all checkpoints done by the
253 * bgwriter, this is just pro forma).
258 typedef struct XLogwrtRqst
260 XLogRecPtr Write; /* last byte + 1 to write out */
261 XLogRecPtr Flush; /* last byte + 1 to flush */
264 typedef struct XLogwrtResult
266 XLogRecPtr Write; /* last byte + 1 written out */
267 XLogRecPtr Flush; /* last byte + 1 flushed */
271 * Shared state data for XLogInsert.
273 typedef struct XLogCtlInsert
275 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
276 XLogRecPtr PrevRecord; /* start of previously-inserted record */
277 int curridx; /* current block index in cache */
278 XLogPageHeader currpage; /* points to header of block in cache */
279 char *currpos; /* current insertion point in cache */
280 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
281 bool forcePageWrites; /* forcing full-page writes for PITR? */
285 * Shared state data for XLogWrite/XLogFlush.
287 typedef struct XLogCtlWrite
289 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
290 int curridx; /* cache index of next block to write */
291 pg_time_t lastSegSwitchTime; /* time of last xlog segment switch */
295 * Total shared-memory state for XLOG.
297 typedef struct XLogCtlData
299 /* Protected by WALInsertLock: */
300 XLogCtlInsert Insert;
302 /* Protected by info_lck: */
303 XLogwrtRqst LogwrtRqst;
304 XLogwrtResult LogwrtResult;
305 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
306 TransactionId ckptXid;
307 XLogRecPtr asyncCommitLSN; /* LSN of newest async commit */
309 /* Protected by WALWriteLock: */
313 * These values do not change after startup, although the pointed-to pages
314 * and xlblocks values certainly do. Permission to read/write the pages
315 * and xlblocks values depends on WALInsertLock and WALWriteLock.
317 char *pages; /* buffers for unwritten XLOG pages */
318 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
319 int XLogCacheBlck; /* highest allocated xlog buffer index */
320 TimeLineID ThisTimeLineID;
322 slock_t info_lck; /* locks shared variables shown above */
325 static XLogCtlData *XLogCtl = NULL;
328 * We maintain an image of pg_control in shared memory.
330 static ControlFileData *ControlFile = NULL;
333 * Macros for managing XLogInsert state. In most cases, the calling routine
334 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
335 * so these are passed as parameters instead of being fetched via XLogCtl.
338 /* Free space remaining in the current xlog page buffer */
339 #define INSERT_FREESPACE(Insert) \
340 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
342 /* Construct XLogRecPtr value for current insertion point */
343 #define INSERT_RECPTR(recptr,Insert,curridx) \
345 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
347 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
350 #define PrevBufIdx(idx) \
351 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
353 #define NextBufIdx(idx) \
354 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
357 * Private, possibly out-of-date copy of shared LogwrtResult.
358 * See discussion above.
360 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
363 * openLogFile is -1 or a kernel FD for an open log file segment.
364 * When it's open, openLogOff is the current seek offset in the file.
365 * openLogId/openLogSeg identify the segment. These variables are only
366 * used to write the XLOG, and so will normally refer to the active segment.
368 static int openLogFile = -1;
369 static uint32 openLogId = 0;
370 static uint32 openLogSeg = 0;
371 static uint32 openLogOff = 0;
374 * These variables are used similarly to the ones above, but for reading
375 * the XLOG. Note, however, that readOff generally represents the offset
376 * of the page just read, not the seek position of the FD itself, which
377 * will be just past that page.
379 static int readFile = -1;
380 static uint32 readId = 0;
381 static uint32 readSeg = 0;
382 static uint32 readOff = 0;
384 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
385 static char *readBuf = NULL;
387 /* Buffer for current ReadRecord result (expandable) */
388 static char *readRecordBuf = NULL;
389 static uint32 readRecordBufSize = 0;
391 /* State information for XLOG reading */
392 static XLogRecPtr ReadRecPtr; /* start of last record read */
393 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
394 static XLogRecord *nextRecord = NULL;
395 static TimeLineID lastPageTLI = 0;
397 static bool InRedo = false;
400 static void XLogArchiveNotify(const char *xlog);
401 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
402 static bool XLogArchiveCheckDone(const char *xlog, bool create_if_missing);
403 static void XLogArchiveCleanup(const char *xlog);
404 static void readRecoveryCommandFile(void);
405 static void exitArchiveRecovery(TimeLineID endTLI,
406 uint32 endLogId, uint32 endLogSeg);
407 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
408 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
410 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
411 XLogRecPtr *lsn, BkpBlock *bkpb);
412 static bool AdvanceXLInsertBuffer(bool new_segment);
413 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
414 static int XLogFileInit(uint32 log, uint32 seg,
415 bool *use_existent, bool use_lock);
416 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
417 bool find_free, int *max_advance,
419 static int XLogFileOpen(uint32 log, uint32 seg);
420 static int XLogFileRead(uint32 log, uint32 seg, int emode);
421 static void XLogFileClose(void);
422 static bool RestoreArchivedFile(char *path, const char *xlogfname,
423 const char *recovername, off_t expectedSize);
424 static void PreallocXlogFiles(XLogRecPtr endptr);
425 static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
426 static void CleanupBackupHistory(void);
427 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
428 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
429 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
430 static List *readTimeLineHistory(TimeLineID targetTLI);
431 static bool existsTimeLineHistory(TimeLineID probeTLI);
432 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
433 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
435 uint32 endLogId, uint32 endLogSeg);
436 static void WriteControlFile(void);
437 static void ReadControlFile(void);
438 static char *str_time(pg_time_t tnow);
440 static void xlog_outrec(StringInfo buf, XLogRecord *record);
442 static void issue_xlog_fsync(void);
443 static void pg_start_backup_callback(int code, Datum arg);
444 static bool read_backup_label(XLogRecPtr *checkPointLoc,
445 XLogRecPtr *minRecoveryLoc);
446 static void rm_redo_error_callback(void *arg);
450 * Insert an XLOG record having the specified RMID and info bytes,
451 * with the body of the record being the data chunk(s) described by
452 * the rdata chain (see xlog.h for notes about rdata).
454 * Returns XLOG pointer to end of record (beginning of next record).
455 * This can be used as LSN for data pages affected by the logged action.
456 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
457 * before the data page can be written out. This implements the basic
458 * WAL rule "write the log before the data".)
460 * NB: this routine feels free to scribble on the XLogRecData structs,
461 * though not on the data they reference. This is OK since the XLogRecData
462 * structs are always just temporaries in the calling code.
465 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
467 XLogCtlInsert *Insert = &XLogCtl->Insert;
469 XLogContRecord *contrecord;
471 XLogRecPtr WriteRqst;
475 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
476 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
477 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
478 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
479 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
480 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
481 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
488 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
490 /* info's high bits are reserved for use by me */
491 if (info & XLR_INFO_MASK)
492 elog(PANIC, "invalid xlog info mask %02X", info);
495 * In bootstrap mode, we don't actually log anything but XLOG resources;
496 * return a phony record pointer.
498 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
501 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
506 * Here we scan the rdata chain, determine which buffers must be backed
507 * up, and compute the CRC values for the data. Note that the record
508 * header isn't added into the CRC initially since we don't know the final
509 * length or info bits quite yet. Thus, the CRC will represent the CRC of
510 * the whole record in the order "rdata, then backup blocks, then record
513 * We may have to loop back to here if a race condition is detected below.
514 * We could prevent the race by doing all this work while holding the
515 * insert lock, but it seems better to avoid doing CRC calculations while
516 * holding the lock. This means we have to be careful about modifying the
517 * rdata chain until we know we aren't going to loop back again. The only
518 * change we allow ourselves to make earlier is to set rdt->data = NULL in
519 * chain items we have decided we will have to back up the whole buffer
520 * for. This is OK because we will certainly decide the same thing again
521 * for those items if we do it over; doing it here saves an extra pass
522 * over the chain later.
525 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
527 dtbuf[i] = InvalidBuffer;
528 dtbuf_bkp[i] = false;
532 * Decide if we need to do full-page writes in this XLOG record: true if
533 * full_page_writes is on or we have a PITR request for it. Since we
534 * don't yet have the insert lock, forcePageWrites could change under us,
535 * but we'll recheck it once we have the lock.
537 doPageWrites = fullPageWrites || Insert->forcePageWrites;
539 INIT_CRC32(rdata_crc);
543 if (rdt->buffer == InvalidBuffer)
545 /* Simple data, just include it */
547 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
551 /* Find info for buffer */
552 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
554 if (rdt->buffer == dtbuf[i])
556 /* Buffer already referenced by earlier chain item */
562 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
566 if (dtbuf[i] == InvalidBuffer)
568 /* OK, put it in this slot */
569 dtbuf[i] = rdt->buffer;
570 if (XLogCheckBuffer(rdt, doPageWrites,
571 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
579 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
584 if (i >= XLR_MAX_BKP_BLOCKS)
585 elog(PANIC, "can backup at most %d blocks per xlog record",
588 /* Break out of loop when rdt points to last chain item */
589 if (rdt->next == NULL)
595 * Now add the backup block headers and data into the CRC
597 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
601 BkpBlock *bkpb = &(dtbuf_xlg[i]);
604 COMP_CRC32(rdata_crc,
607 page = (char *) BufferGetBlock(dtbuf[i]);
608 if (bkpb->hole_length == 0)
610 COMP_CRC32(rdata_crc,
616 /* must skip the hole */
617 COMP_CRC32(rdata_crc,
620 COMP_CRC32(rdata_crc,
621 page + (bkpb->hole_offset + bkpb->hole_length),
622 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
628 * NOTE: We disallow len == 0 because it provides a useful bit of extra
629 * error checking in ReadRecord. This means that all callers of
630 * XLogInsert must supply at least some not-in-a-buffer data. However, we
631 * make an exception for XLOG SWITCH records because we don't want them to
632 * ever cross a segment boundary.
634 if (len == 0 && !isLogSwitch)
635 elog(PANIC, "invalid xlog record length %u", len);
637 START_CRIT_SECTION();
639 /* Now wait to get insert lock */
640 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
643 * Check to see if my RedoRecPtr is out of date. If so, may have to go
644 * back and recompute everything. This can only happen just after a
645 * checkpoint, so it's better to be slow in this case and fast otherwise.
647 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
648 * affect the contents of the XLOG record, so we'll update our local copy
649 * but not force a recomputation.
651 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
653 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
654 RedoRecPtr = Insert->RedoRecPtr;
658 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
660 if (dtbuf[i] == InvalidBuffer)
662 if (dtbuf_bkp[i] == false &&
663 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
666 * Oops, this buffer now needs to be backed up, but we
667 * didn't think so above. Start over.
669 LWLockRelease(WALInsertLock);
678 * Also check to see if forcePageWrites was just turned on; if we weren't
679 * already doing full-page writes then go back and recompute. (If it was
680 * just turned off, we could recompute the record without full pages, but
681 * we choose not to bother.)
683 if (Insert->forcePageWrites && !doPageWrites)
685 /* Oops, must redo it with full-page data */
686 LWLockRelease(WALInsertLock);
692 * Make additional rdata chain entries for the backup blocks, so that we
693 * don't need to special-case them in the write loop. Note that we have
694 * now irrevocably changed the input rdata chain. At the exit of this
695 * loop, write_len includes the backup block data.
697 * Also set the appropriate info bits to show which buffers were backed
698 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
699 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
702 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
710 info |= XLR_SET_BKP_BLOCK(i);
712 bkpb = &(dtbuf_xlg[i]);
713 page = (char *) BufferGetBlock(dtbuf[i]);
715 rdt->next = &(dtbuf_rdt1[i]);
718 rdt->data = (char *) bkpb;
719 rdt->len = sizeof(BkpBlock);
720 write_len += sizeof(BkpBlock);
722 rdt->next = &(dtbuf_rdt2[i]);
725 if (bkpb->hole_length == 0)
734 /* must skip the hole */
736 rdt->len = bkpb->hole_offset;
737 write_len += bkpb->hole_offset;
739 rdt->next = &(dtbuf_rdt3[i]);
742 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
743 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
744 write_len += rdt->len;
750 * If we backed up any full blocks and online backup is not in progress,
751 * mark the backup blocks as removable. This allows the WAL archiver to
752 * know whether it is safe to compress archived WAL data by transforming
753 * full-block records into the non-full-block format.
755 * Note: we could just set the flag whenever !forcePageWrites, but
756 * defining it like this leaves the info bit free for some potential other
757 * use in records without any backup blocks.
759 if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
760 info |= XLR_BKP_REMOVABLE;
763 * If there isn't enough space on the current XLOG page for a record
764 * header, advance to the next page (leaving the unused space as zeroes).
767 freespace = INSERT_FREESPACE(Insert);
768 if (freespace < SizeOfXLogRecord)
770 updrqst = AdvanceXLInsertBuffer(false);
771 freespace = INSERT_FREESPACE(Insert);
774 /* Compute record's XLOG location */
775 curridx = Insert->curridx;
776 INSERT_RECPTR(RecPtr, Insert, curridx);
779 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
780 * segment, we need not insert it (and don't want to because we'd like
781 * consecutive switch requests to be no-ops). Instead, make sure
782 * everything is written and flushed through the end of the prior segment,
783 * and return the prior segment's end address.
786 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
788 /* We can release insert lock immediately */
789 LWLockRelease(WALInsertLock);
791 RecPtr.xrecoff -= SizeOfXLogLongPHD;
792 if (RecPtr.xrecoff == 0)
794 /* crossing a logid boundary */
796 RecPtr.xrecoff = XLogFileSize;
799 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
800 LogwrtResult = XLogCtl->Write.LogwrtResult;
801 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
803 XLogwrtRqst FlushRqst;
805 FlushRqst.Write = RecPtr;
806 FlushRqst.Flush = RecPtr;
807 XLogWrite(FlushRqst, false, false);
809 LWLockRelease(WALWriteLock);
816 /* Insert record header */
818 record = (XLogRecord *) Insert->currpos;
819 record->xl_prev = Insert->PrevRecord;
820 record->xl_xid = GetCurrentTransactionIdIfAny();
821 record->xl_tot_len = SizeOfXLogRecord + write_len;
822 record->xl_len = len; /* doesn't include backup blocks */
823 record->xl_info = info;
824 record->xl_rmid = rmid;
826 /* Now we can finish computing the record's CRC */
827 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
828 SizeOfXLogRecord - sizeof(pg_crc32));
829 FIN_CRC32(rdata_crc);
830 record->xl_crc = rdata_crc;
837 initStringInfo(&buf);
838 appendStringInfo(&buf, "INSERT @ %X/%X: ",
839 RecPtr.xlogid, RecPtr.xrecoff);
840 xlog_outrec(&buf, record);
841 if (rdata->data != NULL)
843 appendStringInfo(&buf, " - ");
844 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
846 elog(LOG, "%s", buf.data);
851 /* Record begin of record in appropriate places */
852 ProcLastRecPtr = RecPtr;
853 Insert->PrevRecord = RecPtr;
855 Insert->currpos += SizeOfXLogRecord;
856 freespace -= SizeOfXLogRecord;
859 * Append the data, including backup blocks if any
863 while (rdata->data == NULL)
868 if (rdata->len > freespace)
870 memcpy(Insert->currpos, rdata->data, freespace);
871 rdata->data += freespace;
872 rdata->len -= freespace;
873 write_len -= freespace;
877 memcpy(Insert->currpos, rdata->data, rdata->len);
878 freespace -= rdata->len;
879 write_len -= rdata->len;
880 Insert->currpos += rdata->len;
886 /* Use next buffer */
887 updrqst = AdvanceXLInsertBuffer(false);
888 curridx = Insert->curridx;
889 /* Insert cont-record header */
890 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
891 contrecord = (XLogContRecord *) Insert->currpos;
892 contrecord->xl_rem_len = write_len;
893 Insert->currpos += SizeOfXLogContRecord;
894 freespace = INSERT_FREESPACE(Insert);
897 /* Ensure next record will be properly aligned */
898 Insert->currpos = (char *) Insert->currpage +
899 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
900 freespace = INSERT_FREESPACE(Insert);
903 * The recptr I return is the beginning of the *next* record. This will be
904 * stored as LSN for changed data pages...
906 INSERT_RECPTR(RecPtr, Insert, curridx);
909 * If the record is an XLOG_SWITCH, we must now write and flush all the
910 * existing data, and then forcibly advance to the start of the next
911 * segment. It's not good to do this I/O while holding the insert lock,
912 * but there seems too much risk of confusion if we try to release the
913 * lock sooner. Fortunately xlog switch needn't be a high-performance
914 * operation anyway...
918 XLogCtlWrite *Write = &XLogCtl->Write;
919 XLogwrtRqst FlushRqst;
920 XLogRecPtr OldSegEnd;
922 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
925 * Flush through the end of the page containing XLOG_SWITCH, and
926 * perform end-of-segment actions (eg, notifying archiver).
928 WriteRqst = XLogCtl->xlblocks[curridx];
929 FlushRqst.Write = WriteRqst;
930 FlushRqst.Flush = WriteRqst;
931 XLogWrite(FlushRqst, false, true);
933 /* Set up the next buffer as first page of next segment */
934 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
935 (void) AdvanceXLInsertBuffer(true);
937 /* There should be no unwritten data */
938 curridx = Insert->curridx;
939 Assert(curridx == Write->curridx);
941 /* Compute end address of old segment */
942 OldSegEnd = XLogCtl->xlblocks[curridx];
943 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
944 if (OldSegEnd.xrecoff == 0)
946 /* crossing a logid boundary */
947 OldSegEnd.xlogid -= 1;
948 OldSegEnd.xrecoff = XLogFileSize;
951 /* Make it look like we've written and synced all of old segment */
952 LogwrtResult.Write = OldSegEnd;
953 LogwrtResult.Flush = OldSegEnd;
956 * Update shared-memory status --- this code should match XLogWrite
959 /* use volatile pointer to prevent code rearrangement */
960 volatile XLogCtlData *xlogctl = XLogCtl;
962 SpinLockAcquire(&xlogctl->info_lck);
963 xlogctl->LogwrtResult = LogwrtResult;
964 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
965 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
966 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
967 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
968 SpinLockRelease(&xlogctl->info_lck);
971 Write->LogwrtResult = LogwrtResult;
973 LWLockRelease(WALWriteLock);
975 updrqst = false; /* done already */
979 /* normal case, ie not xlog switch */
981 /* Need to update shared LogwrtRqst if some block was filled up */
982 if (freespace < SizeOfXLogRecord)
984 /* curridx is filled and available for writing out */
989 /* if updrqst already set, write through end of previous buf */
990 curridx = PrevBufIdx(curridx);
992 WriteRqst = XLogCtl->xlblocks[curridx];
995 LWLockRelease(WALInsertLock);
999 /* use volatile pointer to prevent code rearrangement */
1000 volatile XLogCtlData *xlogctl = XLogCtl;
1002 SpinLockAcquire(&xlogctl->info_lck);
1003 /* advance global request to include new block(s) */
1004 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
1005 xlogctl->LogwrtRqst.Write = WriteRqst;
1006 /* update local result copy while I have the chance */
1007 LogwrtResult = xlogctl->LogwrtResult;
1008 SpinLockRelease(&xlogctl->info_lck);
1011 XactLastRecEnd = RecPtr;
1019 * Determine whether the buffer referenced by an XLogRecData item has to
1020 * be backed up, and if so fill a BkpBlock struct for it. In any case
1021 * save the buffer's LSN at *lsn.
1024 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1025 XLogRecPtr *lsn, BkpBlock *bkpb)
1029 page = (PageHeader) BufferGetBlock(rdata->buffer);
1032 * XXX We assume page LSN is first data on *every* page that can be passed
1033 * to XLogInsert, whether it otherwise has the standard page layout or
1036 *lsn = page->pd_lsn;
1039 XLByteLE(page->pd_lsn, RedoRecPtr))
1042 * The page needs to be backed up, so set up *bkpb
1044 bkpb->node = BufferGetFileNode(rdata->buffer);
1045 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1047 if (rdata->buffer_std)
1049 /* Assume we can omit data between pd_lower and pd_upper */
1050 uint16 lower = page->pd_lower;
1051 uint16 upper = page->pd_upper;
1053 if (lower >= SizeOfPageHeaderData &&
1057 bkpb->hole_offset = lower;
1058 bkpb->hole_length = upper - lower;
1062 /* No "hole" to compress out */
1063 bkpb->hole_offset = 0;
1064 bkpb->hole_length = 0;
1069 /* Not a standard page header, don't try to eliminate "hole" */
1070 bkpb->hole_offset = 0;
1071 bkpb->hole_length = 0;
1074 return true; /* buffer requires backup */
1077 return false; /* buffer does not need to be backed up */
1083 * Create an archive notification file
1085 * The name of the notification file is the message that will be picked up
1086 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1087 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1088 * then when complete, rename it to 0000000100000001000000C6.done
1091 XLogArchiveNotify(const char *xlog)
1093 char archiveStatusPath[MAXPGPATH];
1096 /* insert an otherwise empty file called <XLOG>.ready */
1097 StatusFilePath(archiveStatusPath, xlog, ".ready");
1098 fd = AllocateFile(archiveStatusPath, "w");
1102 (errcode_for_file_access(),
1103 errmsg("could not create archive status file \"%s\": %m",
1104 archiveStatusPath)));
1110 (errcode_for_file_access(),
1111 errmsg("could not write archive status file \"%s\": %m",
1112 archiveStatusPath)));
1116 /* Notify archiver that it's got something to do */
1117 if (IsUnderPostmaster)
1118 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1122 * Convenience routine to notify using log/seg representation of filename
1125 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1127 char xlog[MAXFNAMELEN];
1129 XLogFileName(xlog, ThisTimeLineID, log, seg);
1130 XLogArchiveNotify(xlog);
1134 * XLogArchiveCheckDone
1136 * This is called when we are ready to delete or recycle an old XLOG segment
1137 * file or backup history file. If it is okay to delete it then return true.
1138 * If it is not time to delete it, make sure a .ready file exists, and return
1141 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1142 * then return false; else create <XLOG>.ready and return false.
1144 * The reason we do things this way is so that if the original attempt to
1145 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1148 XLogArchiveCheckDone(const char *xlog, bool create_if_missing)
1150 char archiveStatusPath[MAXPGPATH];
1151 struct stat stat_buf;
1153 /* Always deletable if archiving is off */
1154 if (!XLogArchivingActive())
1157 /* First check for .done --- this means archiver is done with it */
1158 StatusFilePath(archiveStatusPath, xlog, ".done");
1159 if (stat(archiveStatusPath, &stat_buf) == 0)
1162 /* check for .ready --- this means archiver is still busy with it */
1163 StatusFilePath(archiveStatusPath, xlog, ".ready");
1164 if (stat(archiveStatusPath, &stat_buf) == 0)
1167 /* Race condition --- maybe archiver just finished, so recheck */
1168 StatusFilePath(archiveStatusPath, xlog, ".done");
1169 if (stat(archiveStatusPath, &stat_buf) == 0)
1172 /* Retry creation of the .ready file */
1173 if (create_if_missing)
1174 XLogArchiveNotify(xlog);
1180 * XLogArchiveCleanup
1182 * Cleanup archive notification file(s) for a particular xlog segment
1185 XLogArchiveCleanup(const char *xlog)
1187 char archiveStatusPath[MAXPGPATH];
1189 /* Remove the .done file */
1190 StatusFilePath(archiveStatusPath, xlog, ".done");
1191 unlink(archiveStatusPath);
1192 /* should we complain about failure? */
1194 /* Remove the .ready file if present --- normally it shouldn't be */
1195 StatusFilePath(archiveStatusPath, xlog, ".ready");
1196 unlink(archiveStatusPath);
1197 /* should we complain about failure? */
1201 * Advance the Insert state to the next buffer page, writing out the next
1202 * buffer if it still contains unwritten data.
1204 * If new_segment is TRUE then we set up the next buffer page as the first
1205 * page of the next xlog segment file, possibly but not usually the next
1206 * consecutive file page.
1208 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1209 * just-filled page. If we can do this for free (without an extra lock),
1210 * we do so here. Otherwise the caller must do it. We return TRUE if the
1211 * request update still needs to be done, FALSE if we did it internally.
1213 * Must be called with WALInsertLock held.
1216 AdvanceXLInsertBuffer(bool new_segment)
1218 XLogCtlInsert *Insert = &XLogCtl->Insert;
1219 XLogCtlWrite *Write = &XLogCtl->Write;
1220 int nextidx = NextBufIdx(Insert->curridx);
1221 bool update_needed = true;
1222 XLogRecPtr OldPageRqstPtr;
1223 XLogwrtRqst WriteRqst;
1224 XLogRecPtr NewPageEndPtr;
1225 XLogPageHeader NewPage;
1227 /* Use Insert->LogwrtResult copy if it's more fresh */
1228 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1229 LogwrtResult = Insert->LogwrtResult;
1232 * Get ending-offset of the buffer page we need to replace (this may be
1233 * zero if the buffer hasn't been used yet). Fall through if it's already
1236 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1237 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1239 /* nope, got work to do... */
1240 XLogRecPtr FinishedPageRqstPtr;
1242 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1244 /* Before waiting, get info_lck and update LogwrtResult */
1246 /* use volatile pointer to prevent code rearrangement */
1247 volatile XLogCtlData *xlogctl = XLogCtl;
1249 SpinLockAcquire(&xlogctl->info_lck);
1250 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1251 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1252 LogwrtResult = xlogctl->LogwrtResult;
1253 SpinLockRelease(&xlogctl->info_lck);
1256 update_needed = false; /* Did the shared-request update */
1258 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1260 /* OK, someone wrote it already */
1261 Insert->LogwrtResult = LogwrtResult;
1265 /* Must acquire write lock */
1266 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1267 LogwrtResult = Write->LogwrtResult;
1268 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1270 /* OK, someone wrote it already */
1271 LWLockRelease(WALWriteLock);
1272 Insert->LogwrtResult = LogwrtResult;
1277 * Have to write buffers while holding insert lock. This is
1278 * not good, so only write as much as we absolutely must.
1280 WriteRqst.Write = OldPageRqstPtr;
1281 WriteRqst.Flush.xlogid = 0;
1282 WriteRqst.Flush.xrecoff = 0;
1283 XLogWrite(WriteRqst, false, false);
1284 LWLockRelease(WALWriteLock);
1285 Insert->LogwrtResult = LogwrtResult;
1291 * Now the next buffer slot is free and we can set it up to be the next
1294 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1298 /* force it to a segment start point */
1299 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1300 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1303 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1305 /* crossing a logid boundary */
1306 NewPageEndPtr.xlogid += 1;
1307 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1310 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1311 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1312 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1314 Insert->curridx = nextidx;
1315 Insert->currpage = NewPage;
1317 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1320 * Be sure to re-zero the buffer so that bytes beyond what we've written
1321 * will look like zeroes and not valid XLOG records...
1323 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1326 * Fill the new page's header
1328 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1330 /* NewPage->xlp_info = 0; */ /* done by memset */
1331 NewPage ->xlp_tli = ThisTimeLineID;
1332 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1333 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1336 * If first page of an XLOG segment file, make it a long header.
1338 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1340 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1342 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1343 NewLongPage->xlp_seg_size = XLogSegSize;
1344 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1345 NewPage ->xlp_info |= XLP_LONG_HEADER;
1347 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1350 return update_needed;
1354 * Check whether we've consumed enough xlog space that a checkpoint is needed.
1356 * Caller must have just finished filling the open log file (so that
1357 * openLogId/openLogSeg are valid). We measure the distance from RedoRecPtr
1358 * to the open log file and see if that exceeds CheckPointSegments.
1360 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
1363 XLogCheckpointNeeded(void)
1366 * A straight computation of segment number could overflow 32 bits. Rather
1367 * than assuming we have working 64-bit arithmetic, we compare the
1368 * highest-order bits separately, and force a checkpoint immediately when
1373 uint32 old_highbits,
1376 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1377 (RedoRecPtr.xrecoff / XLogSegSize);
1378 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1379 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile + openLogSeg;
1380 new_highbits = openLogId / XLogSegSize;
1381 if (new_highbits != old_highbits ||
1382 new_segno >= old_segno + (uint32) (CheckPointSegments - 1))
1388 * Write and/or fsync the log at least as far as WriteRqst indicates.
1390 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1391 * may stop at any convenient boundary (such as a cache or logfile boundary).
1392 * This option allows us to avoid uselessly issuing multiple writes when a
1393 * single one would do.
1395 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1396 * perform end-of-segment actions after writing the last page, even if
1397 * it's not physically the end of its segment. (NB: this will work properly
1398 * only if caller specifies WriteRqst == page-end and flexible == false,
1399 * and there is some data to write.)
1401 * Must be called with WALWriteLock held.
1404 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1406 XLogCtlWrite *Write = &XLogCtl->Write;
1408 bool last_iteration;
1416 /* We should always be inside a critical section here */
1417 Assert(CritSectionCount > 0);
1420 * Update local LogwrtResult (caller probably did this already, but...)
1422 LogwrtResult = Write->LogwrtResult;
1425 * Since successive pages in the xlog cache are consecutively allocated,
1426 * we can usually gather multiple pages together and issue just one
1427 * write() call. npages is the number of pages we have determined can be
1428 * written together; startidx is the cache block index of the first one,
1429 * and startoffset is the file offset at which it should go. The latter
1430 * two variables are only valid when npages > 0, but we must initialize
1431 * all of them to keep the compiler quiet.
1438 * Within the loop, curridx is the cache block index of the page to
1439 * consider writing. We advance Write->curridx only after successfully
1440 * writing pages. (Right now, this refinement is useless since we are
1441 * going to PANIC if any error occurs anyway; but someday it may come in
1444 curridx = Write->curridx;
1446 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1449 * Make sure we're not ahead of the insert process. This could happen
1450 * if we're passed a bogus WriteRqst.Write that is past the end of the
1451 * last page that's been initialized by AdvanceXLInsertBuffer.
1453 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1454 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1455 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1456 XLogCtl->xlblocks[curridx].xlogid,
1457 XLogCtl->xlblocks[curridx].xrecoff);
1459 /* Advance LogwrtResult.Write to end of current buffer page */
1460 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1461 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1463 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1466 * Switch to new logfile segment. We cannot have any pending
1467 * pages here (since we dump what we have at segment end).
1469 Assert(npages == 0);
1470 if (openLogFile >= 0)
1472 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1474 /* create/use new log file */
1475 use_existent = true;
1476 openLogFile = XLogFileInit(openLogId, openLogSeg,
1477 &use_existent, true);
1481 /* Make sure we have the current logfile open */
1482 if (openLogFile < 0)
1484 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1485 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1489 /* Add current page to the set of pending pages-to-dump */
1492 /* first of group */
1494 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1499 * Dump the set if this will be the last loop iteration, or if we are
1500 * at the last page of the cache area (since the next page won't be
1501 * contiguous in memory), or if we are at the end of the logfile
1504 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1506 finishing_seg = !ispartialpage &&
1507 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1509 if (last_iteration ||
1510 curridx == XLogCtl->XLogCacheBlck ||
1516 /* Need to seek in the file? */
1517 if (openLogOff != startoffset)
1519 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1521 (errcode_for_file_access(),
1522 errmsg("could not seek in log file %u, "
1523 "segment %u to offset %u: %m",
1524 openLogId, openLogSeg, startoffset)));
1525 openLogOff = startoffset;
1528 /* OK to write the page(s) */
1529 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1530 nbytes = npages * (Size) XLOG_BLCKSZ;
1532 if (write(openLogFile, from, nbytes) != nbytes)
1534 /* if write didn't set errno, assume no disk space */
1538 (errcode_for_file_access(),
1539 errmsg("could not write to log file %u, segment %u "
1540 "at offset %u, length %lu: %m",
1541 openLogId, openLogSeg,
1542 openLogOff, (unsigned long) nbytes)));
1545 /* Update state for write */
1546 openLogOff += nbytes;
1547 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1551 * If we just wrote the whole last page of a logfile segment,
1552 * fsync the segment immediately. This avoids having to go back
1553 * and re-open prior segments when an fsync request comes along
1554 * later. Doing it here ensures that one and only one backend will
1555 * perform this fsync.
1557 * We also do this if this is the last page written for an xlog
1560 * This is also the right place to notify the Archiver that the
1561 * segment is ready to copy to archival storage, and to update the
1562 * timer for archive_timeout, and to signal for a checkpoint if
1563 * too many logfile segments have been used since the last
1566 if (finishing_seg || (xlog_switch && last_iteration))
1569 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1571 if (XLogArchivingActive())
1572 XLogArchiveNotifySeg(openLogId, openLogSeg);
1574 Write->lastSegSwitchTime = (pg_time_t) time(NULL);
1577 * Signal bgwriter to start a checkpoint if we've consumed too
1578 * much xlog since the last one. For speed, we first check
1579 * using the local copy of RedoRecPtr, which might be out of
1580 * date; if it looks like a checkpoint is needed, forcibly
1581 * update RedoRecPtr and recheck.
1583 if (IsUnderPostmaster &&
1584 XLogCheckpointNeeded())
1586 (void) GetRedoRecPtr();
1587 if (XLogCheckpointNeeded())
1588 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1595 /* Only asked to write a partial page */
1596 LogwrtResult.Write = WriteRqst.Write;
1599 curridx = NextBufIdx(curridx);
1601 /* If flexible, break out of loop as soon as we wrote something */
1602 if (flexible && npages == 0)
1606 Assert(npages == 0);
1607 Assert(curridx == Write->curridx);
1610 * If asked to flush, do so
1612 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1613 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1616 * Could get here without iterating above loop, in which case we might
1617 * have no open file or the wrong one. However, we do not need to
1618 * fsync more than one file.
1620 if (sync_method != SYNC_METHOD_OPEN && sync_method != SYNC_METHOD_OPEN_DSYNC)
1622 if (openLogFile >= 0 &&
1623 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1625 if (openLogFile < 0)
1627 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1628 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1633 LogwrtResult.Flush = LogwrtResult.Write;
1637 * Update shared-memory status
1639 * We make sure that the shared 'request' values do not fall behind the
1640 * 'result' values. This is not absolutely essential, but it saves some
1641 * code in a couple of places.
1644 /* use volatile pointer to prevent code rearrangement */
1645 volatile XLogCtlData *xlogctl = XLogCtl;
1647 SpinLockAcquire(&xlogctl->info_lck);
1648 xlogctl->LogwrtResult = LogwrtResult;
1649 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1650 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1651 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1652 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1653 SpinLockRelease(&xlogctl->info_lck);
1656 Write->LogwrtResult = LogwrtResult;
1660 * Record the LSN for an asynchronous transaction commit.
1661 * (This should not be called for aborts, nor for synchronous commits.)
1664 XLogSetAsyncCommitLSN(XLogRecPtr asyncCommitLSN)
1666 /* use volatile pointer to prevent code rearrangement */
1667 volatile XLogCtlData *xlogctl = XLogCtl;
1669 SpinLockAcquire(&xlogctl->info_lck);
1670 if (XLByteLT(xlogctl->asyncCommitLSN, asyncCommitLSN))
1671 xlogctl->asyncCommitLSN = asyncCommitLSN;
1672 SpinLockRelease(&xlogctl->info_lck);
1676 * Ensure that all XLOG data through the given position is flushed to disk.
1678 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1679 * already held, and we try to avoid acquiring it if possible.
1682 XLogFlush(XLogRecPtr record)
1684 XLogRecPtr WriteRqstPtr;
1685 XLogwrtRqst WriteRqst;
1687 /* Disabled during REDO */
1691 /* Quick exit if already known flushed */
1692 if (XLByteLE(record, LogwrtResult.Flush))
1697 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1698 record.xlogid, record.xrecoff,
1699 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1700 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1703 START_CRIT_SECTION();
1706 * Since fsync is usually a horribly expensive operation, we try to
1707 * piggyback as much data as we can on each fsync: if we see any more data
1708 * entered into the xlog buffer, we'll write and fsync that too, so that
1709 * the final value of LogwrtResult.Flush is as large as possible. This
1710 * gives us some chance of avoiding another fsync immediately after.
1713 /* initialize to given target; may increase below */
1714 WriteRqstPtr = record;
1716 /* read LogwrtResult and update local state */
1718 /* use volatile pointer to prevent code rearrangement */
1719 volatile XLogCtlData *xlogctl = XLogCtl;
1721 SpinLockAcquire(&xlogctl->info_lck);
1722 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1723 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1724 LogwrtResult = xlogctl->LogwrtResult;
1725 SpinLockRelease(&xlogctl->info_lck);
1729 if (!XLByteLE(record, LogwrtResult.Flush))
1731 /* now wait for the write lock */
1732 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1733 LogwrtResult = XLogCtl->Write.LogwrtResult;
1734 if (!XLByteLE(record, LogwrtResult.Flush))
1736 /* try to write/flush later additions to XLOG as well */
1737 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1739 XLogCtlInsert *Insert = &XLogCtl->Insert;
1740 uint32 freespace = INSERT_FREESPACE(Insert);
1742 if (freespace < SizeOfXLogRecord) /* buffer is full */
1743 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1746 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1747 WriteRqstPtr.xrecoff -= freespace;
1749 LWLockRelease(WALInsertLock);
1750 WriteRqst.Write = WriteRqstPtr;
1751 WriteRqst.Flush = WriteRqstPtr;
1755 WriteRqst.Write = WriteRqstPtr;
1756 WriteRqst.Flush = record;
1758 XLogWrite(WriteRqst, false, false);
1760 LWLockRelease(WALWriteLock);
1766 * If we still haven't flushed to the request point then we have a
1767 * problem; most likely, the requested flush point is past end of XLOG.
1768 * This has been seen to occur when a disk page has a corrupted LSN.
1770 * Formerly we treated this as a PANIC condition, but that hurts the
1771 * system's robustness rather than helping it: we do not want to take down
1772 * the whole system due to corruption on one data page. In particular, if
1773 * the bad page is encountered again during recovery then we would be
1774 * unable to restart the database at all! (This scenario has actually
1775 * happened in the field several times with 7.1 releases. Note that we
1776 * cannot get here while InRedo is true, but if the bad page is brought in
1777 * and marked dirty during recovery then CreateCheckPoint will try to
1778 * flush it at the end of recovery.)
1780 * The current approach is to ERROR under normal conditions, but only
1781 * WARNING during recovery, so that the system can be brought up even if
1782 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1783 * be promoted to PANIC since xact.c calls this routine inside a critical
1784 * section. However, calls from bufmgr.c are not within critical sections
1785 * and so we will not force a restart for a bad LSN on a data page.
1787 if (XLByteLT(LogwrtResult.Flush, record))
1788 elog(InRecovery ? WARNING : ERROR,
1789 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1790 record.xlogid, record.xrecoff,
1791 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1795 * Flush xlog, but without specifying exactly where to flush to.
1797 * We normally flush only completed blocks; but if there is nothing to do on
1798 * that basis, we check for unflushed async commits in the current incomplete
1799 * block, and flush through the latest one of those. Thus, if async commits
1800 * are not being used, we will flush complete blocks only. We can guarantee
1801 * that async commits reach disk after at most three cycles; normally only
1802 * one or two. (We allow XLogWrite to write "flexibly", meaning it can stop
1803 * at the end of the buffer ring; this makes a difference only with very high
1804 * load or long wal_writer_delay, but imposes one extra cycle for the worst
1805 * case for async commits.)
1807 * This routine is invoked periodically by the background walwriter process.
1810 XLogBackgroundFlush(void)
1812 XLogRecPtr WriteRqstPtr;
1813 bool flexible = true;
1815 /* read LogwrtResult and update local state */
1817 /* use volatile pointer to prevent code rearrangement */
1818 volatile XLogCtlData *xlogctl = XLogCtl;
1820 SpinLockAcquire(&xlogctl->info_lck);
1821 LogwrtResult = xlogctl->LogwrtResult;
1822 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1823 SpinLockRelease(&xlogctl->info_lck);
1826 /* back off to last completed page boundary */
1827 WriteRqstPtr.xrecoff -= WriteRqstPtr.xrecoff % XLOG_BLCKSZ;
1829 /* if we have already flushed that far, consider async commit records */
1830 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1832 /* use volatile pointer to prevent code rearrangement */
1833 volatile XLogCtlData *xlogctl = XLogCtl;
1835 SpinLockAcquire(&xlogctl->info_lck);
1836 WriteRqstPtr = xlogctl->asyncCommitLSN;
1837 SpinLockRelease(&xlogctl->info_lck);
1838 flexible = false; /* ensure it all gets written */
1841 /* Done if already known flushed */
1842 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1847 elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
1848 WriteRqstPtr.xlogid, WriteRqstPtr.xrecoff,
1849 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1850 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1853 START_CRIT_SECTION();
1855 /* now wait for the write lock */
1856 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1857 LogwrtResult = XLogCtl->Write.LogwrtResult;
1858 if (!XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1860 XLogwrtRqst WriteRqst;
1862 WriteRqst.Write = WriteRqstPtr;
1863 WriteRqst.Flush = WriteRqstPtr;
1864 XLogWrite(WriteRqst, flexible, false);
1866 LWLockRelease(WALWriteLock);
1872 * Flush any previous asynchronously-committed transactions' commit records.
1874 * NOTE: it is unwise to assume that this provides any strong guarantees.
1875 * In particular, because of the inexact LSN bookkeeping used by clog.c,
1876 * we cannot assume that hint bits will be settable for these transactions.
1879 XLogAsyncCommitFlush(void)
1881 XLogRecPtr WriteRqstPtr;
1883 /* use volatile pointer to prevent code rearrangement */
1884 volatile XLogCtlData *xlogctl = XLogCtl;
1886 SpinLockAcquire(&xlogctl->info_lck);
1887 WriteRqstPtr = xlogctl->asyncCommitLSN;
1888 SpinLockRelease(&xlogctl->info_lck);
1890 XLogFlush(WriteRqstPtr);
1894 * Test whether XLOG data has been flushed up to (at least) the given position.
1896 * Returns true if a flush is still needed. (It may be that someone else
1897 * is already in process of flushing that far, however.)
1900 XLogNeedsFlush(XLogRecPtr record)
1902 /* Quick exit if already known flushed */
1903 if (XLByteLE(record, LogwrtResult.Flush))
1906 /* read LogwrtResult and update local state */
1908 /* use volatile pointer to prevent code rearrangement */
1909 volatile XLogCtlData *xlogctl = XLogCtl;
1911 SpinLockAcquire(&xlogctl->info_lck);
1912 LogwrtResult = xlogctl->LogwrtResult;
1913 SpinLockRelease(&xlogctl->info_lck);
1917 if (XLByteLE(record, LogwrtResult.Flush))
1924 * Create a new XLOG file segment, or open a pre-existing one.
1926 * log, seg: identify segment to be created/opened.
1928 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1929 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1932 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1933 * place. This should be TRUE except during bootstrap log creation. The
1934 * caller must *not* hold the lock at call.
1936 * Returns FD of opened file.
1938 * Note: errors here are ERROR not PANIC because we might or might not be
1939 * inside a critical section (eg, during checkpoint there is no reason to
1940 * take down the system on failure). They will promote to PANIC if we are
1941 * in a critical section.
1944 XLogFileInit(uint32 log, uint32 seg,
1945 bool *use_existent, bool use_lock)
1947 char path[MAXPGPATH];
1948 char tmppath[MAXPGPATH];
1950 uint32 installed_log;
1951 uint32 installed_seg;
1956 XLogFilePath(path, ThisTimeLineID, log, seg);
1959 * Try to use existent file (checkpoint maker may have created it already)
1963 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1967 if (errno != ENOENT)
1969 (errcode_for_file_access(),
1970 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1978 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
1979 * another process is doing the same thing. If so, we will end up
1980 * pre-creating an extra log segment. That seems OK, and better than
1981 * holding the lock throughout this lengthy process.
1983 elog(DEBUG2, "creating and filling new WAL file");
1985 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1989 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1990 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1994 (errcode_for_file_access(),
1995 errmsg("could not create file \"%s\": %m", tmppath)));
1998 * Zero-fill the file. We have to do this the hard way to ensure that all
1999 * the file space has really been allocated --- on platforms that allow
2000 * "holes" in files, just seeking to the end doesn't allocate intermediate
2001 * space. This way, we know that we have all the space and (after the
2002 * fsync below) that all the indirect blocks are down on disk. Therefore,
2003 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
2006 * Note: palloc zbuffer, instead of just using a local char array, to
2007 * ensure it is reasonably well-aligned; this may save a few cycles
2008 * transferring data to the kernel.
2010 zbuffer = (char *) palloc0(XLOG_BLCKSZ);
2011 for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
2014 if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
2016 int save_errno = errno;
2019 * If we fail to make the file, delete it to release disk space
2022 /* if write didn't set errno, assume problem is no disk space */
2023 errno = save_errno ? save_errno : ENOSPC;
2026 (errcode_for_file_access(),
2027 errmsg("could not write to file \"%s\": %m", tmppath)));
2032 if (pg_fsync(fd) != 0)
2034 (errcode_for_file_access(),
2035 errmsg("could not fsync file \"%s\": %m", tmppath)));
2039 (errcode_for_file_access(),
2040 errmsg("could not close file \"%s\": %m", tmppath)));
2043 * Now move the segment into place with its final name.
2045 * If caller didn't want to use a pre-existing file, get rid of any
2046 * pre-existing file. Otherwise, cope with possibility that someone else
2047 * has created the file while we were filling ours: if so, use ours to
2048 * pre-create a future log segment.
2050 installed_log = log;
2051 installed_seg = seg;
2052 max_advance = XLOGfileslop;
2053 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
2054 *use_existent, &max_advance,
2057 /* No need for any more future segments... */
2061 elog(DEBUG2, "done creating and filling new WAL file");
2063 /* Set flag to tell caller there was no existent file */
2064 *use_existent = false;
2066 /* Now open original target segment (might not be file I just made) */
2067 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2071 (errcode_for_file_access(),
2072 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2079 * Create a new XLOG file segment by copying a pre-existing one.
2081 * log, seg: identify segment to be created.
2083 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
2084 * a different timeline)
2086 * Currently this is only used during recovery, and so there are no locking
2087 * considerations. But we should be just as tense as XLogFileInit to avoid
2088 * emplacing a bogus file.
2091 XLogFileCopy(uint32 log, uint32 seg,
2092 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
2094 char path[MAXPGPATH];
2095 char tmppath[MAXPGPATH];
2096 char buffer[XLOG_BLCKSZ];
2102 * Open the source file
2104 XLogFilePath(path, srcTLI, srclog, srcseg);
2105 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2108 (errcode_for_file_access(),
2109 errmsg("could not open file \"%s\": %m", path)));
2112 * Copy into a temp file name.
2114 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2118 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2119 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2123 (errcode_for_file_access(),
2124 errmsg("could not create file \"%s\": %m", tmppath)));
2127 * Do the data copying.
2129 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2132 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2136 (errcode_for_file_access(),
2137 errmsg("could not read file \"%s\": %m", path)));
2140 (errmsg("not enough data in file \"%s\"", path)));
2143 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2145 int save_errno = errno;
2148 * If we fail to make the file, delete it to release disk space
2151 /* if write didn't set errno, assume problem is no disk space */
2152 errno = save_errno ? save_errno : ENOSPC;
2155 (errcode_for_file_access(),
2156 errmsg("could not write to file \"%s\": %m", tmppath)));
2160 if (pg_fsync(fd) != 0)
2162 (errcode_for_file_access(),
2163 errmsg("could not fsync file \"%s\": %m", tmppath)));
2167 (errcode_for_file_access(),
2168 errmsg("could not close file \"%s\": %m", tmppath)));
2173 * Now move the segment into place with its final name.
2175 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2176 elog(ERROR, "InstallXLogFileSegment should not have failed");
2180 * Install a new XLOG segment file as a current or future log segment.
2182 * This is used both to install a newly-created segment (which has a temp
2183 * filename while it's being created) and to recycle an old segment.
2185 * *log, *seg: identify segment to install as (or first possible target).
2186 * When find_free is TRUE, these are modified on return to indicate the
2187 * actual installation location or last segment searched.
2189 * tmppath: initial name of file to install. It will be renamed into place.
2191 * find_free: if TRUE, install the new segment at the first empty log/seg
2192 * number at or after the passed numbers. If FALSE, install the new segment
2193 * exactly where specified, deleting any existing segment file there.
2195 * *max_advance: maximum number of log/seg slots to advance past the starting
2196 * point. Fail if no free slot is found in this range. On return, reduced
2197 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2198 * when find_free is FALSE.)
2200 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2201 * place. This should be TRUE except during bootstrap log creation. The
2202 * caller must *not* hold the lock at call.
2204 * Returns TRUE if file installed, FALSE if not installed because of
2205 * exceeding max_advance limit. On Windows, we also return FALSE if we
2206 * can't rename the file into place because someone's got it open.
2207 * (Any other kind of failure causes ereport().)
2210 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2211 bool find_free, int *max_advance,
2214 char path[MAXPGPATH];
2215 struct stat stat_buf;
2217 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2220 * We want to be sure that only one process does this at a time.
2223 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2227 /* Force installation: get rid of any pre-existing segment file */
2232 /* Find a free slot to put it in */
2233 while (stat(path, &stat_buf) == 0)
2235 if (*max_advance <= 0)
2237 /* Failed to find a free slot within specified range */
2239 LWLockRelease(ControlFileLock);
2242 NextLogSeg(*log, *seg);
2244 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2249 * Prefer link() to rename() here just to be really sure that we don't
2250 * overwrite an existing logfile. However, there shouldn't be one, so
2251 * rename() is an acceptable substitute except for the truly paranoid.
2253 #if HAVE_WORKING_LINK
2254 if (link(tmppath, path) < 0)
2256 (errcode_for_file_access(),
2257 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2258 tmppath, path, *log, *seg)));
2261 if (rename(tmppath, path) < 0)
2264 #if !defined(__CYGWIN__)
2265 if (GetLastError() == ERROR_ACCESS_DENIED)
2267 if (errno == EACCES)
2271 LWLockRelease(ControlFileLock);
2277 (errcode_for_file_access(),
2278 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2279 tmppath, path, *log, *seg)));
2284 LWLockRelease(ControlFileLock);
2290 * Open a pre-existing logfile segment for writing.
2293 XLogFileOpen(uint32 log, uint32 seg)
2295 char path[MAXPGPATH];
2298 XLogFilePath(path, ThisTimeLineID, log, seg);
2300 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2304 (errcode_for_file_access(),
2305 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2312 * Open a logfile segment for reading (during recovery).
2315 XLogFileRead(uint32 log, uint32 seg, int emode)
2317 char path[MAXPGPATH];
2318 char xlogfname[MAXFNAMELEN];
2319 char activitymsg[MAXFNAMELEN + 16];
2324 * Loop looking for a suitable timeline ID: we might need to read any of
2325 * the timelines listed in expectedTLIs.
2327 * We expect curFileTLI on entry to be the TLI of the preceding file in
2328 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2329 * to go backwards; this prevents us from picking up the wrong file when a
2330 * parent timeline extends to higher segment numbers than the child we
2333 foreach(cell, expectedTLIs)
2335 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2337 if (tli < curFileTLI)
2338 break; /* don't bother looking at too-old TLIs */
2340 XLogFileName(xlogfname, tli, log, seg);
2342 if (InArchiveRecovery)
2344 /* Report recovery progress in PS display */
2345 snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
2347 set_ps_display(activitymsg, false);
2349 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2354 XLogFilePath(path, tli, log, seg);
2356 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2362 /* Report recovery progress in PS display */
2363 snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
2365 set_ps_display(activitymsg, false);
2369 if (errno != ENOENT) /* unexpected failure? */
2371 (errcode_for_file_access(),
2372 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2376 /* Couldn't find it. For simplicity, complain about front timeline */
2377 XLogFilePath(path, recoveryTargetTLI, log, seg);
2380 (errcode_for_file_access(),
2381 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2387 * Close the current logfile segment for writing.
2392 Assert(openLogFile >= 0);
2395 * posix_fadvise is problematic on many platforms: on older x86 Linux it
2396 * just dumps core, and there are reports of problems on PPC platforms as
2397 * well. The following is therefore disabled for the time being. We could
2398 * consider some kind of configure test to see if it's safe to use, but
2399 * since we lack hard evidence that there's any useful performance gain to
2400 * be had, spending time on that seems unprofitable for now.
2405 * WAL segment files will not be re-read in normal operation, so we advise
2406 * OS to release any cached pages. But do not do so if WAL archiving is
2407 * active, because archiver process could use the cache to read the WAL
2410 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
2411 * O_SYNC, and some platforms only have posix_fadvise().
2413 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2414 if (!XLogArchivingActive())
2415 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2417 #endif /* NOT_USED */
2419 if (close(openLogFile))
2421 (errcode_for_file_access(),
2422 errmsg("could not close log file %u, segment %u: %m",
2423 openLogId, openLogSeg)));
2428 * Attempt to retrieve the specified file from off-line archival storage.
2429 * If successful, fill "path" with its complete path (note that this will be
2430 * a temp file name that doesn't follow the normal naming convention), and
2433 * If not successful, fill "path" with the name of the normal on-line file
2434 * (which may or may not actually exist, but we'll try to use it), and return
2437 * For fixed-size files, the caller may pass the expected size as an
2438 * additional crosscheck on successful recovery. If the file size is not
2439 * known, set expectedSize = 0.
2442 RestoreArchivedFile(char *path, const char *xlogfname,
2443 const char *recovername, off_t expectedSize)
2445 char xlogpath[MAXPGPATH];
2446 char xlogRestoreCmd[MAXPGPATH];
2447 char lastRestartPointFname[MAXPGPATH];
2453 struct stat stat_buf;
2458 * When doing archive recovery, we always prefer an archived log file even
2459 * if a file of the same name exists in XLOGDIR. The reason is that the
2460 * file in XLOGDIR could be an old, un-filled or partly-filled version
2461 * that was copied and restored as part of backing up $PGDATA.
2463 * We could try to optimize this slightly by checking the local copy
2464 * lastchange timestamp against the archived copy, but we have no API to
2465 * do this, nor can we guarantee that the lastchange timestamp was
2466 * preserved correctly when we copied to archive. Our aim is robustness,
2467 * so we elect not to do this.
2469 * If we cannot obtain the log file from the archive, however, we will try
2470 * to use the XLOGDIR file if it exists. This is so that we can make use
2471 * of log segments that weren't yet transferred to the archive.
2473 * Notice that we don't actually overwrite any files when we copy back
2474 * from archive because the recoveryRestoreCommand may inadvertently
2475 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2476 * fallback to the segments remaining in current XLOGDIR later. The
2477 * copy-from-archive filename is always the same, ensuring that we don't
2478 * run out of disk space on long recoveries.
2480 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2483 * Make sure there is no existing file named recovername.
2485 if (stat(xlogpath, &stat_buf) != 0)
2487 if (errno != ENOENT)
2489 (errcode_for_file_access(),
2490 errmsg("could not stat file \"%s\": %m",
2495 if (unlink(xlogpath) != 0)
2497 (errcode_for_file_access(),
2498 errmsg("could not remove file \"%s\": %m",
2503 * Calculate the archive file cutoff point for use during log shipping
2504 * replication. All files earlier than this point can be deleted
2505 * from the archive, though there is no requirement to do so.
2507 * We initialise this with the filename of an InvalidXLogRecPtr, which
2508 * will prevent the deletion of any WAL files from the archive
2509 * because of the alphabetic sorting property of WAL filenames.
2511 * Once we have successfully located the redo pointer of the checkpoint
2512 * from which we start recovery we never request a file prior to the redo
2513 * pointer of the last restartpoint. When redo begins we know that we
2514 * have successfully located it, so there is no need for additional
2515 * status flags to signify the point when we can begin deleting WAL files
2520 XLByteToSeg(ControlFile->checkPointCopy.redo,
2521 restartLog, restartSeg);
2522 XLogFileName(lastRestartPointFname,
2523 ControlFile->checkPointCopy.ThisTimeLineID,
2524 restartLog, restartSeg);
2525 /* we shouldn't need anything earlier than last restart point */
2526 Assert(strcmp(lastRestartPointFname, xlogfname) <= 0);
2529 XLogFileName(lastRestartPointFname, 0, 0, 0);
2532 * construct the command to be executed
2534 dp = xlogRestoreCmd;
2535 endp = xlogRestoreCmd + MAXPGPATH - 1;
2538 for (sp = recoveryRestoreCommand; *sp; sp++)
2545 /* %p: relative path of target file */
2547 StrNCpy(dp, xlogpath, endp - dp);
2548 make_native_path(dp);
2552 /* %f: filename of desired file */
2554 StrNCpy(dp, xlogfname, endp - dp);
2558 /* %r: filename of last restartpoint */
2560 StrNCpy(dp, lastRestartPointFname, endp - dp);
2564 /* convert %% to a single % */
2570 /* otherwise treat the % as not special */
2585 (errmsg_internal("executing restore command \"%s\"",
2589 * Copy xlog from archival storage to XLOGDIR
2591 rc = system(xlogRestoreCmd);
2595 * command apparently succeeded, but let's make sure the file is
2596 * really there now and has the correct size.
2598 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2599 * it, but is that too strong? We could try to plow ahead with a
2600 * local copy of the file ... but the problem is that there probably
2601 * isn't one, and we'd incorrectly conclude we've reached the end of
2602 * WAL and we're done recovering ...
2604 if (stat(xlogpath, &stat_buf) == 0)
2606 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2608 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2610 (unsigned long) stat_buf.st_size,
2611 (unsigned long) expectedSize)));
2615 (errmsg("restored log file \"%s\" from archive",
2617 strcpy(path, xlogpath);
2624 if (errno != ENOENT)
2626 (errcode_for_file_access(),
2627 errmsg("could not stat file \"%s\": %m",
2633 * Remember, we rollforward UNTIL the restore fails so failure here is
2634 * just part of the process... that makes it difficult to determine
2635 * whether the restore failed because there isn't an archive to restore,
2636 * or because the administrator has specified the restore program
2637 * incorrectly. We have to assume the former.
2639 * However, if the failure was due to any sort of signal, it's best to
2640 * punt and abort recovery. (If we "return false" here, upper levels will
2641 * assume that recovery is complete and start up the database!) It's
2642 * essential to abort on child SIGINT and SIGQUIT, because per spec
2643 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2644 * those it's a good bet we should have gotten it too. Aborting on other
2645 * signals such as SIGTERM seems a good idea as well.
2647 * Per the Single Unix Spec, shells report exit status > 128 when a called
2648 * command died on a signal. Also, 126 and 127 are used to report
2649 * problems such as an unfindable command; treat those as fatal errors
2652 signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;
2654 ereport(signaled ? FATAL : DEBUG2,
2655 (errmsg("could not restore file \"%s\" from archive: return code %d",
2659 * if an archived file is not available, there might still be a version of
2660 * this file in XLOGDIR, so return that as the filename to open.
2662 * In many recovery scenarios we expect this to fail also, but if so that
2663 * just means we've reached the end of WAL.
2665 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2670 * Preallocate log files beyond the specified log endpoint.
2672 * XXX this is currently extremely conservative, since it forces only one
2673 * future log segment to exist, and even that only if we are 75% done with
2674 * the current one. This is only appropriate for very low-WAL-volume systems.
2675 * High-volume systems will be OK once they've built up a sufficient set of
2676 * recycled log segments, but the startup transient is likely to include
2677 * a lot of segment creations by foreground processes, which is not so good.
2680 PreallocXlogFiles(XLogRecPtr endptr)
2687 XLByteToPrevSeg(endptr, _logId, _logSeg);
2688 if ((endptr.xrecoff - 1) % XLogSegSize >=
2689 (uint32) (0.75 * XLogSegSize))
2691 NextLogSeg(_logId, _logSeg);
2692 use_existent = true;
2693 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2696 CheckpointStats.ckpt_segs_added++;
2701 * Recycle or remove all log files older or equal to passed log/seg#
2703 * endptr is current (or recent) end of xlog; this is used to determine
2704 * whether we want to recycle rather than delete no-longer-wanted log files.
2707 RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
2713 struct dirent *xlde;
2714 char lastoff[MAXFNAMELEN];
2715 char path[MAXPGPATH];
2718 * Initialize info about where to try to recycle to. We allow recycling
2719 * segments up to XLOGfileslop segments beyond the current XLOG location.
2721 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2722 max_advance = XLOGfileslop;
2724 xldir = AllocateDir(XLOGDIR);
2727 (errcode_for_file_access(),
2728 errmsg("could not open transaction log directory \"%s\": %m",
2731 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2733 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2736 * We ignore the timeline part of the XLOG segment identifiers in
2737 * deciding whether a segment is still needed. This ensures that we
2738 * won't prematurely remove a segment from a parent timeline. We could
2739 * probably be a little more proactive about removing segments of
2740 * non-parent timelines, but that would be a whole lot more
2743 * We use the alphanumeric sorting property of the filenames to decide
2744 * which ones are earlier than the lastoff segment.
2746 if (strlen(xlde->d_name) == 24 &&
2747 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2748 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2750 if (XLogArchiveCheckDone(xlde->d_name, true))
2752 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2755 * Before deleting the file, see if it can be recycled as a
2756 * future log segment.
2758 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2763 (errmsg("recycled transaction log file \"%s\"",
2765 CheckpointStats.ckpt_segs_recycled++;
2766 /* Needn't recheck that slot on future iterations */
2767 if (max_advance > 0)
2769 NextLogSeg(endlogId, endlogSeg);
2775 /* No need for any more future segments... */
2777 (errmsg("removing transaction log file \"%s\"",
2780 CheckpointStats.ckpt_segs_removed++;
2783 XLogArchiveCleanup(xlde->d_name);
2792 * Remove previous backup history files. This also retries creation of
2793 * .ready files for any backup history files for which XLogArchiveNotify
2797 CleanupBackupHistory(void)
2800 struct dirent *xlde;
2801 char path[MAXPGPATH];
2803 xldir = AllocateDir(XLOGDIR);
2806 (errcode_for_file_access(),
2807 errmsg("could not open transaction log directory \"%s\": %m",
2810 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2812 if (strlen(xlde->d_name) > 24 &&
2813 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2814 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2817 if (XLogArchiveCheckDone(xlde->d_name, true))
2820 (errmsg("removing transaction log backup history file \"%s\"",
2822 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2824 XLogArchiveCleanup(xlde->d_name);
2833 * Restore the backup blocks present in an XLOG record, if any.
2835 * We assume all of the record has been read into memory at *record.
2837 * Note: when a backup block is available in XLOG, we restore it
2838 * unconditionally, even if the page in the database appears newer.
2839 * This is to protect ourselves against database pages that were partially
2840 * or incorrectly written during a crash. We assume that the XLOG data
2841 * must be good because it has passed a CRC check, while the database
2842 * page might not be. This will force us to replay all subsequent
2843 * modifications of the page that appear in XLOG, rather than possibly
2844 * ignoring them as already applied, but that's not a huge drawback.
2847 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2856 blk = (char *) XLogRecGetData(record) + record->xl_len;
2857 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2859 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2862 memcpy(&bkpb, blk, sizeof(BkpBlock));
2863 blk += sizeof(BkpBlock);
2865 reln = XLogOpenRelation(bkpb.node);
2866 buffer = XLogReadBuffer(reln, bkpb.block, true);
2867 Assert(BufferIsValid(buffer));
2868 page = (Page) BufferGetPage(buffer);
2870 if (bkpb.hole_length == 0)
2872 memcpy((char *) page, blk, BLCKSZ);
2876 /* must zero-fill the hole */
2877 MemSet((char *) page, 0, BLCKSZ);
2878 memcpy((char *) page, blk, bkpb.hole_offset);
2879 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2880 blk + bkpb.hole_offset,
2881 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2884 PageSetLSN(page, lsn);
2885 PageSetTLI(page, ThisTimeLineID);
2886 MarkBufferDirty(buffer);
2887 UnlockReleaseBuffer(buffer);
2889 blk += BLCKSZ - bkpb.hole_length;
2894 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2895 * record (other than to the minimal extent of computing the amount of
2896 * data to read in) until we've checked the CRCs.
2898 * We assume all of the record has been read into memory at *record.
2901 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2905 uint32 len = record->xl_len;
2909 /* First the rmgr data */
2911 COMP_CRC32(crc, XLogRecGetData(record), len);
2913 /* Add in the backup blocks, if any */
2914 blk = (char *) XLogRecGetData(record) + len;
2915 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2919 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2922 memcpy(&bkpb, blk, sizeof(BkpBlock));
2923 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2926 (errmsg("incorrect hole size in record at %X/%X",
2927 recptr.xlogid, recptr.xrecoff)));
2930 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2931 COMP_CRC32(crc, blk, blen);
2935 /* Check that xl_tot_len agrees with our calculation */
2936 if (blk != (char *) record + record->xl_tot_len)
2939 (errmsg("incorrect total length in record at %X/%X",
2940 recptr.xlogid, recptr.xrecoff)));
2944 /* Finally include the record header */
2945 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2946 SizeOfXLogRecord - sizeof(pg_crc32));
2949 if (!EQ_CRC32(record->xl_crc, crc))
2952 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2953 recptr.xlogid, recptr.xrecoff)));
2961 * Attempt to read an XLOG record.
2963 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2964 * try to read a record just after the last one previously read.
2966 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2967 * (emode must be either PANIC or LOG.)
2969 * The record is copied into readRecordBuf, so that on successful return,
2970 * the returned record pointer always points there.
2973 ReadRecord(XLogRecPtr *RecPtr, int emode)
2977 XLogRecPtr tmpRecPtr = EndRecPtr;
2978 bool randAccess = false;
2981 uint32 targetPageOff;
2982 uint32 targetRecOff;
2983 uint32 pageHeaderSize;
2985 if (readBuf == NULL)
2988 * First time through, permanently allocate readBuf. We do it this
2989 * way, rather than just making a static array, for two reasons: (1)
2990 * no need to waste the storage in most instantiations of the backend;
2991 * (2) a static char array isn't guaranteed to have any particular
2992 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2994 readBuf = (char *) malloc(XLOG_BLCKSZ);
2995 Assert(readBuf != NULL);
3000 RecPtr = &tmpRecPtr;
3001 /* fast case if next record is on same page */
3002 if (nextRecord != NULL)
3004 record = nextRecord;
3007 /* align old recptr to next page */
3008 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
3009 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
3010 if (tmpRecPtr.xrecoff >= XLogFileSize)
3012 (tmpRecPtr.xlogid)++;
3013 tmpRecPtr.xrecoff = 0;
3015 /* We will account for page header size below */
3019 if (!XRecOffIsValid(RecPtr->xrecoff))
3021 (errmsg("invalid record offset at %X/%X",
3022 RecPtr->xlogid, RecPtr->xrecoff)));
3025 * Since we are going to a random position in WAL, forget any prior
3026 * state about what timeline we were in, and allow it to be any
3027 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
3028 * to go backwards (but we can't reset that variable right here, since
3029 * we might not change files at all).
3031 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
3032 randAccess = true; /* allow curFileTLI to go backwards too */
3035 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
3040 XLByteToSeg(*RecPtr, readId, readSeg);
3043 /* Now it's okay to reset curFileTLI if random fetch */
3047 readFile = XLogFileRead(readId, readSeg, emode);
3049 goto next_record_is_invalid;
3052 * Whenever switching to a new WAL segment, we read the first page of
3053 * the file and validate its header, even if that's not where the
3054 * target record is. This is so that we can check the additional
3055 * identification info that is present in the first page's "long"
3059 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3062 (errcode_for_file_access(),
3063 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3064 readId, readSeg, readOff)));
3065 goto next_record_is_invalid;
3067 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3068 goto next_record_is_invalid;
3071 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
3072 if (readOff != targetPageOff)
3074 readOff = targetPageOff;
3075 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
3078 (errcode_for_file_access(),
3079 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
3080 readId, readSeg, readOff)));
3081 goto next_record_is_invalid;
3083 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3086 (errcode_for_file_access(),
3087 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3088 readId, readSeg, readOff)));
3089 goto next_record_is_invalid;
3091 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3092 goto next_record_is_invalid;
3094 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3095 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
3096 if (targetRecOff == 0)
3099 * Can only get here in the continuing-from-prev-page case, because
3100 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
3101 * to skip over the new page's header.
3103 tmpRecPtr.xrecoff += pageHeaderSize;
3104 targetRecOff = pageHeaderSize;
3106 else if (targetRecOff < pageHeaderSize)
3109 (errmsg("invalid record offset at %X/%X",
3110 RecPtr->xlogid, RecPtr->xrecoff)));
3111 goto next_record_is_invalid;
3113 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3114 targetRecOff == pageHeaderSize)
3117 (errmsg("contrecord is requested by %X/%X",
3118 RecPtr->xlogid, RecPtr->xrecoff)));
3119 goto next_record_is_invalid;
3121 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3126 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
3129 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3131 if (record->xl_len != 0)
3134 (errmsg("invalid xlog switch record at %X/%X",
3135 RecPtr->xlogid, RecPtr->xrecoff)));
3136 goto next_record_is_invalid;
3139 else if (record->xl_len == 0)
3142 (errmsg("record with zero length at %X/%X",
3143 RecPtr->xlogid, RecPtr->xrecoff)));
3144 goto next_record_is_invalid;
3146 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3147 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3148 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3151 (errmsg("invalid record length at %X/%X",
3152 RecPtr->xlogid, RecPtr->xrecoff)));
3153 goto next_record_is_invalid;
3155 if (record->xl_rmid > RM_MAX_ID)
3158 (errmsg("invalid resource manager ID %u at %X/%X",
3159 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3160 goto next_record_is_invalid;
3165 * We can't exactly verify the prev-link, but surely it should be less
3166 * than the record's own address.
3168 if (!XLByteLT(record->xl_prev, *RecPtr))
3171 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3172 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3173 RecPtr->xlogid, RecPtr->xrecoff)));
3174 goto next_record_is_invalid;
3180 * Record's prev-link should exactly match our previous location. This
3181 * check guards against torn WAL pages where a stale but valid-looking
3182 * WAL record starts on a sector boundary.
3184 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3187 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3188 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3189 RecPtr->xlogid, RecPtr->xrecoff)));
3190 goto next_record_is_invalid;
3195 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3196 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3197 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3198 * enough for all "normal" records, but very large commit or abort records
3199 * might need more space.)
3201 total_len = record->xl_tot_len;
3202 if (total_len > readRecordBufSize)
3204 uint32 newSize = total_len;
3206 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3207 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3209 free(readRecordBuf);
3210 readRecordBuf = (char *) malloc(newSize);
3213 readRecordBufSize = 0;
3214 /* We treat this as a "bogus data" condition */
3216 (errmsg("record length %u at %X/%X too long",
3217 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3218 goto next_record_is_invalid;
3220 readRecordBufSize = newSize;
3223 buffer = readRecordBuf;
3225 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3226 if (total_len > len)
3228 /* Need to reassemble record */
3229 XLogContRecord *contrecord;
3230 uint32 gotlen = len;
3232 memcpy(buffer, record, len);
3233 record = (XLogRecord *) buffer;
3237 readOff += XLOG_BLCKSZ;
3238 if (readOff >= XLogSegSize)
3242 NextLogSeg(readId, readSeg);
3243 readFile = XLogFileRead(readId, readSeg, emode);
3245 goto next_record_is_invalid;
3248 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3251 (errcode_for_file_access(),
3252 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3253 readId, readSeg, readOff)));
3254 goto next_record_is_invalid;
3256 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3257 goto next_record_is_invalid;
3258 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3261 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3262 readId, readSeg, readOff)));
3263 goto next_record_is_invalid;
3265 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3266 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3267 if (contrecord->xl_rem_len == 0 ||
3268 total_len != (contrecord->xl_rem_len + gotlen))
3271 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3272 contrecord->xl_rem_len,
3273 readId, readSeg, readOff)));
3274 goto next_record_is_invalid;
3276 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3277 if (contrecord->xl_rem_len > len)
3279 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3284 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3285 contrecord->xl_rem_len);
3288 if (!RecordIsValid(record, *RecPtr, emode))
3289 goto next_record_is_invalid;
3290 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3291 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3292 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3294 nextRecord = (XLogRecord *) ((char *) contrecord +
3295 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3297 EndRecPtr.xlogid = readId;
3298 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3300 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3301 ReadRecPtr = *RecPtr;
3302 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3306 /* Record does not cross a page boundary */
3307 if (!RecordIsValid(record, *RecPtr, emode))
3308 goto next_record_is_invalid;
3309 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3310 MAXALIGN(total_len))
3311 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3312 EndRecPtr.xlogid = RecPtr->xlogid;
3313 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3314 ReadRecPtr = *RecPtr;
3315 memcpy(buffer, record, total_len);
3318 * Special processing if it's an XLOG SWITCH record
3320 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3322 /* Pretend it extends to end of segment */
3323 EndRecPtr.xrecoff += XLogSegSize - 1;
3324 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3325 nextRecord = NULL; /* definitely not on same page */
3328 * Pretend that readBuf contains the last page of the segment. This is
3329 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3332 readOff = XLogSegSize - XLOG_BLCKSZ;
3334 return (XLogRecord *) buffer;
3336 next_record_is_invalid:;
3344 * Check whether the xlog header of a page just read in looks valid.
3346 * This is just a convenience subroutine to avoid duplicated code in
3347 * ReadRecord. It's not intended for use from anywhere else.
3350 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3354 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3357 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3358 hdr->xlp_magic, readId, readSeg, readOff)));
3361 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3364 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3365 hdr->xlp_info, readId, readSeg, readOff)));
3368 if (hdr->xlp_info & XLP_LONG_HEADER)
3370 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3372 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3374 char fhdrident_str[32];
3375 char sysident_str[32];
3378 * Format sysids separately to keep platform-dependent format code
3379 * out of the translatable message string.
3381 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3382 longhdr->xlp_sysid);
3383 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3384 ControlFile->system_identifier);
3386 (errmsg("WAL file is from different system"),
3387 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3388 fhdrident_str, sysident_str)));
3391 if (longhdr->xlp_seg_size != XLogSegSize)
3394 (errmsg("WAL file is from different system"),
3395 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3398 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3401 (errmsg("WAL file is from different system"),
3402 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3406 else if (readOff == 0)
3408 /* hmm, first page of file doesn't have a long header? */
3410 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3411 hdr->xlp_info, readId, readSeg, readOff)));
3415 recaddr.xlogid = readId;
3416 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3417 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3420 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3421 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3422 readId, readSeg, readOff)));
3427 * Check page TLI is one of the expected values.
3429 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3432 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3434 readId, readSeg, readOff)));
3439 * Since child timelines are always assigned a TLI greater than their
3440 * immediate parent's TLI, we should never see TLI go backwards across
3441 * successive pages of a consistent WAL sequence.
3443 * Of course this check should only be applied when advancing sequentially
3444 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3445 * going to a random page.
3447 if (hdr->xlp_tli < lastPageTLI)
3450 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3451 hdr->xlp_tli, lastPageTLI,
3452 readId, readSeg, readOff)));
3455 lastPageTLI = hdr->xlp_tli;
3460 * Try to read a timeline's history file.
3462 * If successful, return the list of component TLIs (the given TLI followed by
3463 * its ancestor TLIs). If we can't find the history file, assume that the
3464 * timeline has no parents, and return a list of just the specified timeline
3468 readTimeLineHistory(TimeLineID targetTLI)
3471 char path[MAXPGPATH];
3472 char histfname[MAXFNAMELEN];
3473 char fline[MAXPGPATH];
3476 if (InArchiveRecovery)
3478 TLHistoryFileName(histfname, targetTLI);
3479 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3482 TLHistoryFilePath(path, targetTLI);
3484 fd = AllocateFile(path, "r");
3487 if (errno != ENOENT)
3489 (errcode_for_file_access(),
3490 errmsg("could not open file \"%s\": %m", path)));
3491 /* Not there, so assume no parents */
3492 return list_make1_int((int) targetTLI);
3500 while (fgets(fline, sizeof(fline), fd) != NULL)
3502 /* skip leading whitespace and check for # comment */
3507 for (ptr = fline; *ptr; ptr++)
3509 if (!isspace((unsigned char) *ptr))
3512 if (*ptr == '\0' || *ptr == '#')
3515 /* expect a numeric timeline ID as first field of line */
3516 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3519 (errmsg("syntax error in history file: %s", fline),
3520 errhint("Expected a numeric timeline ID.")));
3523 tli <= (TimeLineID) linitial_int(result))
3525 (errmsg("invalid data in history file: %s", fline),
3526 errhint("Timeline IDs must be in increasing sequence.")));
3528 /* Build list with newest item first */
3529 result = lcons_int((int) tli, result);
3531 /* we ignore the remainder of each line */
3537 targetTLI <= (TimeLineID) linitial_int(result))
3539 (errmsg("invalid data in history file \"%s\"", path),
3540 errhint("Timeline IDs must be less than child timeline's ID.")));
3542 result = lcons_int((int) targetTLI, result);
3545 (errmsg_internal("history of timeline %u is %s",
3546 targetTLI, nodeToString(result))));
3552 * Probe whether a timeline history file exists for the given timeline ID
3555 existsTimeLineHistory(TimeLineID probeTLI)
3557 char path[MAXPGPATH];
3558 char histfname[MAXFNAMELEN];
3561 if (InArchiveRecovery)
3563 TLHistoryFileName(histfname, probeTLI);
3564 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3567 TLHistoryFilePath(path, probeTLI);
3569 fd = AllocateFile(path, "r");
3577 if (errno != ENOENT)
3579 (errcode_for_file_access(),
3580 errmsg("could not open file \"%s\": %m", path)));
3586 * Find the newest existing timeline, assuming that startTLI exists.
3588 * Note: while this is somewhat heuristic, it does positively guarantee
3589 * that (result + 1) is not a known timeline, and therefore it should
3590 * be safe to assign that ID to a new timeline.
3593 findNewestTimeLine(TimeLineID startTLI)
3595 TimeLineID newestTLI;
3596 TimeLineID probeTLI;
3599 * The algorithm is just to probe for the existence of timeline history
3600 * files. XXX is it useful to allow gaps in the sequence?
3602 newestTLI = startTLI;
3604 for (probeTLI = startTLI + 1;; probeTLI++)
3606 if (existsTimeLineHistory(probeTLI))
3608 newestTLI = probeTLI; /* probeTLI exists */
3612 /* doesn't exist, assume we're done */
3621 * Create a new timeline history file.
3623 * newTLI: ID of the new timeline
3624 * parentTLI: ID of its immediate parent
3625 * endTLI et al: ID of the last used WAL file, for annotation purposes
3627 * Currently this is only used during recovery, and so there are no locking
3628 * considerations. But we should be just as tense as XLogFileInit to avoid
3629 * emplacing a bogus file.
3632 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3633 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3635 char path[MAXPGPATH];
3636 char tmppath[MAXPGPATH];
3637 char histfname[MAXFNAMELEN];
3638 char xlogfname[MAXFNAMELEN];
3639 char buffer[BLCKSZ];
3644 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3647 * Write into a temp file name.
3649 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3653 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3654 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3658 (errcode_for_file_access(),
3659 errmsg("could not create file \"%s\": %m", tmppath)));
3662 * If a history file exists for the parent, copy it verbatim
3664 if (InArchiveRecovery)
3666 TLHistoryFileName(histfname, parentTLI);
3667 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3670 TLHistoryFilePath(path, parentTLI);
3672 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3675 if (errno != ENOENT)
3677 (errcode_for_file_access(),
3678 errmsg("could not open file \"%s\": %m", path)));
3679 /* Not there, so assume parent has no parents */
3686 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3687 if (nbytes < 0 || errno != 0)
3689 (errcode_for_file_access(),
3690 errmsg("could not read file \"%s\": %m", path)));
3694 if ((int) write(fd, buffer, nbytes) != nbytes)
3696 int save_errno = errno;
3699 * If we fail to make the file, delete it to release disk
3705 * if write didn't set errno, assume problem is no disk space
3707 errno = save_errno ? save_errno : ENOSPC;
3710 (errcode_for_file_access(),
3711 errmsg("could not write to file \"%s\": %m", tmppath)));
3718 * Append one line with the details of this timeline split.
3720 * If we did have a parent file, insert an extra newline just in case the
3721 * parent file failed to end with one.
3723 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3725 snprintf(buffer, sizeof(buffer),
3726 "%s%u\t%s\t%s transaction %u at %s\n",
3727 (srcfd < 0) ? "" : "\n",
3730 recoveryStopAfter ? "after" : "before",
3732 timestamptz_to_str(recoveryStopTime));
3734 nbytes = strlen(buffer);
3736 if ((int) write(fd, buffer, nbytes) != nbytes)
3738 int save_errno = errno;
3741 * If we fail to make the file, delete it to release disk space
3744 /* if write didn't set errno, assume problem is no disk space */
3745 errno = save_errno ? save_errno : ENOSPC;
3748 (errcode_for_file_access(),
3749 errmsg("could not write to file \"%s\": %m", tmppath)));
3752 if (pg_fsync(fd) != 0)
3754 (errcode_for_file_access(),
3755 errmsg("could not fsync file \"%s\": %m", tmppath)));
3759 (errcode_for_file_access(),
3760 errmsg("could not close file \"%s\": %m", tmppath)));
3764 * Now move the completed history file into place with its final name.
3766 TLHistoryFilePath(path, newTLI);
3769 * Prefer link() to rename() here just to be really sure that we don't
3770 * overwrite an existing logfile. However, there shouldn't be one, so
3771 * rename() is an acceptable substitute except for the truly paranoid.
3773 #if HAVE_WORKING_LINK
3774 if (link(tmppath, path) < 0)
3776 (errcode_for_file_access(),
3777 errmsg("could not link file \"%s\" to \"%s\": %m",
3781 if (rename(tmppath, path) < 0)
3783 (errcode_for_file_access(),
3784 errmsg("could not rename file \"%s\" to \"%s\": %m",
3788 /* The history file can be archived immediately. */
3789 TLHistoryFileName(histfname, newTLI);
3790 XLogArchiveNotify(histfname);
3794 * I/O routines for pg_control
3796 * *ControlFile is a buffer in shared memory that holds an image of the
3797 * contents of pg_control. WriteControlFile() initializes pg_control
3798 * given a preloaded buffer, ReadControlFile() loads the buffer from
3799 * the pg_control file (during postmaster or standalone-backend startup),
3800 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3802 * For simplicity, WriteControlFile() initializes the fields of pg_control
3803 * that are related to checking backend/database compatibility, and
3804 * ReadControlFile() verifies they are correct. We could split out the
3805 * I/O and compatibility-check functions, but there seems no need currently.
3808 WriteControlFile(void)
3811 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3815 * Initialize version and compatibility-check fields
3817 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3818 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3820 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3821 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3823 ControlFile->blcksz = BLCKSZ;
3824 ControlFile->relseg_size = RELSEG_SIZE;
3825 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3826 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3828 ControlFile->nameDataLen = NAMEDATALEN;
3829 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3831 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
3833 #ifdef HAVE_INT64_TIMESTAMP
3834 ControlFile->enableIntTimes = true;
3836 ControlFile->enableIntTimes = false;
3838 ControlFile->float4ByVal = FLOAT4PASSBYVAL;
3839 ControlFile->float8ByVal = FLOAT8PASSBYVAL;
3841 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3842 localeptr = setlocale(LC_COLLATE, NULL);
3845 (errmsg("invalid LC_COLLATE setting")));
3846 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3847 localeptr = setlocale(LC_CTYPE, NULL);
3850 (errmsg("invalid LC_CTYPE setting")));
3851 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3853 /* Contents are protected with a CRC */
3854 INIT_CRC32(ControlFile->crc);
3855 COMP_CRC32(ControlFile->crc,
3856 (char *) ControlFile,
3857 offsetof(ControlFileData, crc));
3858 FIN_CRC32(ControlFile->crc);
3861 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3862 * excess over sizeof(ControlFileData). This reduces the odds of
3863 * premature-EOF errors when reading pg_control. We'll still fail when we
3864 * check the contents of the file, but hopefully with a more specific
3865 * error than "couldn't read pg_control".
3867 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3868 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3870 memset(buffer, 0, PG_CONTROL_SIZE);
3871 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3873 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3874 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3878 (errcode_for_file_access(),
3879 errmsg("could not create control file \"%s\": %m",
3880 XLOG_CONTROL_FILE)));
3883 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3885 /* if write didn't set errno, assume problem is no disk space */
3889 (errcode_for_file_access(),
3890 errmsg("could not write to control file: %m")));
3893 if (pg_fsync(fd) != 0)
3895 (errcode_for_file_access(),
3896 errmsg("could not fsync control file: %m")));
3900 (errcode_for_file_access(),
3901 errmsg("could not close control file: %m")));
3905 ReadControlFile(void)
3913 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3918 (errcode_for_file_access(),
3919 errmsg("could not open control file \"%s\": %m",
3920 XLOG_CONTROL_FILE)));
3922 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3924 (errcode_for_file_access(),
3925 errmsg("could not read from control file: %m")));
3930 * Check for expected pg_control format version. If this is wrong, the
3931 * CRC check will likely fail because we'll be checking the wrong number
3932 * of bytes. Complaining about wrong version will probably be more
3933 * enlightening than complaining about wrong CRC.
3936 if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
3938 (errmsg("database files are incompatible with server"),
3939 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
3940 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
3941 ControlFile->pg_control_version, ControlFile->pg_control_version,
3942 PG_CONTROL_VERSION, PG_CONTROL_VERSION),
3943 errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
3945 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3947 (errmsg("database files are incompatible with server"),
3948 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3949 " but the server was compiled with PG_CONTROL_VERSION %d.",
3950 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3951 errhint("It looks like you need to initdb.")));
3953 /* Now check the CRC. */
3956 (char *) ControlFile,
3957 offsetof(ControlFileData, crc));
3960 if (!EQ_CRC32(crc, ControlFile->crc))
3962 (errmsg("incorrect checksum in control file")));
3965 * Do compatibility checking immediately. We do this here for 2 reasons:
3967 * (1) if the database isn't compatible with the backend executable, we
3968 * want to abort before we can possibly do any damage;
3970 * (2) this code is executed in the postmaster, so the setlocale() will
3971 * propagate to forked backends, which aren't going to read this file for
3972 * themselves. (These locale settings are considered critical
3973 * compatibility items because they can affect sort order of indexes.)
3975 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3977 (errmsg("database files are incompatible with server"),
3978 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3979 " but the server was compiled with CATALOG_VERSION_NO %d.",
3980 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3981 errhint("It looks like you need to initdb.")));
3982 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3984 (errmsg("database files are incompatible with server"),
3985 errdetail("The database cluster was initialized with MAXALIGN %d,"
3986 " but the server was compiled with MAXALIGN %d.",
3987 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3988 errhint("It looks like you need to initdb.")));
3989 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3991 (errmsg("database files are incompatible with server"),
3992 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3993 errhint("It looks like you need to initdb.")));
3994 if (ControlFile->blcksz != BLCKSZ)
3996 (errmsg("database files are incompatible with server"),
3997 errdetail("The database cluster was initialized with BLCKSZ %d,"
3998 " but the server was compiled with BLCKSZ %d.",
3999 ControlFile->blcksz, BLCKSZ),
4000 errhint("It looks like you need to recompile or initdb.")));
4001 if (ControlFile->relseg_size != RELSEG_SIZE)
4003 (errmsg("database files are incompatible with server"),
4004 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
4005 " but the server was compiled with RELSEG_SIZE %d.",
4006 ControlFile->relseg_size, RELSEG_SIZE),
4007 errhint("It looks like you need to recompile or initdb.")));
4008 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4010 (errmsg("database files are incompatible with server"),
4011 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
4012 " but the server was compiled with XLOG_BLCKSZ %d.",
4013 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4014 errhint("It looks like you need to recompile or initdb.")));
4015 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
4017 (errmsg("database files are incompatible with server"),
4018 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
4019 " but the server was compiled with XLOG_SEG_SIZE %d.",
4020 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
4021 errhint("It looks like you need to recompile or initdb.")));
4022 if (ControlFile->nameDataLen != NAMEDATALEN)
4024 (errmsg("database files are incompatible with server"),
4025 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
4026 " but the server was compiled with NAMEDATALEN %d.",
4027 ControlFile->nameDataLen, NAMEDATALEN),
4028 errhint("It looks like you need to recompile or initdb.")));
4029 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4031 (errmsg("database files are incompatible with server"),
4032 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
4033 " but the server was compiled with INDEX_MAX_KEYS %d.",
4034 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
4035 errhint("It looks like you need to recompile or initdb.")));
4036 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
4038 (errmsg("database files are incompatible with server"),
4039 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
4040 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
4041 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4042 errhint("It looks like you need to recompile or initdb.")));
4044 #ifdef HAVE_INT64_TIMESTAMP
4045 if (ControlFile->enableIntTimes != true)
4047 (errmsg("database files are incompatible with server"),
4048 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
4049 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
4050 errhint("It looks like you need to recompile or initdb.")));
4052 if (ControlFile->enableIntTimes != false)
4054 (errmsg("database files are incompatible with server"),
4055 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
4056 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
4057 errhint("It looks like you need to recompile or initdb.")));
4060 #ifdef USE_FLOAT4_BYVAL
4061 if (ControlFile->float4ByVal != true)
4063 (errmsg("database files are incompatible with server"),
4064 errdetail("The database cluster was initialized without USE_FLOAT4_BYVAL"
4065 " but the server was compiled with USE_FLOAT4_BYVAL."),
4066 errhint("It looks like you need to recompile or initdb.")));
4068 if (ControlFile->float4ByVal != false)
4070 (errmsg("database files are incompatible with server"),
4071 errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
4072 " but the server was compiled without USE_FLOAT4_BYVAL."),
4073 errhint("It looks like you need to recompile or initdb.")));
4076 #ifdef USE_FLOAT8_BYVAL
4077 if (ControlFile->float8ByVal != true)
4079 (errmsg("database files are incompatible with server"),
4080 errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4081 " but the server was compiled with USE_FLOAT8_BYVAL."),
4082 errhint("It looks like you need to recompile or initdb.")));
4084 if (ControlFile->float8ByVal != false)
4086 (errmsg("database files are incompatible with server"),
4087 errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4088 " but the server was compiled without USE_FLOAT8_BYVAL."),
4089 errhint("It looks like you need to recompile or initdb.")));
4092 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
4094 (errmsg("database files are incompatible with server"),
4095 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
4096 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
4097 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
4098 errhint("It looks like you need to recompile or initdb.")));
4099 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
4101 (errmsg("database files are incompatible with operating system"),
4102 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
4103 " which is not recognized by setlocale().",
4104 ControlFile->lc_collate),
4105 errhint("It looks like you need to initdb or install locale support.")));
4106 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
4108 (errmsg("database files are incompatible with operating system"),
4109 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
4110 " which is not recognized by setlocale().",
4111 ControlFile->lc_ctype),
4112 errhint("It looks like you need to initdb or install locale support.")));
4114 /* Make the fixed locale settings visible as GUC variables, too */
4115 SetConfigOption("lc_collate", ControlFile->lc_collate,
4116 PGC_INTERNAL, PGC_S_OVERRIDE);
4117 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
4118 PGC_INTERNAL, PGC_S_OVERRIDE);
4122 UpdateControlFile(void)
4126 INIT_CRC32(ControlFile->crc);
4127 COMP_CRC32(ControlFile->crc,
4128 (char *) ControlFile,
4129 offsetof(ControlFileData, crc));
4130 FIN_CRC32(ControlFile->crc);
4132 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4137 (errcode_for_file_access(),
4138 errmsg("could not open control file \"%s\": %m",
4139 XLOG_CONTROL_FILE)));
4142 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4144 /* if write didn't set errno, assume problem is no disk space */
4148 (errcode_for_file_access(),
4149 errmsg("could not write to control file: %m")));
4152 if (pg_fsync(fd) != 0)
4154 (errcode_for_file_access(),
4155 errmsg("could not fsync control file: %m")));
4159 (errcode_for_file_access(),
4160 errmsg("could not close control file: %m")));
4164 * Initialization of shared memory for XLOG
4172 size = sizeof(XLogCtlData);
4173 /* xlblocks array */
4174 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
4175 /* extra alignment padding for XLOG I/O buffers */
4176 size = add_size(size, ALIGNOF_XLOG_BUFFER);
4177 /* and the buffers themselves */
4178 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4181 * Note: we don't count ControlFileData, it comes out of the "slop factor"
4182 * added by CreateSharedMemoryAndSemaphores. This lets us use this
4183 * routine again below to compute the actual allocation size.
4196 ControlFile = (ControlFileData *)
4197 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4198 XLogCtl = (XLogCtlData *)
4199 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4201 if (foundCFile || foundXLog)
4203 /* both should be present or neither */
4204 Assert(foundCFile && foundXLog);
4208 memset(XLogCtl, 0, sizeof(XLogCtlData));
4211 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4212 * multiple of the alignment for same, so no extra alignment padding is
4215 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4216 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4217 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4218 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4221 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4223 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4224 XLogCtl->pages = allocptr;
4225 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4228 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4229 * in additional info.)
4231 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4232 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4233 SpinLockInit(&XLogCtl->info_lck);
4236 * If we are not in bootstrap mode, pg_control should already exist. Read
4237 * and validate it immediately (see comments in ReadControlFile() for the
4240 if (!IsBootstrapProcessingMode())
4245 * This func must be called ONCE on system install. It creates pg_control
4246 * and the initial XLOG segment.
4251 CheckPoint checkPoint;
4253 XLogPageHeader page;
4254 XLogLongPageHeader longpage;
4257 uint64 sysidentifier;
4262 * Select a hopefully-unique system identifier code for this installation.
4263 * We use the result of gettimeofday(), including the fractional seconds
4264 * field, as being about as unique as we can easily get. (Think not to
4265 * use random(), since it hasn't been seeded and there's no portable way
4266 * to seed it other than the system clock value...) The upper half of the
4267 * uint64 value is just the tv_sec part, while the lower half is the XOR
4268 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4269 * unnecessarily if "uint64" is really only 32 bits wide. A person
4270 * knowing this encoding can determine the initialization time of the
4271 * installation, which could perhaps be useful sometimes.
4273 gettimeofday(&tv, NULL);
4274 sysidentifier = ((uint64) tv.tv_sec) << 32;
4275 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4277 /* First timeline ID is always 1 */
4280 /* page buffer must be aligned suitably for O_DIRECT */
4281 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4282 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4283 memset(page, 0, XLOG_BLCKSZ);
4285 /* Set up information for the initial checkpoint record */
4286 checkPoint.redo.xlogid = 0;
4287 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4288 checkPoint.ThisTimeLineID = ThisTimeLineID;
4289 checkPoint.nextXidEpoch = 0;
4290 checkPoint.nextXid = FirstNormalTransactionId;
4291 checkPoint.nextOid = FirstBootstrapObjectId;
4292 checkPoint.nextMulti = FirstMultiXactId;
4293 checkPoint.nextMultiOffset = 0;
4294 checkPoint.time = (pg_time_t) time(NULL);
4296 ShmemVariableCache->nextXid = checkPoint.nextXid;
4297 ShmemVariableCache->nextOid = checkPoint.nextOid;
4298 ShmemVariableCache->oidCount = 0;
4299 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4301 /* Set up the XLOG page header */
4302 page->xlp_magic = XLOG_PAGE_MAGIC;
4303 page->xlp_info = XLP_LONG_HEADER;
4304 page->xlp_tli = ThisTimeLineID;
4305 page->xlp_pageaddr.xlogid = 0;
4306 page->xlp_pageaddr.xrecoff = 0;
4307 longpage = (XLogLongPageHeader) page;
4308 longpage->xlp_sysid = sysidentifier;
4309 longpage->xlp_seg_size = XLogSegSize;
4310 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4312 /* Insert the initial checkpoint record */
4313 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4314 record->xl_prev.xlogid = 0;
4315 record->xl_prev.xrecoff = 0;
4316 record->xl_xid = InvalidTransactionId;
4317 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4318 record->xl_len = sizeof(checkPoint);
4319 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4320 record->xl_rmid = RM_XLOG_ID;
4321 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4324 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4325 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4326 SizeOfXLogRecord - sizeof(pg_crc32));
4328 record->xl_crc = crc;
4330 /* Create first XLOG segment file */
4331 use_existent = false;
4332 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4334 /* Write the first page with the initial record */
4336 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4338 /* if write didn't set errno, assume problem is no disk space */
4342 (errcode_for_file_access(),
4343 errmsg("could not write bootstrap transaction log file: %m")));
4346 if (pg_fsync(openLogFile) != 0)
4348 (errcode_for_file_access(),
4349 errmsg("could not fsync bootstrap transaction log file: %m")));
4351 if (close(openLogFile))
4353 (errcode_for_file_access(),
4354 errmsg("could not close bootstrap transaction log file: %m")));
4358 /* Now create pg_control */
4360 memset(ControlFile, 0, sizeof(ControlFileData));
4361 /* Initialize pg_control status fields */
4362 ControlFile->system_identifier = sysidentifier;
4363 ControlFile->state = DB_SHUTDOWNED;
4364 ControlFile->time = checkPoint.time;
4365 ControlFile->checkPoint = checkPoint.redo;
4366 ControlFile->checkPointCopy = checkPoint;
4367 /* some additional ControlFile fields are set in WriteControlFile() */
4371 /* Bootstrap the commit log, too */
4373 BootStrapSUBTRANS();
4374 BootStrapMultiXact();
4380 str_time(pg_time_t tnow)
4382 static char buf[128];
4384 pg_strftime(buf, sizeof(buf),
4385 "%Y-%m-%d %H:%M:%S %Z",
4386 pg_localtime(&tnow, log_timezone));
4392 * See if there is a recovery command file (recovery.conf), and if so
4393 * read in parameters for archive recovery.
4395 * XXX longer term intention is to expand this to
4396 * cater for additional parameters and controls
4397 * possibly use a flex lexer similar to the GUC one
4400 readRecoveryCommandFile(void)
4403 char cmdline[MAXPGPATH];
4404 TimeLineID rtli = 0;
4405 bool rtliGiven = false;
4406 bool syntaxError = false;
4408 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4411 if (errno == ENOENT)
4412 return; /* not there, so no archive recovery */
4414 (errcode_for_file_access(),
4415 errmsg("could not open recovery command file \"%s\": %m",
4416 RECOVERY_COMMAND_FILE)));
4420 (errmsg("starting archive recovery")));
4425 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4427 /* skip leading whitespace and check for # comment */
4432 for (ptr = cmdline; *ptr; ptr++)
4434 if (!isspace((unsigned char) *ptr))
4437 if (*ptr == '\0' || *ptr == '#')
4440 /* identify the quoted parameter value */
4441 tok1 = strtok(ptr, "'");
4447 tok2 = strtok(NULL, "'");
4453 /* reparse to get just the parameter name */
4454 tok1 = strtok(ptr, " \t=");
4461 if (strcmp(tok1, "restore_command") == 0)
4463 recoveryRestoreCommand = pstrdup(tok2);
4465 (errmsg("restore_command = '%s'",
4466 recoveryRestoreCommand)));
4468 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4471 if (strcmp(tok2, "latest") == 0)
4476 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4477 if (errno == EINVAL || errno == ERANGE)
4479 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4484 (errmsg("recovery_target_timeline = %u", rtli)));
4487 (errmsg("recovery_target_timeline = latest")));
4489 else if (strcmp(tok1, "recovery_target_xid") == 0)
4492 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4493 if (errno == EINVAL || errno == ERANGE)
4495 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4498 (errmsg("recovery_target_xid = %u",
4499 recoveryTargetXid)));
4500 recoveryTarget = true;
4501 recoveryTargetExact = true;
4503 else if (strcmp(tok1, "recovery_target_time") == 0)
4506 * if recovery_target_xid specified, then this overrides
4507 * recovery_target_time
4509 if (recoveryTargetExact)
4511 recoveryTarget = true;
4512 recoveryTargetExact = false;
4515 * Convert the time string given by the user to TimestampTz form.
4517 recoveryTargetTime =
4518 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
4519 CStringGetDatum(tok2),
4520 ObjectIdGetDatum(InvalidOid),
4521 Int32GetDatum(-1)));
4523 (errmsg("recovery_target_time = '%s'",
4524 timestamptz_to_str(recoveryTargetTime))));
4526 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4529 * does nothing if a recovery_target is not also set
4531 if (strcmp(tok2, "true") == 0)
4532 recoveryTargetInclusive = true;
4535 recoveryTargetInclusive = false;
4539 (errmsg("recovery_target_inclusive = %s", tok2)));
4541 else if (strcmp(tok1, "log_restartpoints") == 0)
4544 * does nothing if a recovery_target is not also set
4546 if (strcmp(tok2, "true") == 0)
4547 recoveryLogRestartpoints = true;
4550 recoveryLogRestartpoints = false;
4554 (errmsg("log_restartpoints = %s", tok2)));
4558 (errmsg("unrecognized recovery parameter \"%s\"",
4566 (errmsg("syntax error in recovery command file: %s",
4568 errhint("Lines should have the format parameter = 'value'.")));
4570 /* Check that required parameters were supplied */
4571 if (recoveryRestoreCommand == NULL)
4573 (errmsg("recovery command file \"%s\" did not specify restore_command",
4574 RECOVERY_COMMAND_FILE)));
4576 /* Enable fetching from archive recovery area */
4577 InArchiveRecovery = true;
4580 * If user specified recovery_target_timeline, validate it or compute the
4581 * "latest" value. We can't do this until after we've gotten the restore
4582 * command and set InArchiveRecovery, because we need to fetch timeline
4583 * history files from the archive.
4589 /* Timeline 1 does not have a history file, all else should */
4590 if (rtli != 1 && !existsTimeLineHistory(rtli))
4592 (errmsg("recovery target timeline %u does not exist",
4594 recoveryTargetTLI = rtli;
4598 /* We start the "latest" search from pg_control's timeline */
4599 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4605 * Exit archive-recovery state
4608 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4610 char recoveryPath[MAXPGPATH];
4611 char xlogpath[MAXPGPATH];
4614 * We are no longer in archive recovery state.
4616 InArchiveRecovery = false;
4619 * We should have the ending log segment currently open. Verify, and then
4620 * close it (to avoid problems on Windows with trying to rename or delete
4623 Assert(readFile >= 0);
4624 Assert(readId == endLogId);
4625 Assert(readSeg == endLogSeg);
4631 * If the segment was fetched from archival storage, we want to replace
4632 * the existing xlog segment (if any) with the archival version. This is
4633 * because whatever is in XLOGDIR is very possibly older than what we have
4634 * from the archives, since it could have come from restoring a PGDATA
4635 * backup. In any case, the archival version certainly is more
4636 * descriptive of what our current database state is, because that is what
4639 * Note that if we are establishing a new timeline, ThisTimeLineID is
4640 * already set to the new value, and so we will create a new file instead
4641 * of overwriting any existing file. (This is, in fact, always the case
4644 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4645 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4647 if (restoredFromArchive)
4650 (errmsg_internal("moving last restored xlog to \"%s\"",
4652 unlink(xlogpath); /* might or might not exist */
4653 if (rename(recoveryPath, xlogpath) != 0)
4655 (errcode_for_file_access(),
4656 errmsg("could not rename file \"%s\" to \"%s\": %m",
4657 recoveryPath, xlogpath)));
4658 /* XXX might we need to fix permissions on the file? */
4663 * If the latest segment is not archival, but there's still a
4664 * RECOVERYXLOG laying about, get rid of it.
4666 unlink(recoveryPath); /* ignore any error */
4669 * If we are establishing a new timeline, we have to copy data from
4670 * the last WAL segment of the old timeline to create a starting WAL
4671 * segment for the new timeline.
4673 if (endTLI != ThisTimeLineID)
4674 XLogFileCopy(endLogId, endLogSeg,
4675 endTLI, endLogId, endLogSeg);
4679 * Let's just make real sure there are not .ready or .done flags posted
4680 * for the new segment.
4682 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4683 XLogArchiveCleanup(xlogpath);
4685 /* Get rid of any remaining recovered timeline-history file, too */
4686 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4687 unlink(recoveryPath); /* ignore any error */
4690 * Rename the config file out of the way, so that we don't accidentally
4691 * re-enter archive recovery mode in a subsequent crash.
4693 unlink(RECOVERY_COMMAND_DONE);
4694 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4696 (errcode_for_file_access(),
4697 errmsg("could not rename file \"%s\" to \"%s\": %m",
4698 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4701 (errmsg("archive recovery complete")));
4705 * For point-in-time recovery, this function decides whether we want to
4706 * stop applying the XLOG at or after the current record.
4708 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4709 * *includeThis is set TRUE if we should apply this record before stopping.
4710 * Also, some information is saved in recoveryStopXid et al for use in
4711 * annotating the new timeline's history file.
4714 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4718 TimestampTz recordXtime;
4720 /* We only consider stopping at COMMIT or ABORT records */
4721 if (record->xl_rmid != RM_XACT_ID)
4723 record_info = record->xl_info & ~XLR_INFO_MASK;
4724 if (record_info == XLOG_XACT_COMMIT)
4726 xl_xact_commit *recordXactCommitData;
4728 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4729 recordXtime = recordXactCommitData->xact_time;
4731 else if (record_info == XLOG_XACT_ABORT)
4733 xl_xact_abort *recordXactAbortData;
4735 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4736 recordXtime = recordXactAbortData->xact_time;
4741 /* Remember the most recent COMMIT/ABORT time for logging purposes */
4742 recoveryLastXTime = recordXtime;
4744 /* Do we have a PITR target at all? */
4745 if (!recoveryTarget)
4748 if (recoveryTargetExact)
4751 * there can be only one transaction end record with this exact
4754 * when testing for an xid, we MUST test for equality only, since
4755 * transactions are numbered in the order they start, not the order
4756 * they complete. A higher numbered xid will complete before you about
4757 * 50% of the time...
4759 stopsHere = (record->xl_xid == recoveryTargetXid);
4761 *includeThis = recoveryTargetInclusive;
4766 * there can be many transactions that share the same commit time, so
4767 * we stop after the last one, if we are inclusive, or stop at the
4768 * first one if we are exclusive
4770 if (recoveryTargetInclusive)
4771 stopsHere = (recordXtime > recoveryTargetTime);
4773 stopsHere = (recordXtime >= recoveryTargetTime);
4775 *includeThis = false;
4780 recoveryStopXid = record->xl_xid;
4781 recoveryStopTime = recordXtime;
4782 recoveryStopAfter = *includeThis;
4784 if (record_info == XLOG_XACT_COMMIT)
4786 if (recoveryStopAfter)
4788 (errmsg("recovery stopping after commit of transaction %u, time %s",
4790 timestamptz_to_str(recoveryStopTime))));
4793 (errmsg("recovery stopping before commit of transaction %u, time %s",
4795 timestamptz_to_str(recoveryStopTime))));
4799 if (recoveryStopAfter)
4801 (errmsg("recovery stopping after abort of transaction %u, time %s",
4803 timestamptz_to_str(recoveryStopTime))));
4806 (errmsg("recovery stopping before abort of transaction %u, time %s",
4808 timestamptz_to_str(recoveryStopTime))));
4816 * This must be called ONCE during postmaster or standalone-backend startup
4821 XLogCtlInsert *Insert;
4822 CheckPoint checkPoint;
4824 bool reachedStopPoint = false;
4825 bool haveBackupLabel = false;
4835 TransactionId oldestActiveXID;
4838 * Read control file and check XLOG status looks valid.
4840 * Note: in most control paths, *ControlFile is already valid and we need
4841 * not do ReadControlFile() here, but might as well do it to be sure.
4845 if (ControlFile->state < DB_SHUTDOWNED ||
4846 ControlFile->state > DB_IN_PRODUCTION ||
4847 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4849 (errmsg("control file contains invalid data")));
4851 if (ControlFile->state == DB_SHUTDOWNED)
4853 (errmsg("database system was shut down at %s",
4854 str_time(ControlFile->time))));
4855 else if (ControlFile->state == DB_SHUTDOWNING)
4857 (errmsg("database system shutdown was interrupted; last known up at %s",
4858 str_time(ControlFile->time))));
4859 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4861 (errmsg("database system was interrupted while in recovery at %s",
4862 str_time(ControlFile->time)),
4863 errhint("This probably means that some data is corrupted and"
4864 " you will have to use the last backup for recovery.")));
4865 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4867 (errmsg("database system was interrupted while in recovery at log time %s",
4868 str_time(ControlFile->checkPointCopy.time)),
4869 errhint("If this has occurred more than once some data might be corrupted"
4870 " and you might need to choose an earlier recovery target.")));
4871 else if (ControlFile->state == DB_IN_PRODUCTION)
4873 (errmsg("database system was interrupted; last known up at %s",
4874 str_time(ControlFile->time))));
4876 /* This is just to allow attaching to startup process with a debugger */
4877 #ifdef XLOG_REPLAY_DELAY
4878 if (ControlFile->state != DB_SHUTDOWNED)
4879 pg_usleep(60000000L);
4883 * Initialize on the assumption we want to recover to the same timeline
4884 * that's active according to pg_control.
4886 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4889 * Check for recovery control file, and if so set up state for offline
4892 readRecoveryCommandFile();
4894 /* Now we can determine the list of expected TLIs */
4895 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4898 * If pg_control's timeline is not in expectedTLIs, then we cannot
4899 * proceed: the backup is not part of the history of the requested
4902 if (!list_member_int(expectedTLIs,
4903 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4905 (errmsg("requested timeline %u is not a child of database system timeline %u",
4907 ControlFile->checkPointCopy.ThisTimeLineID)));
4909 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4912 * When a backup_label file is present, we want to roll forward from
4913 * the checkpoint it identifies, rather than using pg_control.
4915 record = ReadCheckpointRecord(checkPointLoc, 0);
4919 (errmsg("checkpoint record is at %X/%X",
4920 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4921 InRecovery = true; /* force recovery even if SHUTDOWNED */
4926 (errmsg("could not locate required checkpoint record"),
4927 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4929 /* set flag to delete it later */
4930 haveBackupLabel = true;
4935 * Get the last valid checkpoint record. If the latest one according
4936 * to pg_control is broken, try the next-to-last one.
4938 checkPointLoc = ControlFile->checkPoint;
4939 record = ReadCheckpointRecord(checkPointLoc, 1);
4943 (errmsg("checkpoint record is at %X/%X",
4944 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4948 checkPointLoc = ControlFile->prevCheckPoint;
4949 record = ReadCheckpointRecord(checkPointLoc, 2);
4953 (errmsg("using previous checkpoint record at %X/%X",
4954 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4955 InRecovery = true; /* force recovery even if SHUTDOWNED */
4959 (errmsg("could not locate a valid checkpoint record")));
4963 LastRec = RecPtr = checkPointLoc;
4964 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4965 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4968 (errmsg("redo record is at %X/%X; shutdown %s",
4969 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4970 wasShutdown ? "TRUE" : "FALSE")));
4972 (errmsg("next transaction ID: %u/%u; next OID: %u",
4973 checkPoint.nextXidEpoch, checkPoint.nextXid,
4974 checkPoint.nextOid)));
4976 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4977 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4978 if (!TransactionIdIsNormal(checkPoint.nextXid))
4980 (errmsg("invalid next transaction ID")));
4982 ShmemVariableCache->nextXid = checkPoint.nextXid;
4983 ShmemVariableCache->nextOid = checkPoint.nextOid;
4984 ShmemVariableCache->oidCount = 0;
4985 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4988 * We must replay WAL entries using the same TimeLineID they were created
4989 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4990 * also xlog_redo()).
4992 ThisTimeLineID = checkPoint.ThisTimeLineID;
4994 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4996 if (XLByteLT(RecPtr, checkPoint.redo))
4998 (errmsg("invalid redo in checkpoint record")));
5001 * Check whether we need to force recovery from WAL. If it appears to
5002 * have been a clean shutdown and we did not have a recovery.conf file,
5003 * then assume no recovery needed.
5005 if (XLByteLT(checkPoint.redo, RecPtr))
5009 (errmsg("invalid redo record in shutdown checkpoint")));
5012 else if (ControlFile->state != DB_SHUTDOWNED)
5014 else if (InArchiveRecovery)
5016 /* force recovery due to presence of recovery.conf */
5026 * Update pg_control to show that we are recovering and to show the
5027 * selected checkpoint as the place we are starting from. We also mark
5028 * pg_control with any minimum recovery stop point obtained from a
5029 * backup history file.
5031 if (InArchiveRecovery)
5034 (errmsg("automatic recovery in progress")));
5035 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
5040 (errmsg("database system was not properly shut down; "
5041 "automatic recovery in progress")));
5042 ControlFile->state = DB_IN_CRASH_RECOVERY;
5044 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5045 ControlFile->checkPoint = checkPointLoc;
5046 ControlFile->checkPointCopy = checkPoint;
5047 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
5048 ControlFile->minRecoveryPoint = minRecoveryLoc;
5049 ControlFile->time = (pg_time_t) time(NULL);
5050 UpdateControlFile();
5053 * If there was a backup label file, it's done its job and the info
5054 * has now been propagated into pg_control. We must get rid of the
5055 * label file so that if we crash during recovery, we'll pick up at
5056 * the latest recovery restartpoint instead of going all the way back
5057 * to the backup start point. It seems prudent though to just rename
5058 * the file out of the way rather than delete it completely.
5060 if (haveBackupLabel)
5062 unlink(BACKUP_LABEL_OLD);
5063 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
5065 (errcode_for_file_access(),
5066 errmsg("could not rename file \"%s\" to \"%s\": %m",
5067 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
5070 /* Start up the recovery environment */
5071 XLogInitRelationCache();
5073 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5075 if (RmgrTable[rmid].rm_startup != NULL)
5076 RmgrTable[rmid].rm_startup();
5080 * Find the first record that logically follows the checkpoint --- it
5081 * might physically precede it, though.
5083 if (XLByteLT(checkPoint.redo, RecPtr))
5085 /* back up to find the record */
5086 record = ReadRecord(&(checkPoint.redo), PANIC);
5090 /* just have to read next record after CheckPoint */
5091 record = ReadRecord(NULL, LOG);
5096 bool recoveryContinue = true;
5097 bool recoveryApply = true;
5098 ErrorContextCallback errcontext;
5102 (errmsg("redo starts at %X/%X",
5103 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5106 * main redo apply loop
5115 initStringInfo(&buf);
5116 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
5117 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
5118 EndRecPtr.xlogid, EndRecPtr.xrecoff);
5119 xlog_outrec(&buf, record);
5120 appendStringInfo(&buf, " - ");
5121 RmgrTable[record->xl_rmid].rm_desc(&buf,
5123 XLogRecGetData(record));
5124 elog(LOG, "%s", buf.data);
5130 * Have we reached our recovery target?
5132 if (recoveryStopsHere(record, &recoveryApply))
5134 reachedStopPoint = true; /* see below */
5135 recoveryContinue = false;
5140 /* Setup error traceback support for ereport() */
5141 errcontext.callback = rm_redo_error_callback;
5142 errcontext.arg = (void *) record;
5143 errcontext.previous = error_context_stack;
5144 error_context_stack = &errcontext;
5146 /* nextXid must be beyond record's xid */
5147 if (TransactionIdFollowsOrEquals(record->xl_xid,
5148 ShmemVariableCache->nextXid))
5150 ShmemVariableCache->nextXid = record->xl_xid;
5151 TransactionIdAdvance(ShmemVariableCache->nextXid);
5154 if (record->xl_info & XLR_BKP_BLOCK_MASK)
5155 RestoreBkpBlocks(record, EndRecPtr);
5157 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
5159 /* Pop the error context stack */
5160 error_context_stack = errcontext.previous;
5162 LastRec = ReadRecPtr;
5164 record = ReadRecord(NULL, LOG);
5165 } while (record != NULL && recoveryContinue);
5168 * end of main redo apply loop
5172 (errmsg("redo done at %X/%X",
5173 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5174 if (recoveryLastXTime)
5176 (errmsg("last completed transaction was at log time %s",
5177 timestamptz_to_str(recoveryLastXTime))));
5182 /* there are no WAL records following the checkpoint */
5184 (errmsg("redo is not required")));
5189 * Re-fetch the last valid or last applied record, so we can identify the
5190 * exact endpoint of what we consider the valid portion of WAL.
5192 record = ReadRecord(&LastRec, PANIC);
5193 EndOfLog = EndRecPtr;
5194 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
5197 * Complain if we did not roll forward far enough to render the backup
5200 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
5202 if (reachedStopPoint) /* stopped because of stop request */
5204 (errmsg("requested recovery stop point is before end time of backup dump")));
5205 else /* ran off end of WAL */
5207 (errmsg("WAL ends before end time of backup dump")));
5211 * Consider whether we need to assign a new timeline ID.
5213 * If we are doing an archive recovery, we always assign a new ID. This
5214 * handles a couple of issues. If we stopped short of the end of WAL
5215 * during recovery, then we are clearly generating a new timeline and must
5216 * assign it a unique new ID. Even if we ran to the end, modifying the
5217 * current last segment is problematic because it may result in trying to
5218 * overwrite an already-archived copy of that segment, and we encourage
5219 * DBAs to make their archive_commands reject that. We can dodge the
5220 * problem by making the new active segment have a new timeline ID.
5222 * In a normal crash recovery, we can just extend the timeline we were in.
5224 if (InArchiveRecovery)
5226 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5228 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5229 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5230 curFileTLI, endLogId, endLogSeg);
5233 /* Save the selected TimeLineID in shared memory, too */
5234 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5237 * We are now done reading the old WAL. Turn off archive fetching if it
5238 * was active, and make a writable copy of the last WAL segment. (Note
5239 * that we also have a copy of the last block of the old WAL in readBuf;
5240 * we will use that below.)
5242 if (InArchiveRecovery)
5243 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5246 * Prepare to write WAL starting at EndOfLog position, and init xlog
5247 * buffer cache using the block containing the last record from the
5248 * previous incarnation.
5250 openLogId = endLogId;
5251 openLogSeg = endLogSeg;
5252 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5254 Insert = &XLogCtl->Insert;
5255 Insert->PrevRecord = LastRec;
5256 XLogCtl->xlblocks[0].xlogid = openLogId;
5257 XLogCtl->xlblocks[0].xrecoff =
5258 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5261 * Tricky point here: readBuf contains the *last* block that the LastRec
5262 * record spans, not the one it starts in. The last block is indeed the
5263 * one we want to use.
5265 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5266 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5267 Insert->currpos = (char *) Insert->currpage +
5268 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5270 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5272 XLogCtl->Write.LogwrtResult = LogwrtResult;
5273 Insert->LogwrtResult = LogwrtResult;
5274 XLogCtl->LogwrtResult = LogwrtResult;
5276 XLogCtl->LogwrtRqst.Write = EndOfLog;
5277 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5279 freespace = INSERT_FREESPACE(Insert);
5282 /* Make sure rest of page is zero */
5283 MemSet(Insert->currpos, 0, freespace);
5284 XLogCtl->Write.curridx = 0;
5289 * Whenever Write.LogwrtResult points to exactly the end of a page,
5290 * Write.curridx must point to the *next* page (see XLogWrite()).
5292 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5293 * this is sufficient. The first actual attempt to insert a log
5294 * record will advance the insert state.
5296 XLogCtl->Write.curridx = NextBufIdx(0);
5299 /* Pre-scan prepared transactions to find out the range of XIDs present */
5300 oldestActiveXID = PrescanPreparedTransactions();
5307 * Allow resource managers to do any required cleanup.
5309 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5311 if (RmgrTable[rmid].rm_cleanup != NULL)
5312 RmgrTable[rmid].rm_cleanup();
5316 * Check to see if the XLOG sequence contained any unresolved
5317 * references to uninitialized pages.
5319 XLogCheckInvalidPages();
5322 * Reset pgstat data, because it may be invalid after recovery.
5327 * Perform a checkpoint to update all our recovery activity to disk.
5329 * Note that we write a shutdown checkpoint rather than an on-line
5330 * one. This is not particularly critical, but since we may be
5331 * assigning a new TLI, using a shutdown checkpoint allows us to have
5332 * the rule that TLI only changes in shutdown checkpoints, which
5333 * allows some extra error checking in xlog_redo.
5335 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5338 * Close down recovery environment
5340 XLogCloseRelationCache();
5344 * Preallocate additional log files, if wanted.
5346 PreallocXlogFiles(EndOfLog);
5349 * Okay, we're officially UP.
5353 ControlFile->state = DB_IN_PRODUCTION;
5354 ControlFile->time = (pg_time_t) time(NULL);
5355 UpdateControlFile();
5357 /* start the archive_timeout timer running */
5358 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5360 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5361 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5362 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5364 /* also initialize latestCompletedXid, to nextXid - 1 */
5365 ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
5366 TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);
5368 /* Start up the commit log and related stuff, too */
5370 StartupSUBTRANS(oldestActiveXID);
5373 /* Reload shared-memory state for prepared transactions */
5374 RecoverPreparedTransactions();
5376 /* Shut down readFile facility, free space */
5389 free(readRecordBuf);
5390 readRecordBuf = NULL;
5391 readRecordBufSize = 0;
5396 * Subroutine to try to fetch and validate a prior checkpoint record.
5398 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5399 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5402 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5406 if (!XRecOffIsValid(RecPtr.xrecoff))
5412 (errmsg("invalid primary checkpoint link in control file")));
5416 (errmsg("invalid secondary checkpoint link in control file")));
5420 (errmsg("invalid checkpoint link in backup_label file")));
5426 record = ReadRecord(&RecPtr, LOG);
5434 (errmsg("invalid primary checkpoint record")));
5438 (errmsg("invalid secondary checkpoint record")));
5442 (errmsg("invalid checkpoint record")));
5447 if (record->xl_rmid != RM_XLOG_ID)
5453 (errmsg("invalid resource manager ID in primary checkpoint record")));
5457 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5461 (errmsg("invalid resource manager ID in checkpoint record")));
5466 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5467 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5473 (errmsg("invalid xl_info in primary checkpoint record")));
5477 (errmsg("invalid xl_info in secondary checkpoint record")));
5481 (errmsg("invalid xl_info in checkpoint record")));
5486 if (record->xl_len != sizeof(CheckPoint) ||
5487 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5493 (errmsg("invalid length of primary checkpoint record")));
5497 (errmsg("invalid length of secondary checkpoint record")));
5501 (errmsg("invalid length of checkpoint record")));
5510 * This must be called during startup of a backend process, except that
5511 * it need not be called in a standalone backend (which does StartupXLOG
5512 * instead). We need to initialize the local copies of ThisTimeLineID and
5515 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5516 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5517 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5520 InitXLOGAccess(void)
5522 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5523 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5524 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5525 (void) GetRedoRecPtr();
5529 * Once spawned, a backend may update its local RedoRecPtr from
5530 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5531 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5536 /* use volatile pointer to prevent code rearrangement */
5537 volatile XLogCtlData *xlogctl = XLogCtl;
5539 SpinLockAcquire(&xlogctl->info_lck);
5540 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5541 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5542 SpinLockRelease(&xlogctl->info_lck);
5548 * GetInsertRecPtr -- Returns the current insert position.
5550 * NOTE: The value *actually* returned is the position of the last full
5551 * xlog page. It lags behind the real insert position by at most 1 page.
5552 * For that, we don't need to acquire WALInsertLock which can be quite
5553 * heavily contended, and an approximation is enough for the current
5554 * usage of this function.
5557 GetInsertRecPtr(void)
5559 /* use volatile pointer to prevent code rearrangement */
5560 volatile XLogCtlData *xlogctl = XLogCtl;
5563 SpinLockAcquire(&xlogctl->info_lck);
5564 recptr = xlogctl->LogwrtRqst.Write;
5565 SpinLockRelease(&xlogctl->info_lck);
5571 * Get the time of the last xlog segment switch
5574 GetLastSegSwitchTime(void)
5578 /* Need WALWriteLock, but shared lock is sufficient */
5579 LWLockAcquire(WALWriteLock, LW_SHARED);
5580 result = XLogCtl->Write.lastSegSwitchTime;
5581 LWLockRelease(WALWriteLock);
5587 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5589 * This is exported for use by code that would like to have 64-bit XIDs.
5590 * We don't really support such things, but all XIDs within the system
5591 * can be presumed "close to" the result, and thus the epoch associated
5592 * with them can be determined.
5595 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5597 uint32 ckptXidEpoch;
5598 TransactionId ckptXid;
5599 TransactionId nextXid;
5601 /* Must read checkpoint info first, else have race condition */
5603 /* use volatile pointer to prevent code rearrangement */
5604 volatile XLogCtlData *xlogctl = XLogCtl;
5606 SpinLockAcquire(&xlogctl->info_lck);
5607 ckptXidEpoch = xlogctl->ckptXidEpoch;
5608 ckptXid = xlogctl->ckptXid;
5609 SpinLockRelease(&xlogctl->info_lck);
5612 /* Now fetch current nextXid */
5613 nextXid = ReadNewTransactionId();
5616 * nextXid is certainly logically later than ckptXid. So if it's
5617 * numerically less, it must have wrapped into the next epoch.
5619 if (nextXid < ckptXid)
5623 *epoch = ckptXidEpoch;
5627 * This must be called ONCE during postmaster or standalone-backend shutdown
5630 ShutdownXLOG(int code, Datum arg)
5633 (errmsg("shutting down")));
5635 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5638 ShutdownMultiXact();
5641 (errmsg("database system is shut down")));
5645 * Log start of a checkpoint.
5648 LogCheckpointStart(int flags)
5650 elog(LOG, "checkpoint starting:%s%s%s%s%s%s",
5651 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
5652 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
5653 (flags & CHECKPOINT_FORCE) ? " force" : "",
5654 (flags & CHECKPOINT_WAIT) ? " wait" : "",
5655 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
5656 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
5660 * Log end of a checkpoint.
5663 LogCheckpointEnd(void)
5672 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
5674 TimestampDifference(CheckpointStats.ckpt_start_t,
5675 CheckpointStats.ckpt_end_t,
5676 &total_secs, &total_usecs);
5678 TimestampDifference(CheckpointStats.ckpt_write_t,
5679 CheckpointStats.ckpt_sync_t,
5680 &write_secs, &write_usecs);
5682 TimestampDifference(CheckpointStats.ckpt_sync_t,
5683 CheckpointStats.ckpt_sync_end_t,
5684 &sync_secs, &sync_usecs);
5686 elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
5687 "%d transaction log file(s) added, %d removed, %d recycled; "
5688 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
5689 CheckpointStats.ckpt_bufs_written,
5690 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
5691 CheckpointStats.ckpt_segs_added,
5692 CheckpointStats.ckpt_segs_removed,
5693 CheckpointStats.ckpt_segs_recycled,
5694 write_secs, write_usecs / 1000,
5695 sync_secs, sync_usecs / 1000,
5696 total_secs, total_usecs / 1000);
5700 * Perform a checkpoint --- either during shutdown, or on-the-fly
5702 * flags is a bitwise OR of the following:
5703 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
5704 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
5705 * ignoring checkpoint_completion_target parameter.
5706 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
5707 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
5709 * Note: flags contains other bits, of interest here only for logging purposes.
5710 * In particular note that this routine is synchronous and does not pay
5711 * attention to CHECKPOINT_WAIT.
5714 CreateCheckPoint(int flags)
5716 bool shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
5717 CheckPoint checkPoint;
5719 XLogCtlInsert *Insert = &XLogCtl->Insert;
5724 TransactionId *inCommitXids;
5728 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5729 * (This is just pro forma, since in the present system structure there is
5730 * only one process that is allowed to issue checkpoints at any given
5733 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5736 * Prepare to accumulate statistics.
5738 * Note: because it is possible for log_checkpoints to change while a
5739 * checkpoint proceeds, we always accumulate stats, even if
5740 * log_checkpoints is currently off.
5742 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
5743 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
5746 * Use a critical section to force system panic if we have trouble.
5748 START_CRIT_SECTION();
5752 ControlFile->state = DB_SHUTDOWNING;
5753 ControlFile->time = (pg_time_t) time(NULL);
5754 UpdateControlFile();
5758 * Let smgr prepare for checkpoint; this has to happen before we determine
5759 * the REDO pointer. Note that smgr must not do anything that'd have to
5760 * be undone if we decide no checkpoint is needed.
5764 /* Begin filling in the checkpoint WAL record */
5765 MemSet(&checkPoint, 0, sizeof(checkPoint));
5766 checkPoint.ThisTimeLineID = ThisTimeLineID;
5767 checkPoint.time = (pg_time_t) time(NULL);
5770 * We must hold WALInsertLock while examining insert state to determine
5771 * the checkpoint REDO pointer.
5773 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5776 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5777 * any XLOG records since the start of the last checkpoint, skip the
5778 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5779 * when the system is idle. That wastes log space, and more importantly it
5780 * exposes us to possible loss of both current and previous checkpoint
5781 * records if the machine crashes just as we're writing the update.
5782 * (Perhaps it'd make even more sense to checkpoint only when the previous
5783 * checkpoint record is in a different xlog page?)
5785 * We have to make two tests to determine that nothing has happened since
5786 * the start of the last checkpoint: current insertion point must match
5787 * the end of the last checkpoint record, and its redo pointer must point
5790 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
5792 XLogRecPtr curInsert;
5794 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5795 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5796 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5797 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5798 ControlFile->checkPoint.xlogid ==
5799 ControlFile->checkPointCopy.redo.xlogid &&
5800 ControlFile->checkPoint.xrecoff ==
5801 ControlFile->checkPointCopy.redo.xrecoff)
5803 LWLockRelease(WALInsertLock);
5804 LWLockRelease(CheckpointLock);
5811 * Compute new REDO record ptr = location of next XLOG record.
5813 * NB: this is NOT necessarily where the checkpoint record itself will be,
5814 * since other backends may insert more XLOG records while we're off doing
5815 * the buffer flush work. Those XLOG records are logically after the
5816 * checkpoint, even though physically before it. Got that?
5818 freespace = INSERT_FREESPACE(Insert);
5819 if (freespace < SizeOfXLogRecord)
5821 (void) AdvanceXLInsertBuffer(false);
5822 /* OK to ignore update return flag, since we will do flush anyway */
5823 freespace = INSERT_FREESPACE(Insert);
5825 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5828 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5829 * must be done while holding the insert lock AND the info_lck.
5831 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5832 * pointing past where it really needs to point. This is okay; the only
5833 * consequence is that XLogInsert might back up whole buffers that it
5834 * didn't really need to. We can't postpone advancing RedoRecPtr because
5835 * XLogInserts that happen while we are dumping buffers must assume that
5836 * their buffer changes are not included in the checkpoint.
5839 /* use volatile pointer to prevent code rearrangement */
5840 volatile XLogCtlData *xlogctl = XLogCtl;
5842 SpinLockAcquire(&xlogctl->info_lck);
5843 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5844 SpinLockRelease(&xlogctl->info_lck);
5848 * Now we can release WAL insert lock, allowing other xacts to proceed
5849 * while we are flushing disk buffers.
5851 LWLockRelease(WALInsertLock);
5854 * If enabled, log checkpoint start. We postpone this until now so as not
5855 * to log anything if we decided to skip the checkpoint.
5857 if (log_checkpoints)
5858 LogCheckpointStart(flags);
5861 * Before flushing data, we must wait for any transactions that are
5862 * currently in their commit critical sections. If an xact inserted its
5863 * commit record into XLOG just before the REDO point, then a crash
5864 * restart from the REDO point would not replay that record, which means
5865 * that our flushing had better include the xact's update of pg_clog. So
5866 * we wait till he's out of his commit critical section before proceeding.
5867 * See notes in RecordTransactionCommit().
5869 * Because we've already released WALInsertLock, this test is a bit fuzzy:
5870 * it is possible that we will wait for xacts we didn't really need to
5871 * wait for. But the delay should be short and it seems better to make
5872 * checkpoint take a bit longer than to hold locks longer than necessary.
5873 * (In fact, the whole reason we have this issue is that xact.c does
5874 * commit record XLOG insertion and clog update as two separate steps
5875 * protected by different locks, but again that seems best on grounds of
5876 * minimizing lock contention.)
5878 * A transaction that has not yet set inCommit when we look cannot be at
5879 * risk, since he's not inserted his commit record yet; and one that's
5880 * already cleared it is not at risk either, since he's done fixing clog
5881 * and we will correctly flush the update below. So we cannot miss any
5882 * xacts we need to wait for.
5884 nInCommit = GetTransactionsInCommit(&inCommitXids);
5889 pg_usleep(10000L); /* wait for 10 msec */
5890 } while (HaveTransactionsInCommit(inCommitXids, nInCommit));
5892 pfree(inCommitXids);
5895 * Get the other info we need for the checkpoint record.
5897 LWLockAcquire(XidGenLock, LW_SHARED);
5898 checkPoint.nextXid = ShmemVariableCache->nextXid;
5899 LWLockRelease(XidGenLock);
5901 /* Increase XID epoch if we've wrapped around since last checkpoint */
5902 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5903 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5904 checkPoint.nextXidEpoch++;
5906 LWLockAcquire(OidGenLock, LW_SHARED);
5907 checkPoint.nextOid = ShmemVariableCache->nextOid;
5909 checkPoint.nextOid += ShmemVariableCache->oidCount;
5910 LWLockRelease(OidGenLock);
5912 MultiXactGetCheckptMulti(shutdown,
5913 &checkPoint.nextMulti,
5914 &checkPoint.nextMultiOffset);
5917 * Having constructed the checkpoint record, ensure all shmem disk buffers
5918 * and commit-log buffers are flushed to disk.
5920 * This I/O could fail for various reasons. If so, we will fail to
5921 * complete the checkpoint, but there is no reason to force a system
5922 * panic. Accordingly, exit critical section while doing it.
5926 CheckPointGuts(checkPoint.redo, flags);
5928 START_CRIT_SECTION();
5931 * Now insert the checkpoint record into XLOG.
5933 rdata.data = (char *) (&checkPoint);
5934 rdata.len = sizeof(checkPoint);
5935 rdata.buffer = InvalidBuffer;
5938 recptr = XLogInsert(RM_XLOG_ID,
5939 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5940 XLOG_CHECKPOINT_ONLINE,
5946 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5947 * = end of actual checkpoint record.
5949 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5951 (errmsg("concurrent transaction log activity while database system is shutting down")));
5954 * Select point at which we can truncate the log, which we base on the
5955 * prior checkpoint's earliest info.
5957 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5960 * Update the control file.
5962 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5964 ControlFile->state = DB_SHUTDOWNED;
5965 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5966 ControlFile->checkPoint = ProcLastRecPtr;
5967 ControlFile->checkPointCopy = checkPoint;
5968 ControlFile->time = (pg_time_t) time(NULL);
5969 UpdateControlFile();
5970 LWLockRelease(ControlFileLock);
5972 /* Update shared-memory copy of checkpoint XID/epoch */
5974 /* use volatile pointer to prevent code rearrangement */
5975 volatile XLogCtlData *xlogctl = XLogCtl;
5977 SpinLockAcquire(&xlogctl->info_lck);
5978 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5979 xlogctl->ckptXid = checkPoint.nextXid;
5980 SpinLockRelease(&xlogctl->info_lck);
5984 * We are now done with critical updates; no need for system panic if we
5985 * have trouble while fooling with old log segments.
5990 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
5995 * Delete old log files (those no longer needed even for previous
5998 if (_logId || _logSeg)
6000 PrevLogSeg(_logId, _logSeg);
6001 RemoveOldXlogFiles(_logId, _logSeg, recptr);
6005 * Make more log segments if needed. (Do this after recycling old log
6006 * segments, since that may supply some of the needed files.)
6009 PreallocXlogFiles(recptr);
6012 * Truncate pg_subtrans if possible. We can throw away all data before
6013 * the oldest XMIN of any running transaction. No future transaction will
6014 * attempt to reference any pg_subtrans entry older than that (see Asserts
6015 * in subtrans.c). During recovery, though, we mustn't do this because
6016 * StartupSUBTRANS hasn't been called yet.
6019 TruncateSUBTRANS(GetOldestXmin(true, false));
6021 /* All real work is done, but log before releasing lock. */
6022 if (log_checkpoints)
6025 LWLockRelease(CheckpointLock);
6029 * Flush all data in shared memory to disk, and fsync
6031 * This is the common code shared between regular checkpoints and
6032 * recovery restartpoints.
6035 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
6038 CheckPointSUBTRANS();
6039 CheckPointMultiXact();
6040 CheckPointBuffers(flags); /* performs all required fsyncs */
6041 /* We deliberately delay 2PC checkpointing as long as possible */
6042 CheckPointTwoPhase(checkPointRedo);
6046 * Set a recovery restart point if appropriate
6048 * This is similar to CreateCheckPoint, but is used during WAL recovery
6049 * to establish a point from which recovery can roll forward without
6050 * replaying the entire recovery log. This function is called each time
6051 * a checkpoint record is read from XLOG; it must determine whether a
6052 * restartpoint is needed or not.
6055 RecoveryRestartPoint(const CheckPoint *checkPoint)
6061 * Do nothing if the elapsed time since the last restartpoint is less than
6062 * half of checkpoint_timeout. (We use a value less than
6063 * checkpoint_timeout so that variations in the timing of checkpoints on
6064 * the master, or speed of transmission of WAL segments to a slave, won't
6065 * make the slave skip a restartpoint once it's synced with the master.)
6066 * Checking true elapsed time keeps us from doing restartpoints too often
6067 * while rapidly scanning large amounts of WAL.
6069 elapsed_secs = (pg_time_t) time(NULL) - ControlFile->time;
6070 if (elapsed_secs < CheckPointTimeout / 2)
6074 * Is it safe to checkpoint? We must ask each of the resource managers
6075 * whether they have any partial state information that might prevent a
6076 * correct restart from this point. If so, we skip this opportunity, but
6077 * return at the next checkpoint record for another try.
6079 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
6081 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
6082 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
6084 elog(DEBUG2, "RM %d not safe to record restart point at %X/%X",
6086 checkPoint->redo.xlogid,
6087 checkPoint->redo.xrecoff);
6093 * OK, force data out to disk
6095 CheckPointGuts(checkPoint->redo, CHECKPOINT_IMMEDIATE);
6098 * Update pg_control so that any subsequent crash will restart from this
6099 * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
6102 ControlFile->prevCheckPoint = ControlFile->checkPoint;
6103 ControlFile->checkPoint = ReadRecPtr;
6104 ControlFile->checkPointCopy = *checkPoint;
6105 ControlFile->time = (pg_time_t) time(NULL);
6106 UpdateControlFile();
6108 ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
6109 (errmsg("recovery restart point at %X/%X",
6110 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
6111 if (recoveryLastXTime)
6112 ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
6113 (errmsg("last completed transaction was at log time %s",
6114 timestamptz_to_str(recoveryLastXTime))));
6118 * Write a NEXTOID log record
6121 XLogPutNextOid(Oid nextOid)
6125 rdata.data = (char *) (&nextOid);
6126 rdata.len = sizeof(Oid);
6127 rdata.buffer = InvalidBuffer;
6129 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
6132 * We need not flush the NEXTOID record immediately, because any of the
6133 * just-allocated OIDs could only reach disk as part of a tuple insert or
6134 * update that would have its own XLOG record that must follow the NEXTOID
6135 * record. Therefore, the standard buffer LSN interlock applied to those
6136 * records will ensure no such OID reaches disk before the NEXTOID record
6139 * Note, however, that the above statement only covers state "within" the
6140 * database. When we use a generated OID as a file or directory name, we
6141 * are in a sense violating the basic WAL rule, because that filesystem
6142 * change may reach disk before the NEXTOID WAL record does. The impact
6143 * of this is that if a database crash occurs immediately afterward, we
6144 * might after restart re-generate the same OID and find that it conflicts
6145 * with the leftover file or directory. But since for safety's sake we
6146 * always loop until finding a nonconflicting filename, this poses no real
6147 * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
6152 * Write an XLOG SWITCH record.
6154 * Here we just blindly issue an XLogInsert request for the record.
6155 * All the magic happens inside XLogInsert.
6157 * The return value is either the end+1 address of the switch record,
6158 * or the end+1 address of the prior segment if we did not need to
6159 * write a switch record because we are already at segment start.
6162 RequestXLogSwitch(void)
6167 /* XLOG SWITCH, alone among xlog record types, has no data */
6168 rdata.buffer = InvalidBuffer;
6173 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
6179 * XLOG resource manager's routines
6182 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
6184 uint8 info = record->xl_info & ~XLR_INFO_MASK;
6186 if (info == XLOG_NEXTOID)
6190 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
6191 if (ShmemVariableCache->nextOid < nextOid)
6193 ShmemVariableCache->nextOid = nextOid;
6194 ShmemVariableCache->oidCount = 0;
6197 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
6199 CheckPoint checkPoint;
6201 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6202 /* In a SHUTDOWN checkpoint, believe the counters exactly */
6203 ShmemVariableCache->nextXid = checkPoint.nextXid;
6204 ShmemVariableCache->nextOid = checkPoint.nextOid;
6205 ShmemVariableCache->oidCount = 0;
6206 MultiXactSetNextMXact(checkPoint.nextMulti,
6207 checkPoint.nextMultiOffset);
6209 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6210 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6211 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6214 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
6216 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6218 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
6219 !list_member_int(expectedTLIs,
6220 (int) checkPoint.ThisTimeLineID))
6222 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
6223 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6224 /* Following WAL records should be run with new TLI */
6225 ThisTimeLineID = checkPoint.ThisTimeLineID;
6228 RecoveryRestartPoint(&checkPoint);
6230 else if (info == XLOG_CHECKPOINT_ONLINE)
6232 CheckPoint checkPoint;
6234 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6235 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
6236 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
6237 checkPoint.nextXid))
6238 ShmemVariableCache->nextXid = checkPoint.nextXid;
6239 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
6241 ShmemVariableCache->nextOid = checkPoint.nextOid;
6242 ShmemVariableCache->oidCount = 0;
6244 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
6245 checkPoint.nextMultiOffset);
6247 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6248 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6249 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6251 /* TLI should not change in an on-line checkpoint */
6252 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6254 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
6255 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6257 RecoveryRestartPoint(&checkPoint);
6259 else if (info == XLOG_NOOP)
6261 /* nothing to do here */
6263 else if (info == XLOG_SWITCH)
6265 /* nothing to do here */
6270 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
6272 uint8 info = xl_info & ~XLR_INFO_MASK;
6274 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
6275 info == XLOG_CHECKPOINT_ONLINE)
6277 CheckPoint *checkpoint = (CheckPoint *) rec;
6279 appendStringInfo(buf, "checkpoint: redo %X/%X; "
6280 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
6281 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
6282 checkpoint->ThisTimeLineID,
6283 checkpoint->nextXidEpoch, checkpoint->nextXid,
6284 checkpoint->nextOid,
6285 checkpoint->nextMulti,
6286 checkpoint->nextMultiOffset,
6287 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
6289 else if (info == XLOG_NOOP)
6291 appendStringInfo(buf, "xlog no-op");
6293 else if (info == XLOG_NEXTOID)
6297 memcpy(&nextOid, rec, sizeof(Oid));
6298 appendStringInfo(buf, "nextOid: %u", nextOid);
6300 else if (info == XLOG_SWITCH)
6302 appendStringInfo(buf, "xlog switch");
6305 appendStringInfo(buf, "UNKNOWN");
6311 xlog_outrec(StringInfo buf, XLogRecord *record)
6315 appendStringInfo(buf, "prev %X/%X; xid %u",
6316 record->xl_prev.xlogid, record->xl_prev.xrecoff,
6319 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
6321 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
6322 appendStringInfo(buf, "; bkpb%d", i + 1);
6325 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
6327 #endif /* WAL_DEBUG */
6334 assign_xlog_sync_method(int new_sync_method, bool doit, GucSource source)
6336 int new_sync_bit = 0;
6338 switch (new_sync_method)
6341 * Values for these sync options are defined even if they are not
6342 * supported on the current platform. They are not included in
6343 * the enum option array, and therefor will never be set if the
6344 * platform doesn't support it.
6346 case SYNC_METHOD_FSYNC:
6347 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6348 case SYNC_METHOD_FDATASYNC:
6351 #ifdef OPEN_SYNC_FLAG
6352 case SYNC_METHOD_OPEN:
6353 new_sync_bit = OPEN_SYNC_FLAG;
6356 #ifdef OPEN_DATASYNC_FLAG
6357 case SYNC_METHOD_OPEN_DSYNC:
6358 new_sync_bit = OPEN_DATASYNC_FLAG;
6363 * This "can never happen", since the available values in
6364 * new_sync_method are controlled by the available enum
6367 elog(PANIC, "unrecognized wal_sync_method: %d", new_sync_method);
6374 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
6377 * To ensure that no blocks escape unsynced, force an fsync on the
6378 * currently open log segment (if any). Also, if the open flag is
6379 * changing, close the log file so it will be reopened (with new flag
6382 if (openLogFile >= 0)
6384 if (pg_fsync(openLogFile) != 0)
6386 (errcode_for_file_access(),
6387 errmsg("could not fsync log file %u, segment %u: %m",
6388 openLogId, openLogSeg)));
6389 if (open_sync_bit != new_sync_bit)
6392 sync_method = new_sync_method;
6393 open_sync_bit = new_sync_bit;
6401 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6404 issue_xlog_fsync(void)
6406 switch (sync_method)
6408 case SYNC_METHOD_FSYNC:
6409 if (pg_fsync_no_writethrough(openLogFile) != 0)
6411 (errcode_for_file_access(),
6412 errmsg("could not fsync log file %u, segment %u: %m",
6413 openLogId, openLogSeg)));
6415 #ifdef HAVE_FSYNC_WRITETHROUGH
6416 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6417 if (pg_fsync_writethrough(openLogFile) != 0)
6419 (errcode_for_file_access(),
6420 errmsg("could not fsync write-through log file %u, segment %u: %m",
6421 openLogId, openLogSeg)));
6424 #ifdef HAVE_FDATASYNC
6425 case SYNC_METHOD_FDATASYNC:
6426 if (pg_fdatasync(openLogFile) != 0)
6428 (errcode_for_file_access(),
6429 errmsg("could not fdatasync log file %u, segment %u: %m",
6430 openLogId, openLogSeg)));
6433 case SYNC_METHOD_OPEN:
6434 case SYNC_METHOD_OPEN_DSYNC:
6435 /* write synced it already */
6438 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6445 * pg_start_backup: set up for taking an on-line backup dump
6447 * Essentially what this does is to create a backup label file in $PGDATA,
6448 * where it will be archived as part of the backup dump. The label file
6449 * contains the user-supplied label string (typically this would be used
6450 * to tell where the backup dump will be stored) and the starting time and
6451 * starting WAL location for the dump.
6454 pg_start_backup(PG_FUNCTION_ARGS)
6456 text *backupid = PG_GETARG_TEXT_P(0);
6458 XLogRecPtr checkpointloc;
6459 XLogRecPtr startpoint;
6460 pg_time_t stamp_time;
6462 char xlogfilename[MAXFNAMELEN];
6465 struct stat stat_buf;
6470 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6471 errmsg("must be superuser to run a backup")));
6473 if (!XLogArchivingActive())
6475 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6476 errmsg("WAL archiving is not active"),
6477 errhint("archive_mode must be enabled at server start.")));
6479 if (!XLogArchiveCommandSet())
6481 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6482 errmsg("WAL archiving is not active"),
6483 errhint("archive_command must be defined before "
6484 "online backups can be made safely.")));
6486 backupidstr = text_to_cstring(backupid);
6489 * Mark backup active in shared memory. We must do full-page WAL writes
6490 * during an on-line backup even if not doing so at other times, because
6491 * it's quite possible for the backup dump to obtain a "torn" (partially
6492 * written) copy of a database page if it reads the page concurrently with
6493 * our write to the same page. This can be fixed as long as the first
6494 * write to the page in the WAL sequence is a full-page write. Hence, we
6495 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6496 * are no dirty pages in shared memory that might get dumped while the
6497 * backup is in progress without having a corresponding WAL record. (Once
6498 * the backup is complete, we need not force full-page writes anymore,
6499 * since we expect that any pages not modified during the backup interval
6500 * must have been correctly captured by the backup.)
6502 * We must hold WALInsertLock to change the value of forcePageWrites, to
6503 * ensure adequate interlocking against XLogInsert().
6505 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6506 if (XLogCtl->Insert.forcePageWrites)
6508 LWLockRelease(WALInsertLock);
6510 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6511 errmsg("a backup is already in progress"),
6512 errhint("Run pg_stop_backup() and try again.")));
6514 XLogCtl->Insert.forcePageWrites = true;
6515 LWLockRelease(WALInsertLock);
6517 /* Ensure we release forcePageWrites if fail below */
6518 PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
6521 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6522 * page problems, this guarantees that two successive backup runs will
6523 * have different checkpoint positions and hence different history
6524 * file names, even if nothing happened in between.
6526 * We don't use CHECKPOINT_IMMEDIATE, hence this can take awhile.
6528 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT);
6531 * Now we need to fetch the checkpoint record location, and also its
6532 * REDO pointer. The oldest point in WAL that would be needed to
6533 * restore starting from the checkpoint is precisely the REDO pointer.
6535 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6536 checkpointloc = ControlFile->checkPoint;
6537 startpoint = ControlFile->checkPointCopy.redo;
6538 LWLockRelease(ControlFileLock);
6540 XLByteToSeg(startpoint, _logId, _logSeg);
6541 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6543 /* Use the log timezone here, not the session timezone */
6544 stamp_time = (pg_time_t) time(NULL);
6545 pg_strftime(strfbuf, sizeof(strfbuf),
6546 "%Y-%m-%d %H:%M:%S %Z",
6547 pg_localtime(&stamp_time, log_timezone));
6550 * Check for existing backup label --- implies a backup is already
6551 * running. (XXX given that we checked forcePageWrites above, maybe
6552 * it would be OK to just unlink any such label file?)
6554 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6556 if (errno != ENOENT)
6558 (errcode_for_file_access(),
6559 errmsg("could not stat file \"%s\": %m",
6560 BACKUP_LABEL_FILE)));
6564 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6565 errmsg("a backup is already in progress"),
6566 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6567 BACKUP_LABEL_FILE)));
6570 * Okay, write the file
6572 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6575 (errcode_for_file_access(),
6576 errmsg("could not create file \"%s\": %m",
6577 BACKUP_LABEL_FILE)));
6578 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6579 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6580 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6581 checkpointloc.xlogid, checkpointloc.xrecoff);
6582 fprintf(fp, "START TIME: %s\n", strfbuf);
6583 fprintf(fp, "LABEL: %s\n", backupidstr);
6584 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6586 (errcode_for_file_access(),
6587 errmsg("could not write file \"%s\": %m",
6588 BACKUP_LABEL_FILE)));
6590 PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
6593 * We're done. As a convenience, return the starting WAL location.
6595 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6596 startpoint.xlogid, startpoint.xrecoff);
6597 PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
6600 /* Error cleanup callback for pg_start_backup */
6602 pg_start_backup_callback(int code, Datum arg)
6604 /* Turn off forcePageWrites on failure */
6605 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6606 XLogCtl->Insert.forcePageWrites = false;
6607 LWLockRelease(WALInsertLock);
6611 * pg_stop_backup: finish taking an on-line backup dump
6613 * We remove the backup label file created by pg_start_backup, and instead
6614 * create a backup history file in pg_xlog (whence it will immediately be
6615 * archived). The backup history file contains the same info found in
6616 * the label file, plus the backup-end time and WAL location.
6617 * Note: different from CancelBackup which just cancels online backup mode.
6620 pg_stop_backup(PG_FUNCTION_ARGS)
6622 XLogRecPtr startpoint;
6623 XLogRecPtr stoppoint;
6624 pg_time_t stamp_time;
6626 char histfilepath[MAXPGPATH];
6627 char startxlogfilename[MAXFNAMELEN];
6628 char stopxlogfilename[MAXFNAMELEN];
6635 int seconds_before_warning;
6640 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6641 (errmsg("must be superuser to run a backup"))));
6644 * OK to clear forcePageWrites
6646 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6647 XLogCtl->Insert.forcePageWrites = false;
6648 LWLockRelease(WALInsertLock);
6651 * Force a switch to a new xlog segment file, so that the backup is valid
6652 * as soon as archiver moves out the current segment file. We'll report
6653 * the end address of the XLOG SWITCH record as the backup stopping point.
6655 stoppoint = RequestXLogSwitch();
6657 XLByteToSeg(stoppoint, _logId, _logSeg);
6658 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
6660 /* Use the log timezone here, not the session timezone */
6661 stamp_time = (pg_time_t) time(NULL);
6662 pg_strftime(strfbuf, sizeof(strfbuf),
6663 "%Y-%m-%d %H:%M:%S %Z",
6664 pg_localtime(&stamp_time, log_timezone));
6667 * Open the existing label file
6669 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6672 if (errno != ENOENT)
6674 (errcode_for_file_access(),
6675 errmsg("could not read file \"%s\": %m",
6676 BACKUP_LABEL_FILE)));
6678 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6679 errmsg("a backup is not in progress")));
6683 * Read and parse the START WAL LOCATION line (this code is pretty crude,
6684 * but we are not expecting any variability in the file format).
6686 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
6687 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6688 &ch) != 4 || ch != '\n')
6690 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6691 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6694 * Write the backup history file
6696 XLByteToSeg(startpoint, _logId, _logSeg);
6697 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6698 startpoint.xrecoff % XLogSegSize);
6699 fp = AllocateFile(histfilepath, "w");
6702 (errcode_for_file_access(),
6703 errmsg("could not create file \"%s\": %m",
6705 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6706 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
6707 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
6708 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
6709 /* transfer remaining lines from label to history file */
6710 while ((ich = fgetc(lfp)) != EOF)
6712 fprintf(fp, "STOP TIME: %s\n", strfbuf);
6713 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6715 (errcode_for_file_access(),
6716 errmsg("could not write file \"%s\": %m",
6720 * Close and remove the backup label file
6722 if (ferror(lfp) || FreeFile(lfp))
6724 (errcode_for_file_access(),
6725 errmsg("could not read file \"%s\": %m",
6726 BACKUP_LABEL_FILE)));
6727 if (unlink(BACKUP_LABEL_FILE) != 0)
6729 (errcode_for_file_access(),
6730 errmsg("could not remove file \"%s\": %m",
6731 BACKUP_LABEL_FILE)));
6734 * Clean out any no-longer-needed history files. As a side effect, this
6735 * will post a .ready file for the newly created history file, notifying
6736 * the archiver that history file may be archived immediately.
6738 CleanupBackupHistory();
6741 * Wait until the history file has been archived. We assume that the
6742 * alphabetic sorting property of the WAL files ensures the last WAL
6743 * file is guaranteed archived by the time the history file is archived.
6745 * We wait forever, since archive_command is supposed to work and
6746 * we assume the admin wanted his backup to work completely. If you
6747 * don't wish to wait, you can SET statement_timeout = xx;
6749 * If the status file is missing, we assume that is because it was
6750 * set to .ready before we slept, then while asleep it has been set
6751 * to .done and then removed by a concurrent checkpoint.
6753 BackupHistoryFileName(histfilepath, ThisTimeLineID, _logId, _logSeg,
6754 startpoint.xrecoff % XLogSegSize);
6756 seconds_before_warning = 60;
6759 while (!XLogArchiveCheckDone(histfilepath, false))
6761 CHECK_FOR_INTERRUPTS();
6763 pg_usleep(1000000L);
6765 if (++waits >= seconds_before_warning)
6767 seconds_before_warning *= 2; /* This wraps in >10 years... */
6768 elog(WARNING, "pg_stop_backup() waiting for archive to complete "
6769 "(%d seconds delay)", waits);
6774 * We're done. As a convenience, return the ending WAL location.
6776 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
6777 stoppoint.xlogid, stoppoint.xrecoff);
6778 PG_RETURN_TEXT_P(cstring_to_text(stopxlogfilename));
6782 * pg_switch_xlog: switch to next xlog file
6785 pg_switch_xlog(PG_FUNCTION_ARGS)
6787 XLogRecPtr switchpoint;
6788 char location[MAXFNAMELEN];
6792 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6793 (errmsg("must be superuser to switch transaction log files"))));
6795 switchpoint = RequestXLogSwitch();
6798 * As a convenience, return the WAL location of the switch record
6800 snprintf(location, sizeof(location), "%X/%X",
6801 switchpoint.xlogid, switchpoint.xrecoff);
6802 PG_RETURN_TEXT_P(cstring_to_text(location));
6806 * Report the current WAL write location (same format as pg_start_backup etc)
6808 * This is useful for determining how much of WAL is visible to an external
6809 * archiving process. Note that the data before this point is written out
6810 * to the kernel, but is not necessarily synced to disk.
6813 pg_current_xlog_location(PG_FUNCTION_ARGS)
6815 char location[MAXFNAMELEN];
6817 /* Make sure we have an up-to-date local LogwrtResult */
6819 /* use volatile pointer to prevent code rearrangement */
6820 volatile XLogCtlData *xlogctl = XLogCtl;
6822 SpinLockAcquire(&xlogctl->info_lck);
6823 LogwrtResult = xlogctl->LogwrtResult;
6824 SpinLockRelease(&xlogctl->info_lck);
6827 snprintf(location, sizeof(location), "%X/%X",
6828 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
6829 PG_RETURN_TEXT_P(cstring_to_text(location));
6833 * Report the current WAL insert location (same format as pg_start_backup etc)
6835 * This function is mostly for debugging purposes.
6838 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
6840 XLogCtlInsert *Insert = &XLogCtl->Insert;
6841 XLogRecPtr current_recptr;
6842 char location[MAXFNAMELEN];
6845 * Get the current end-of-WAL position ... shared lock is sufficient
6847 LWLockAcquire(WALInsertLock, LW_SHARED);
6848 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
6849 LWLockRelease(WALInsertLock);
6851 snprintf(location, sizeof(location), "%X/%X",
6852 current_recptr.xlogid, current_recptr.xrecoff);
6853 PG_RETURN_TEXT_P(cstring_to_text(location));
6857 * Compute an xlog file name and decimal byte offset given a WAL location,
6858 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6860 * Note that a location exactly at a segment boundary is taken to be in
6861 * the previous segment. This is usually the right thing, since the
6862 * expected usage is to determine which xlog file(s) are ready to archive.
6865 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
6867 text *location = PG_GETARG_TEXT_P(0);
6869 unsigned int uxlogid;
6870 unsigned int uxrecoff;
6874 XLogRecPtr locationpoint;
6875 char xlogfilename[MAXFNAMELEN];
6878 TupleDesc resultTupleDesc;
6879 HeapTuple resultHeapTuple;
6883 * Read input and parse
6885 locationstr = text_to_cstring(location);
6887 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6889 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6890 errmsg("could not parse transaction log location \"%s\"",
6893 locationpoint.xlogid = uxlogid;
6894 locationpoint.xrecoff = uxrecoff;
6897 * Construct a tuple descriptor for the result row. This must match this
6898 * function's pg_proc entry!
6900 resultTupleDesc = CreateTemplateTupleDesc(2, false);
6901 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
6903 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
6906 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
6911 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6912 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6914 values[0] = CStringGetTextDatum(xlogfilename);
6920 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
6922 values[1] = UInt32GetDatum(xrecoff);
6926 * Tuple jam: Having first prepared your Datums, then squash together
6928 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
6930 result = HeapTupleGetDatum(resultHeapTuple);
6932 PG_RETURN_DATUM(result);
6936 * Compute an xlog file name given a WAL location,
6937 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6940 pg_xlogfile_name(PG_FUNCTION_ARGS)
6942 text *location = PG_GETARG_TEXT_P(0);
6944 unsigned int uxlogid;
6945 unsigned int uxrecoff;
6948 XLogRecPtr locationpoint;
6949 char xlogfilename[MAXFNAMELEN];
6951 locationstr = text_to_cstring(location);
6953 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6955 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6956 errmsg("could not parse transaction log location \"%s\"",
6959 locationpoint.xlogid = uxlogid;
6960 locationpoint.xrecoff = uxrecoff;
6962 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6963 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6965 PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
6969 * read_backup_label: check to see if a backup_label file is present
6971 * If we see a backup_label during recovery, we assume that we are recovering
6972 * from a backup dump file, and we therefore roll forward from the checkpoint
6973 * identified by the label file, NOT what pg_control says. This avoids the
6974 * problem that pg_control might have been archived one or more checkpoints
6975 * later than the start of the dump, and so if we rely on it as the start
6976 * point, we will fail to restore a consistent database state.
6978 * We also attempt to retrieve the corresponding backup history file.
6979 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6982 * Returns TRUE if a backup_label was found (and fills the checkpoint
6983 * location into *checkPointLoc); returns FALSE if not.
6986 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6988 XLogRecPtr startpoint;
6989 XLogRecPtr stoppoint;
6990 char histfilename[MAXFNAMELEN];
6991 char histfilepath[MAXPGPATH];
6992 char startxlogfilename[MAXFNAMELEN];
6993 char stopxlogfilename[MAXFNAMELEN];
7001 /* Default is to not constrain recovery stop point */
7002 minRecoveryLoc->xlogid = 0;
7003 minRecoveryLoc->xrecoff = 0;
7006 * See if label file is present
7008 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
7011 if (errno != ENOENT)
7013 (errcode_for_file_access(),
7014 errmsg("could not read file \"%s\": %m",
7015 BACKUP_LABEL_FILE)));
7016 return false; /* it's not there, all is fine */
7020 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
7021 * is pretty crude, but we are not expecting any variability in the file
7024 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
7025 &startpoint.xlogid, &startpoint.xrecoff, &tli,
7026 startxlogfilename, &ch) != 5 || ch != '\n')
7028 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7029 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7030 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
7031 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
7032 &ch) != 3 || ch != '\n')
7034 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7035 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7036 if (ferror(lfp) || FreeFile(lfp))
7038 (errcode_for_file_access(),
7039 errmsg("could not read file \"%s\": %m",
7040 BACKUP_LABEL_FILE)));
7043 * Try to retrieve the backup history file (no error if we can't)
7045 XLByteToSeg(startpoint, _logId, _logSeg);
7046 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
7047 startpoint.xrecoff % XLogSegSize);
7049 if (InArchiveRecovery)
7050 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
7052 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
7053 startpoint.xrecoff % XLogSegSize);
7055 fp = AllocateFile(histfilepath, "r");
7059 * Parse history file to identify stop point.
7061 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
7062 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
7063 &ch) != 4 || ch != '\n')
7065 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7066 errmsg("invalid data in file \"%s\"", histfilename)));
7067 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
7068 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
7069 &ch) != 4 || ch != '\n')
7071 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7072 errmsg("invalid data in file \"%s\"", histfilename)));
7073 *minRecoveryLoc = stoppoint;
7074 if (ferror(fp) || FreeFile(fp))
7076 (errcode_for_file_access(),
7077 errmsg("could not read file \"%s\": %m",
7085 * Error context callback for errors occurring during rm_redo().
7088 rm_redo_error_callback(void *arg)
7090 XLogRecord *record = (XLogRecord *) arg;
7093 initStringInfo(&buf);
7094 RmgrTable[record->xl_rmid].rm_desc(&buf,
7096 XLogRecGetData(record));
7098 /* don't bother emitting empty description */
7100 errcontext("xlog redo %s", buf.data);
7106 * BackupInProgress: check if online backup mode is active
7108 * This is done by checking for existence of the "backup_label" file.
7111 BackupInProgress(void)
7113 struct stat stat_buf;
7115 return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
7119 * CancelBackup: rename the "backup_label" file to cancel backup mode
7121 * If the "backup_label" file exists, it will be renamed to "backup_label.old".
7122 * Note that this will render an online backup in progress useless.
7123 * To correctly finish an online backup, pg_stop_backup must be called.
7128 struct stat stat_buf;
7130 /* if the file is not there, return */
7131 if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
7134 /* remove leftover file from previously cancelled backup if it exists */
7135 unlink(BACKUP_LABEL_OLD);
7137 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) == 0)
7140 (errmsg("online backup mode cancelled"),
7141 errdetail("\"%s\" was renamed to \"%s\".",
7142 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
7147 (errcode_for_file_access(),
7148 errmsg("online backup mode was not cancelled"),
7149 errdetail("Could not rename \"%s\" to \"%s\": %m.",
7150 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));