1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2004, 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.172 2004/10/09 02:46:40 momjian Exp $
12 *-------------------------------------------------------------------------
25 #include "access/clog.h"
26 #include "access/subtrans.h"
27 #include "access/xact.h"
28 #include "access/xlog.h"
29 #include "access/xlog_internal.h"
30 #include "access/xlogutils.h"
31 #include "catalog/catversion.h"
32 #include "catalog/pg_control.h"
33 #include "miscadmin.h"
34 #include "postmaster/bgwriter.h"
35 #include "storage/bufpage.h"
36 #include "storage/fd.h"
37 #include "storage/lwlock.h"
38 #include "storage/pmsignal.h"
39 #include "storage/proc.h"
40 #include "storage/sinval.h"
41 #include "storage/spin.h"
42 #include "utils/builtins.h"
43 #include "utils/guc.h"
44 #include "utils/relcache.h"
48 * This chunk of hackery attempts to determine which file sync methods
49 * are available on the current platform, and to choose an appropriate
50 * default method. We assume that fsync() is always available, and that
51 * configure determined whether fdatasync() is.
53 #define SYNC_METHOD_FSYNC 0
54 #define SYNC_METHOD_FDATASYNC 1
55 #define SYNC_METHOD_OPEN 2 /* used for both O_SYNC and
59 #define OPEN_SYNC_FLAG O_SYNC
62 #define OPEN_SYNC_FLAG O_FSYNC
66 #if defined(OPEN_SYNC_FLAG)
67 #if defined(O_DSYNC) && (O_DSYNC != OPEN_SYNC_FLAG)
68 #define OPEN_DATASYNC_FLAG O_DSYNC
72 #if defined(OPEN_DATASYNC_FLAG)
73 #define DEFAULT_SYNC_METHOD_STR "open_datasync"
74 #define DEFAULT_SYNC_METHOD SYNC_METHOD_OPEN
75 #define DEFAULT_SYNC_FLAGBIT OPEN_DATASYNC_FLAG
77 #if defined(HAVE_FDATASYNC)
78 #define DEFAULT_SYNC_METHOD_STR "fdatasync"
79 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FDATASYNC
80 #define DEFAULT_SYNC_FLAGBIT 0
82 #define DEFAULT_SYNC_METHOD_STR "fsync"
83 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FSYNC
84 #define DEFAULT_SYNC_FLAGBIT 0
89 /* User-settable parameters */
90 int CheckPointSegments = 3;
92 char *XLogArchiveCommand = NULL;
93 char *XLOG_sync_method = NULL;
94 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
97 bool XLOG_DEBUG = false;
101 * XLOGfileslop is used in the code as the allowed "fuzz" in the number of
102 * preallocated XLOG segments --- we try to have at least XLOGfiles advance
103 * segments but no more than XLOGfileslop segments. This could
104 * be made a separate GUC variable, but at present I think it's sufficient
105 * to hardwire it as 2*CheckPointSegments+1. Under normal conditions, a
106 * checkpoint will free no more than 2*CheckPointSegments log segments, and
107 * we want to recycle all of them; the +1 allows boundary cases to happen
108 * without wasting a delete/create-segment cycle.
111 #define XLOGfileslop (2*CheckPointSegments + 1)
114 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
115 static int sync_method = DEFAULT_SYNC_METHOD;
116 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
118 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
120 #define MinXLOGbuffers 4
124 * ThisTimeLineID will be same in all backends --- it identifies current
125 * WAL timeline for the database system.
127 TimeLineID ThisTimeLineID = 0;
129 /* Are we doing recovery from XLOG? */
130 bool InRecovery = false;
132 /* Are we recovering using offline XLOG archives? */
133 static bool InArchiveRecovery = false;
135 /* Was the last xlog file restored from archive, or local? */
136 static bool restoredFromArchive = false;
138 /* options taken from recovery.conf */
139 static char *recoveryRestoreCommand = NULL;
140 static bool recoveryTarget = false;
141 static bool recoveryTargetExact = false;
142 static bool recoveryTargetInclusive = true;
143 static TransactionId recoveryTargetXid;
144 static time_t recoveryTargetTime;
146 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
147 static TransactionId recoveryStopXid;
148 static time_t recoveryStopTime;
149 static bool recoveryStopAfter;
151 /* constraint set by read_backup_label */
152 static XLogRecPtr recoveryMinXlogOffset = {0, 0};
155 * During normal operation, the only timeline we care about is ThisTimeLineID.
156 * During recovery, however, things are more complicated. To simplify life
157 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
158 * scan through the WAL history (that is, it is the line that was active when
159 * the currently-scanned WAL record was generated). We also need these
162 * recoveryTargetTLI: the desired timeline that we want to end in.
164 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
165 * its known parents, newest first (so recoveryTargetTLI is always the
166 * first list member). Only these TLIs are expected to be seen in the WAL
167 * segments we read, and indeed only these TLIs will be considered as
168 * candidate WAL files to open at all.
170 * curFileTLI: the TLI appearing in the name of the current input WAL file.
171 * (This is not necessarily the same as ThisTimeLineID, because we could
172 * be scanning data that was copied from an ancestor timeline when the current
173 * file was created.) During a sequential scan we do not allow this value
176 static TimeLineID recoveryTargetTLI;
177 static List *expectedTLIs;
178 static TimeLineID curFileTLI;
181 * MyLastRecPtr points to the start of the last XLOG record inserted by the
182 * current transaction. If MyLastRecPtr.xrecoff == 0, then the current
183 * xact hasn't yet inserted any transaction-controlled XLOG records.
185 * Note that XLOG records inserted outside transaction control are not
186 * reflected into MyLastRecPtr. They do, however, cause MyXactMadeXLogEntry
187 * to be set true. The latter can be used to test whether the current xact
188 * made any loggable changes (including out-of-xact changes, such as
191 * When we insert/update/delete a tuple in a temporary relation, we do not
192 * make any XLOG record, since we don't care about recovering the state of
193 * the temp rel after a crash. However, we will still need to remember
194 * whether our transaction committed or aborted in that case. So, we must
195 * set MyXactMadeTempRelUpdate true to indicate that the XID will be of
198 XLogRecPtr MyLastRecPtr = {0, 0};
200 bool MyXactMadeXLogEntry = false;
202 bool MyXactMadeTempRelUpdate = false;
205 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
206 * current backend. It is updated for all inserts, transaction-controlled
207 * or not. ProcLastRecEnd is similar but points to end+1 of last record.
209 static XLogRecPtr ProcLastRecPtr = {0, 0};
211 XLogRecPtr ProcLastRecEnd = {0, 0};
214 * RedoRecPtr is this backend's local copy of the REDO record pointer
215 * (which is almost but not quite the same as a pointer to the most recent
216 * CHECKPOINT record). We update this from the shared-memory copy,
217 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
218 * hold the Insert lock). See XLogInsert for details. We are also allowed
219 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
220 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
223 static XLogRecPtr RedoRecPtr;
226 * Shared-memory data structures for XLOG control
228 * LogwrtRqst indicates a byte position that we need to write and/or fsync
229 * the log up to (all records before that point must be written or fsynced).
230 * LogwrtResult indicates the byte positions we have already written/fsynced.
231 * These structs are identical but are declared separately to indicate their
232 * slightly different functions.
234 * We do a lot of pushups to minimize the amount of access to lockable
235 * shared memory values. There are actually three shared-memory copies of
236 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
237 * XLogCtl->LogwrtResult is protected by info_lck
238 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
239 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
240 * One must hold the associated lock to read or write any of these, but
241 * of course no lock is needed to read/write the unshared LogwrtResult.
243 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
244 * right", since both are updated by a write or flush operation before
245 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
246 * is that it can be examined/modified by code that already holds WALWriteLock
247 * without needing to grab info_lck as well.
249 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
250 * but is updated when convenient. Again, it exists for the convenience of
251 * code that is already holding WALInsertLock but not the other locks.
253 * The unshared LogwrtResult may lag behind any or all of these, and again
254 * is updated when convenient.
256 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
257 * (protected by info_lck), but we don't need to cache any copies of it.
259 * Note that this all works because the request and result positions can only
260 * advance forward, never back up, and so we can easily determine which of two
261 * values is "more up to date".
263 * info_lck is only held long enough to read/update the protected variables,
264 * so it's a plain spinlock. The other locks are held longer (potentially
265 * over I/O operations), so we use LWLocks for them. These locks are:
267 * WALInsertLock: must be held to insert a record into the WAL buffers.
269 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
272 * ControlFileLock: must be held to read/update control file or create
275 * CheckpointLock: must be held to do a checkpoint (ensures only one
276 * checkpointer at a time; even though the postmaster won't launch
277 * parallel checkpoint processes, we need this because manual checkpoints
278 * could be launched simultaneously).
283 typedef struct XLogwrtRqst
285 XLogRecPtr Write; /* last byte + 1 to write out */
286 XLogRecPtr Flush; /* last byte + 1 to flush */
289 typedef struct XLogwrtResult
291 XLogRecPtr Write; /* last byte + 1 written out */
292 XLogRecPtr Flush; /* last byte + 1 flushed */
296 * Shared state data for XLogInsert.
298 typedef struct XLogCtlInsert
300 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
301 XLogRecPtr PrevRecord; /* start of previously-inserted record */
302 uint16 curridx; /* current block index in cache */
303 XLogPageHeader currpage; /* points to header of block in cache */
304 char *currpos; /* current insertion point in cache */
305 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
309 * Shared state data for XLogWrite/XLogFlush.
311 typedef struct XLogCtlWrite
313 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
314 uint16 curridx; /* cache index of next block to write */
318 * Total shared-memory state for XLOG.
320 typedef struct XLogCtlData
322 /* Protected by WALInsertLock: */
323 XLogCtlInsert Insert;
324 /* Protected by info_lck: */
325 XLogwrtRqst LogwrtRqst;
326 XLogwrtResult LogwrtResult;
327 /* Protected by WALWriteLock: */
331 * These values do not change after startup, although the pointed-to
332 * pages and xlblocks values certainly do. Permission to read/write
333 * the pages and xlblocks values depends on WALInsertLock and
336 char *pages; /* buffers for unwritten XLOG pages */
337 XLogRecPtr *xlblocks; /* 1st byte ptr-s + BLCKSZ */
338 uint32 XLogCacheByte; /* # bytes in xlog buffers */
339 uint32 XLogCacheBlck; /* highest allocated xlog buffer index */
340 TimeLineID ThisTimeLineID;
342 slock_t info_lck; /* locks shared LogwrtRqst/LogwrtResult */
345 static XLogCtlData *XLogCtl = NULL;
348 * We maintain an image of pg_control in shared memory.
350 static ControlFileData *ControlFile = NULL;
353 * Macros for managing XLogInsert state. In most cases, the calling routine
354 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
355 * so these are passed as parameters instead of being fetched via XLogCtl.
358 /* Free space remaining in the current xlog page buffer */
359 #define INSERT_FREESPACE(Insert) \
360 (BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
362 /* Construct XLogRecPtr value for current insertion point */
363 #define INSERT_RECPTR(recptr,Insert,curridx) \
365 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
367 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
370 #define PrevBufIdx(idx) \
371 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
373 #define NextBufIdx(idx) \
374 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
377 /* File path names */
378 char XLogDir[MAXPGPATH];
379 static char ControlFilePath[MAXPGPATH];
382 * Private, possibly out-of-date copy of shared LogwrtResult.
383 * See discussion above.
385 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
388 * openLogFile is -1 or a kernel FD for an open log file segment.
389 * When it's open, openLogOff is the current seek offset in the file.
390 * openLogId/openLogSeg identify the segment. These variables are only
391 * used to write the XLOG, and so will normally refer to the active segment.
393 static int openLogFile = -1;
394 static uint32 openLogId = 0;
395 static uint32 openLogSeg = 0;
396 static uint32 openLogOff = 0;
399 * These variables are used similarly to the ones above, but for reading
400 * the XLOG. Note, however, that readOff generally represents the offset
401 * of the page just read, not the seek position of the FD itself, which
402 * will be just past that page.
404 static int readFile = -1;
405 static uint32 readId = 0;
406 static uint32 readSeg = 0;
407 static uint32 readOff = 0;
409 /* Buffer for currently read page (BLCKSZ bytes) */
410 static char *readBuf = NULL;
412 /* Buffer for current ReadRecord result (expandable) */
413 static char *readRecordBuf = NULL;
414 static uint32 readRecordBufSize = 0;
416 /* State information for XLOG reading */
417 static XLogRecPtr ReadRecPtr;
418 static XLogRecPtr EndRecPtr;
419 static XLogRecord *nextRecord = NULL;
420 static TimeLineID lastPageTLI = 0;
422 static bool InRedo = false;
425 static void XLogArchiveNotify(const char *xlog);
426 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
427 static bool XLogArchiveIsDone(const char *xlog);
428 static void XLogArchiveCleanup(const char *xlog);
429 static void readRecoveryCommandFile(void);
430 static void exitArchiveRecovery(TimeLineID endTLI,
431 uint32 endLogId, uint32 endLogSeg);
432 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
434 static bool AdvanceXLInsertBuffer(void);
435 static void XLogWrite(XLogwrtRqst WriteRqst);
436 static int XLogFileInit(uint32 log, uint32 seg,
437 bool *use_existent, bool use_lock);
438 static bool InstallXLogFileSegment(uint32 log, uint32 seg, char *tmppath,
439 bool find_free, int max_advance,
441 static int XLogFileOpen(uint32 log, uint32 seg);
442 static int XLogFileRead(uint32 log, uint32 seg, int emode);
443 static bool RestoreArchivedFile(char *path, const char *xlogfname,
444 const char *recovername, off_t expectedSize);
445 static void PreallocXlogFiles(XLogRecPtr endptr);
446 static void MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr);
447 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
448 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
449 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
450 static List *readTimeLineHistory(TimeLineID targetTLI);
451 static bool existsTimeLineHistory(TimeLineID probeTLI);
452 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
453 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
455 uint32 endLogId, uint32 endLogSeg);
456 static void WriteControlFile(void);
457 static void ReadControlFile(void);
458 static char *str_time(time_t tnow);
459 static void issue_xlog_fsync(void);
462 static void xlog_outrec(char *buf, XLogRecord *record);
464 static bool read_backup_label(XLogRecPtr *checkPointLoc);
465 static void remove_backup_label(void);
469 * Insert an XLOG record having the specified RMID and info bytes,
470 * with the body of the record being the data chunk(s) described by
471 * the rdata list (see xlog.h for notes about rdata).
473 * Returns XLOG pointer to end of record (beginning of next record).
474 * This can be used as LSN for data pages affected by the logged action.
475 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
476 * before the data page can be written out. This implements the basic
477 * WAL rule "write the log before the data".)
479 * NB: this routine feels free to scribble on the XLogRecData structs,
480 * though not on the data they reference. This is OK since the XLogRecData
481 * structs are always just temporaries in the calling code.
484 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
486 XLogCtlInsert *Insert = &XLogCtl->Insert;
488 XLogContRecord *contrecord;
490 XLogRecPtr WriteRqst;
494 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
495 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
496 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
497 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
498 XLogRecData dtbuf_rdt[2 * XLR_MAX_BKP_BLOCKS];
503 XLogwrtRqst LogwrtRqst;
505 bool no_tran = (rmid == RM_XLOG_ID) ? true : false;
507 if (info & XLR_INFO_MASK)
509 if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
510 elog(PANIC, "invalid xlog info mask %02X", (info & XLR_INFO_MASK));
512 info &= ~XLR_INFO_MASK;
516 * In bootstrap mode, we don't actually log anything but XLOG
517 * resources; return a phony record pointer.
519 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
522 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt
528 * Here we scan the rdata list, determine which buffers must be backed
529 * up, and compute the CRC values for the data. Note that the record
530 * header isn't added into the CRC yet since we don't know the final
531 * length or info bits quite yet.
533 * We may have to loop back to here if a race condition is detected
534 * below. We could prevent the race by doing all this work while
535 * holding the insert lock, but it seems better to avoid doing CRC
536 * calculations while holding the lock. This means we have to be
537 * careful about modifying the rdata list until we know we aren't
538 * going to loop back again. The only change we allow ourselves to
539 * make earlier is to set rdt->data = NULL in list items we have
540 * decided we will have to back up the whole buffer for. This is OK
541 * because we will certainly decide the same thing again for those
542 * items if we do it over; doing it here saves an extra pass over the
546 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
548 dtbuf[i] = InvalidBuffer;
549 dtbuf_bkp[i] = false;
552 INIT_CRC64(rdata_crc);
556 if (rdt->buffer == InvalidBuffer)
558 /* Simple data, just include it */
560 COMP_CRC64(rdata_crc, rdt->data, rdt->len);
564 /* Find info for buffer */
565 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
567 if (rdt->buffer == dtbuf[i])
569 /* Buffer already referenced by earlier list item */
575 COMP_CRC64(rdata_crc, rdt->data, rdt->len);
579 if (dtbuf[i] == InvalidBuffer)
581 /* OK, put it in this slot */
582 dtbuf[i] = rdt->buffer;
585 * XXX We assume page LSN is first data on page
587 dtbuf_lsn[i] = *((XLogRecPtr *) BufferGetBlock(rdt->buffer));
588 if (XLByteLE(dtbuf_lsn[i], RedoRecPtr))
596 BufferGetBlock(dtbuf[i]),
598 dtbuf_xlg[i].node = BufferGetFileNode(dtbuf[i]);
599 dtbuf_xlg[i].block = BufferGetBlockNumber(dtbuf[i]);
601 (char *) &(dtbuf_xlg[i]) + sizeof(crc64),
602 sizeof(BkpBlock) - sizeof(crc64));
604 dtbuf_xlg[i].crc = dtcrc;
609 COMP_CRC64(rdata_crc, rdt->data, rdt->len);
614 if (i >= XLR_MAX_BKP_BLOCKS)
615 elog(PANIC, "can backup at most %d blocks per xlog record",
618 /* Break out of loop when rdt points to last list item */
619 if (rdt->next == NULL)
625 * NOTE: the test for len == 0 here is somewhat fishy, since in theory
626 * all of the rmgr data might have been suppressed in favor of backup
627 * blocks. Currently, all callers of XLogInsert provide at least some
628 * not-in-a-buffer data and so len == 0 should never happen, but that
629 * may not be true forever. If you need to remove the len == 0 check,
630 * also remove the check for xl_len == 0 in ReadRecord, below.
633 elog(PANIC, "invalid xlog record length %u", len);
635 START_CRIT_SECTION();
637 /* update LogwrtResult before doing cache fill check */
639 /* use volatile pointer to prevent code rearrangement */
640 volatile XLogCtlData *xlogctl = XLogCtl;
642 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
643 LogwrtRqst = xlogctl->LogwrtRqst;
644 LogwrtResult = xlogctl->LogwrtResult;
645 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
649 * If cache is half filled then try to acquire write lock and do
650 * XLogWrite. Ignore any fractional blocks in performing this check.
652 LogwrtRqst.Write.xrecoff -= LogwrtRqst.Write.xrecoff % BLCKSZ;
653 if (LogwrtRqst.Write.xlogid != LogwrtResult.Write.xlogid ||
654 (LogwrtRqst.Write.xrecoff >= LogwrtResult.Write.xrecoff +
655 XLogCtl->XLogCacheByte / 2))
657 if (LWLockConditionalAcquire(WALWriteLock, LW_EXCLUSIVE))
659 LogwrtResult = XLogCtl->Write.LogwrtResult;
660 if (XLByteLT(LogwrtResult.Write, LogwrtRqst.Write))
661 XLogWrite(LogwrtRqst);
662 LWLockRelease(WALWriteLock);
666 /* Now wait to get insert lock */
667 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
670 * Check to see if my RedoRecPtr is out of date. If so, may have to
671 * go back and recompute everything. This can only happen just after
672 * a checkpoint, so it's better to be slow in this case and fast
675 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
677 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
678 RedoRecPtr = Insert->RedoRecPtr;
680 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
682 if (dtbuf[i] == InvalidBuffer)
684 if (dtbuf_bkp[i] == false &&
685 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
688 * Oops, this buffer now needs to be backed up, but we
689 * didn't think so above. Start over.
691 LWLockRelease(WALInsertLock);
699 * Make additional rdata list entries for the backup blocks, so that
700 * we don't need to special-case them in the write loop. Note that we
701 * have now irrevocably changed the input rdata list. At the exit of
702 * this loop, write_len includes the backup block data.
704 * Also set the appropriate info bits to show which buffers were backed
705 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th
706 * distinct buffer value (ignoring InvalidBuffer) appearing in the
710 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
712 if (dtbuf[i] == InvalidBuffer || !(dtbuf_bkp[i]))
715 info |= XLR_SET_BKP_BLOCK(i);
717 rdt->next = &(dtbuf_rdt[2 * i]);
719 dtbuf_rdt[2 * i].data = (char *) &(dtbuf_xlg[i]);
720 dtbuf_rdt[2 * i].len = sizeof(BkpBlock);
721 write_len += sizeof(BkpBlock);
723 rdt = dtbuf_rdt[2 * i].next = &(dtbuf_rdt[2 * i + 1]);
725 dtbuf_rdt[2 * i + 1].data = (char *) BufferGetBlock(dtbuf[i]);
726 dtbuf_rdt[2 * i + 1].len = BLCKSZ;
728 dtbuf_rdt[2 * i + 1].next = NULL;
732 * If there isn't enough space on the current XLOG page for a record
733 * header, advance to the next page (leaving the unused space as
737 freespace = INSERT_FREESPACE(Insert);
738 if (freespace < SizeOfXLogRecord)
740 updrqst = AdvanceXLInsertBuffer();
741 freespace = INSERT_FREESPACE(Insert);
744 curridx = Insert->curridx;
745 record = (XLogRecord *) Insert->currpos;
747 /* Insert record header */
749 record->xl_prev = Insert->PrevRecord;
750 record->xl_xid = GetCurrentTransactionIdIfAny();
751 record->xl_len = len; /* doesn't include backup blocks */
752 record->xl_info = info;
753 record->xl_rmid = rmid;
755 /* Now we can finish computing the main CRC */
756 COMP_CRC64(rdata_crc, (char *) record + sizeof(crc64),
757 SizeOfXLogRecord - sizeof(crc64));
758 FIN_CRC64(rdata_crc);
759 record->xl_crc = rdata_crc;
761 /* Compute record's XLOG location */
762 INSERT_RECPTR(RecPtr, Insert, curridx);
764 /* If first XLOG record of transaction, save it in PGPROC array */
765 if (MyLastRecPtr.xrecoff == 0 && !no_tran)
768 * We do not acquire SInvalLock here because of possible deadlock.
769 * Anyone who wants to inspect other procs' logRec must acquire
770 * WALInsertLock, instead. A better solution would be a per-PROC
771 * spinlock, but no time for that before 7.2 --- tgl 12/19/01.
773 MyProc->logRec = RecPtr;
781 sprintf(buf, "INSERT @ %X/%X: ", RecPtr.xlogid, RecPtr.xrecoff);
782 xlog_outrec(buf, record);
783 if (rdata->data != NULL)
786 RmgrTable[record->xl_rmid].rm_desc(buf, record->xl_info, rdata->data);
788 elog(LOG, "%s", buf);
792 /* Record begin of record in appropriate places */
794 MyLastRecPtr = RecPtr;
795 ProcLastRecPtr = RecPtr;
796 Insert->PrevRecord = RecPtr;
797 MyXactMadeXLogEntry = true;
799 Insert->currpos += SizeOfXLogRecord;
800 freespace -= SizeOfXLogRecord;
803 * Append the data, including backup blocks if any
807 while (rdata->data == NULL)
812 if (rdata->len > freespace)
814 memcpy(Insert->currpos, rdata->data, freespace);
815 rdata->data += freespace;
816 rdata->len -= freespace;
817 write_len -= freespace;
821 memcpy(Insert->currpos, rdata->data, rdata->len);
822 freespace -= rdata->len;
823 write_len -= rdata->len;
824 Insert->currpos += rdata->len;
830 /* Use next buffer */
831 updrqst = AdvanceXLInsertBuffer();
832 curridx = Insert->curridx;
833 /* Insert cont-record header */
834 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
835 contrecord = (XLogContRecord *) Insert->currpos;
836 contrecord->xl_rem_len = write_len;
837 Insert->currpos += SizeOfXLogContRecord;
838 freespace = INSERT_FREESPACE(Insert);
841 /* Ensure next record will be properly aligned */
842 Insert->currpos = (char *) Insert->currpage +
843 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
844 freespace = INSERT_FREESPACE(Insert);
847 * The recptr I return is the beginning of the *next* record. This
848 * will be stored as LSN for changed data pages...
850 INSERT_RECPTR(RecPtr, Insert, curridx);
852 /* Need to update shared LogwrtRqst if some block was filled up */
853 if (freespace < SizeOfXLogRecord)
854 updrqst = true; /* curridx is filled and available for
857 curridx = PrevBufIdx(curridx);
858 WriteRqst = XLogCtl->xlblocks[curridx];
860 LWLockRelease(WALInsertLock);
864 /* use volatile pointer to prevent code rearrangement */
865 volatile XLogCtlData *xlogctl = XLogCtl;
867 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
868 /* advance global request to include new block(s) */
869 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
870 xlogctl->LogwrtRqst.Write = WriteRqst;
871 /* update local result copy while I have the chance */
872 LogwrtResult = xlogctl->LogwrtResult;
873 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
876 ProcLastRecEnd = RecPtr;
886 * Create an archive notification file
888 * The name of the notification file is the message that will be picked up
889 * by the archiver, e.g. we write 0000000100000001000000C6.ready
890 * and the archiver then knows to archive XLogDir/0000000100000001000000C6,
891 * then when complete, rename it to 0000000100000001000000C6.done
894 XLogArchiveNotify(const char *xlog)
896 char archiveStatusPath[MAXPGPATH];
899 /* insert an otherwise empty file called <XLOG>.ready */
900 StatusFilePath(archiveStatusPath, xlog, ".ready");
901 fd = AllocateFile(archiveStatusPath, "w");
905 (errcode_for_file_access(),
906 errmsg("could not create archive status file \"%s\": %m",
907 archiveStatusPath)));
913 (errcode_for_file_access(),
914 errmsg("could not write archive status file \"%s\": %m",
915 archiveStatusPath)));
919 /* Notify archiver that it's got something to do */
920 if (IsUnderPostmaster)
921 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
925 * Convenience routine to notify using log/seg representation of filename
928 XLogArchiveNotifySeg(uint32 log, uint32 seg)
930 char xlog[MAXFNAMELEN];
932 XLogFileName(xlog, ThisTimeLineID, log, seg);
933 XLogArchiveNotify(xlog);
939 * Checks for a ".done" archive notification file. This is called when we
940 * are ready to delete or recycle an old XLOG segment file. If it is okay
941 * to delete it then return true.
943 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
944 * then return false; else create <XLOG>.ready and return false. The
945 * last case covers the possibility that the original attempt to create
946 * <XLOG>.ready failed.
949 XLogArchiveIsDone(const char *xlog)
951 char archiveStatusPath[MAXPGPATH];
952 struct stat stat_buf;
954 /* First check for .done --- this is the expected case */
955 StatusFilePath(archiveStatusPath, xlog, ".done");
956 if (stat(archiveStatusPath, &stat_buf) == 0)
959 /* check for .ready --- this means archiver is still busy with it */
960 StatusFilePath(archiveStatusPath, xlog, ".ready");
961 if (stat(archiveStatusPath, &stat_buf) == 0)
964 /* Race condition --- maybe archiver just finished, so recheck */
965 StatusFilePath(archiveStatusPath, xlog, ".done");
966 if (stat(archiveStatusPath, &stat_buf) == 0)
969 /* Retry creation of the .ready file */
970 XLogArchiveNotify(xlog);
977 * Cleanup archive notification file(s) for a particular xlog segment
980 XLogArchiveCleanup(const char *xlog)
982 char archiveStatusPath[MAXPGPATH];
984 /* Remove the .done file */
985 StatusFilePath(archiveStatusPath, xlog, ".done");
986 unlink(archiveStatusPath);
987 /* should we complain about failure? */
989 /* Remove the .ready file if present --- normally it shouldn't be */
990 StatusFilePath(archiveStatusPath, xlog, ".ready");
991 unlink(archiveStatusPath);
992 /* should we complain about failure? */
996 * Advance the Insert state to the next buffer page, writing out the next
997 * buffer if it still contains unwritten data.
999 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1000 * just-filled page. If we can do this for free (without an extra lock),
1001 * we do so here. Otherwise the caller must do it. We return TRUE if the
1002 * request update still needs to be done, FALSE if we did it internally.
1004 * Must be called with WALInsertLock held.
1007 AdvanceXLInsertBuffer(void)
1009 XLogCtlInsert *Insert = &XLogCtl->Insert;
1010 XLogCtlWrite *Write = &XLogCtl->Write;
1011 uint16 nextidx = NextBufIdx(Insert->curridx);
1012 bool update_needed = true;
1013 XLogRecPtr OldPageRqstPtr;
1014 XLogwrtRqst WriteRqst;
1015 XLogRecPtr NewPageEndPtr;
1016 XLogPageHeader NewPage;
1018 /* Use Insert->LogwrtResult copy if it's more fresh */
1019 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1020 LogwrtResult = Insert->LogwrtResult;
1023 * Get ending-offset of the buffer page we need to replace (this may
1024 * be zero if the buffer hasn't been used yet). Fall through if it's
1025 * already written out.
1027 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1028 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1030 /* nope, got work to do... */
1031 XLogRecPtr FinishedPageRqstPtr;
1033 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1035 /* Before waiting, get info_lck and update LogwrtResult */
1037 /* use volatile pointer to prevent code rearrangement */
1038 volatile XLogCtlData *xlogctl = XLogCtl;
1040 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
1041 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1042 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1043 LogwrtResult = xlogctl->LogwrtResult;
1044 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
1047 update_needed = false; /* Did the shared-request update */
1049 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1051 /* OK, someone wrote it already */
1052 Insert->LogwrtResult = LogwrtResult;
1056 /* Must acquire write lock */
1057 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1058 LogwrtResult = Write->LogwrtResult;
1059 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1061 /* OK, someone wrote it already */
1062 LWLockRelease(WALWriteLock);
1063 Insert->LogwrtResult = LogwrtResult;
1068 * Have to write buffers while holding insert lock. This
1069 * is not good, so only write as much as we absolutely
1072 WriteRqst.Write = OldPageRqstPtr;
1073 WriteRqst.Flush.xlogid = 0;
1074 WriteRqst.Flush.xrecoff = 0;
1075 XLogWrite(WriteRqst);
1076 LWLockRelease(WALWriteLock);
1077 Insert->LogwrtResult = LogwrtResult;
1083 * Now the next buffer slot is free and we can set it up to be the
1086 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1087 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1089 /* crossing a logid boundary */
1090 NewPageEndPtr.xlogid += 1;
1091 NewPageEndPtr.xrecoff = BLCKSZ;
1094 NewPageEndPtr.xrecoff += BLCKSZ;
1095 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1096 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * BLCKSZ);
1097 Insert->curridx = nextidx;
1098 Insert->currpage = NewPage;
1099 Insert->currpos = ((char *) NewPage) + SizeOfXLogShortPHD;
1102 * Be sure to re-zero the buffer so that bytes beyond what we've
1103 * written will look like zeroes and not valid XLOG records...
1105 MemSet((char *) NewPage, 0, BLCKSZ);
1108 * Fill the new page's header
1110 NewPage->xlp_magic = XLOG_PAGE_MAGIC;
1111 /* NewPage->xlp_info = 0; */ /* done by memset */
1112 NewPage->xlp_tli = ThisTimeLineID;
1113 NewPage->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1114 NewPage->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - BLCKSZ;
1117 * If first page of an XLOG segment file, make it a long header.
1119 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1121 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1123 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1124 NewLongPage->xlp_seg_size = XLogSegSize;
1125 NewPage->xlp_info |= XLP_LONG_HEADER;
1126 Insert->currpos = ((char *) NewPage) + SizeOfXLogLongPHD;
1129 return update_needed;
1133 * Write and/or fsync the log at least as far as WriteRqst indicates.
1135 * Must be called with WALWriteLock held.
1138 XLogWrite(XLogwrtRqst WriteRqst)
1140 XLogCtlWrite *Write = &XLogCtl->Write;
1146 * Update local LogwrtResult (caller probably did this already,
1149 LogwrtResult = Write->LogwrtResult;
1151 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1154 * Make sure we're not ahead of the insert process. This could
1155 * happen if we're passed a bogus WriteRqst.Write that is past the
1156 * end of the last page that's been initialized by
1157 * AdvanceXLInsertBuffer.
1159 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[Write->curridx]))
1160 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1161 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1162 XLogCtl->xlblocks[Write->curridx].xlogid,
1163 XLogCtl->xlblocks[Write->curridx].xrecoff);
1165 /* Advance LogwrtResult.Write to end of current buffer page */
1166 LogwrtResult.Write = XLogCtl->xlblocks[Write->curridx];
1167 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1169 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1172 * Switch to new logfile segment.
1174 if (openLogFile >= 0)
1176 if (close(openLogFile))
1178 (errcode_for_file_access(),
1179 errmsg("could not close log file %u, segment %u: %m",
1180 openLogId, openLogSeg)));
1183 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1185 /* create/use new log file */
1186 use_existent = true;
1187 openLogFile = XLogFileInit(openLogId, openLogSeg,
1188 &use_existent, true);
1191 /* update pg_control, unless someone else already did */
1192 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1193 if (ControlFile->logId < openLogId ||
1194 (ControlFile->logId == openLogId &&
1195 ControlFile->logSeg < openLogSeg + 1))
1197 ControlFile->logId = openLogId;
1198 ControlFile->logSeg = openLogSeg + 1;
1199 ControlFile->time = time(NULL);
1200 UpdateControlFile();
1203 * Signal postmaster to start a checkpoint if it's been
1204 * too long since the last one. (We look at local copy of
1205 * RedoRecPtr which might be a little out of date, but
1206 * should be close enough for this purpose.)
1208 if (IsUnderPostmaster &&
1209 (openLogId != RedoRecPtr.xlogid ||
1210 openLogSeg >= (RedoRecPtr.xrecoff / XLogSegSize) +
1211 (uint32) CheckPointSegments))
1215 elog(LOG, "time for a checkpoint, signaling bgwriter");
1217 RequestCheckpoint(false);
1220 LWLockRelease(ControlFileLock);
1223 if (openLogFile < 0)
1225 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1226 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1230 /* Need to seek in the file? */
1231 if (openLogOff != (LogwrtResult.Write.xrecoff - BLCKSZ) % XLogSegSize)
1233 openLogOff = (LogwrtResult.Write.xrecoff - BLCKSZ) % XLogSegSize;
1234 if (lseek(openLogFile, (off_t) openLogOff, SEEK_SET) < 0)
1236 (errcode_for_file_access(),
1237 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
1238 openLogId, openLogSeg, openLogOff)));
1241 /* OK to write the page */
1242 from = XLogCtl->pages + Write->curridx * BLCKSZ;
1244 if (write(openLogFile, from, BLCKSZ) != BLCKSZ)
1246 /* if write didn't set errno, assume problem is no disk space */
1250 (errcode_for_file_access(),
1251 errmsg("could not write to log file %u, segment %u at offset %u: %m",
1252 openLogId, openLogSeg, openLogOff)));
1254 openLogOff += BLCKSZ;
1257 * If we just wrote the whole last page of a logfile segment,
1258 * fsync the segment immediately. This avoids having to go back
1259 * and re-open prior segments when an fsync request comes along
1260 * later. Doing it here ensures that one and only one backend will
1261 * perform this fsync.
1263 * This is also the right place to notify the Archiver that the
1264 * segment is ready to copy to archival storage.
1266 if (openLogOff >= XLogSegSize && !ispartialpage)
1269 LogwrtResult.Flush = LogwrtResult.Write; /* end of current page */
1271 if (XLogArchivingActive())
1272 XLogArchiveNotifySeg(openLogId, openLogSeg);
1277 /* Only asked to write a partial page */
1278 LogwrtResult.Write = WriteRqst.Write;
1281 Write->curridx = NextBufIdx(Write->curridx);
1285 * If asked to flush, do so
1287 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1288 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1291 * Could get here without iterating above loop, in which case we
1292 * might have no open file or the wrong one. However, we do not
1293 * need to fsync more than one file.
1295 if (sync_method != SYNC_METHOD_OPEN)
1297 if (openLogFile >= 0 &&
1298 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1300 if (close(openLogFile))
1302 (errcode_for_file_access(),
1303 errmsg("could not close log file %u, segment %u: %m",
1304 openLogId, openLogSeg)));
1307 if (openLogFile < 0)
1309 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1310 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1315 LogwrtResult.Flush = LogwrtResult.Write;
1319 * Update shared-memory status
1321 * We make sure that the shared 'request' values do not fall behind the
1322 * 'result' values. This is not absolutely essential, but it saves
1323 * some code in a couple of places.
1326 /* use volatile pointer to prevent code rearrangement */
1327 volatile XLogCtlData *xlogctl = XLogCtl;
1329 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
1330 xlogctl->LogwrtResult = LogwrtResult;
1331 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1332 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1333 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1334 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1335 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
1338 Write->LogwrtResult = LogwrtResult;
1342 * Ensure that all XLOG data through the given position is flushed to disk.
1344 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1345 * already held, and we try to avoid acquiring it if possible.
1348 XLogFlush(XLogRecPtr record)
1350 XLogRecPtr WriteRqstPtr;
1351 XLogwrtRqst WriteRqst;
1353 /* Disabled during REDO */
1357 /* Quick exit if already known flushed */
1358 if (XLByteLE(record, LogwrtResult.Flush))
1363 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1364 record.xlogid, record.xrecoff,
1365 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1366 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1369 START_CRIT_SECTION();
1372 * Since fsync is usually a horribly expensive operation, we try to
1373 * piggyback as much data as we can on each fsync: if we see any more
1374 * data entered into the xlog buffer, we'll write and fsync that too,
1375 * so that the final value of LogwrtResult.Flush is as large as
1376 * possible. This gives us some chance of avoiding another fsync
1377 * immediately after.
1380 /* initialize to given target; may increase below */
1381 WriteRqstPtr = record;
1383 /* read LogwrtResult and update local state */
1385 /* use volatile pointer to prevent code rearrangement */
1386 volatile XLogCtlData *xlogctl = XLogCtl;
1388 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
1389 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1390 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1391 LogwrtResult = xlogctl->LogwrtResult;
1392 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
1396 if (!XLByteLE(record, LogwrtResult.Flush))
1398 /* now wait for the write lock */
1399 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1400 LogwrtResult = XLogCtl->Write.LogwrtResult;
1401 if (!XLByteLE(record, LogwrtResult.Flush))
1403 /* try to write/flush later additions to XLOG as well */
1404 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1406 XLogCtlInsert *Insert = &XLogCtl->Insert;
1407 uint32 freespace = INSERT_FREESPACE(Insert);
1409 if (freespace < SizeOfXLogRecord) /* buffer is full */
1410 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1413 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1414 WriteRqstPtr.xrecoff -= freespace;
1416 LWLockRelease(WALInsertLock);
1417 WriteRqst.Write = WriteRqstPtr;
1418 WriteRqst.Flush = WriteRqstPtr;
1422 WriteRqst.Write = WriteRqstPtr;
1423 WriteRqst.Flush = record;
1425 XLogWrite(WriteRqst);
1427 LWLockRelease(WALWriteLock);
1433 * If we still haven't flushed to the request point then we have a
1434 * problem; most likely, the requested flush point is past end of
1435 * XLOG. This has been seen to occur when a disk page has a corrupted
1438 * Formerly we treated this as a PANIC condition, but that hurts the
1439 * system's robustness rather than helping it: we do not want to take
1440 * down the whole system due to corruption on one data page. In
1441 * particular, if the bad page is encountered again during recovery
1442 * then we would be unable to restart the database at all! (This
1443 * scenario has actually happened in the field several times with 7.1
1444 * releases. Note that we cannot get here while InRedo is true, but if
1445 * the bad page is brought in and marked dirty during recovery then
1446 * CreateCheckPoint will try to flush it at the end of recovery.)
1448 * The current approach is to ERROR under normal conditions, but only
1449 * WARNING during recovery, so that the system can be brought up even
1450 * if there's a corrupt LSN. Note that for calls from xact.c, the
1451 * ERROR will be promoted to PANIC since xact.c calls this routine
1452 * inside a critical section. However, calls from bufmgr.c are not
1453 * within critical sections and so we will not force a restart for a
1454 * bad LSN on a data page.
1456 if (XLByteLT(LogwrtResult.Flush, record))
1457 elog(InRecovery ? WARNING : ERROR,
1458 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1459 record.xlogid, record.xrecoff,
1460 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1464 * Create a new XLOG file segment, or open a pre-existing one.
1466 * log, seg: identify segment to be created/opened.
1468 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1469 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1472 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1473 * place. This should be TRUE except during bootstrap log creation. The
1474 * caller must *not* hold the lock at call.
1476 * Returns FD of opened file.
1479 XLogFileInit(uint32 log, uint32 seg,
1480 bool *use_existent, bool use_lock)
1482 char path[MAXPGPATH];
1483 char tmppath[MAXPGPATH];
1484 char zbuffer[BLCKSZ];
1488 XLogFilePath(path, ThisTimeLineID, log, seg);
1491 * Try to use existent file (checkpoint maker may have created it
1496 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1500 if (errno != ENOENT)
1502 (errcode_for_file_access(),
1503 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1511 * Initialize an empty (all zeroes) segment. NOTE: it is possible
1512 * that another process is doing the same thing. If so, we will end
1513 * up pre-creating an extra log segment. That seems OK, and better
1514 * than holding the lock throughout this lengthy process.
1516 snprintf(tmppath, MAXPGPATH, "%s/xlogtemp.%d", XLogDir, getpid());
1520 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1521 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1525 (errcode_for_file_access(),
1526 errmsg("could not create file \"%s\": %m", tmppath)));
1529 * Zero-fill the file. We have to do this the hard way to ensure that
1530 * all the file space has really been allocated --- on platforms that
1531 * allow "holes" in files, just seeking to the end doesn't allocate
1532 * intermediate space. This way, we know that we have all the space
1533 * and (after the fsync below) that all the indirect blocks are down
1534 * on disk. Therefore, fdatasync(2) or O_DSYNC will be sufficient to
1535 * sync future writes to the log file.
1537 MemSet(zbuffer, 0, sizeof(zbuffer));
1538 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(zbuffer))
1541 if ((int) write(fd, zbuffer, sizeof(zbuffer)) != (int) sizeof(zbuffer))
1543 int save_errno = errno;
1546 * If we fail to make the file, delete it to release disk
1550 /* if write didn't set errno, assume problem is no disk space */
1551 errno = save_errno ? save_errno : ENOSPC;
1554 (errcode_for_file_access(),
1555 errmsg("could not write to file \"%s\": %m", tmppath)));
1559 if (pg_fsync(fd) != 0)
1561 (errcode_for_file_access(),
1562 errmsg("could not fsync file \"%s\": %m", tmppath)));
1566 (errcode_for_file_access(),
1567 errmsg("could not close file \"%s\": %m", tmppath)));
1570 * Now move the segment into place with its final name.
1572 * If caller didn't want to use a pre-existing file, get rid of any
1573 * pre-existing file. Otherwise, cope with possibility that someone
1574 * else has created the file while we were filling ours: if so, use
1575 * ours to pre-create a future log segment.
1577 if (!InstallXLogFileSegment(log, seg, tmppath,
1578 *use_existent, XLOGfileslop,
1581 /* No need for any more future segments... */
1585 /* Set flag to tell caller there was no existent file */
1586 *use_existent = false;
1588 /* Now open original target segment (might not be file I just made) */
1589 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1593 (errcode_for_file_access(),
1594 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1601 * Create a new XLOG file segment by copying a pre-existing one.
1603 * log, seg: identify segment to be created.
1605 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
1606 * a different timeline)
1608 * Currently this is only used during recovery, and so there are no locking
1609 * considerations. But we should be just as tense as XLogFileInit to avoid
1610 * emplacing a bogus file.
1613 XLogFileCopy(uint32 log, uint32 seg,
1614 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
1616 char path[MAXPGPATH];
1617 char tmppath[MAXPGPATH];
1618 char buffer[BLCKSZ];
1624 * Open the source file
1626 XLogFilePath(path, srcTLI, srclog, srcseg);
1627 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1630 (errcode_for_file_access(),
1631 errmsg("could not open file \"%s\": %m", path)));
1634 * Copy into a temp file name.
1636 snprintf(tmppath, MAXPGPATH, "%s/xlogtemp.%d", XLogDir, getpid());
1640 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1641 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1645 (errcode_for_file_access(),
1646 errmsg("could not create file \"%s\": %m", tmppath)));
1649 * Do the data copying.
1651 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
1654 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
1658 (errcode_for_file_access(),
1659 errmsg("could not read file \"%s\": %m", path)));
1662 (errmsg("insufficient data in file \"%s\"", path)));
1665 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
1667 int save_errno = errno;
1670 * If we fail to make the file, delete it to release disk
1674 /* if write didn't set errno, assume problem is no disk space */
1675 errno = save_errno ? save_errno : ENOSPC;
1678 (errcode_for_file_access(),
1679 errmsg("could not write to file \"%s\": %m", tmppath)));
1683 if (pg_fsync(fd) != 0)
1685 (errcode_for_file_access(),
1686 errmsg("could not fsync file \"%s\": %m", tmppath)));
1690 (errcode_for_file_access(),
1691 errmsg("could not close file \"%s\": %m", tmppath)));
1696 * Now move the segment into place with its final name.
1698 if (!InstallXLogFileSegment(log, seg, tmppath, false, 0, false))
1699 elog(PANIC, "InstallXLogFileSegment should not have failed");
1703 * Install a new XLOG segment file as a current or future log segment.
1705 * This is used both to install a newly-created segment (which has a temp
1706 * filename while it's being created) and to recycle an old segment.
1708 * log, seg: identify segment to install as (or first possible target).
1710 * tmppath: initial name of file to install. It will be renamed into place.
1712 * find_free: if TRUE, install the new segment at the first empty log/seg
1713 * number at or after the passed numbers. If FALSE, install the new segment
1714 * exactly where specified, deleting any existing segment file there.
1716 * max_advance: maximum number of log/seg slots to advance past the starting
1717 * point. Fail if no free slot is found in this range. (Irrelevant if
1718 * find_free is FALSE.)
1720 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1721 * place. This should be TRUE except during bootstrap log creation. The
1722 * caller must *not* hold the lock at call.
1724 * Returns TRUE if file installed, FALSE if not installed because of
1725 * exceeding max_advance limit. (Any other kind of failure causes ereport().)
1728 InstallXLogFileSegment(uint32 log, uint32 seg, char *tmppath,
1729 bool find_free, int max_advance,
1732 char path[MAXPGPATH];
1733 struct stat stat_buf;
1735 XLogFilePath(path, ThisTimeLineID, log, seg);
1738 * We want to be sure that only one process does this at a time.
1741 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1745 /* Force installation: get rid of any pre-existing segment file */
1750 /* Find a free slot to put it in */
1751 while (stat(path, &stat_buf) == 0)
1753 if (--max_advance < 0)
1755 /* Failed to find a free slot within specified range */
1757 LWLockRelease(ControlFileLock);
1760 NextLogSeg(log, seg);
1761 XLogFilePath(path, ThisTimeLineID, log, seg);
1766 * Prefer link() to rename() here just to be really sure that we don't
1767 * overwrite an existing logfile. However, there shouldn't be one, so
1768 * rename() is an acceptable substitute except for the truly paranoid.
1770 #if HAVE_WORKING_LINK
1771 if (link(tmppath, path) < 0)
1773 (errcode_for_file_access(),
1774 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
1775 tmppath, path, log, seg)));
1778 if (rename(tmppath, path) < 0)
1780 (errcode_for_file_access(),
1781 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
1782 tmppath, path, log, seg)));
1786 LWLockRelease(ControlFileLock);
1792 * Open a pre-existing logfile segment for writing.
1795 XLogFileOpen(uint32 log, uint32 seg)
1797 char path[MAXPGPATH];
1800 XLogFilePath(path, ThisTimeLineID, log, seg);
1802 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1806 (errcode_for_file_access(),
1807 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1814 * Open a logfile segment for reading (during recovery).
1817 XLogFileRead(uint32 log, uint32 seg, int emode)
1819 char path[MAXPGPATH];
1820 char xlogfname[MAXFNAMELEN];
1825 * Loop looking for a suitable timeline ID: we might need to read any
1826 * of the timelines listed in expectedTLIs.
1828 * We expect curFileTLI on entry to be the TLI of the preceding file in
1829 * sequence, or 0 if there was no predecessor. We do not allow
1830 * curFileTLI to go backwards; this prevents us from picking up the
1831 * wrong file when a parent timeline extends to higher segment numbers
1832 * than the child we want to read.
1834 foreach(cell, expectedTLIs)
1836 TimeLineID tli = (TimeLineID) lfirst_int(cell);
1838 if (tli < curFileTLI)
1839 break; /* don't bother looking at too-old TLIs */
1841 if (InArchiveRecovery)
1843 XLogFileName(xlogfname, tli, log, seg);
1844 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
1849 XLogFilePath(path, tli, log, seg);
1851 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1858 if (errno != ENOENT) /* unexpected failure? */
1860 (errcode_for_file_access(),
1861 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1865 /* Couldn't find it. For simplicity, complain about front timeline */
1866 XLogFilePath(path, recoveryTargetTLI, log, seg);
1869 (errcode_for_file_access(),
1870 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1876 * Attempt to retrieve the specified file from off-line archival storage.
1877 * If successful, fill "path" with its complete path (note that this will be
1878 * a temp file name that doesn't follow the normal naming convention), and
1881 * If not successful, fill "path" with the name of the normal on-line file
1882 * (which may or may not actually exist, but we'll try to use it), and return
1885 * For fixed-size files, the caller may pass the expected size as an
1886 * additional crosscheck on successful recovery. If the file size is not
1887 * known, set expectedSize = 0.
1890 RestoreArchivedFile(char *path, const char *xlogfname,
1891 const char *recovername, off_t expectedSize)
1893 char xlogpath[MAXPGPATH];
1894 char xlogRestoreCmd[MAXPGPATH];
1899 struct stat stat_buf;
1902 * When doing archive recovery, we always prefer an archived log file
1903 * even if a file of the same name exists in XLogDir. The reason is
1904 * that the file in XLogDir could be an old, un-filled or
1905 * partly-filled version that was copied and restored as part of
1906 * backing up $PGDATA.
1908 * We could try to optimize this slightly by checking the local copy
1909 * lastchange timestamp against the archived copy, but we have no API
1910 * to do this, nor can we guarantee that the lastchange timestamp was
1911 * preserved correctly when we copied to archive. Our aim is
1912 * robustness, so we elect not to do this.
1914 * If we cannot obtain the log file from the archive, however, we will
1915 * try to use the XLogDir file if it exists. This is so that we can
1916 * make use of log segments that weren't yet transferred to the
1919 * Notice that we don't actually overwrite any files when we copy back
1920 * from archive because the recoveryRestoreCommand may inadvertently
1921 * restore inappropriate xlogs, or they may be corrupt, so we may wish
1922 * to fallback to the segments remaining in current XLogDir later. The
1923 * copy-from-archive filename is always the same, ensuring that we
1924 * don't run out of disk space on long recoveries.
1926 snprintf(xlogpath, MAXPGPATH, "%s/%s", XLogDir, recovername);
1929 * Make sure there is no existing file named recovername.
1931 if (stat(xlogpath, &stat_buf) != 0)
1933 if (errno != ENOENT)
1935 (errcode_for_file_access(),
1936 errmsg("could not stat \"%s\": %m",
1941 if (unlink(xlogpath) != 0)
1943 (errcode_for_file_access(),
1944 errmsg("could not remove file \"%s\": %m",
1949 * construct the command to be executed
1951 dp = xlogRestoreCmd;
1952 endp = xlogRestoreCmd + MAXPGPATH - 1;
1955 for (sp = recoveryRestoreCommand; *sp; sp++)
1962 /* %p: full path of target file */
1964 StrNCpy(dp, xlogpath, endp - dp);
1965 make_native_path(dp);
1969 /* %f: filename of desired file */
1971 StrNCpy(dp, xlogfname, endp - dp);
1975 /* convert %% to a single % */
1981 /* otherwise treat the % as not special */
1996 (errmsg_internal("executing restore command \"%s\"",
2000 * Copy xlog from archival storage to XLogDir
2002 rc = system(xlogRestoreCmd);
2006 * command apparently succeeded, but let's make sure the file is
2007 * really there now and has the correct size.
2009 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2010 * it, but is that too strong? We could try to plow ahead with a
2011 * local copy of the file ... but the problem is that there
2012 * probably isn't one, and we'd incorrectly conclude we've reached
2013 * the end of WAL and we're done recovering ...
2015 if (stat(xlogpath, &stat_buf) == 0)
2017 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2019 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2021 (unsigned long) stat_buf.st_size,
2022 (unsigned long) expectedSize)));
2026 (errmsg("restored log file \"%s\" from archive",
2028 strcpy(path, xlogpath);
2035 if (errno != ENOENT)
2037 (errcode_for_file_access(),
2038 errmsg("could not stat \"%s\": %m",
2044 * remember, we rollforward UNTIL the restore fails so failure here is
2045 * just part of the process... that makes it difficult to determine
2046 * whether the restore failed because there isn't an archive to
2047 * restore, or because the administrator has specified the restore
2048 * program incorrectly. We have to assume the former.
2051 (errmsg("could not restore \"%s\" from archive: return code %d",
2055 * if an archived file is not available, there might still be a
2056 * version of this file in XLogDir, so return that as the filename to
2059 * In many recovery scenarios we expect this to fail also, but if so that
2060 * just means we've reached the end of WAL.
2062 snprintf(path, MAXPGPATH, "%s/%s", XLogDir, xlogfname);
2067 * Preallocate log files beyond the specified log endpoint, according to
2068 * the XLOGfile user parameter.
2071 PreallocXlogFiles(XLogRecPtr endptr)
2078 XLByteToPrevSeg(endptr, _logId, _logSeg);
2079 if ((endptr.xrecoff - 1) % XLogSegSize >=
2080 (uint32) (0.75 * XLogSegSize))
2082 NextLogSeg(_logId, _logSeg);
2083 use_existent = true;
2084 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2090 * Remove or move offline all log files older or equal to passed log/seg#
2092 * endptr is current (or recent) end of xlog; this is used to determine
2093 * whether we want to recycle rather than delete no-longer-wanted log files.
2096 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr)
2101 struct dirent *xlde;
2102 char lastoff[MAXFNAMELEN];
2103 char path[MAXPGPATH];
2105 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2107 xldir = AllocateDir(XLogDir);
2110 (errcode_for_file_access(),
2111 errmsg("could not open transaction log directory \"%s\": %m",
2114 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2117 while ((xlde = readdir(xldir)) != NULL)
2120 * We ignore the timeline part of the XLOG segment identifiers in
2121 * deciding whether a segment is still needed. This ensures that
2122 * we won't prematurely remove a segment from a parent timeline.
2123 * We could probably be a little more proactive about removing
2124 * segments of non-parent timelines, but that would be a whole lot
2127 * We use the alphanumeric sorting property of the filenames to
2128 * decide which ones are earlier than the lastoff segment.
2130 if (strlen(xlde->d_name) == 24 &&
2131 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2132 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2136 if (XLogArchivingActive())
2137 recycle = XLogArchiveIsDone(xlde->d_name);
2143 snprintf(path, MAXPGPATH, "%s/%s", XLogDir, xlde->d_name);
2146 * Before deleting the file, see if it can be recycled as
2147 * a future log segment. We allow recycling segments up
2148 * to XLOGfileslop segments beyond the current XLOG
2151 if (InstallXLogFileSegment(endlogId, endlogSeg, path,
2156 (errmsg("recycled transaction log file \"%s\"",
2161 /* No need for any more future segments... */
2163 (errmsg("removing transaction log file \"%s\"",
2168 XLogArchiveCleanup(xlde->d_name);
2176 * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but
2177 * not in released version
2179 if (GetLastError() == ERROR_NO_MORE_FILES)
2184 (errcode_for_file_access(),
2185 errmsg("could not read transaction log directory \"%s\": %m",
2191 * Restore the backup blocks present in an XLOG record, if any.
2193 * We assume all of the record has been read into memory at *record.
2195 * Note: when a backup block is available in XLOG, we restore it
2196 * unconditionally, even if the page in the database appears newer.
2197 * This is to protect ourselves against database pages that were partially
2198 * or incorrectly written during a crash. We assume that the XLOG data
2199 * must be good because it has passed a CRC check, while the database
2200 * page might not be. This will force us to replay all subsequent
2201 * modifications of the page that appear in XLOG, rather than possibly
2202 * ignoring them as already applied, but that's not a huge drawback.
2205 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2214 blk = (char *) XLogRecGetData(record) + record->xl_len;
2215 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2217 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2220 memcpy((char *) &bkpb, blk, sizeof(BkpBlock));
2221 blk += sizeof(BkpBlock);
2223 reln = XLogOpenRelation(true, record->xl_rmid, bkpb.node);
2227 buffer = XLogReadBuffer(true, reln, bkpb.block);
2228 if (BufferIsValid(buffer))
2230 page = (Page) BufferGetPage(buffer);
2231 memcpy((char *) page, blk, BLCKSZ);
2232 PageSetLSN(page, lsn);
2233 PageSetTLI(page, ThisTimeLineID);
2234 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2235 WriteBuffer(buffer);
2244 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2245 * record (other than to the minimal extent of computing the amount of
2246 * data to read in) until we've checked the CRCs.
2248 * We assume all of the record has been read into memory at *record.
2251 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2256 uint32 len = record->xl_len;
2259 /* Check CRC of rmgr data and record header */
2261 COMP_CRC64(crc, XLogRecGetData(record), len);
2262 COMP_CRC64(crc, (char *) record + sizeof(crc64),
2263 SizeOfXLogRecord - sizeof(crc64));
2266 if (!EQ_CRC64(record->xl_crc, crc))
2269 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2270 recptr.xlogid, recptr.xrecoff)));
2274 /* Check CRCs of backup blocks, if any */
2275 blk = (char *) XLogRecGetData(record) + len;
2276 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2278 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2282 COMP_CRC64(crc, blk + sizeof(BkpBlock), BLCKSZ);
2283 COMP_CRC64(crc, blk + sizeof(crc64),
2284 sizeof(BkpBlock) - sizeof(crc64));
2286 memcpy((char *) &cbuf, blk, sizeof(crc64)); /* don't assume
2289 if (!EQ_CRC64(cbuf, crc))
2292 (errmsg("incorrect checksum of backup block %d in record at %X/%X",
2293 i + 1, recptr.xlogid, recptr.xrecoff)));
2296 blk += sizeof(BkpBlock) + BLCKSZ;
2303 * Attempt to read an XLOG record.
2305 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2306 * try to read a record just after the last one previously read.
2308 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2309 * (emode must be either PANIC or LOG.)
2311 * The record is copied into readRecordBuf, so that on successful return,
2312 * the returned record pointer always points there.
2315 ReadRecord(XLogRecPtr *RecPtr, int emode)
2319 XLogRecPtr tmpRecPtr = EndRecPtr;
2320 bool randAccess = false;
2323 uint32 targetPageOff;
2324 uint32 targetRecOff;
2325 uint32 pageHeaderSize;
2328 if (readBuf == NULL)
2331 * First time through, permanently allocate readBuf. We do it
2332 * this way, rather than just making a static array, for two
2333 * reasons: (1) no need to waste the storage in most
2334 * instantiations of the backend; (2) a static char array isn't
2335 * guaranteed to have any particular alignment, whereas malloc()
2336 * will provide MAXALIGN'd storage.
2338 readBuf = (char *) malloc(BLCKSZ);
2339 Assert(readBuf != NULL);
2344 RecPtr = &tmpRecPtr;
2345 /* fast case if next record is on same page */
2346 if (nextRecord != NULL)
2348 record = nextRecord;
2351 /* align old recptr to next page */
2352 if (tmpRecPtr.xrecoff % BLCKSZ != 0)
2353 tmpRecPtr.xrecoff += (BLCKSZ - tmpRecPtr.xrecoff % BLCKSZ);
2354 if (tmpRecPtr.xrecoff >= XLogFileSize)
2356 (tmpRecPtr.xlogid)++;
2357 tmpRecPtr.xrecoff = 0;
2359 /* We will account for page header size below */
2363 if (!XRecOffIsValid(RecPtr->xrecoff))
2365 (errmsg("invalid record offset at %X/%X",
2366 RecPtr->xlogid, RecPtr->xrecoff)));
2369 * Since we are going to a random position in WAL, forget any
2370 * prior state about what timeline we were in, and allow it to be
2371 * any timeline in expectedTLIs. We also set a flag to allow
2372 * curFileTLI to go backwards (but we can't reset that variable
2373 * right here, since we might not change files at all).
2375 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2376 randAccess = true; /* allow curFileTLI to go backwards too */
2379 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2384 XLByteToSeg(*RecPtr, readId, readSeg);
2387 /* Now it's okay to reset curFileTLI if random fetch */
2391 readFile = XLogFileRead(readId, readSeg, emode);
2393 goto next_record_is_invalid;
2394 readOff = (uint32) (-1); /* force read to occur below */
2397 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / BLCKSZ) * BLCKSZ;
2398 if (readOff != targetPageOff)
2400 readOff = targetPageOff;
2401 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2404 (errcode_for_file_access(),
2405 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2406 readId, readSeg, readOff)));
2407 goto next_record_is_invalid;
2409 if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
2412 (errcode_for_file_access(),
2413 errmsg("could not read from log file %u, segment %u at offset %u: %m",
2414 readId, readSeg, readOff)));
2415 goto next_record_is_invalid;
2417 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2418 goto next_record_is_invalid;
2420 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2421 targetRecOff = RecPtr->xrecoff % BLCKSZ;
2422 if (targetRecOff == 0)
2425 * Can only get here in the continuing-from-prev-page case,
2426 * because XRecOffIsValid eliminated the zero-page-offset case
2427 * otherwise. Need to skip over the new page's header.
2429 tmpRecPtr.xrecoff += pageHeaderSize;
2430 targetRecOff = pageHeaderSize;
2432 else if (targetRecOff < pageHeaderSize)
2435 (errmsg("invalid record offset at %X/%X",
2436 RecPtr->xlogid, RecPtr->xrecoff)));
2437 goto next_record_is_invalid;
2439 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
2440 targetRecOff == pageHeaderSize)
2443 (errmsg("contrecord is requested by %X/%X",
2444 RecPtr->xlogid, RecPtr->xrecoff)));
2445 goto next_record_is_invalid;
2447 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % BLCKSZ);
2452 * Currently, xl_len == 0 must be bad data, but that might not be true
2453 * forever. See note in XLogInsert.
2455 if (record->xl_len == 0)
2458 (errmsg("record with zero length at %X/%X",
2459 RecPtr->xlogid, RecPtr->xrecoff)));
2460 goto next_record_is_invalid;
2462 if (record->xl_rmid > RM_MAX_ID)
2465 (errmsg("invalid resource manager ID %u at %X/%X",
2466 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
2467 goto next_record_is_invalid;
2471 * Compute total length of record including any appended backup
2474 total_len = SizeOfXLogRecord + record->xl_len;
2475 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2477 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2479 total_len += sizeof(BkpBlock) + BLCKSZ;
2483 * Allocate or enlarge readRecordBuf as needed. To avoid useless
2484 * small increases, round its size to a multiple of BLCKSZ, and make
2485 * sure it's at least 4*BLCKSZ to start with. (That is enough for all
2486 * "normal" records, but very large commit or abort records might need
2489 if (total_len > readRecordBufSize)
2491 uint32 newSize = total_len;
2493 newSize += BLCKSZ - (newSize % BLCKSZ);
2494 newSize = Max(newSize, 4 * BLCKSZ);
2496 free(readRecordBuf);
2497 readRecordBuf = (char *) malloc(newSize);
2500 readRecordBufSize = 0;
2501 /* We treat this as a "bogus data" condition */
2503 (errmsg("record length %u at %X/%X too long",
2504 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
2505 goto next_record_is_invalid;
2507 readRecordBufSize = newSize;
2510 buffer = readRecordBuf;
2512 len = BLCKSZ - RecPtr->xrecoff % BLCKSZ;
2513 if (total_len > len)
2515 /* Need to reassemble record */
2516 XLogContRecord *contrecord;
2517 uint32 gotlen = len;
2519 memcpy(buffer, record, len);
2520 record = (XLogRecord *) buffer;
2525 if (readOff >= XLogSegSize)
2529 NextLogSeg(readId, readSeg);
2530 readFile = XLogFileRead(readId, readSeg, emode);
2532 goto next_record_is_invalid;
2535 if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
2538 (errcode_for_file_access(),
2539 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2540 readId, readSeg, readOff)));
2541 goto next_record_is_invalid;
2543 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2544 goto next_record_is_invalid;
2545 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
2548 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
2549 readId, readSeg, readOff)));
2550 goto next_record_is_invalid;
2552 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2553 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
2554 if (contrecord->xl_rem_len == 0 ||
2555 total_len != (contrecord->xl_rem_len + gotlen))
2558 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
2559 contrecord->xl_rem_len,
2560 readId, readSeg, readOff)));
2561 goto next_record_is_invalid;
2563 len = BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
2564 if (contrecord->xl_rem_len > len)
2566 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
2571 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
2572 contrecord->xl_rem_len);
2575 if (!RecordIsValid(record, *RecPtr, emode))
2576 goto next_record_is_invalid;
2577 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
2578 if (BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
2579 SizeOfXLogContRecord + MAXALIGN(contrecord->xl_rem_len))
2581 nextRecord = (XLogRecord *) ((char *) contrecord +
2582 SizeOfXLogContRecord + MAXALIGN(contrecord->xl_rem_len));
2584 EndRecPtr.xlogid = readId;
2585 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
2586 pageHeaderSize + SizeOfXLogContRecord +
2587 MAXALIGN(contrecord->xl_rem_len);
2588 ReadRecPtr = *RecPtr;
2592 /* Record does not cross a page boundary */
2593 if (!RecordIsValid(record, *RecPtr, emode))
2594 goto next_record_is_invalid;
2595 if (BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % BLCKSZ +
2596 MAXALIGN(total_len))
2597 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
2598 EndRecPtr.xlogid = RecPtr->xlogid;
2599 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
2600 ReadRecPtr = *RecPtr;
2601 memcpy(buffer, record, total_len);
2602 return (XLogRecord *) buffer;
2604 next_record_is_invalid:;
2612 * Check whether the xlog header of a page just read in looks valid.
2614 * This is just a convenience subroutine to avoid duplicated code in
2615 * ReadRecord. It's not intended for use from anywhere else.
2618 ValidXLOGHeader(XLogPageHeader hdr, int emode)
2622 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
2625 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
2626 hdr->xlp_magic, readId, readSeg, readOff)));
2629 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
2632 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
2633 hdr->xlp_info, readId, readSeg, readOff)));
2636 if (hdr->xlp_info & XLP_LONG_HEADER)
2638 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
2640 if (longhdr->xlp_sysid != ControlFile->system_identifier)
2642 char fhdrident_str[32];
2643 char sysident_str[32];
2646 * Format sysids separately to keep platform-dependent format
2647 * code out of the translatable message string.
2649 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
2650 longhdr->xlp_sysid);
2651 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
2652 ControlFile->system_identifier);
2654 (errmsg("WAL file is from different system"),
2655 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
2656 fhdrident_str, sysident_str)));
2659 if (longhdr->xlp_seg_size != XLogSegSize)
2662 (errmsg("WAL file is from different system"),
2663 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
2667 recaddr.xlogid = readId;
2668 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
2669 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
2672 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
2673 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
2674 readId, readSeg, readOff)));
2679 * Check page TLI is one of the expected values.
2681 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
2684 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
2686 readId, readSeg, readOff)));
2691 * Since child timelines are always assigned a TLI greater than their
2692 * immediate parent's TLI, we should never see TLI go backwards across
2693 * successive pages of a consistent WAL sequence.
2695 * Of course this check should only be applied when advancing
2696 * sequentially across pages; therefore ReadRecord resets lastPageTLI
2697 * to zero when going to a random page.
2699 if (hdr->xlp_tli < lastPageTLI)
2702 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
2703 hdr->xlp_tli, lastPageTLI,
2704 readId, readSeg, readOff)));
2707 lastPageTLI = hdr->xlp_tli;
2712 * Try to read a timeline's history file.
2714 * If successful, return the list of component TLIs (the given TLI followed by
2715 * its ancestor TLIs). If we can't find the history file, assume that the
2716 * timeline has no parents, and return a list of just the specified timeline
2720 readTimeLineHistory(TimeLineID targetTLI)
2723 char path[MAXPGPATH];
2724 char histfname[MAXFNAMELEN];
2725 char fline[MAXPGPATH];
2728 if (InArchiveRecovery)
2730 TLHistoryFileName(histfname, targetTLI);
2731 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
2734 TLHistoryFilePath(path, targetTLI);
2736 fd = AllocateFile(path, "r");
2739 if (errno != ENOENT)
2741 (errcode_for_file_access(),
2742 errmsg("could not open \"%s\": %m", path)));
2743 /* Not there, so assume no parents */
2744 return list_make1_int((int) targetTLI);
2752 while (fgets(fline, MAXPGPATH, fd) != NULL)
2754 /* skip leading whitespace and check for # comment */
2759 for (ptr = fline; *ptr; ptr++)
2761 if (!isspace((unsigned char) *ptr))
2764 if (*ptr == '\0' || *ptr == '#')
2767 /* expect a numeric timeline ID as first field of line */
2768 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
2771 (errmsg("syntax error in history file: %s", fline),
2772 errhint("Expected a numeric timeline ID.")));
2775 tli <= (TimeLineID) linitial_int(result))
2777 (errmsg("invalid data in history file: %s", fline),
2778 errhint("Timeline IDs must be in increasing sequence.")));
2780 /* Build list with newest item first */
2781 result = lcons_int((int) tli, result);
2783 /* we ignore the remainder of each line */
2789 targetTLI <= (TimeLineID) linitial_int(result))
2791 (errmsg("invalid data in history file \"%s\"", path),
2792 errhint("Timeline IDs must be less than child timeline's ID.")));
2794 result = lcons_int((int) targetTLI, result);
2797 (errmsg_internal("history of timeline %u is %s",
2798 targetTLI, nodeToString(result))));
2804 * Probe whether a timeline history file exists for the given timeline ID
2807 existsTimeLineHistory(TimeLineID probeTLI)
2809 char path[MAXPGPATH];
2810 char histfname[MAXFNAMELEN];
2813 if (InArchiveRecovery)
2815 TLHistoryFileName(histfname, probeTLI);
2816 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
2819 TLHistoryFilePath(path, probeTLI);
2821 fd = AllocateFile(path, "r");
2829 if (errno != ENOENT)
2831 (errcode_for_file_access(),
2832 errmsg("could not open \"%s\": %m", path)));
2838 * Find the newest existing timeline, assuming that startTLI exists.
2840 * Note: while this is somewhat heuristic, it does positively guarantee
2841 * that (result + 1) is not a known timeline, and therefore it should
2842 * be safe to assign that ID to a new timeline.
2845 findNewestTimeLine(TimeLineID startTLI)
2847 TimeLineID newestTLI;
2848 TimeLineID probeTLI;
2851 * The algorithm is just to probe for the existence of timeline
2852 * history files. XXX is it useful to allow gaps in the sequence?
2854 newestTLI = startTLI;
2856 for (probeTLI = startTLI + 1;; probeTLI++)
2858 if (existsTimeLineHistory(probeTLI))
2860 newestTLI = probeTLI; /* probeTLI exists */
2864 /* doesn't exist, assume we're done */
2873 * Create a new timeline history file.
2875 * newTLI: ID of the new timeline
2876 * parentTLI: ID of its immediate parent
2877 * endTLI et al: ID of the last used WAL file, for annotation purposes
2879 * Currently this is only used during recovery, and so there are no locking
2880 * considerations. But we should be just as tense as XLogFileInit to avoid
2881 * emplacing a bogus file.
2884 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
2885 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
2887 char path[MAXPGPATH];
2888 char tmppath[MAXPGPATH];
2889 char histfname[MAXFNAMELEN];
2890 char xlogfname[MAXFNAMELEN];
2891 char buffer[BLCKSZ];
2896 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
2899 * Write into a temp file name.
2901 snprintf(tmppath, MAXPGPATH, "%s/xlogtemp.%d", XLogDir, getpid());
2905 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2906 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
2910 (errcode_for_file_access(),
2911 errmsg("could not create file \"%s\": %m", tmppath)));
2914 * If a history file exists for the parent, copy it verbatim
2916 if (InArchiveRecovery)
2918 TLHistoryFileName(histfname, parentTLI);
2919 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
2922 TLHistoryFilePath(path, parentTLI);
2924 srcfd = BasicOpenFile(path, O_RDONLY, 0);
2927 if (errno != ENOENT)
2929 (errcode_for_file_access(),
2930 errmsg("could not open \"%s\": %m", path)));
2931 /* Not there, so assume parent has no parents */
2938 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
2939 if (nbytes < 0 || errno != 0)
2941 (errcode_for_file_access(),
2942 errmsg("could not read file \"%s\": %m", path)));
2946 if ((int) write(fd, buffer, nbytes) != nbytes)
2948 int save_errno = errno;
2951 * If we fail to make the file, delete it to release disk
2957 * if write didn't set errno, assume problem is no disk
2960 errno = save_errno ? save_errno : ENOSPC;
2963 (errcode_for_file_access(),
2964 errmsg("could not write to file \"%s\": %m", tmppath)));
2971 * Append one line with the details of this timeline split.
2973 * If we did have a parent file, insert an extra newline just in case the
2974 * parent file failed to end with one.
2976 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
2978 snprintf(buffer, sizeof(buffer),
2979 "%s%u\t%s\t%s transaction %u at %s\n",
2980 (srcfd < 0) ? "" : "\n",
2983 recoveryStopAfter ? "after" : "before",
2985 str_time(recoveryStopTime));
2987 nbytes = strlen(buffer);
2989 if ((int) write(fd, buffer, nbytes) != nbytes)
2991 int save_errno = errno;
2994 * If we fail to make the file, delete it to release disk space
2997 /* if write didn't set errno, assume problem is no disk space */
2998 errno = save_errno ? save_errno : ENOSPC;
3001 (errcode_for_file_access(),
3002 errmsg("could not write to file \"%s\": %m", tmppath)));
3005 if (pg_fsync(fd) != 0)
3007 (errcode_for_file_access(),
3008 errmsg("could not fsync file \"%s\": %m", tmppath)));
3012 (errcode_for_file_access(),
3013 errmsg("could not close file \"%s\": %m", tmppath)));
3017 * Now move the completed history file into place with its final name.
3019 TLHistoryFilePath(path, newTLI);
3022 * Prefer link() to rename() here just to be really sure that we don't
3023 * overwrite an existing logfile. However, there shouldn't be one, so
3024 * rename() is an acceptable substitute except for the truly paranoid.
3026 #if HAVE_WORKING_LINK
3027 if (link(tmppath, path) < 0)
3029 (errcode_for_file_access(),
3030 errmsg("could not link file \"%s\" to \"%s\": %m",
3034 if (rename(tmppath, path) < 0)
3036 (errcode_for_file_access(),
3037 errmsg("could not rename file \"%s\" to \"%s\": %m",
3041 /* The history file can be archived immediately. */
3042 TLHistoryFileName(histfname, newTLI);
3043 XLogArchiveNotify(histfname);
3047 * I/O routines for pg_control
3049 * *ControlFile is a buffer in shared memory that holds an image of the
3050 * contents of pg_control. WriteControlFile() initializes pg_control
3051 * given a preloaded buffer, ReadControlFile() loads the buffer from
3052 * the pg_control file (during postmaster or standalone-backend startup),
3053 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3055 * For simplicity, WriteControlFile() initializes the fields of pg_control
3056 * that are related to checking backend/database compatibility, and
3057 * ReadControlFile() verifies they are correct. We could split out the
3058 * I/O and compatibility-check functions, but there seems no need currently.
3064 /* Init XLOG file paths */
3065 snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
3066 snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
3070 WriteControlFile(void)
3073 char buffer[BLCKSZ]; /* need not be aligned */
3077 * Initialize version and compatibility-check fields
3079 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3080 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3081 ControlFile->blcksz = BLCKSZ;
3082 ControlFile->relseg_size = RELSEG_SIZE;
3083 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3085 ControlFile->nameDataLen = NAMEDATALEN;
3086 ControlFile->funcMaxArgs = FUNC_MAX_ARGS;
3088 #ifdef HAVE_INT64_TIMESTAMP
3089 ControlFile->enableIntTimes = TRUE;
3091 ControlFile->enableIntTimes = FALSE;
3094 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3095 localeptr = setlocale(LC_COLLATE, NULL);
3098 (errmsg("invalid LC_COLLATE setting")));
3099 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3100 localeptr = setlocale(LC_CTYPE, NULL);
3103 (errmsg("invalid LC_CTYPE setting")));
3104 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3106 /* Contents are protected with a CRC */
3107 INIT_CRC64(ControlFile->crc);
3108 COMP_CRC64(ControlFile->crc,
3109 (char *) ControlFile + sizeof(crc64),
3110 sizeof(ControlFileData) - sizeof(crc64));
3111 FIN_CRC64(ControlFile->crc);
3114 * We write out BLCKSZ bytes into pg_control, zero-padding the excess
3115 * over sizeof(ControlFileData). This reduces the odds of
3116 * premature-EOF errors when reading pg_control. We'll still fail
3117 * when we check the contents of the file, but hopefully with a more
3118 * specific error than "couldn't read pg_control".
3120 if (sizeof(ControlFileData) > BLCKSZ)
3122 (errmsg("sizeof(ControlFileData) is larger than BLCKSZ; fix either one")));
3124 memset(buffer, 0, BLCKSZ);
3125 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3127 fd = BasicOpenFile(ControlFilePath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3131 (errcode_for_file_access(),
3132 errmsg("could not create control file \"%s\": %m",
3136 if (write(fd, buffer, BLCKSZ) != BLCKSZ)
3138 /* if write didn't set errno, assume problem is no disk space */
3142 (errcode_for_file_access(),
3143 errmsg("could not write to control file: %m")));
3146 if (pg_fsync(fd) != 0)
3148 (errcode_for_file_access(),
3149 errmsg("could not fsync control file: %m")));
3153 (errcode_for_file_access(),
3154 errmsg("could not close control file: %m")));
3158 ReadControlFile(void)
3166 fd = BasicOpenFile(ControlFilePath, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
3169 (errcode_for_file_access(),
3170 errmsg("could not open control file \"%s\": %m",
3173 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3175 (errcode_for_file_access(),
3176 errmsg("could not read from control file: %m")));
3181 * Check for expected pg_control format version. If this is wrong,
3182 * the CRC check will likely fail because we'll be checking the wrong
3183 * number of bytes. Complaining about wrong version will probably be
3184 * more enlightening than complaining about wrong CRC.
3186 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3188 (errmsg("database files are incompatible with server"),
3189 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3190 " but the server was compiled with PG_CONTROL_VERSION %d.",
3191 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3192 errhint("It looks like you need to initdb.")));
3193 /* Now check the CRC. */
3196 (char *) ControlFile + sizeof(crc64),
3197 sizeof(ControlFileData) - sizeof(crc64));
3200 if (!EQ_CRC64(crc, ControlFile->crc))
3202 (errmsg("incorrect checksum in control file")));
3205 * Do compatibility checking immediately. We do this here for 2
3208 * (1) if the database isn't compatible with the backend executable, we
3209 * want to abort before we can possibly do any damage;
3211 * (2) this code is executed in the postmaster, so the setlocale() will
3212 * propagate to forked backends, which aren't going to read this file
3213 * for themselves. (These locale settings are considered critical
3214 * compatibility items because they can affect sort order of indexes.)
3216 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3218 (errmsg("database files are incompatible with server"),
3219 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3220 " but the server was compiled with CATALOG_VERSION_NO %d.",
3221 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3222 errhint("It looks like you need to initdb.")));
3223 if (ControlFile->blcksz != BLCKSZ)
3225 (errmsg("database files are incompatible with server"),
3226 errdetail("The database cluster was initialized with BLCKSZ %d,"
3227 " but the server was compiled with BLCKSZ %d.",
3228 ControlFile->blcksz, BLCKSZ),
3229 errhint("It looks like you need to recompile or initdb.")));
3230 if (ControlFile->relseg_size != RELSEG_SIZE)
3232 (errmsg("database files are incompatible with server"),
3233 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3234 " but the server was compiled with RELSEG_SIZE %d.",
3235 ControlFile->relseg_size, RELSEG_SIZE),
3236 errhint("It looks like you need to recompile or initdb.")));
3237 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3239 (errmsg("database files are incompatible with server"),
3240 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3241 " but the server was compiled with XLOG_SEG_SIZE %d.",
3242 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3243 errhint("It looks like you need to recompile or initdb.")));
3244 if (ControlFile->nameDataLen != NAMEDATALEN)
3246 (errmsg("database files are incompatible with server"),
3247 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3248 " but the server was compiled with NAMEDATALEN %d.",
3249 ControlFile->nameDataLen, NAMEDATALEN),
3250 errhint("It looks like you need to recompile or initdb.")));
3251 if (ControlFile->funcMaxArgs != FUNC_MAX_ARGS)
3253 (errmsg("database files are incompatible with server"),
3254 errdetail("The database cluster was initialized with FUNC_MAX_ARGS %d,"
3255 " but the server was compiled with FUNC_MAX_ARGS %d.",
3256 ControlFile->funcMaxArgs, FUNC_MAX_ARGS),
3257 errhint("It looks like you need to recompile or initdb.")));
3259 #ifdef HAVE_INT64_TIMESTAMP
3260 if (ControlFile->enableIntTimes != TRUE)
3262 (errmsg("database files are incompatible with server"),
3263 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3264 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3265 errhint("It looks like you need to recompile or initdb.")));
3267 if (ControlFile->enableIntTimes != FALSE)
3269 (errmsg("database files are incompatible with server"),
3270 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3271 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3272 errhint("It looks like you need to recompile or initdb.")));
3275 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3277 (errmsg("database files are incompatible with server"),
3278 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3279 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3280 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3281 errhint("It looks like you need to recompile or initdb.")));
3282 if (setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3284 (errmsg("database files are incompatible with operating system"),
3285 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3286 " which is not recognized by setlocale().",
3287 ControlFile->lc_collate),
3288 errhint("It looks like you need to initdb or install locale support.")));
3289 if (setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3291 (errmsg("database files are incompatible with operating system"),
3292 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3293 " which is not recognized by setlocale().",
3294 ControlFile->lc_ctype),
3295 errhint("It looks like you need to initdb or install locale support.")));
3297 /* Make the fixed locale settings visible as GUC variables, too */
3298 SetConfigOption("lc_collate", ControlFile->lc_collate,
3299 PGC_INTERNAL, PGC_S_OVERRIDE);
3300 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3301 PGC_INTERNAL, PGC_S_OVERRIDE);
3305 UpdateControlFile(void)
3309 INIT_CRC64(ControlFile->crc);
3310 COMP_CRC64(ControlFile->crc,
3311 (char *) ControlFile + sizeof(crc64),
3312 sizeof(ControlFileData) - sizeof(crc64));
3313 FIN_CRC64(ControlFile->crc);
3315 fd = BasicOpenFile(ControlFilePath, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
3318 (errcode_for_file_access(),
3319 errmsg("could not open control file \"%s\": %m",
3323 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3325 /* if write didn't set errno, assume problem is no disk space */
3329 (errcode_for_file_access(),
3330 errmsg("could not write to control file: %m")));
3333 if (pg_fsync(fd) != 0)
3335 (errcode_for_file_access(),
3336 errmsg("could not fsync control file: %m")));
3340 (errcode_for_file_access(),
3341 errmsg("could not close control file: %m")));
3345 * Initialization of shared memory for XLOG
3351 if (XLOGbuffers < MinXLOGbuffers)
3352 XLOGbuffers = MinXLOGbuffers;
3354 return MAXALIGN(sizeof(XLogCtlData) + sizeof(XLogRecPtr) * XLOGbuffers)
3355 + BLCKSZ * XLOGbuffers +
3356 MAXALIGN(sizeof(ControlFileData));
3365 /* this must agree with space requested by XLOGShmemSize() */
3366 if (XLOGbuffers < MinXLOGbuffers)
3367 XLOGbuffers = MinXLOGbuffers;
3369 XLogCtl = (XLogCtlData *)
3370 ShmemInitStruct("XLOG Ctl",
3371 MAXALIGN(sizeof(XLogCtlData) +
3372 sizeof(XLogRecPtr) * XLOGbuffers)
3373 + BLCKSZ * XLOGbuffers,
3375 ControlFile = (ControlFileData *)
3376 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
3378 if (foundXLog || foundCFile)
3380 /* both should be present or neither */
3381 Assert(foundXLog && foundCFile);
3385 memset(XLogCtl, 0, sizeof(XLogCtlData));
3388 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be
3389 * a multiple of the alignment for same, so no extra alignment padding
3392 XLogCtl->xlblocks = (XLogRecPtr *)
3393 (((char *) XLogCtl) + sizeof(XLogCtlData));
3394 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
3397 * Here, on the other hand, we must MAXALIGN to ensure the page
3398 * buffers have worst-case alignment.
3401 ((char *) XLogCtl) + MAXALIGN(sizeof(XLogCtlData) +
3402 sizeof(XLogRecPtr) * XLOGbuffers);
3403 memset(XLogCtl->pages, 0, BLCKSZ * XLOGbuffers);
3406 * Do basic initialization of XLogCtl shared data. (StartupXLOG will
3407 * fill in additional info.)
3409 XLogCtl->XLogCacheByte = BLCKSZ * XLOGbuffers;
3410 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
3411 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
3412 SpinLockInit(&XLogCtl->info_lck);
3415 * If we are not in bootstrap mode, pg_control should already exist.
3416 * Read and validate it immediately (see comments in ReadControlFile()
3417 * for the reasons why).
3419 if (!IsBootstrapProcessingMode())
3424 * This func must be called ONCE on system install. It creates pg_control
3425 * and the initial XLOG segment.
3430 CheckPoint checkPoint;
3432 XLogPageHeader page;
3433 XLogLongPageHeader longpage;
3436 uint64 sysidentifier;
3441 * Select a hopefully-unique system identifier code for this
3442 * installation. We use the result of gettimeofday(), including the
3443 * fractional seconds field, as being about as unique as we can easily
3444 * get. (Think not to use random(), since it hasn't been seeded and
3445 * there's no portable way to seed it other than the system clock
3446 * value...) The upper half of the uint64 value is just the tv_sec
3447 * part, while the lower half is the XOR of tv_sec and tv_usec. This
3448 * is to ensure that we don't lose uniqueness unnecessarily if
3449 * "uint64" is really only 32 bits wide. A person knowing this
3450 * encoding can determine the initialization time of the installation,
3451 * which could perhaps be useful sometimes.
3453 gettimeofday(&tv, NULL);
3454 sysidentifier = ((uint64) tv.tv_sec) << 32;
3455 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
3457 /* First timeline ID is always 1 */
3460 /* Use malloc() to ensure buffer is MAXALIGNED */
3461 buffer = (char *) malloc(BLCKSZ);
3462 page = (XLogPageHeader) buffer;
3463 memset(buffer, 0, BLCKSZ);
3465 /* Set up information for the initial checkpoint record */
3466 checkPoint.redo.xlogid = 0;
3467 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
3468 checkPoint.undo = checkPoint.redo;
3469 checkPoint.ThisTimeLineID = ThisTimeLineID;
3470 checkPoint.nextXid = FirstNormalTransactionId;
3471 checkPoint.nextOid = BootstrapObjectIdData;
3472 checkPoint.time = time(NULL);
3474 ShmemVariableCache->nextXid = checkPoint.nextXid;
3475 ShmemVariableCache->nextOid = checkPoint.nextOid;
3476 ShmemVariableCache->oidCount = 0;
3478 /* Set up the XLOG page header */
3479 page->xlp_magic = XLOG_PAGE_MAGIC;
3480 page->xlp_info = XLP_LONG_HEADER;
3481 page->xlp_tli = ThisTimeLineID;
3482 page->xlp_pageaddr.xlogid = 0;
3483 page->xlp_pageaddr.xrecoff = 0;
3484 longpage = (XLogLongPageHeader) page;
3485 longpage->xlp_sysid = sysidentifier;
3486 longpage->xlp_seg_size = XLogSegSize;
3488 /* Insert the initial checkpoint record */
3489 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
3490 record->xl_prev.xlogid = 0;
3491 record->xl_prev.xrecoff = 0;
3492 record->xl_xid = InvalidTransactionId;
3493 record->xl_len = sizeof(checkPoint);
3494 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
3495 record->xl_rmid = RM_XLOG_ID;
3496 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
3499 COMP_CRC64(crc, &checkPoint, sizeof(checkPoint));
3500 COMP_CRC64(crc, (char *) record + sizeof(crc64),
3501 SizeOfXLogRecord - sizeof(crc64));
3503 record->xl_crc = crc;
3505 /* Create first XLOG segment file */
3506 use_existent = false;
3507 openLogFile = XLogFileInit(0, 0, &use_existent, false);
3509 /* Write the first page with the initial record */
3511 if (write(openLogFile, buffer, BLCKSZ) != BLCKSZ)
3513 /* if write didn't set errno, assume problem is no disk space */
3517 (errcode_for_file_access(),
3518 errmsg("could not write bootstrap transaction log file: %m")));
3521 if (pg_fsync(openLogFile) != 0)
3523 (errcode_for_file_access(),
3524 errmsg("could not fsync bootstrap transaction log file: %m")));
3526 if (close(openLogFile))
3528 (errcode_for_file_access(),
3529 errmsg("could not close bootstrap transaction log file: %m")));
3533 /* Now create pg_control */
3535 memset(ControlFile, 0, sizeof(ControlFileData));
3536 /* Initialize pg_control status fields */
3537 ControlFile->system_identifier = sysidentifier;
3538 ControlFile->state = DB_SHUTDOWNED;
3539 ControlFile->time = checkPoint.time;
3540 ControlFile->logId = 0;
3541 ControlFile->logSeg = 1;
3542 ControlFile->checkPoint = checkPoint.redo;
3543 ControlFile->checkPointCopy = checkPoint;
3544 /* some additional ControlFile fields are set in WriteControlFile() */
3548 /* Bootstrap the commit log, too */
3550 BootStrapSUBTRANS();
3554 str_time(time_t tnow)
3556 static char buf[128];
3558 strftime(buf, sizeof(buf),
3559 "%Y-%m-%d %H:%M:%S %Z",
3566 * See if there is a recovery command file (recovery.conf), and if so
3567 * read in parameters for archive recovery.
3569 * XXX longer term intention is to expand this to
3570 * cater for additional parameters and controls
3571 * possibly use a flex lexer similar to the GUC one
3574 readRecoveryCommandFile(void)
3576 char recoveryCommandFile[MAXPGPATH];
3578 char cmdline[MAXPGPATH];
3579 TimeLineID rtli = 0;
3580 bool rtliGiven = false;
3581 bool syntaxError = false;
3583 snprintf(recoveryCommandFile, MAXPGPATH, "%s/recovery.conf", DataDir);
3584 fd = AllocateFile(recoveryCommandFile, "r");
3587 if (errno == ENOENT)
3588 return; /* not there, so no archive recovery */
3590 (errcode_for_file_access(),
3591 errmsg("could not open recovery command file \"%s\": %m",
3592 recoveryCommandFile)));
3596 (errmsg("starting archive recovery")));
3601 while (fgets(cmdline, MAXPGPATH, fd) != NULL)
3603 /* skip leading whitespace and check for # comment */
3608 for (ptr = cmdline; *ptr; ptr++)
3610 if (!isspace((unsigned char) *ptr))
3613 if (*ptr == '\0' || *ptr == '#')
3616 /* identify the quoted parameter value */
3617 tok1 = strtok(ptr, "'");
3623 tok2 = strtok(NULL, "'");
3629 /* reparse to get just the parameter name */
3630 tok1 = strtok(ptr, " \t=");
3637 if (strcmp(tok1, "restore_command") == 0)
3639 recoveryRestoreCommand = pstrdup(tok2);
3641 (errmsg("restore_command = \"%s\"",
3642 recoveryRestoreCommand)));
3644 else if (strcmp(tok1, "recovery_target_timeline") == 0)
3647 if (strcmp(tok2, "latest") == 0)
3652 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
3653 if (errno == EINVAL || errno == ERANGE)
3655 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
3660 (errmsg("recovery_target_timeline = %u", rtli)));
3663 (errmsg("recovery_target_timeline = latest")));
3665 else if (strcmp(tok1, "recovery_target_xid") == 0)
3668 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
3669 if (errno == EINVAL || errno == ERANGE)
3671 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
3674 (errmsg("recovery_target_xid = %u",
3675 recoveryTargetXid)));
3676 recoveryTarget = true;
3677 recoveryTargetExact = true;
3679 else if (strcmp(tok1, "recovery_target_time") == 0)
3682 * if recovery_target_xid specified, then this overrides
3683 * recovery_target_time
3685 if (recoveryTargetExact)
3687 recoveryTarget = true;
3688 recoveryTargetExact = false;
3691 * Convert the time string given by the user to the time_t
3692 * format. We use type abstime's input converter because we
3693 * know abstime has the same representation as time_t.
3695 recoveryTargetTime = (time_t)
3696 DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
3697 CStringGetDatum(tok2)));
3699 (errmsg("recovery_target_time = %s",
3700 DatumGetCString(DirectFunctionCall1(abstimeout,
3701 AbsoluteTimeGetDatum((AbsoluteTime) recoveryTargetTime))))));
3703 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
3706 * does nothing if a recovery_target is not also set
3708 if (strcmp(tok2, "true") == 0)
3709 recoveryTargetInclusive = true;
3712 recoveryTargetInclusive = false;
3716 (errmsg("recovery_target_inclusive = %s", tok2)));
3720 (errmsg("unrecognized recovery parameter \"%s\"",
3728 (errmsg("syntax error in recovery command file: %s",
3730 errhint("Lines should have the format parameter = 'value'.")));
3732 /* Check that required parameters were supplied */
3733 if (recoveryRestoreCommand == NULL)
3735 (errmsg("recovery command file \"%s\" did not specify restore_command",
3736 recoveryCommandFile)));
3738 /* Enable fetching from archive recovery area */
3739 InArchiveRecovery = true;
3742 * If user specified recovery_target_timeline, validate it or compute
3743 * the "latest" value. We can't do this until after we've gotten the
3744 * restore command and set InArchiveRecovery, because we need to fetch
3745 * timeline history files from the archive.
3751 /* Timeline 1 does not have a history file, all else should */
3752 if (rtli != 1 && !existsTimeLineHistory(rtli))
3754 (errmsg("recovery_target_timeline %u does not exist",
3756 recoveryTargetTLI = rtli;
3760 /* We start the "latest" search from pg_control's timeline */
3761 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
3767 * Exit archive-recovery state
3770 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3772 char recoveryPath[MAXPGPATH];
3773 char xlogpath[MAXPGPATH];
3774 char recoveryCommandFile[MAXPGPATH];
3775 char recoveryCommandDone[MAXPGPATH];
3778 * We are no longer in archive recovery state.
3780 InArchiveRecovery = false;
3783 * We should have the ending log segment currently open. Verify, and
3784 * then close it (to avoid problems on Windows with trying to rename
3785 * or delete an open file).
3787 Assert(readFile >= 0);
3788 Assert(readId == endLogId);
3789 Assert(readSeg == endLogSeg);
3795 * If the segment was fetched from archival storage, we want to
3796 * replace the existing xlog segment (if any) with the archival
3797 * version. This is because whatever is in XLogDir is very possibly
3798 * older than what we have from the archives, since it could have come
3799 * from restoring a PGDATA backup. In any case, the archival version
3800 * certainly is more descriptive of what our current database state
3801 * is, because that is what we replayed from.
3803 * Note that if we are establishing a new timeline, ThisTimeLineID is
3804 * already set to the new value, and so we will create a new file
3805 * instead of overwriting any existing file.
3807 snprintf(recoveryPath, MAXPGPATH, "%s/RECOVERYXLOG", XLogDir);
3808 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
3810 if (restoredFromArchive)
3813 (errmsg_internal("moving last restored xlog to \"%s\"",
3815 unlink(xlogpath); /* might or might not exist */
3816 if (rename(recoveryPath, xlogpath) != 0)
3818 (errcode_for_file_access(),
3819 errmsg("could not rename file \"%s\" to \"%s\": %m",
3820 recoveryPath, xlogpath)));
3821 /* XXX might we need to fix permissions on the file? */
3826 * If the latest segment is not archival, but there's still a
3827 * RECOVERYXLOG laying about, get rid of it.
3829 unlink(recoveryPath); /* ignore any error */
3832 * If we are establishing a new timeline, we have to copy data
3833 * from the last WAL segment of the old timeline to create a
3834 * starting WAL segment for the new timeline.
3836 if (endTLI != ThisTimeLineID)
3837 XLogFileCopy(endLogId, endLogSeg,
3838 endTLI, endLogId, endLogSeg);
3842 * Let's just make real sure there are not .ready or .done flags
3843 * posted for the new segment.
3845 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
3846 XLogArchiveCleanup(xlogpath);
3848 /* Get rid of any remaining recovered timeline-history file, too */
3849 snprintf(recoveryPath, MAXPGPATH, "%s/RECOVERYHISTORY", XLogDir);
3850 unlink(recoveryPath); /* ignore any error */
3853 * Rename the config file out of the way, so that we don't
3854 * accidentally re-enter archive recovery mode in a subsequent crash.
3856 snprintf(recoveryCommandFile, MAXPGPATH, "%s/recovery.conf", DataDir);
3857 snprintf(recoveryCommandDone, MAXPGPATH, "%s/recovery.done", DataDir);
3858 unlink(recoveryCommandDone);
3859 if (rename(recoveryCommandFile, recoveryCommandDone) != 0)
3861 (errcode_for_file_access(),
3862 errmsg("could not rename file \"%s\" to \"%s\": %m",
3863 recoveryCommandFile, recoveryCommandDone)));
3866 (errmsg("archive recovery complete")));
3870 * For point-in-time recovery, this function decides whether we want to
3871 * stop applying the XLOG at or after the current record.
3873 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
3874 * *includeThis is set TRUE if we should apply this record before stopping.
3875 * Also, some information is saved in recoveryStopXid et al for use in
3876 * annotating the new timeline's history file.
3879 recoveryStopsHere(XLogRecord *record, bool *includeThis)
3885 /* Do we have a PITR target at all? */
3886 if (!recoveryTarget)
3889 /* We only consider stopping at COMMIT or ABORT records */
3890 if (record->xl_rmid != RM_XACT_ID)
3892 record_info = record->xl_info & ~XLR_INFO_MASK;
3893 if (record_info == XLOG_XACT_COMMIT)
3895 xl_xact_commit *recordXactCommitData;
3897 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
3898 recordXtime = recordXactCommitData->xtime;
3900 else if (record_info == XLOG_XACT_ABORT)
3902 xl_xact_abort *recordXactAbortData;
3904 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
3905 recordXtime = recordXactAbortData->xtime;
3910 if (recoveryTargetExact)
3913 * there can be only one transaction end record with this exact
3916 * when testing for an xid, we MUST test for equality only, since
3917 * transactions are numbered in the order they start, not the
3918 * order they complete. A higher numbered xid will complete before
3919 * you about 50% of the time...
3921 stopsHere = (record->xl_xid == recoveryTargetXid);
3923 *includeThis = recoveryTargetInclusive;
3928 * there can be many transactions that share the same commit time,
3929 * so we stop after the last one, if we are inclusive, or stop at
3930 * the first one if we are exclusive
3932 if (recoveryTargetInclusive)
3933 stopsHere = (recordXtime > recoveryTargetTime);
3935 stopsHere = (recordXtime >= recoveryTargetTime);
3937 *includeThis = false;
3942 recoveryStopXid = record->xl_xid;
3943 recoveryStopTime = recordXtime;
3944 recoveryStopAfter = *includeThis;
3946 if (record_info == XLOG_XACT_COMMIT)
3948 if (recoveryStopAfter)
3950 (errmsg("recovery stopping after commit of transaction %u, time %s",
3951 recoveryStopXid, str_time(recoveryStopTime))));
3954 (errmsg("recovery stopping before commit of transaction %u, time %s",
3955 recoveryStopXid, str_time(recoveryStopTime))));
3959 if (recoveryStopAfter)
3961 (errmsg("recovery stopping after abort of transaction %u, time %s",
3962 recoveryStopXid, str_time(recoveryStopTime))));
3965 (errmsg("recovery stopping before abort of transaction %u, time %s",
3966 recoveryStopXid, str_time(recoveryStopTime))));
3974 * This must be called ONCE during postmaster or standalone-backend startup
3979 XLogCtlInsert *Insert;
3980 CheckPoint checkPoint;
3982 bool needNewTimeLine = false;
3995 * Read control file and check XLOG status looks valid.
3997 * Note: in most control paths, *ControlFile is already valid and we need
3998 * not do ReadControlFile() here, but might as well do it to be sure.
4002 if (ControlFile->logSeg == 0 ||
4003 ControlFile->state < DB_SHUTDOWNED ||
4004 ControlFile->state > DB_IN_PRODUCTION ||
4005 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4007 (errmsg("control file contains invalid data")));
4009 if (ControlFile->state == DB_SHUTDOWNED)
4011 (errmsg("database system was shut down at %s",
4012 str_time(ControlFile->time))));
4013 else if (ControlFile->state == DB_SHUTDOWNING)
4015 (errmsg("database system shutdown was interrupted at %s",
4016 str_time(ControlFile->time))));
4017 else if (ControlFile->state == DB_IN_RECOVERY)
4019 (errmsg("database system was interrupted while in recovery at %s",
4020 str_time(ControlFile->time)),
4021 errhint("This probably means that some data is corrupted and"
4022 " you will have to use the last backup for recovery.")));
4023 else if (ControlFile->state == DB_IN_PRODUCTION)
4025 (errmsg("database system was interrupted at %s",
4026 str_time(ControlFile->time))));
4028 /* This is just to allow attaching to startup process with a debugger */
4029 #ifdef XLOG_REPLAY_DELAY
4030 if (ControlFile->state != DB_SHUTDOWNED)
4031 pg_usleep(60000000L);
4035 * Initialize on the assumption we want to recover to the same
4036 * timeline that's active according to pg_control.
4038 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4041 * Check for recovery control file, and if so set up state for offline
4044 readRecoveryCommandFile();
4046 /* Now we can determine the list of expected TLIs */
4047 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4050 * If pg_control's timeline is not in expectedTLIs, then we cannot
4051 * proceed: the backup is not part of the history of the requested
4054 if (!list_member_int(expectedTLIs,
4055 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4057 (errmsg("requested timeline %u is not a child of database system timeline %u",
4059 ControlFile->checkPointCopy.ThisTimeLineID)));
4061 if (read_backup_label(&checkPointLoc))
4064 * When a backup_label file is present, we want to roll forward
4065 * from the checkpoint it identifies, rather than using
4068 record = ReadCheckpointRecord(checkPointLoc, 0);
4072 (errmsg("checkpoint record is at %X/%X",
4073 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4074 InRecovery = true; /* force recovery even if SHUTDOWNED */
4079 (errmsg("could not locate required checkpoint record"),
4080 errhint("If you are not restoring from a backup, try removing $PGDATA/backup_label.")));
4086 * Get the last valid checkpoint record. If the latest one
4087 * according to pg_control is broken, try the next-to-last one.
4089 checkPointLoc = ControlFile->checkPoint;
4090 record = ReadCheckpointRecord(checkPointLoc, 1);
4094 (errmsg("checkpoint record is at %X/%X",
4095 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4099 checkPointLoc = ControlFile->prevCheckPoint;
4100 record = ReadCheckpointRecord(checkPointLoc, 2);
4104 (errmsg("using previous checkpoint record at %X/%X",
4105 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4106 InRecovery = true; /* force recovery even if
4111 (errmsg("could not locate a valid checkpoint record")));
4115 LastRec = RecPtr = checkPointLoc;
4116 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4117 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4120 (errmsg("redo record is at %X/%X; undo record is at %X/%X; shutdown %s",
4121 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4122 checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
4123 wasShutdown ? "TRUE" : "FALSE")));
4125 (errmsg("next transaction ID: %u; next OID: %u",
4126 checkPoint.nextXid, checkPoint.nextOid)));
4127 if (!TransactionIdIsNormal(checkPoint.nextXid))
4129 (errmsg("invalid next transaction ID")));
4131 ShmemVariableCache->nextXid = checkPoint.nextXid;
4132 ShmemVariableCache->nextOid = checkPoint.nextOid;
4133 ShmemVariableCache->oidCount = 0;
4136 * We must replay WAL entries using the same TimeLineID they were
4137 * created under, so temporarily adopt the TLI indicated by the
4138 * checkpoint (see also xlog_redo()).
4140 ThisTimeLineID = checkPoint.ThisTimeLineID;
4142 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4144 if (XLByteLT(RecPtr, checkPoint.redo))
4146 (errmsg("invalid redo in checkpoint record")));
4147 if (checkPoint.undo.xrecoff == 0)
4148 checkPoint.undo = RecPtr;
4151 * Check whether we need to force recovery from WAL. If it appears to
4152 * have been a clean shutdown and we did not have a recovery.conf
4153 * file, then assume no recovery needed.
4155 if (XLByteLT(checkPoint.undo, RecPtr) ||
4156 XLByteLT(checkPoint.redo, RecPtr))
4160 (errmsg("invalid redo/undo record in shutdown checkpoint")));
4163 else if (ControlFile->state != DB_SHUTDOWNED)
4165 else if (InArchiveRecovery)
4167 /* force recovery due to presence of recovery.conf */
4176 if (InArchiveRecovery)
4178 (errmsg("automatic recovery in progress")));
4181 (errmsg("database system was not properly shut down; "
4182 "automatic recovery in progress")));
4183 ControlFile->state = DB_IN_RECOVERY;
4184 ControlFile->time = time(NULL);
4185 UpdateControlFile();
4187 /* Start up the recovery environment */
4188 XLogInitRelationCache();
4190 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4192 if (RmgrTable[rmid].rm_startup != NULL)
4193 RmgrTable[rmid].rm_startup();
4197 * Find the first record that logically follows the checkpoint ---
4198 * it might physically precede it, though.
4200 if (XLByteLT(checkPoint.redo, RecPtr))
4202 /* back up to find the record */
4203 record = ReadRecord(&(checkPoint.redo), PANIC);
4207 /* just have to read next record after CheckPoint */
4208 record = ReadRecord(NULL, LOG);
4213 bool recoveryContinue = true;
4214 bool recoveryApply = true;
4218 (errmsg("redo starts at %X/%X",
4219 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4222 * main redo apply loop
4231 sprintf(buf, "REDO @ %X/%X; LSN %X/%X: ",
4232 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4233 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4234 xlog_outrec(buf, record);
4236 RmgrTable[record->xl_rmid].rm_desc(buf,
4237 record->xl_info, XLogRecGetData(record));
4238 elog(LOG, "%s", buf);
4243 * Have we reached our recovery target?
4245 if (recoveryStopsHere(record, &recoveryApply))
4247 needNewTimeLine = true; /* see below */
4248 recoveryContinue = false;
4253 /* nextXid must be beyond record's xid */
4254 if (TransactionIdFollowsOrEquals(record->xl_xid,
4255 ShmemVariableCache->nextXid))
4257 ShmemVariableCache->nextXid = record->xl_xid;
4258 TransactionIdAdvance(ShmemVariableCache->nextXid);
4261 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4262 RestoreBkpBlocks(record, EndRecPtr);
4264 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
4266 LastRec = ReadRecPtr;
4268 record = ReadRecord(NULL, LOG);
4269 } while (record != NULL && recoveryContinue);
4272 * end of main redo apply loop
4276 (errmsg("redo done at %X/%X",
4277 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4282 /* there are no WAL records following the checkpoint */
4284 (errmsg("redo is not required")));
4289 * Re-fetch the last valid or last applied record, so we can identify
4290 * the exact endpoint of what we consider the valid portion of WAL.
4292 record = ReadRecord(&LastRec, PANIC);
4293 EndOfLog = EndRecPtr;
4294 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
4297 * Complain if we did not roll forward far enough to render the backup
4300 if (XLByteLT(EndOfLog, recoveryMinXlogOffset))
4302 if (needNewTimeLine) /* stopped because of stop request */
4304 (errmsg("requested recovery stop point is before end time of backup dump")));
4306 /* ran off end of WAL */
4308 (errmsg("WAL ends before end time of backup dump")));
4312 * Consider whether we need to assign a new timeline ID.
4314 * If we stopped short of the end of WAL during recovery, then we are
4315 * generating a new timeline and must assign it a unique new ID.
4316 * Otherwise, we can just extend the timeline we were in when we ran
4319 if (needNewTimeLine)
4321 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
4323 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
4324 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
4325 curFileTLI, endLogId, endLogSeg);
4328 /* Save the selected TimeLineID in shared memory, too */
4329 XLogCtl->ThisTimeLineID = ThisTimeLineID;
4332 * We are now done reading the old WAL. Turn off archive fetching if
4333 * it was active, and make a writable copy of the last WAL segment.
4334 * (Note that we also have a copy of the last block of the old WAL in
4335 * readBuf; we will use that below.)
4337 if (InArchiveRecovery)
4338 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
4341 * Prepare to write WAL starting at EndOfLog position, and init xlog
4342 * buffer cache using the block containing the last record from the
4343 * previous incarnation.
4345 openLogId = endLogId;
4346 openLogSeg = endLogSeg;
4347 openLogFile = XLogFileOpen(openLogId, openLogSeg);
4349 ControlFile->logId = openLogId;
4350 ControlFile->logSeg = openLogSeg + 1;
4351 Insert = &XLogCtl->Insert;
4352 Insert->PrevRecord = LastRec;
4353 XLogCtl->xlblocks[0].xlogid = openLogId;
4354 XLogCtl->xlblocks[0].xrecoff =
4355 ((EndOfLog.xrecoff - 1) / BLCKSZ + 1) * BLCKSZ;
4358 * Tricky point here: readBuf contains the *last* block that the
4359 * LastRec record spans, not the one it starts in. The last block is
4360 * indeed the one we want to use.
4362 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - BLCKSZ) % XLogSegSize);
4363 memcpy((char *) Insert->currpage, readBuf, BLCKSZ);
4364 Insert->currpos = (char *) Insert->currpage +
4365 (EndOfLog.xrecoff + BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
4367 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
4369 XLogCtl->Write.LogwrtResult = LogwrtResult;
4370 Insert->LogwrtResult = LogwrtResult;
4371 XLogCtl->LogwrtResult = LogwrtResult;
4373 XLogCtl->LogwrtRqst.Write = EndOfLog;
4374 XLogCtl->LogwrtRqst.Flush = EndOfLog;
4376 freespace = INSERT_FREESPACE(Insert);
4379 /* Make sure rest of page is zero */
4380 MemSet(Insert->currpos, 0, freespace);
4381 XLogCtl->Write.curridx = 0;
4386 * Whenever Write.LogwrtResult points to exactly the end of a
4387 * page, Write.curridx must point to the *next* page (see
4390 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
4391 * this is sufficient. The first actual attempt to insert a log
4392 * record will advance the insert state.
4394 XLogCtl->Write.curridx = NextBufIdx(0);
4401 RecPtr = ReadRecPtr;
4402 if (XLByteLT(checkPoint.undo, RecPtr))
4405 (errmsg("undo starts at %X/%X",
4406 RecPtr.xlogid, RecPtr.xrecoff)));
4409 record = ReadRecord(&RecPtr, PANIC);
4410 if (TransactionIdIsValid(record->xl_xid) &&
4411 !TransactionIdDidCommit(record->xl_xid))
4412 RmgrTable[record->xl_rmid].rm_undo(EndRecPtr, record);
4413 RecPtr = record->xl_prev;
4414 } while (XLByteLE(checkPoint.undo, RecPtr));
4416 (errmsg("undo done at %X/%X",
4417 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4421 (errmsg("undo is not required")));
4430 * Allow resource managers to do any required cleanup.
4432 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4434 if (RmgrTable[rmid].rm_cleanup != NULL)
4435 RmgrTable[rmid].rm_cleanup();
4439 * Perform a new checkpoint to update our recovery activity to
4442 * Note that we write a shutdown checkpoint rather than an on-line
4443 * one. This is not particularly critical, but since we may be
4444 * assigning a new TLI, using a shutdown checkpoint allows us to
4445 * have the rule that TLI only changes in shutdown checkpoints,
4446 * which allows some extra error checking in xlog_redo.
4448 * In case we had to use the secondary checkpoint, make sure that it
4449 * will still be shown as the secondary checkpoint after this
4450 * CreateCheckPoint operation; we don't want the broken primary
4451 * checkpoint to become prevCheckPoint...
4453 if (XLByteEQ(checkPointLoc, ControlFile->prevCheckPoint))
4454 ControlFile->checkPoint = checkPointLoc;
4456 CreateCheckPoint(true, true);
4459 * Close down recovery environment
4461 XLogCloseRelationCache();
4464 * Now that we've checkpointed the recovery, it's safe to flush
4465 * old backup_label, if present.
4467 remove_backup_label();
4471 * Preallocate additional log files, if wanted.
4473 PreallocXlogFiles(EndOfLog);
4476 * Okay, we're officially UP.
4480 ControlFile->state = DB_IN_PRODUCTION;
4481 ControlFile->time = time(NULL);
4482 UpdateControlFile();
4484 /* Start up the commit log, too */
4489 (errmsg("database system is ready")));
4492 /* Shut down readFile facility, free space */
4505 free(readRecordBuf);
4506 readRecordBuf = NULL;
4507 readRecordBufSize = 0;
4512 * Subroutine to try to fetch and validate a prior checkpoint record.
4514 * whichChkpt identifies the checkpoint (merely for reporting purposes).
4515 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
4518 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
4522 if (!XRecOffIsValid(RecPtr.xrecoff))
4528 (errmsg("invalid primary checkpoint link in control file")));
4532 (errmsg("invalid secondary checkpoint link in control file")));
4536 (errmsg("invalid checkpoint link in backup_label file")));
4542 record = ReadRecord(&RecPtr, LOG);
4550 (errmsg("invalid primary checkpoint record")));
4554 (errmsg("invalid secondary checkpoint record")));
4558 (errmsg("invalid checkpoint record")));
4563 if (record->xl_rmid != RM_XLOG_ID)
4569 (errmsg("invalid resource manager ID in primary checkpoint record")));
4573 (errmsg("invalid resource manager ID in secondary checkpoint record")));
4577 (errmsg("invalid resource manager ID in checkpoint record")));
4582 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
4583 record->xl_info != XLOG_CHECKPOINT_ONLINE)
4589 (errmsg("invalid xl_info in primary checkpoint record")));
4593 (errmsg("invalid xl_info in secondary checkpoint record")));
4597 (errmsg("invalid xl_info in checkpoint record")));
4602 if (record->xl_len != sizeof(CheckPoint))
4608 (errmsg("invalid length of primary checkpoint record")));
4612 (errmsg("invalid length of secondary checkpoint record")));
4616 (errmsg("invalid length of checkpoint record")));
4625 * This must be called during startup of a backend process, except that
4626 * it need not be called in a standalone backend (which does StartupXLOG
4627 * instead). We need to initialize the local copies of ThisTimeLineID and
4630 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
4631 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
4632 * unnecessary however, since the postmaster itself never touches XLOG anyway.
4635 InitXLOGAccess(void)
4637 /* ThisTimeLineID doesn't change so we need no lock to copy it */
4638 ThisTimeLineID = XLogCtl->ThisTimeLineID;
4639 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
4640 (void) GetRedoRecPtr();
4644 * Once spawned, a backend may update its local RedoRecPtr from
4645 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
4646 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
4651 /* use volatile pointer to prevent code rearrangement */
4652 volatile XLogCtlData *xlogctl = XLogCtl;
4654 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
4655 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
4656 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
4657 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
4663 * This must be called ONCE during postmaster or standalone-backend shutdown
4666 ShutdownXLOG(int code, Datum arg)
4669 (errmsg("shutting down")));
4672 CreateCheckPoint(true, true);
4678 (errmsg("database system is shut down")));
4682 * Perform a checkpoint --- either during shutdown, or on-the-fly
4684 * If force is true, we force a checkpoint regardless of whether any XLOG
4685 * activity has occurred since the last one.
4688 CreateCheckPoint(bool shutdown, bool force)
4690 CheckPoint checkPoint;
4692 XLogCtlInsert *Insert = &XLogCtl->Insert;
4699 * Acquire CheckpointLock to ensure only one checkpoint happens at a
4700 * time. (This is just pro forma, since in the present system
4701 * structure there is only one process that is allowed to issue
4702 * checkpoints at any given time.)
4704 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
4707 * Use a critical section to force system panic if we have trouble.
4709 START_CRIT_SECTION();
4713 ControlFile->state = DB_SHUTDOWNING;
4714 ControlFile->time = time(NULL);
4715 UpdateControlFile();
4718 MemSet(&checkPoint, 0, sizeof(checkPoint));
4719 checkPoint.ThisTimeLineID = ThisTimeLineID;
4720 checkPoint.time = time(NULL);
4723 * We must hold CheckpointStartLock while determining the checkpoint
4724 * REDO pointer. This ensures that any concurrent transaction commits
4725 * will be either not yet logged, or logged and recorded in pg_clog.
4726 * See notes in RecordTransactionCommit().
4728 LWLockAcquire(CheckpointStartLock, LW_EXCLUSIVE);
4730 /* And we need WALInsertLock too */
4731 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
4734 * If this isn't a shutdown or forced checkpoint, and we have not
4735 * inserted any XLOG records since the start of the last checkpoint,
4736 * skip the checkpoint. The idea here is to avoid inserting duplicate
4737 * checkpoints when the system is idle. That wastes log space, and
4738 * more importantly it exposes us to possible loss of both current and
4739 * previous checkpoint records if the machine crashes just as we're
4740 * writing the update. (Perhaps it'd make even more sense to
4741 * checkpoint only when the previous checkpoint record is in a
4742 * different xlog page?)
4744 * We have to make two tests to determine that nothing has happened since
4745 * the start of the last checkpoint: current insertion point must
4746 * match the end of the last checkpoint record, and its redo pointer
4747 * must point to itself.
4749 if (!shutdown && !force)
4751 XLogRecPtr curInsert;
4753 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
4754 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
4755 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
4756 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
4757 ControlFile->checkPoint.xlogid ==
4758 ControlFile->checkPointCopy.redo.xlogid &&
4759 ControlFile->checkPoint.xrecoff ==
4760 ControlFile->checkPointCopy.redo.xrecoff)
4762 LWLockRelease(WALInsertLock);
4763 LWLockRelease(CheckpointStartLock);
4764 LWLockRelease(CheckpointLock);
4771 * Compute new REDO record ptr = location of next XLOG record.
4773 * NB: this is NOT necessarily where the checkpoint record itself will
4774 * be, since other backends may insert more XLOG records while we're
4775 * off doing the buffer flush work. Those XLOG records are logically
4776 * after the checkpoint, even though physically before it. Got that?
4778 freespace = INSERT_FREESPACE(Insert);
4779 if (freespace < SizeOfXLogRecord)
4781 (void) AdvanceXLInsertBuffer();
4782 /* OK to ignore update return flag, since we will do flush anyway */
4783 freespace = INSERT_FREESPACE(Insert);
4785 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
4788 * Here we update the shared RedoRecPtr for future XLogInsert calls;
4789 * this must be done while holding the insert lock AND the info_lck.
4791 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
4792 * pointing past where it really needs to point. This is okay; the
4793 * only consequence is that XLogInsert might back up whole buffers
4794 * that it didn't really need to. We can't postpone advancing
4795 * RedoRecPtr because XLogInserts that happen while we are dumping
4796 * buffers must assume that their buffer changes are not included in
4800 /* use volatile pointer to prevent code rearrangement */
4801 volatile XLogCtlData *xlogctl = XLogCtl;
4803 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
4804 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
4805 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
4809 * Get UNDO record ptr - this is oldest of PGPROC->logRec values. We
4810 * do this while holding insert lock to ensure that we won't miss any
4811 * about-to-commit transactions (UNDO must include all xacts that have
4812 * commits after REDO point).
4814 * XXX temporarily ifdef'd out to avoid three-way deadlock condition:
4815 * GetUndoRecPtr needs to grab SInvalLock to ensure that it is looking
4816 * at a stable set of proc records, but grabbing SInvalLock while
4817 * holding WALInsertLock is no good. GetNewTransactionId may cause a
4818 * WAL record to be written while holding XidGenLock, and
4819 * GetSnapshotData needs to get XidGenLock while holding SInvalLock,
4820 * so there's a risk of deadlock. Need to find a better solution. See
4821 * pgsql-hackers discussion of 17-Dec-01.
4823 * XXX actually, the whole UNDO code is dead code and unlikely to ever be
4824 * revived, so the lack of a good solution here is not troubling.
4827 checkPoint.undo = GetUndoRecPtr();
4829 if (shutdown && checkPoint.undo.xrecoff != 0)
4830 elog(PANIC, "active transaction while database system is shutting down");
4834 * Now we can release insert lock and checkpoint start lock, allowing
4835 * other xacts to proceed even while we are flushing disk buffers.
4837 LWLockRelease(WALInsertLock);
4839 LWLockRelease(CheckpointStartLock);
4842 * Get the other info we need for the checkpoint record.
4844 LWLockAcquire(XidGenLock, LW_SHARED);
4845 checkPoint.nextXid = ShmemVariableCache->nextXid;
4846 LWLockRelease(XidGenLock);
4848 LWLockAcquire(OidGenLock, LW_SHARED);
4849 checkPoint.nextOid = ShmemVariableCache->nextOid;
4851 checkPoint.nextOid += ShmemVariableCache->oidCount;
4852 LWLockRelease(OidGenLock);
4855 * Having constructed the checkpoint record, ensure all shmem disk
4856 * buffers and commit-log buffers are flushed to disk.
4858 * This I/O could fail for various reasons. If so, we will fail to
4859 * complete the checkpoint, but there is no reason to force a system
4860 * panic. Accordingly, exit critical section while doing it.
4865 CheckPointSUBTRANS();
4868 START_CRIT_SECTION();
4871 * Now insert the checkpoint record into XLOG.
4873 rdata.buffer = InvalidBuffer;
4874 rdata.data = (char *) (&checkPoint);
4875 rdata.len = sizeof(checkPoint);
4878 recptr = XLogInsert(RM_XLOG_ID,
4879 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
4880 XLOG_CHECKPOINT_ONLINE,
4886 * We now have ProcLastRecPtr = start of actual checkpoint record,
4887 * recptr = end of actual checkpoint record.
4889 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
4891 (errmsg("concurrent transaction log activity while database system is shutting down")));
4894 * Select point at which we can truncate the log, which we base on the
4895 * prior checkpoint's earliest info.
4897 * With UNDO support: oldest item is redo or undo, whichever is older;
4898 * but watch out for case that undo = 0.
4900 * Without UNDO support: just use the redo pointer. This allows xlog
4901 * space to be freed much faster when there are long-running
4905 if (ControlFile->checkPointCopy.undo.xrecoff != 0 &&
4906 XLByteLT(ControlFile->checkPointCopy.undo,
4907 ControlFile->checkPointCopy.redo))
4908 XLByteToSeg(ControlFile->checkPointCopy.undo, _logId, _logSeg);
4911 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
4914 * Update the control file.
4916 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
4918 ControlFile->state = DB_SHUTDOWNED;
4919 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4920 ControlFile->checkPoint = ProcLastRecPtr;
4921 ControlFile->checkPointCopy = checkPoint;
4922 ControlFile->time = time(NULL);
4923 UpdateControlFile();
4924 LWLockRelease(ControlFileLock);
4927 * We are now done with critical updates; no need for system panic if
4928 * we have trouble while fooling with offline log segments.
4933 * Delete offline log files (those no longer needed even for previous
4936 if (_logId || _logSeg)
4938 PrevLogSeg(_logId, _logSeg);
4939 MoveOfflineLogs(_logId, _logSeg, recptr);
4943 * Make more log segments if needed. (Do this after deleting offline
4944 * log segments, to avoid having peak disk space usage higher than
4948 PreallocXlogFiles(recptr);
4951 * Truncate pg_subtrans if possible. We can throw away all data
4952 * before the oldest XMIN of any running transaction. No future
4953 * transaction will attempt to reference any pg_subtrans entry older
4954 * than that (see Asserts in subtrans.c). During recovery, though, we
4955 * mustn't do this because StartupSUBTRANS hasn't been called yet.
4958 TruncateSUBTRANS(GetOldestXmin(true));
4960 LWLockRelease(CheckpointLock);
4964 * Write a NEXTOID log record
4967 XLogPutNextOid(Oid nextOid)
4971 rdata.buffer = InvalidBuffer;
4972 rdata.data = (char *) (&nextOid);
4973 rdata.len = sizeof(Oid);
4975 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
4979 * XLOG resource manager's routines
4982 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
4984 uint8 info = record->xl_info & ~XLR_INFO_MASK;
4986 if (info == XLOG_NEXTOID)
4990 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
4991 if (ShmemVariableCache->nextOid < nextOid)
4993 ShmemVariableCache->nextOid = nextOid;
4994 ShmemVariableCache->oidCount = 0;
4997 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
4999 CheckPoint checkPoint;
5001 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5002 /* In a SHUTDOWN checkpoint, believe the counters exactly */
5003 ShmemVariableCache->nextXid = checkPoint.nextXid;
5004 ShmemVariableCache->nextOid = checkPoint.nextOid;
5005 ShmemVariableCache->oidCount = 0;
5008 * TLI may change in a shutdown checkpoint, but it shouldn't
5011 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5013 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
5014 !list_member_int(expectedTLIs,
5015 (int) checkPoint.ThisTimeLineID))
5017 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
5018 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5019 /* Following WAL records should be run with new TLI */
5020 ThisTimeLineID = checkPoint.ThisTimeLineID;
5023 else if (info == XLOG_CHECKPOINT_ONLINE)
5025 CheckPoint checkPoint;
5027 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5028 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
5029 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
5030 checkPoint.nextXid))
5031 ShmemVariableCache->nextXid = checkPoint.nextXid;
5032 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
5034 ShmemVariableCache->nextOid = checkPoint.nextOid;
5035 ShmemVariableCache->oidCount = 0;
5037 /* TLI should not change in an on-line checkpoint */
5038 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
5040 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
5041 checkPoint.ThisTimeLineID, ThisTimeLineID)));
5046 xlog_undo(XLogRecPtr lsn, XLogRecord *record)
5051 xlog_desc(char *buf, uint8 xl_info, char *rec)
5053 uint8 info = xl_info & ~XLR_INFO_MASK;
5055 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
5056 info == XLOG_CHECKPOINT_ONLINE)
5058 CheckPoint *checkpoint = (CheckPoint *) rec;
5060 sprintf(buf + strlen(buf), "checkpoint: redo %X/%X; undo %X/%X; "
5061 "tli %u; xid %u; oid %u; %s",
5062 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
5063 checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
5064 checkpoint->ThisTimeLineID, checkpoint->nextXid,
5065 checkpoint->nextOid,
5066 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
5068 else if (info == XLOG_NEXTOID)
5072 memcpy(&nextOid, rec, sizeof(Oid));
5073 sprintf(buf + strlen(buf), "nextOid: %u", nextOid);
5076 strcat(buf, "UNKNOWN");
5082 xlog_outrec(char *buf, XLogRecord *record)
5087 sprintf(buf + strlen(buf), "prev %X/%X; xid %u",
5088 record->xl_prev.xlogid, record->xl_prev.xrecoff,
5091 for (i = 0, bkpb = 0; i < XLR_MAX_BKP_BLOCKS; i++)
5093 if (!(record->xl_info & (XLR_SET_BKP_BLOCK(i))))
5099 sprintf(buf + strlen(buf), "; bkpb %d", bkpb);
5101 sprintf(buf + strlen(buf), ": %s",
5102 RmgrTable[record->xl_rmid].rm_name);
5104 #endif /* WAL_DEBUG */
5111 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
5113 int new_sync_method;
5116 if (pg_strcasecmp(method, "fsync") == 0)
5118 new_sync_method = SYNC_METHOD_FSYNC;
5121 #ifdef HAVE_FDATASYNC
5122 else if (pg_strcasecmp(method, "fdatasync") == 0)
5124 new_sync_method = SYNC_METHOD_FDATASYNC;
5128 #ifdef OPEN_SYNC_FLAG
5129 else if (pg_strcasecmp(method, "open_sync") == 0)
5131 new_sync_method = SYNC_METHOD_OPEN;
5132 new_sync_bit = OPEN_SYNC_FLAG;
5135 #ifdef OPEN_DATASYNC_FLAG
5136 else if (pg_strcasecmp(method, "open_datasync") == 0)
5138 new_sync_method = SYNC_METHOD_OPEN;
5139 new_sync_bit = OPEN_DATASYNC_FLAG;
5148 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
5151 * To ensure that no blocks escape unsynced, force an fsync on the
5152 * currently open log segment (if any). Also, if the open flag is
5153 * changing, close the log file so it will be reopened (with new
5154 * flag bit) at next use.
5156 if (openLogFile >= 0)
5158 if (pg_fsync(openLogFile) != 0)
5160 (errcode_for_file_access(),
5161 errmsg("could not fsync log file %u, segment %u: %m",
5162 openLogId, openLogSeg)));
5163 if (open_sync_bit != new_sync_bit)
5165 if (close(openLogFile))
5167 (errcode_for_file_access(),
5168 errmsg("could not close log file %u, segment %u: %m",
5169 openLogId, openLogSeg)));
5173 sync_method = new_sync_method;
5174 open_sync_bit = new_sync_bit;
5182 * Issue appropriate kind of fsync (if any) on the current XLOG output file
5185 issue_xlog_fsync(void)
5187 switch (sync_method)
5189 case SYNC_METHOD_FSYNC:
5190 if (pg_fsync(openLogFile) != 0)
5192 (errcode_for_file_access(),
5193 errmsg("could not fsync log file %u, segment %u: %m",
5194 openLogId, openLogSeg)));
5196 #ifdef HAVE_FDATASYNC
5197 case SYNC_METHOD_FDATASYNC:
5198 if (pg_fdatasync(openLogFile) != 0)
5200 (errcode_for_file_access(),
5201 errmsg("could not fdatasync log file %u, segment %u: %m",
5202 openLogId, openLogSeg)));
5205 case SYNC_METHOD_OPEN:
5206 /* write synced it already */
5209 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
5216 * pg_start_backup: set up for taking an on-line backup dump
5218 * Essentially what this does is to create a backup label file in $PGDATA,
5219 * where it will be archived as part of the backup dump. The label file
5220 * contains the user-supplied label string (typically this would be used
5221 * to tell where the backup dump will be stored) and the starting time and
5222 * starting WAL offset for the dump.
5225 pg_start_backup(PG_FUNCTION_ARGS)
5227 text *backupid = PG_GETARG_TEXT_P(0);
5230 XLogRecPtr checkpointloc;
5231 XLogRecPtr startpoint;
5234 char labelfilepath[MAXPGPATH];
5235 char xlogfilename[MAXFNAMELEN];
5238 struct stat stat_buf;
5243 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5244 (errmsg("must be superuser to run a backup"))));
5245 backupidstr = DatumGetCString(DirectFunctionCall1(textout,
5246 PointerGetDatum(backupid)));
5249 * Force a CHECKPOINT. This is not strictly necessary, but it seems
5250 * like a good idea to minimize the amount of past WAL needed to use
5251 * the backup. Also, this guarantees that two successive backup runs
5252 * will have different checkpoint positions and hence different
5253 * history file names, even if nothing happened in between.
5255 RequestCheckpoint(true);
5258 * Now we need to fetch the checkpoint record location, and also its
5259 * REDO pointer. The oldest point in WAL that would be needed to
5260 * restore starting from the checkpoint is precisely the REDO pointer.
5262 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5263 checkpointloc = ControlFile->checkPoint;
5264 startpoint = ControlFile->checkPointCopy.redo;
5265 LWLockRelease(ControlFileLock);
5267 XLByteToSeg(startpoint, _logId, _logSeg);
5268 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
5271 * We deliberately use strftime/localtime not the src/timezone
5272 * functions, so that backup labels will consistently be recorded in
5273 * the same timezone regardless of TimeZone setting. This matches
5274 * elog.c's practice.
5276 stamp_time = time(NULL);
5277 strftime(strfbuf, sizeof(strfbuf),
5278 "%Y-%m-%d %H:%M:%S %Z",
5279 localtime(&stamp_time));
5282 * Check for existing backup label --- implies a backup is already
5285 snprintf(labelfilepath, MAXPGPATH, "%s/backup_label", DataDir);
5286 if (stat(labelfilepath, &stat_buf) != 0)
5288 if (errno != ENOENT)
5290 (errcode_for_file_access(),
5291 errmsg("could not stat \"%s\": %m",
5296 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5297 errmsg("a backup is already in progress"),
5298 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
5302 * Okay, write the file
5304 fp = AllocateFile(labelfilepath, "w");
5307 (errcode_for_file_access(),
5308 errmsg("could not create file \"%s\": %m",
5310 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
5311 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
5312 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
5313 checkpointloc.xlogid, checkpointloc.xrecoff);
5314 fprintf(fp, "START TIME: %s\n", strfbuf);
5315 fprintf(fp, "LABEL: %s\n", backupidstr);
5316 if (fflush(fp) || ferror(fp) || FreeFile(fp))
5318 (errcode_for_file_access(),
5319 errmsg("could not write file \"%s\": %m",
5323 * We're done. As a convenience, return the starting WAL offset.
5325 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
5326 startpoint.xlogid, startpoint.xrecoff);
5327 result = DatumGetTextP(DirectFunctionCall1(textin,
5328 CStringGetDatum(xlogfilename)));
5329 PG_RETURN_TEXT_P(result);
5333 * pg_stop_backup: finish taking an on-line backup dump
5335 * We remove the backup label file created by pg_start_backup, and instead
5336 * create a backup history file in pg_xlog (whence it will immediately be
5337 * archived). The backup history file contains the same info found in
5338 * the label file, plus the backup-end time and WAL offset.
5341 pg_stop_backup(PG_FUNCTION_ARGS)
5344 XLogCtlInsert *Insert = &XLogCtl->Insert;
5345 XLogRecPtr startpoint;
5346 XLogRecPtr stoppoint;
5349 char labelfilepath[MAXPGPATH];
5350 char histfilepath[MAXPGPATH];
5351 char startxlogfilename[MAXFNAMELEN];
5352 char stopxlogfilename[MAXFNAMELEN];
5362 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5363 (errmsg("must be superuser to run a backup"))));
5366 * Get the current end-of-WAL position; it will be unsafe to use this
5367 * dump to restore to a point in advance of this time.
5369 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5370 INSERT_RECPTR(stoppoint, Insert, Insert->curridx);
5371 LWLockRelease(WALInsertLock);
5373 XLByteToSeg(stoppoint, _logId, _logSeg);
5374 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
5377 * We deliberately use strftime/localtime not the src/timezone
5378 * functions, so that backup labels will consistently be recorded in
5379 * the same timezone regardless of TimeZone setting. This matches
5380 * elog.c's practice.
5382 stamp_time = time(NULL);
5383 strftime(strfbuf, sizeof(strfbuf),
5384 "%Y-%m-%d %H:%M:%S %Z",
5385 localtime(&stamp_time));
5388 * Open the existing label file
5390 snprintf(labelfilepath, MAXPGPATH, "%s/backup_label", DataDir);
5391 lfp = AllocateFile(labelfilepath, "r");
5394 if (errno != ENOENT)
5396 (errcode_for_file_access(),
5397 errmsg("could not read file \"%s\": %m",
5400 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5401 errmsg("a backup is not in progress")));
5405 * Read and parse the START WAL LOCATION line (this code is pretty
5406 * crude, but we are not expecting any variability in the file
5409 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
5410 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
5411 &ch) != 4 || ch != '\n')
5413 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5414 errmsg("invalid data in file \"%s\"", labelfilepath)));
5417 * Write the backup history file
5419 XLByteToSeg(startpoint, _logId, _logSeg);
5420 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
5421 startpoint.xrecoff % XLogSegSize);
5422 fp = AllocateFile(histfilepath, "w");
5425 (errcode_for_file_access(),
5426 errmsg("could not create file \"%s\": %m",
5428 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
5429 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
5430 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
5431 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
5432 /* transfer remaining lines from label to history file */
5433 while ((ich = fgetc(lfp)) != EOF)
5435 fprintf(fp, "STOP TIME: %s\n", strfbuf);
5436 if (fflush(fp) || ferror(fp) || FreeFile(fp))
5438 (errcode_for_file_access(),
5439 errmsg("could not write file \"%s\": %m",
5443 * Close and remove the backup label file
5445 if (ferror(lfp) || FreeFile(lfp))
5447 (errcode_for_file_access(),
5448 errmsg("could not read file \"%s\": %m",
5450 if (unlink(labelfilepath) != 0)
5452 (errcode_for_file_access(),
5453 errmsg("could not remove file \"%s\": %m",
5457 * Notify archiver that history file may be archived immediately
5459 if (XLogArchivingActive())
5461 BackupHistoryFileName(histfilepath, ThisTimeLineID, _logId, _logSeg,
5462 startpoint.xrecoff % XLogSegSize);
5463 XLogArchiveNotify(histfilepath);
5467 * We're done. As a convenience, return the ending WAL offset.
5469 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
5470 stoppoint.xlogid, stoppoint.xrecoff);
5471 result = DatumGetTextP(DirectFunctionCall1(textin,
5472 CStringGetDatum(stopxlogfilename)));
5473 PG_RETURN_TEXT_P(result);
5477 * read_backup_label: check to see if a backup_label file is present
5479 * If we see a backup_label during recovery, we assume that we are recovering
5480 * from a backup dump file, and we therefore roll forward from the checkpoint
5481 * identified by the label file, NOT what pg_control says. This avoids the
5482 * problem that pg_control might have been archived one or more checkpoints
5483 * later than the start of the dump, and so if we rely on it as the start
5484 * point, we will fail to restore a consistent database state.
5486 * We also attempt to retrieve the corresponding backup history file.
5487 * If successful, set recoveryMinXlogOffset to constrain valid PITR stopping
5490 * Returns TRUE if a backup_label was found (and fills the checkpoint
5491 * location into *checkPointLoc); returns FALSE if not.
5494 read_backup_label(XLogRecPtr *checkPointLoc)
5496 XLogRecPtr startpoint;
5497 XLogRecPtr stoppoint;
5498 char labelfilepath[MAXPGPATH];
5499 char histfilename[MAXFNAMELEN];
5500 char histfilepath[MAXPGPATH];
5501 char startxlogfilename[MAXFNAMELEN];
5502 char stopxlogfilename[MAXFNAMELEN];
5511 * See if label file is present
5513 snprintf(labelfilepath, MAXPGPATH, "%s/backup_label", DataDir);
5514 lfp = AllocateFile(labelfilepath, "r");
5517 if (errno != ENOENT)
5519 (errcode_for_file_access(),
5520 errmsg("could not read file \"%s\": %m",
5522 return false; /* it's not there, all is fine */
5526 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this
5527 * code is pretty crude, but we are not expecting any variability in
5530 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
5531 &startpoint.xlogid, &startpoint.xrecoff, &tli,
5532 startxlogfilename, &ch) != 5 || ch != '\n')
5534 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5535 errmsg("invalid data in file \"%s\"", labelfilepath)));
5536 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
5537 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
5538 &ch) != 3 || ch != '\n')
5540 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5541 errmsg("invalid data in file \"%s\"", labelfilepath)));
5542 if (ferror(lfp) || FreeFile(lfp))
5544 (errcode_for_file_access(),
5545 errmsg("could not read file \"%s\": %m",
5549 * Try to retrieve the backup history file (no error if we can't)
5551 XLByteToSeg(startpoint, _logId, _logSeg);
5552 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
5553 startpoint.xrecoff % XLogSegSize);
5555 if (InArchiveRecovery)
5556 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
5558 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
5559 startpoint.xrecoff % XLogSegSize);
5561 fp = AllocateFile(histfilepath, "r");
5565 * Parse history file to identify stop point.
5567 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
5568 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
5569 &ch) != 4 || ch != '\n')
5571 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5572 errmsg("invalid data in file \"%s\"", histfilename)));
5573 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
5574 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
5575 &ch) != 4 || ch != '\n')
5577 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5578 errmsg("invalid data in file \"%s\"", histfilename)));
5579 recoveryMinXlogOffset = stoppoint;
5580 if (ferror(fp) || FreeFile(fp))
5582 (errcode_for_file_access(),
5583 errmsg("could not read file \"%s\": %m",
5591 * remove_backup_label: remove any extant backup_label after successful
5592 * recovery. Once we have completed the end-of-recovery checkpoint there
5593 * is no reason to have to replay from the start point indicated by the
5594 * label (and indeed we'll probably have removed/recycled the needed WAL
5595 * segments), so remove the label to prevent trouble in later crash recoveries.
5598 remove_backup_label(void)
5600 char labelfilepath[MAXPGPATH];
5602 snprintf(labelfilepath, MAXPGPATH, "%s/backup_label", DataDir);
5603 if (unlink(labelfilepath) != 0)
5604 if (errno != ENOENT)
5606 (errcode_for_file_access(),
5607 errmsg("could not remove file \"%s\": %m",