1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2009, 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.333 2009/03/04 13:56:40 heikki Exp $
12 *-------------------------------------------------------------------------
26 #include "access/clog.h"
27 #include "access/multixact.h"
28 #include "access/subtrans.h"
29 #include "access/transam.h"
30 #include "access/tuptoaster.h"
31 #include "access/twophase.h"
32 #include "access/xact.h"
33 #include "access/xlog_internal.h"
34 #include "access/xlogutils.h"
35 #include "catalog/catversion.h"
36 #include "catalog/pg_control.h"
37 #include "catalog/pg_type.h"
39 #include "libpq/pqsignal.h"
40 #include "miscadmin.h"
42 #include "postmaster/bgwriter.h"
43 #include "storage/bufmgr.h"
44 #include "storage/fd.h"
45 #include "storage/ipc.h"
46 #include "storage/pmsignal.h"
47 #include "storage/procarray.h"
48 #include "storage/smgr.h"
49 #include "storage/spin.h"
50 #include "utils/builtins.h"
51 #include "utils/flatfiles.h"
52 #include "utils/guc.h"
53 #include "utils/ps_status.h"
57 /* File path names (all relative to $PGDATA) */
58 #define BACKUP_LABEL_FILE "backup_label"
59 #define BACKUP_LABEL_OLD "backup_label.old"
60 #define RECOVERY_COMMAND_FILE "recovery.conf"
61 #define RECOVERY_COMMAND_DONE "recovery.done"
64 /* User-settable parameters */
65 int CheckPointSegments = 3;
67 int XLogArchiveTimeout = 0;
68 bool XLogArchiveMode = false;
69 char *XLogArchiveCommand = NULL;
70 bool fullPageWrites = true;
71 bool log_checkpoints = false;
72 int sync_method = DEFAULT_SYNC_METHOD;
75 bool XLOG_DEBUG = false;
79 * XLOGfileslop is the maximum number of preallocated future XLOG segments.
80 * When we are done with an old XLOG segment file, we will recycle it as a
81 * future XLOG segment as long as there aren't already XLOGfileslop future
82 * segments; else we'll delete it. This could be made a separate GUC
83 * variable, but at present I think it's sufficient to hardwire it as
84 * 2*CheckPointSegments+1. Under normal conditions, a checkpoint will free
85 * no more than 2*CheckPointSegments log segments, and we want to recycle all
86 * of them; the +1 allows boundary cases to happen without wasting a
87 * delete/create-segment cycle.
89 #define XLOGfileslop (2*CheckPointSegments + 1)
94 const struct config_enum_entry sync_method_options[] = {
95 {"fsync", SYNC_METHOD_FSYNC, false},
96 #ifdef HAVE_FSYNC_WRITETHROUGH
97 {"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
100 {"fdatasync", SYNC_METHOD_FDATASYNC, false},
102 #ifdef OPEN_SYNC_FLAG
103 {"open_sync", SYNC_METHOD_OPEN, false},
105 #ifdef OPEN_DATASYNC_FLAG
106 {"open_datasync", SYNC_METHOD_OPEN_DSYNC, false},
112 * Statistics for current checkpoint are collected in this global struct.
113 * Because only the background writer or a stand-alone backend can perform
114 * checkpoints, this will be unused in normal backends.
116 CheckpointStatsData CheckpointStats;
119 * ThisTimeLineID will be same in all backends --- it identifies current
120 * WAL timeline for the database system.
122 TimeLineID ThisTimeLineID = 0;
125 * Are we doing recovery from XLOG?
127 * This is only ever true in the startup process, even if the system is still
128 * in recovery. Prior to 8.4, all activity during recovery were carried out
129 * by Startup process. This local variable continues to be used in functions
130 * that need to act differently when called from a redo function (e.g skip
131 * WAL logging). To check whether the system is in recovery regardless of what
132 * process you're running in, use RecoveryInProgress().
134 bool InRecovery = false;
136 /* Are we recovering using offline XLOG archives? */
137 static bool InArchiveRecovery = false;
140 * Local copy of SharedRecoveryInProgress variable. True actually means "not
141 * known, need to check the shared state"
143 static bool LocalRecoveryInProgress = true;
145 /* Was the last xlog file restored from archive, or local? */
146 static bool restoredFromArchive = false;
148 /* options taken from recovery.conf */
149 static char *recoveryRestoreCommand = NULL;
150 static bool recoveryTarget = false;
151 static bool recoveryTargetExact = false;
152 static bool recoveryTargetInclusive = true;
153 static TransactionId recoveryTargetXid;
154 static TimestampTz recoveryTargetTime;
155 static TimestampTz recoveryLastXTime = 0;
157 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
158 static TransactionId recoveryStopXid;
159 static TimestampTz recoveryStopTime;
160 static bool recoveryStopAfter;
163 * During normal operation, the only timeline we care about is ThisTimeLineID.
164 * During recovery, however, things are more complicated. To simplify life
165 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
166 * scan through the WAL history (that is, it is the line that was active when
167 * the currently-scanned WAL record was generated). We also need these
170 * recoveryTargetTLI: the desired timeline that we want to end in.
172 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
173 * its known parents, newest first (so recoveryTargetTLI is always the
174 * first list member). Only these TLIs are expected to be seen in the WAL
175 * segments we read, and indeed only these TLIs will be considered as
176 * candidate WAL files to open at all.
178 * curFileTLI: the TLI appearing in the name of the current input WAL file.
179 * (This is not necessarily the same as ThisTimeLineID, because we could
180 * be scanning data that was copied from an ancestor timeline when the current
181 * file was created.) During a sequential scan we do not allow this value
184 static TimeLineID recoveryTargetTLI;
185 static List *expectedTLIs;
186 static TimeLineID curFileTLI;
189 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
190 * current backend. It is updated for all inserts. XactLastRecEnd points to
191 * end+1 of the last record, and is reset when we end a top-level transaction,
192 * or start a new one; so it can be used to tell if the current transaction has
193 * created any XLOG records.
195 static XLogRecPtr ProcLastRecPtr = {0, 0};
197 XLogRecPtr XactLastRecEnd = {0, 0};
200 * RedoRecPtr is this backend's local copy of the REDO record pointer
201 * (which is almost but not quite the same as a pointer to the most recent
202 * CHECKPOINT record). We update this from the shared-memory copy,
203 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
204 * hold the Insert lock). See XLogInsert for details. We are also allowed
205 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
206 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
209 static XLogRecPtr RedoRecPtr;
212 * Shared-memory data structures for XLOG control
214 * LogwrtRqst indicates a byte position that we need to write and/or fsync
215 * the log up to (all records before that point must be written or fsynced).
216 * LogwrtResult indicates the byte positions we have already written/fsynced.
217 * These structs are identical but are declared separately to indicate their
218 * slightly different functions.
220 * We do a lot of pushups to minimize the amount of access to lockable
221 * shared memory values. There are actually three shared-memory copies of
222 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
223 * XLogCtl->LogwrtResult is protected by info_lck
224 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
225 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
226 * One must hold the associated lock to read or write any of these, but
227 * of course no lock is needed to read/write the unshared LogwrtResult.
229 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
230 * right", since both are updated by a write or flush operation before
231 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
232 * is that it can be examined/modified by code that already holds WALWriteLock
233 * without needing to grab info_lck as well.
235 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
236 * but is updated when convenient. Again, it exists for the convenience of
237 * code that is already holding WALInsertLock but not the other locks.
239 * The unshared LogwrtResult may lag behind any or all of these, and again
240 * is updated when convenient.
242 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
243 * (protected by info_lck), but we don't need to cache any copies of it.
245 * Note that this all works because the request and result positions can only
246 * advance forward, never back up, and so we can easily determine which of two
247 * values is "more up to date".
249 * info_lck is only held long enough to read/update the protected variables,
250 * so it's a plain spinlock. The other locks are held longer (potentially
251 * over I/O operations), so we use LWLocks for them. These locks are:
253 * WALInsertLock: must be held to insert a record into the WAL buffers.
255 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
258 * ControlFileLock: must be held to read/update control file or create
261 * CheckpointLock: must be held to do a checkpoint or restartpoint (ensures
262 * only one checkpointer at a time)
267 typedef struct XLogwrtRqst
269 XLogRecPtr Write; /* last byte + 1 to write out */
270 XLogRecPtr Flush; /* last byte + 1 to flush */
273 typedef struct XLogwrtResult
275 XLogRecPtr Write; /* last byte + 1 written out */
276 XLogRecPtr Flush; /* last byte + 1 flushed */
280 * Shared state data for XLogInsert.
282 typedef struct XLogCtlInsert
284 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
285 XLogRecPtr PrevRecord; /* start of previously-inserted record */
286 int curridx; /* current block index in cache */
287 XLogPageHeader currpage; /* points to header of block in cache */
288 char *currpos; /* current insertion point in cache */
289 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
290 bool forcePageWrites; /* forcing full-page writes for PITR? */
294 * Shared state data for XLogWrite/XLogFlush.
296 typedef struct XLogCtlWrite
298 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
299 int curridx; /* cache index of next block to write */
300 pg_time_t lastSegSwitchTime; /* time of last xlog segment switch */
304 * Total shared-memory state for XLOG.
306 typedef struct XLogCtlData
308 /* Protected by WALInsertLock: */
309 XLogCtlInsert Insert;
311 /* Protected by info_lck: */
312 XLogwrtRqst LogwrtRqst;
313 XLogwrtResult LogwrtResult;
314 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
315 TransactionId ckptXid;
316 XLogRecPtr asyncCommitLSN; /* LSN of newest async commit */
318 /* Protected by WALWriteLock: */
322 * These values do not change after startup, although the pointed-to pages
323 * and xlblocks values certainly do. Permission to read/write the pages
324 * and xlblocks values depends on WALInsertLock and WALWriteLock.
326 char *pages; /* buffers for unwritten XLOG pages */
327 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
328 int XLogCacheBlck; /* highest allocated xlog buffer index */
329 TimeLineID ThisTimeLineID;
332 * SharedRecoveryInProgress indicates if we're still in crash or archive
333 * recovery. It's checked by RecoveryInProgress().
335 bool SharedRecoveryInProgress;
338 * During recovery, we keep a copy of the latest checkpoint record
339 * here. Used by the background writer when it wants to create
342 * Protected by info_lck.
344 XLogRecPtr lastCheckPointRecPtr;
345 CheckPoint lastCheckPoint;
347 /* end+1 of the last record replayed (or being replayed) */
348 XLogRecPtr replayEndRecPtr;
350 slock_t info_lck; /* locks shared variables shown above */
353 static XLogCtlData *XLogCtl = NULL;
356 * We maintain an image of pg_control in shared memory.
358 static ControlFileData *ControlFile = NULL;
361 * Macros for managing XLogInsert state. In most cases, the calling routine
362 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
363 * so these are passed as parameters instead of being fetched via XLogCtl.
366 /* Free space remaining in the current xlog page buffer */
367 #define INSERT_FREESPACE(Insert) \
368 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
370 /* Construct XLogRecPtr value for current insertion point */
371 #define INSERT_RECPTR(recptr,Insert,curridx) \
373 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
375 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
378 #define PrevBufIdx(idx) \
379 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
381 #define NextBufIdx(idx) \
382 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
385 * Private, possibly out-of-date copy of shared LogwrtResult.
386 * See discussion above.
388 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
391 * openLogFile is -1 or a kernel FD for an open log file segment.
392 * When it's open, openLogOff is the current seek offset in the file.
393 * openLogId/openLogSeg identify the segment. These variables are only
394 * used to write the XLOG, and so will normally refer to the active segment.
396 static int openLogFile = -1;
397 static uint32 openLogId = 0;
398 static uint32 openLogSeg = 0;
399 static uint32 openLogOff = 0;
402 * These variables are used similarly to the ones above, but for reading
403 * the XLOG. Note, however, that readOff generally represents the offset
404 * of the page just read, not the seek position of the FD itself, which
405 * will be just past that page.
407 static int readFile = -1;
408 static uint32 readId = 0;
409 static uint32 readSeg = 0;
410 static uint32 readOff = 0;
412 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
413 static char *readBuf = NULL;
415 /* Buffer for current ReadRecord result (expandable) */
416 static char *readRecordBuf = NULL;
417 static uint32 readRecordBufSize = 0;
419 /* State information for XLOG reading */
420 static XLogRecPtr ReadRecPtr; /* start of last record read */
421 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
422 static XLogRecord *nextRecord = NULL;
423 static TimeLineID lastPageTLI = 0;
424 static XLogRecPtr minRecoveryPoint; /* local copy of ControlFile->minRecoveryPoint */
425 static bool updateMinRecoveryPoint = true;
427 static bool InRedo = false;
430 * Flag set by interrupt handlers for later service in the redo loop.
432 static volatile sig_atomic_t got_SIGHUP = false;
433 static volatile sig_atomic_t shutdown_requested = false;
435 * Flag set when executing a restore command, to tell SIGTERM signal handler
436 * that it's safe to just proc_exit.
438 static volatile sig_atomic_t in_restore_command = false;
441 static void XLogArchiveNotify(const char *xlog);
442 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
443 static bool XLogArchiveCheckDone(const char *xlog);
444 static bool XLogArchiveIsBusy(const char *xlog);
445 static void XLogArchiveCleanup(const char *xlog);
446 static void readRecoveryCommandFile(void);
447 static void exitArchiveRecovery(TimeLineID endTLI,
448 uint32 endLogId, uint32 endLogSeg);
449 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
450 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
452 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
453 XLogRecPtr *lsn, BkpBlock *bkpb);
454 static bool AdvanceXLInsertBuffer(bool new_segment);
455 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
456 static int XLogFileInit(uint32 log, uint32 seg,
457 bool *use_existent, bool use_lock);
458 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
459 bool find_free, int *max_advance,
461 static int XLogFileOpen(uint32 log, uint32 seg);
462 static int XLogFileRead(uint32 log, uint32 seg, int emode);
463 static void XLogFileClose(void);
464 static bool RestoreArchivedFile(char *path, const char *xlogfname,
465 const char *recovername, off_t expectedSize);
466 static void PreallocXlogFiles(XLogRecPtr endptr);
467 static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
468 static void ValidateXLOGDirectoryStructure(void);
469 static void CleanupBackupHistory(void);
470 static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
471 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
472 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
473 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
474 static List *readTimeLineHistory(TimeLineID targetTLI);
475 static bool existsTimeLineHistory(TimeLineID probeTLI);
476 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
477 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
479 uint32 endLogId, uint32 endLogSeg);
480 static void WriteControlFile(void);
481 static void ReadControlFile(void);
482 static char *str_time(pg_time_t tnow);
484 static void xlog_outrec(StringInfo buf, XLogRecord *record);
486 static void issue_xlog_fsync(void);
487 static void pg_start_backup_callback(int code, Datum arg);
488 static bool read_backup_label(XLogRecPtr *checkPointLoc,
489 XLogRecPtr *minRecoveryLoc);
490 static void rm_redo_error_callback(void *arg);
491 static int get_sync_bit(int method);
495 * Insert an XLOG record having the specified RMID and info bytes,
496 * with the body of the record being the data chunk(s) described by
497 * the rdata chain (see xlog.h for notes about rdata).
499 * Returns XLOG pointer to end of record (beginning of next record).
500 * This can be used as LSN for data pages affected by the logged action.
501 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
502 * before the data page can be written out. This implements the basic
503 * WAL rule "write the log before the data".)
505 * NB: this routine feels free to scribble on the XLogRecData structs,
506 * though not on the data they reference. This is OK since the XLogRecData
507 * structs are always just temporaries in the calling code.
510 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
512 XLogCtlInsert *Insert = &XLogCtl->Insert;
514 XLogContRecord *contrecord;
516 XLogRecPtr WriteRqst;
520 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
521 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
522 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
523 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
524 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
525 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
526 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
533 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
535 /* cross-check on whether we should be here or not */
536 if (RecoveryInProgress())
537 elog(FATAL, "cannot make new WAL entries during recovery");
539 /* info's high bits are reserved for use by me */
540 if (info & XLR_INFO_MASK)
541 elog(PANIC, "invalid xlog info mask %02X", info);
543 TRACE_POSTGRESQL_XLOG_INSERT(rmid, info);
546 * In bootstrap mode, we don't actually log anything but XLOG resources;
547 * return a phony record pointer.
549 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
552 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
557 * Here we scan the rdata chain, determine which buffers must be backed
558 * up, and compute the CRC values for the data. Note that the record
559 * header isn't added into the CRC initially since we don't know the final
560 * length or info bits quite yet. Thus, the CRC will represent the CRC of
561 * the whole record in the order "rdata, then backup blocks, then record
564 * We may have to loop back to here if a race condition is detected below.
565 * We could prevent the race by doing all this work while holding the
566 * insert lock, but it seems better to avoid doing CRC calculations while
567 * holding the lock. This means we have to be careful about modifying the
568 * rdata chain until we know we aren't going to loop back again. The only
569 * change we allow ourselves to make earlier is to set rdt->data = NULL in
570 * chain items we have decided we will have to back up the whole buffer
571 * for. This is OK because we will certainly decide the same thing again
572 * for those items if we do it over; doing it here saves an extra pass
573 * over the chain later.
576 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
578 dtbuf[i] = InvalidBuffer;
579 dtbuf_bkp[i] = false;
583 * Decide if we need to do full-page writes in this XLOG record: true if
584 * full_page_writes is on or we have a PITR request for it. Since we
585 * don't yet have the insert lock, forcePageWrites could change under us,
586 * but we'll recheck it once we have the lock.
588 doPageWrites = fullPageWrites || Insert->forcePageWrites;
590 INIT_CRC32(rdata_crc);
594 if (rdt->buffer == InvalidBuffer)
596 /* Simple data, just include it */
598 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
602 /* Find info for buffer */
603 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
605 if (rdt->buffer == dtbuf[i])
607 /* Buffer already referenced by earlier chain item */
613 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
617 if (dtbuf[i] == InvalidBuffer)
619 /* OK, put it in this slot */
620 dtbuf[i] = rdt->buffer;
621 if (XLogCheckBuffer(rdt, doPageWrites,
622 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
630 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
635 if (i >= XLR_MAX_BKP_BLOCKS)
636 elog(PANIC, "can backup at most %d blocks per xlog record",
639 /* Break out of loop when rdt points to last chain item */
640 if (rdt->next == NULL)
646 * Now add the backup block headers and data into the CRC
648 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
652 BkpBlock *bkpb = &(dtbuf_xlg[i]);
655 COMP_CRC32(rdata_crc,
658 page = (char *) BufferGetBlock(dtbuf[i]);
659 if (bkpb->hole_length == 0)
661 COMP_CRC32(rdata_crc,
667 /* must skip the hole */
668 COMP_CRC32(rdata_crc,
671 COMP_CRC32(rdata_crc,
672 page + (bkpb->hole_offset + bkpb->hole_length),
673 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
679 * NOTE: We disallow len == 0 because it provides a useful bit of extra
680 * error checking in ReadRecord. This means that all callers of
681 * XLogInsert must supply at least some not-in-a-buffer data. However, we
682 * make an exception for XLOG SWITCH records because we don't want them to
683 * ever cross a segment boundary.
685 if (len == 0 && !isLogSwitch)
686 elog(PANIC, "invalid xlog record length %u", len);
688 START_CRIT_SECTION();
690 /* Now wait to get insert lock */
691 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
694 * Check to see if my RedoRecPtr is out of date. If so, may have to go
695 * back and recompute everything. This can only happen just after a
696 * checkpoint, so it's better to be slow in this case and fast otherwise.
698 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
699 * affect the contents of the XLOG record, so we'll update our local copy
700 * but not force a recomputation.
702 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
704 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
705 RedoRecPtr = Insert->RedoRecPtr;
709 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
711 if (dtbuf[i] == InvalidBuffer)
713 if (dtbuf_bkp[i] == false &&
714 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
717 * Oops, this buffer now needs to be backed up, but we
718 * didn't think so above. Start over.
720 LWLockRelease(WALInsertLock);
729 * Also check to see if forcePageWrites was just turned on; if we weren't
730 * already doing full-page writes then go back and recompute. (If it was
731 * just turned off, we could recompute the record without full pages, but
732 * we choose not to bother.)
734 if (Insert->forcePageWrites && !doPageWrites)
736 /* Oops, must redo it with full-page data */
737 LWLockRelease(WALInsertLock);
743 * Make additional rdata chain entries for the backup blocks, so that we
744 * don't need to special-case them in the write loop. Note that we have
745 * now irrevocably changed the input rdata chain. At the exit of this
746 * loop, write_len includes the backup block data.
748 * Also set the appropriate info bits to show which buffers were backed
749 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
750 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
753 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
761 info |= XLR_SET_BKP_BLOCK(i);
763 bkpb = &(dtbuf_xlg[i]);
764 page = (char *) BufferGetBlock(dtbuf[i]);
766 rdt->next = &(dtbuf_rdt1[i]);
769 rdt->data = (char *) bkpb;
770 rdt->len = sizeof(BkpBlock);
771 write_len += sizeof(BkpBlock);
773 rdt->next = &(dtbuf_rdt2[i]);
776 if (bkpb->hole_length == 0)
785 /* must skip the hole */
787 rdt->len = bkpb->hole_offset;
788 write_len += bkpb->hole_offset;
790 rdt->next = &(dtbuf_rdt3[i]);
793 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
794 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
795 write_len += rdt->len;
801 * If we backed up any full blocks and online backup is not in progress,
802 * mark the backup blocks as removable. This allows the WAL archiver to
803 * know whether it is safe to compress archived WAL data by transforming
804 * full-block records into the non-full-block format.
806 * Note: we could just set the flag whenever !forcePageWrites, but
807 * defining it like this leaves the info bit free for some potential other
808 * use in records without any backup blocks.
810 if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
811 info |= XLR_BKP_REMOVABLE;
814 * If there isn't enough space on the current XLOG page for a record
815 * header, advance to the next page (leaving the unused space as zeroes).
818 freespace = INSERT_FREESPACE(Insert);
819 if (freespace < SizeOfXLogRecord)
821 updrqst = AdvanceXLInsertBuffer(false);
822 freespace = INSERT_FREESPACE(Insert);
825 /* Compute record's XLOG location */
826 curridx = Insert->curridx;
827 INSERT_RECPTR(RecPtr, Insert, curridx);
830 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
831 * segment, we need not insert it (and don't want to because we'd like
832 * consecutive switch requests to be no-ops). Instead, make sure
833 * everything is written and flushed through the end of the prior segment,
834 * and return the prior segment's end address.
837 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
839 /* We can release insert lock immediately */
840 LWLockRelease(WALInsertLock);
842 RecPtr.xrecoff -= SizeOfXLogLongPHD;
843 if (RecPtr.xrecoff == 0)
845 /* crossing a logid boundary */
847 RecPtr.xrecoff = XLogFileSize;
850 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
851 LogwrtResult = XLogCtl->Write.LogwrtResult;
852 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
854 XLogwrtRqst FlushRqst;
856 FlushRqst.Write = RecPtr;
857 FlushRqst.Flush = RecPtr;
858 XLogWrite(FlushRqst, false, false);
860 LWLockRelease(WALWriteLock);
867 /* Insert record header */
869 record = (XLogRecord *) Insert->currpos;
870 record->xl_prev = Insert->PrevRecord;
871 record->xl_xid = GetCurrentTransactionIdIfAny();
872 record->xl_tot_len = SizeOfXLogRecord + write_len;
873 record->xl_len = len; /* doesn't include backup blocks */
874 record->xl_info = info;
875 record->xl_rmid = rmid;
877 /* Now we can finish computing the record's CRC */
878 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
879 SizeOfXLogRecord - sizeof(pg_crc32));
880 FIN_CRC32(rdata_crc);
881 record->xl_crc = rdata_crc;
888 initStringInfo(&buf);
889 appendStringInfo(&buf, "INSERT @ %X/%X: ",
890 RecPtr.xlogid, RecPtr.xrecoff);
891 xlog_outrec(&buf, record);
892 if (rdata->data != NULL)
894 appendStringInfo(&buf, " - ");
895 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
897 elog(LOG, "%s", buf.data);
902 /* Record begin of record in appropriate places */
903 ProcLastRecPtr = RecPtr;
904 Insert->PrevRecord = RecPtr;
906 Insert->currpos += SizeOfXLogRecord;
907 freespace -= SizeOfXLogRecord;
910 * Append the data, including backup blocks if any
914 while (rdata->data == NULL)
919 if (rdata->len > freespace)
921 memcpy(Insert->currpos, rdata->data, freespace);
922 rdata->data += freespace;
923 rdata->len -= freespace;
924 write_len -= freespace;
928 memcpy(Insert->currpos, rdata->data, rdata->len);
929 freespace -= rdata->len;
930 write_len -= rdata->len;
931 Insert->currpos += rdata->len;
937 /* Use next buffer */
938 updrqst = AdvanceXLInsertBuffer(false);
939 curridx = Insert->curridx;
940 /* Insert cont-record header */
941 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
942 contrecord = (XLogContRecord *) Insert->currpos;
943 contrecord->xl_rem_len = write_len;
944 Insert->currpos += SizeOfXLogContRecord;
945 freespace = INSERT_FREESPACE(Insert);
948 /* Ensure next record will be properly aligned */
949 Insert->currpos = (char *) Insert->currpage +
950 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
951 freespace = INSERT_FREESPACE(Insert);
954 * The recptr I return is the beginning of the *next* record. This will be
955 * stored as LSN for changed data pages...
957 INSERT_RECPTR(RecPtr, Insert, curridx);
960 * If the record is an XLOG_SWITCH, we must now write and flush all the
961 * existing data, and then forcibly advance to the start of the next
962 * segment. It's not good to do this I/O while holding the insert lock,
963 * but there seems too much risk of confusion if we try to release the
964 * lock sooner. Fortunately xlog switch needn't be a high-performance
965 * operation anyway...
969 XLogCtlWrite *Write = &XLogCtl->Write;
970 XLogwrtRqst FlushRqst;
971 XLogRecPtr OldSegEnd;
973 TRACE_POSTGRESQL_XLOG_SWITCH();
975 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
978 * Flush through the end of the page containing XLOG_SWITCH, and
979 * perform end-of-segment actions (eg, notifying archiver).
981 WriteRqst = XLogCtl->xlblocks[curridx];
982 FlushRqst.Write = WriteRqst;
983 FlushRqst.Flush = WriteRqst;
984 XLogWrite(FlushRqst, false, true);
986 /* Set up the next buffer as first page of next segment */
987 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
988 (void) AdvanceXLInsertBuffer(true);
990 /* There should be no unwritten data */
991 curridx = Insert->curridx;
992 Assert(curridx == Write->curridx);
994 /* Compute end address of old segment */
995 OldSegEnd = XLogCtl->xlblocks[curridx];
996 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
997 if (OldSegEnd.xrecoff == 0)
999 /* crossing a logid boundary */
1000 OldSegEnd.xlogid -= 1;
1001 OldSegEnd.xrecoff = XLogFileSize;
1004 /* Make it look like we've written and synced all of old segment */
1005 LogwrtResult.Write = OldSegEnd;
1006 LogwrtResult.Flush = OldSegEnd;
1009 * Update shared-memory status --- this code should match XLogWrite
1012 /* use volatile pointer to prevent code rearrangement */
1013 volatile XLogCtlData *xlogctl = XLogCtl;
1015 SpinLockAcquire(&xlogctl->info_lck);
1016 xlogctl->LogwrtResult = LogwrtResult;
1017 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1018 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1019 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1020 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1021 SpinLockRelease(&xlogctl->info_lck);
1024 Write->LogwrtResult = LogwrtResult;
1026 LWLockRelease(WALWriteLock);
1028 updrqst = false; /* done already */
1032 /* normal case, ie not xlog switch */
1034 /* Need to update shared LogwrtRqst if some block was filled up */
1035 if (freespace < SizeOfXLogRecord)
1037 /* curridx is filled and available for writing out */
1042 /* if updrqst already set, write through end of previous buf */
1043 curridx = PrevBufIdx(curridx);
1045 WriteRqst = XLogCtl->xlblocks[curridx];
1048 LWLockRelease(WALInsertLock);
1052 /* use volatile pointer to prevent code rearrangement */
1053 volatile XLogCtlData *xlogctl = XLogCtl;
1055 SpinLockAcquire(&xlogctl->info_lck);
1056 /* advance global request to include new block(s) */
1057 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
1058 xlogctl->LogwrtRqst.Write = WriteRqst;
1059 /* update local result copy while I have the chance */
1060 LogwrtResult = xlogctl->LogwrtResult;
1061 SpinLockRelease(&xlogctl->info_lck);
1064 XactLastRecEnd = RecPtr;
1072 * Determine whether the buffer referenced by an XLogRecData item has to
1073 * be backed up, and if so fill a BkpBlock struct for it. In any case
1074 * save the buffer's LSN at *lsn.
1077 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1078 XLogRecPtr *lsn, BkpBlock *bkpb)
1082 page = BufferGetPage(rdata->buffer);
1085 * XXX We assume page LSN is first data on *every* page that can be passed
1086 * to XLogInsert, whether it otherwise has the standard page layout or
1089 *lsn = PageGetLSN(page);
1092 XLByteLE(PageGetLSN(page), RedoRecPtr))
1095 * The page needs to be backed up, so set up *bkpb
1097 BufferGetTag(rdata->buffer, &bkpb->node, &bkpb->fork, &bkpb->block);
1099 if (rdata->buffer_std)
1101 /* Assume we can omit data between pd_lower and pd_upper */
1102 uint16 lower = ((PageHeader) page)->pd_lower;
1103 uint16 upper = ((PageHeader) page)->pd_upper;
1105 if (lower >= SizeOfPageHeaderData &&
1109 bkpb->hole_offset = lower;
1110 bkpb->hole_length = upper - lower;
1114 /* No "hole" to compress out */
1115 bkpb->hole_offset = 0;
1116 bkpb->hole_length = 0;
1121 /* Not a standard page header, don't try to eliminate "hole" */
1122 bkpb->hole_offset = 0;
1123 bkpb->hole_length = 0;
1126 return true; /* buffer requires backup */
1129 return false; /* buffer does not need to be backed up */
1135 * Create an archive notification file
1137 * The name of the notification file is the message that will be picked up
1138 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1139 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1140 * then when complete, rename it to 0000000100000001000000C6.done
1143 XLogArchiveNotify(const char *xlog)
1145 char archiveStatusPath[MAXPGPATH];
1148 /* insert an otherwise empty file called <XLOG>.ready */
1149 StatusFilePath(archiveStatusPath, xlog, ".ready");
1150 fd = AllocateFile(archiveStatusPath, "w");
1154 (errcode_for_file_access(),
1155 errmsg("could not create archive status file \"%s\": %m",
1156 archiveStatusPath)));
1162 (errcode_for_file_access(),
1163 errmsg("could not write archive status file \"%s\": %m",
1164 archiveStatusPath)));
1168 /* Notify archiver that it's got something to do */
1169 if (IsUnderPostmaster)
1170 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1174 * Convenience routine to notify using log/seg representation of filename
1177 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1179 char xlog[MAXFNAMELEN];
1181 XLogFileName(xlog, ThisTimeLineID, log, seg);
1182 XLogArchiveNotify(xlog);
1186 * XLogArchiveCheckDone
1188 * This is called when we are ready to delete or recycle an old XLOG segment
1189 * file or backup history file. If it is okay to delete it then return true.
1190 * If it is not time to delete it, make sure a .ready file exists, and return
1193 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1194 * then return false; else create <XLOG>.ready and return false.
1196 * The reason we do things this way is so that if the original attempt to
1197 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1200 XLogArchiveCheckDone(const char *xlog)
1202 char archiveStatusPath[MAXPGPATH];
1203 struct stat stat_buf;
1205 /* Always deletable if archiving is off */
1206 if (!XLogArchivingActive())
1209 /* First check for .done --- this means archiver is done with it */
1210 StatusFilePath(archiveStatusPath, xlog, ".done");
1211 if (stat(archiveStatusPath, &stat_buf) == 0)
1214 /* check for .ready --- this means archiver is still busy with it */
1215 StatusFilePath(archiveStatusPath, xlog, ".ready");
1216 if (stat(archiveStatusPath, &stat_buf) == 0)
1219 /* Race condition --- maybe archiver just finished, so recheck */
1220 StatusFilePath(archiveStatusPath, xlog, ".done");
1221 if (stat(archiveStatusPath, &stat_buf) == 0)
1224 /* Retry creation of the .ready file */
1225 XLogArchiveNotify(xlog);
1232 * Check to see if an XLOG segment file is still unarchived.
1233 * This is almost but not quite the inverse of XLogArchiveCheckDone: in
1234 * the first place we aren't chartered to recreate the .ready file, and
1235 * in the second place we should consider that if the file is already gone
1236 * then it's not busy. (This check is needed to handle the race condition
1237 * that a checkpoint already deleted the no-longer-needed file.)
1240 XLogArchiveIsBusy(const char *xlog)
1242 char archiveStatusPath[MAXPGPATH];
1243 struct stat stat_buf;
1245 /* First check for .done --- this means archiver is done with it */
1246 StatusFilePath(archiveStatusPath, xlog, ".done");
1247 if (stat(archiveStatusPath, &stat_buf) == 0)
1250 /* check for .ready --- this means archiver is still busy with it */
1251 StatusFilePath(archiveStatusPath, xlog, ".ready");
1252 if (stat(archiveStatusPath, &stat_buf) == 0)
1255 /* Race condition --- maybe archiver just finished, so recheck */
1256 StatusFilePath(archiveStatusPath, xlog, ".done");
1257 if (stat(archiveStatusPath, &stat_buf) == 0)
1261 * Check to see if the WAL file has been removed by checkpoint,
1262 * which implies it has already been archived, and explains why we
1263 * can't see a status file for it.
1265 snprintf(archiveStatusPath, MAXPGPATH, XLOGDIR "/%s", xlog);
1266 if (stat(archiveStatusPath, &stat_buf) != 0 &&
1274 * XLogArchiveCleanup
1276 * Cleanup archive notification file(s) for a particular xlog segment
1279 XLogArchiveCleanup(const char *xlog)
1281 char archiveStatusPath[MAXPGPATH];
1283 /* Remove the .done file */
1284 StatusFilePath(archiveStatusPath, xlog, ".done");
1285 unlink(archiveStatusPath);
1286 /* should we complain about failure? */
1288 /* Remove the .ready file if present --- normally it shouldn't be */
1289 StatusFilePath(archiveStatusPath, xlog, ".ready");
1290 unlink(archiveStatusPath);
1291 /* should we complain about failure? */
1295 * Advance the Insert state to the next buffer page, writing out the next
1296 * buffer if it still contains unwritten data.
1298 * If new_segment is TRUE then we set up the next buffer page as the first
1299 * page of the next xlog segment file, possibly but not usually the next
1300 * consecutive file page.
1302 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1303 * just-filled page. If we can do this for free (without an extra lock),
1304 * we do so here. Otherwise the caller must do it. We return TRUE if the
1305 * request update still needs to be done, FALSE if we did it internally.
1307 * Must be called with WALInsertLock held.
1310 AdvanceXLInsertBuffer(bool new_segment)
1312 XLogCtlInsert *Insert = &XLogCtl->Insert;
1313 XLogCtlWrite *Write = &XLogCtl->Write;
1314 int nextidx = NextBufIdx(Insert->curridx);
1315 bool update_needed = true;
1316 XLogRecPtr OldPageRqstPtr;
1317 XLogwrtRqst WriteRqst;
1318 XLogRecPtr NewPageEndPtr;
1319 XLogPageHeader NewPage;
1321 /* Use Insert->LogwrtResult copy if it's more fresh */
1322 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1323 LogwrtResult = Insert->LogwrtResult;
1326 * Get ending-offset of the buffer page we need to replace (this may be
1327 * zero if the buffer hasn't been used yet). Fall through if it's already
1330 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1331 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1333 /* nope, got work to do... */
1334 XLogRecPtr FinishedPageRqstPtr;
1336 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1338 /* Before waiting, get info_lck and update LogwrtResult */
1340 /* use volatile pointer to prevent code rearrangement */
1341 volatile XLogCtlData *xlogctl = XLogCtl;
1343 SpinLockAcquire(&xlogctl->info_lck);
1344 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1345 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1346 LogwrtResult = xlogctl->LogwrtResult;
1347 SpinLockRelease(&xlogctl->info_lck);
1350 update_needed = false; /* Did the shared-request update */
1352 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1354 /* OK, someone wrote it already */
1355 Insert->LogwrtResult = LogwrtResult;
1359 /* Must acquire write lock */
1360 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1361 LogwrtResult = Write->LogwrtResult;
1362 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1364 /* OK, someone wrote it already */
1365 LWLockRelease(WALWriteLock);
1366 Insert->LogwrtResult = LogwrtResult;
1371 * Have to write buffers while holding insert lock. This is
1372 * not good, so only write as much as we absolutely must.
1374 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
1375 WriteRqst.Write = OldPageRqstPtr;
1376 WriteRqst.Flush.xlogid = 0;
1377 WriteRqst.Flush.xrecoff = 0;
1378 XLogWrite(WriteRqst, false, false);
1379 LWLockRelease(WALWriteLock);
1380 Insert->LogwrtResult = LogwrtResult;
1381 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
1387 * Now the next buffer slot is free and we can set it up to be the next
1390 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1394 /* force it to a segment start point */
1395 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1396 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1399 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1401 /* crossing a logid boundary */
1402 NewPageEndPtr.xlogid += 1;
1403 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1406 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1407 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1408 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1410 Insert->curridx = nextidx;
1411 Insert->currpage = NewPage;
1413 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1416 * Be sure to re-zero the buffer so that bytes beyond what we've written
1417 * will look like zeroes and not valid XLOG records...
1419 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1422 * Fill the new page's header
1424 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1426 /* NewPage->xlp_info = 0; */ /* done by memset */
1427 NewPage ->xlp_tli = ThisTimeLineID;
1428 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1429 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1432 * If first page of an XLOG segment file, make it a long header.
1434 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1436 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1438 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1439 NewLongPage->xlp_seg_size = XLogSegSize;
1440 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1441 NewPage ->xlp_info |= XLP_LONG_HEADER;
1443 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1446 return update_needed;
1450 * Check whether we've consumed enough xlog space that a checkpoint is needed.
1452 * Caller must have just finished filling the open log file (so that
1453 * openLogId/openLogSeg are valid). We measure the distance from RedoRecPtr
1454 * to the open log file and see if that exceeds CheckPointSegments.
1456 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
1459 XLogCheckpointNeeded(void)
1462 * A straight computation of segment number could overflow 32 bits. Rather
1463 * than assuming we have working 64-bit arithmetic, we compare the
1464 * highest-order bits separately, and force a checkpoint immediately when
1469 uint32 old_highbits,
1472 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1473 (RedoRecPtr.xrecoff / XLogSegSize);
1474 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1475 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile + openLogSeg;
1476 new_highbits = openLogId / XLogSegSize;
1477 if (new_highbits != old_highbits ||
1478 new_segno >= old_segno + (uint32) (CheckPointSegments - 1))
1484 * Write and/or fsync the log at least as far as WriteRqst indicates.
1486 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1487 * may stop at any convenient boundary (such as a cache or logfile boundary).
1488 * This option allows us to avoid uselessly issuing multiple writes when a
1489 * single one would do.
1491 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1492 * perform end-of-segment actions after writing the last page, even if
1493 * it's not physically the end of its segment. (NB: this will work properly
1494 * only if caller specifies WriteRqst == page-end and flexible == false,
1495 * and there is some data to write.)
1497 * Must be called with WALWriteLock held.
1500 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1502 XLogCtlWrite *Write = &XLogCtl->Write;
1504 bool last_iteration;
1512 /* We should always be inside a critical section here */
1513 Assert(CritSectionCount > 0);
1516 * Update local LogwrtResult (caller probably did this already, but...)
1518 LogwrtResult = Write->LogwrtResult;
1521 * Since successive pages in the xlog cache are consecutively allocated,
1522 * we can usually gather multiple pages together and issue just one
1523 * write() call. npages is the number of pages we have determined can be
1524 * written together; startidx is the cache block index of the first one,
1525 * and startoffset is the file offset at which it should go. The latter
1526 * two variables are only valid when npages > 0, but we must initialize
1527 * all of them to keep the compiler quiet.
1534 * Within the loop, curridx is the cache block index of the page to
1535 * consider writing. We advance Write->curridx only after successfully
1536 * writing pages. (Right now, this refinement is useless since we are
1537 * going to PANIC if any error occurs anyway; but someday it may come in
1540 curridx = Write->curridx;
1542 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1545 * Make sure we're not ahead of the insert process. This could happen
1546 * if we're passed a bogus WriteRqst.Write that is past the end of the
1547 * last page that's been initialized by AdvanceXLInsertBuffer.
1549 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1550 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1551 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1552 XLogCtl->xlblocks[curridx].xlogid,
1553 XLogCtl->xlblocks[curridx].xrecoff);
1555 /* Advance LogwrtResult.Write to end of current buffer page */
1556 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1557 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1559 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1562 * Switch to new logfile segment. We cannot have any pending
1563 * pages here (since we dump what we have at segment end).
1565 Assert(npages == 0);
1566 if (openLogFile >= 0)
1568 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1570 /* create/use new log file */
1571 use_existent = true;
1572 openLogFile = XLogFileInit(openLogId, openLogSeg,
1573 &use_existent, true);
1577 /* Make sure we have the current logfile open */
1578 if (openLogFile < 0)
1580 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1581 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1585 /* Add current page to the set of pending pages-to-dump */
1588 /* first of group */
1590 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1595 * Dump the set if this will be the last loop iteration, or if we are
1596 * at the last page of the cache area (since the next page won't be
1597 * contiguous in memory), or if we are at the end of the logfile
1600 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1602 finishing_seg = !ispartialpage &&
1603 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1605 if (last_iteration ||
1606 curridx == XLogCtl->XLogCacheBlck ||
1612 /* Need to seek in the file? */
1613 if (openLogOff != startoffset)
1615 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1617 (errcode_for_file_access(),
1618 errmsg("could not seek in log file %u, "
1619 "segment %u to offset %u: %m",
1620 openLogId, openLogSeg, startoffset)));
1621 openLogOff = startoffset;
1624 /* OK to write the page(s) */
1625 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1626 nbytes = npages * (Size) XLOG_BLCKSZ;
1628 if (write(openLogFile, from, nbytes) != nbytes)
1630 /* if write didn't set errno, assume no disk space */
1634 (errcode_for_file_access(),
1635 errmsg("could not write to log file %u, segment %u "
1636 "at offset %u, length %lu: %m",
1637 openLogId, openLogSeg,
1638 openLogOff, (unsigned long) nbytes)));
1641 /* Update state for write */
1642 openLogOff += nbytes;
1643 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1647 * If we just wrote the whole last page of a logfile segment,
1648 * fsync the segment immediately. This avoids having to go back
1649 * and re-open prior segments when an fsync request comes along
1650 * later. Doing it here ensures that one and only one backend will
1651 * perform this fsync.
1653 * We also do this if this is the last page written for an xlog
1656 * This is also the right place to notify the Archiver that the
1657 * segment is ready to copy to archival storage, and to update the
1658 * timer for archive_timeout, and to signal for a checkpoint if
1659 * too many logfile segments have been used since the last
1662 if (finishing_seg || (xlog_switch && last_iteration))
1665 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1667 if (XLogArchivingActive())
1668 XLogArchiveNotifySeg(openLogId, openLogSeg);
1670 Write->lastSegSwitchTime = (pg_time_t) time(NULL);
1673 * Signal bgwriter to start a checkpoint if we've consumed too
1674 * much xlog since the last one. For speed, we first check
1675 * using the local copy of RedoRecPtr, which might be out of
1676 * date; if it looks like a checkpoint is needed, forcibly
1677 * update RedoRecPtr and recheck.
1679 if (IsUnderPostmaster &&
1680 XLogCheckpointNeeded())
1682 (void) GetRedoRecPtr();
1683 if (XLogCheckpointNeeded())
1684 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1691 /* Only asked to write a partial page */
1692 LogwrtResult.Write = WriteRqst.Write;
1695 curridx = NextBufIdx(curridx);
1697 /* If flexible, break out of loop as soon as we wrote something */
1698 if (flexible && npages == 0)
1702 Assert(npages == 0);
1703 Assert(curridx == Write->curridx);
1706 * If asked to flush, do so
1708 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1709 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1712 * Could get here without iterating above loop, in which case we might
1713 * have no open file or the wrong one. However, we do not need to
1714 * fsync more than one file.
1716 if (sync_method != SYNC_METHOD_OPEN &&
1717 sync_method != SYNC_METHOD_OPEN_DSYNC)
1719 if (openLogFile >= 0 &&
1720 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1722 if (openLogFile < 0)
1724 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1725 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1730 LogwrtResult.Flush = LogwrtResult.Write;
1734 * Update shared-memory status
1736 * We make sure that the shared 'request' values do not fall behind the
1737 * 'result' values. This is not absolutely essential, but it saves some
1738 * code in a couple of places.
1741 /* use volatile pointer to prevent code rearrangement */
1742 volatile XLogCtlData *xlogctl = XLogCtl;
1744 SpinLockAcquire(&xlogctl->info_lck);
1745 xlogctl->LogwrtResult = LogwrtResult;
1746 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1747 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1748 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1749 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1750 SpinLockRelease(&xlogctl->info_lck);
1753 Write->LogwrtResult = LogwrtResult;
1757 * Record the LSN for an asynchronous transaction commit.
1758 * (This should not be called for aborts, nor for synchronous commits.)
1761 XLogSetAsyncCommitLSN(XLogRecPtr asyncCommitLSN)
1763 /* use volatile pointer to prevent code rearrangement */
1764 volatile XLogCtlData *xlogctl = XLogCtl;
1766 SpinLockAcquire(&xlogctl->info_lck);
1767 if (XLByteLT(xlogctl->asyncCommitLSN, asyncCommitLSN))
1768 xlogctl->asyncCommitLSN = asyncCommitLSN;
1769 SpinLockRelease(&xlogctl->info_lck);
1773 * Advance minRecoveryPoint in control file.
1775 * If we crash during recovery, we must reach this point again before the
1776 * database is consistent.
1778 * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
1779 * is is only updated if it's not already greater than or equal to 'lsn'.
1782 UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
1784 /* Quick check using our local copy of the variable */
1785 if (!updateMinRecoveryPoint || (!force && XLByteLE(lsn, minRecoveryPoint)))
1788 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1790 /* update local copy */
1791 minRecoveryPoint = ControlFile->minRecoveryPoint;
1794 * An invalid minRecoveryPoint means that we need to recover all the WAL,
1795 * ie. crash recovery. Don't update the control file in that case.
1797 if (minRecoveryPoint.xlogid == 0 && minRecoveryPoint.xrecoff == 0)
1798 updateMinRecoveryPoint = false;
1799 else if (force || XLByteLT(minRecoveryPoint, lsn))
1801 /* use volatile pointer to prevent code rearrangement */
1802 volatile XLogCtlData *xlogctl = XLogCtl;
1803 XLogRecPtr newMinRecoveryPoint;
1806 * To avoid having to update the control file too often, we update it
1807 * all the way to the last record being replayed, even though 'lsn'
1808 * would suffice for correctness.
1810 SpinLockAcquire(&xlogctl->info_lck);
1811 newMinRecoveryPoint = xlogctl->replayEndRecPtr;
1812 SpinLockRelease(&xlogctl->info_lck);
1814 /* update control file */
1815 if (XLByteLT(ControlFile->minRecoveryPoint, newMinRecoveryPoint))
1817 ControlFile->minRecoveryPoint = newMinRecoveryPoint;
1818 UpdateControlFile();
1819 minRecoveryPoint = newMinRecoveryPoint;
1822 (errmsg("updated min recovery point to %X/%X",
1823 minRecoveryPoint.xlogid, minRecoveryPoint.xrecoff)));
1826 LWLockRelease(ControlFileLock);
1830 * Ensure that all XLOG data through the given position is flushed to disk.
1832 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1833 * already held, and we try to avoid acquiring it if possible.
1836 XLogFlush(XLogRecPtr record)
1838 XLogRecPtr WriteRqstPtr;
1839 XLogwrtRqst WriteRqst;
1842 * During REDO, we don't try to flush the WAL, but update minRecoveryPoint
1845 if (RecoveryInProgress())
1847 UpdateMinRecoveryPoint(record, false);
1851 /* Quick exit if already known flushed */
1852 if (XLByteLE(record, LogwrtResult.Flush))
1857 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1858 record.xlogid, record.xrecoff,
1859 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1860 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1863 START_CRIT_SECTION();
1866 * Since fsync is usually a horribly expensive operation, we try to
1867 * piggyback as much data as we can on each fsync: if we see any more data
1868 * entered into the xlog buffer, we'll write and fsync that too, so that
1869 * the final value of LogwrtResult.Flush is as large as possible. This
1870 * gives us some chance of avoiding another fsync immediately after.
1873 /* initialize to given target; may increase below */
1874 WriteRqstPtr = record;
1876 /* read LogwrtResult and update local state */
1878 /* use volatile pointer to prevent code rearrangement */
1879 volatile XLogCtlData *xlogctl = XLogCtl;
1881 SpinLockAcquire(&xlogctl->info_lck);
1882 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1883 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1884 LogwrtResult = xlogctl->LogwrtResult;
1885 SpinLockRelease(&xlogctl->info_lck);
1889 if (!XLByteLE(record, LogwrtResult.Flush))
1891 /* now wait for the write lock */
1892 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1893 LogwrtResult = XLogCtl->Write.LogwrtResult;
1894 if (!XLByteLE(record, LogwrtResult.Flush))
1896 /* try to write/flush later additions to XLOG as well */
1897 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1899 XLogCtlInsert *Insert = &XLogCtl->Insert;
1900 uint32 freespace = INSERT_FREESPACE(Insert);
1902 if (freespace < SizeOfXLogRecord) /* buffer is full */
1903 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1906 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1907 WriteRqstPtr.xrecoff -= freespace;
1909 LWLockRelease(WALInsertLock);
1910 WriteRqst.Write = WriteRqstPtr;
1911 WriteRqst.Flush = WriteRqstPtr;
1915 WriteRqst.Write = WriteRqstPtr;
1916 WriteRqst.Flush = record;
1918 XLogWrite(WriteRqst, false, false);
1920 LWLockRelease(WALWriteLock);
1926 * If we still haven't flushed to the request point then we have a
1927 * problem; most likely, the requested flush point is past end of XLOG.
1928 * This has been seen to occur when a disk page has a corrupted LSN.
1930 * Formerly we treated this as a PANIC condition, but that hurts the
1931 * system's robustness rather than helping it: we do not want to take down
1932 * the whole system due to corruption on one data page. In particular, if
1933 * the bad page is encountered again during recovery then we would be
1934 * unable to restart the database at all! (This scenario has actually
1935 * happened in the field several times with 7.1 releases. Note that we
1936 * cannot get here while RecoveryInProgress(), but if the bad page is
1937 * brought in and marked dirty during recovery then if a checkpoint were
1938 * performed at the end of recovery it will try to flush it.
1940 * The current approach is to ERROR under normal conditions, but only
1941 * WARNING during recovery, so that the system can be brought up even if
1942 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1943 * be promoted to PANIC since xact.c calls this routine inside a critical
1944 * section. However, calls from bufmgr.c are not within critical sections
1945 * and so we will not force a restart for a bad LSN on a data page.
1947 if (XLByteLT(LogwrtResult.Flush, record))
1948 elog(InRecovery ? WARNING : ERROR,
1949 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1950 record.xlogid, record.xrecoff,
1951 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1955 * Flush xlog, but without specifying exactly where to flush to.
1957 * We normally flush only completed blocks; but if there is nothing to do on
1958 * that basis, we check for unflushed async commits in the current incomplete
1959 * block, and flush through the latest one of those. Thus, if async commits
1960 * are not being used, we will flush complete blocks only. We can guarantee
1961 * that async commits reach disk after at most three cycles; normally only
1962 * one or two. (We allow XLogWrite to write "flexibly", meaning it can stop
1963 * at the end of the buffer ring; this makes a difference only with very high
1964 * load or long wal_writer_delay, but imposes one extra cycle for the worst
1965 * case for async commits.)
1967 * This routine is invoked periodically by the background walwriter process.
1970 XLogBackgroundFlush(void)
1972 XLogRecPtr WriteRqstPtr;
1973 bool flexible = true;
1975 /* XLOG doesn't need flushing during recovery */
1976 if (RecoveryInProgress())
1979 /* read LogwrtResult and update local state */
1981 /* use volatile pointer to prevent code rearrangement */
1982 volatile XLogCtlData *xlogctl = XLogCtl;
1984 SpinLockAcquire(&xlogctl->info_lck);
1985 LogwrtResult = xlogctl->LogwrtResult;
1986 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1987 SpinLockRelease(&xlogctl->info_lck);
1990 /* back off to last completed page boundary */
1991 WriteRqstPtr.xrecoff -= WriteRqstPtr.xrecoff % XLOG_BLCKSZ;
1993 /* if we have already flushed that far, consider async commit records */
1994 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1996 /* use volatile pointer to prevent code rearrangement */
1997 volatile XLogCtlData *xlogctl = XLogCtl;
1999 SpinLockAcquire(&xlogctl->info_lck);
2000 WriteRqstPtr = xlogctl->asyncCommitLSN;
2001 SpinLockRelease(&xlogctl->info_lck);
2002 flexible = false; /* ensure it all gets written */
2005 /* Done if already known flushed */
2006 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
2011 elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
2012 WriteRqstPtr.xlogid, WriteRqstPtr.xrecoff,
2013 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
2014 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
2017 START_CRIT_SECTION();
2019 /* now wait for the write lock */
2020 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2021 LogwrtResult = XLogCtl->Write.LogwrtResult;
2022 if (!XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
2024 XLogwrtRqst WriteRqst;
2026 WriteRqst.Write = WriteRqstPtr;
2027 WriteRqst.Flush = WriteRqstPtr;
2028 XLogWrite(WriteRqst, flexible, false);
2030 LWLockRelease(WALWriteLock);
2036 * Flush any previous asynchronously-committed transactions' commit records.
2038 * NOTE: it is unwise to assume that this provides any strong guarantees.
2039 * In particular, because of the inexact LSN bookkeeping used by clog.c,
2040 * we cannot assume that hint bits will be settable for these transactions.
2043 XLogAsyncCommitFlush(void)
2045 XLogRecPtr WriteRqstPtr;
2047 /* use volatile pointer to prevent code rearrangement */
2048 volatile XLogCtlData *xlogctl = XLogCtl;
2050 /* There's no asynchronously committed transactions during recovery */
2051 if (RecoveryInProgress())
2054 SpinLockAcquire(&xlogctl->info_lck);
2055 WriteRqstPtr = xlogctl->asyncCommitLSN;
2056 SpinLockRelease(&xlogctl->info_lck);
2058 XLogFlush(WriteRqstPtr);
2062 * Test whether XLOG data has been flushed up to (at least) the given position.
2064 * Returns true if a flush is still needed. (It may be that someone else
2065 * is already in process of flushing that far, however.)
2068 XLogNeedsFlush(XLogRecPtr record)
2070 /* XLOG doesn't need flushing during recovery */
2071 if (RecoveryInProgress())
2074 /* Quick exit if already known flushed */
2075 if (XLByteLE(record, LogwrtResult.Flush))
2078 /* read LogwrtResult and update local state */
2080 /* use volatile pointer to prevent code rearrangement */
2081 volatile XLogCtlData *xlogctl = XLogCtl;
2083 SpinLockAcquire(&xlogctl->info_lck);
2084 LogwrtResult = xlogctl->LogwrtResult;
2085 SpinLockRelease(&xlogctl->info_lck);
2089 if (XLByteLE(record, LogwrtResult.Flush))
2096 * Create a new XLOG file segment, or open a pre-existing one.
2098 * log, seg: identify segment to be created/opened.
2100 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
2101 * pre-existing file will be deleted). On return, TRUE if a pre-existing
2104 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2105 * place. This should be TRUE except during bootstrap log creation. The
2106 * caller must *not* hold the lock at call.
2108 * Returns FD of opened file.
2110 * Note: errors here are ERROR not PANIC because we might or might not be
2111 * inside a critical section (eg, during checkpoint there is no reason to
2112 * take down the system on failure). They will promote to PANIC if we are
2113 * in a critical section.
2116 XLogFileInit(uint32 log, uint32 seg,
2117 bool *use_existent, bool use_lock)
2119 char path[MAXPGPATH];
2120 char tmppath[MAXPGPATH];
2122 uint32 installed_log;
2123 uint32 installed_seg;
2128 XLogFilePath(path, ThisTimeLineID, log, seg);
2131 * Try to use existent file (checkpoint maker may have created it already)
2135 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2139 if (errno != ENOENT)
2141 (errcode_for_file_access(),
2142 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2150 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
2151 * another process is doing the same thing. If so, we will end up
2152 * pre-creating an extra log segment. That seems OK, and better than
2153 * holding the lock throughout this lengthy process.
2155 elog(DEBUG2, "creating and filling new WAL file");
2157 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2161 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
2162 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2166 (errcode_for_file_access(),
2167 errmsg("could not create file \"%s\": %m", tmppath)));
2170 * Zero-fill the file. We have to do this the hard way to ensure that all
2171 * the file space has really been allocated --- on platforms that allow
2172 * "holes" in files, just seeking to the end doesn't allocate intermediate
2173 * space. This way, we know that we have all the space and (after the
2174 * fsync below) that all the indirect blocks are down on disk. Therefore,
2175 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
2178 * Note: palloc zbuffer, instead of just using a local char array, to
2179 * ensure it is reasonably well-aligned; this may save a few cycles
2180 * transferring data to the kernel.
2182 zbuffer = (char *) palloc0(XLOG_BLCKSZ);
2183 for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
2186 if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
2188 int save_errno = errno;
2191 * If we fail to make the file, delete it to release disk space
2194 /* if write didn't set errno, assume problem is no disk space */
2195 errno = save_errno ? save_errno : ENOSPC;
2198 (errcode_for_file_access(),
2199 errmsg("could not write to file \"%s\": %m", tmppath)));
2204 if (pg_fsync(fd) != 0)
2206 (errcode_for_file_access(),
2207 errmsg("could not fsync file \"%s\": %m", tmppath)));
2211 (errcode_for_file_access(),
2212 errmsg("could not close file \"%s\": %m", tmppath)));
2215 * Now move the segment into place with its final name.
2217 * If caller didn't want to use a pre-existing file, get rid of any
2218 * pre-existing file. Otherwise, cope with possibility that someone else
2219 * has created the file while we were filling ours: if so, use ours to
2220 * pre-create a future log segment.
2222 installed_log = log;
2223 installed_seg = seg;
2224 max_advance = XLOGfileslop;
2225 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
2226 *use_existent, &max_advance,
2229 /* No need for any more future segments... */
2233 elog(DEBUG2, "done creating and filling new WAL file");
2235 /* Set flag to tell caller there was no existent file */
2236 *use_existent = false;
2238 /* Now open original target segment (might not be file I just made) */
2239 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2243 (errcode_for_file_access(),
2244 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2251 * Create a new XLOG file segment by copying a pre-existing one.
2253 * log, seg: identify segment to be created.
2255 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
2256 * a different timeline)
2258 * Currently this is only used during recovery, and so there are no locking
2259 * considerations. But we should be just as tense as XLogFileInit to avoid
2260 * emplacing a bogus file.
2263 XLogFileCopy(uint32 log, uint32 seg,
2264 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
2266 char path[MAXPGPATH];
2267 char tmppath[MAXPGPATH];
2268 char buffer[XLOG_BLCKSZ];
2274 * Open the source file
2276 XLogFilePath(path, srcTLI, srclog, srcseg);
2277 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2280 (errcode_for_file_access(),
2281 errmsg("could not open file \"%s\": %m", path)));
2284 * Copy into a temp file name.
2286 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2290 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
2291 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2295 (errcode_for_file_access(),
2296 errmsg("could not create file \"%s\": %m", tmppath)));
2299 * Do the data copying.
2301 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2304 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2308 (errcode_for_file_access(),
2309 errmsg("could not read file \"%s\": %m", path)));
2312 (errmsg("not enough data in file \"%s\"", path)));
2315 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2317 int save_errno = errno;
2320 * If we fail to make the file, delete it to release disk space
2323 /* if write didn't set errno, assume problem is no disk space */
2324 errno = save_errno ? save_errno : ENOSPC;
2327 (errcode_for_file_access(),
2328 errmsg("could not write to file \"%s\": %m", tmppath)));
2332 if (pg_fsync(fd) != 0)
2334 (errcode_for_file_access(),
2335 errmsg("could not fsync file \"%s\": %m", tmppath)));
2339 (errcode_for_file_access(),
2340 errmsg("could not close file \"%s\": %m", tmppath)));
2345 * Now move the segment into place with its final name.
2347 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2348 elog(ERROR, "InstallXLogFileSegment should not have failed");
2352 * Install a new XLOG segment file as a current or future log segment.
2354 * This is used both to install a newly-created segment (which has a temp
2355 * filename while it's being created) and to recycle an old segment.
2357 * *log, *seg: identify segment to install as (or first possible target).
2358 * When find_free is TRUE, these are modified on return to indicate the
2359 * actual installation location or last segment searched.
2361 * tmppath: initial name of file to install. It will be renamed into place.
2363 * find_free: if TRUE, install the new segment at the first empty log/seg
2364 * number at or after the passed numbers. If FALSE, install the new segment
2365 * exactly where specified, deleting any existing segment file there.
2367 * *max_advance: maximum number of log/seg slots to advance past the starting
2368 * point. Fail if no free slot is found in this range. On return, reduced
2369 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2370 * when find_free is FALSE.)
2372 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2373 * place. This should be TRUE except during bootstrap log creation. The
2374 * caller must *not* hold the lock at call.
2376 * Returns TRUE if file installed, FALSE if not installed because of
2377 * exceeding max_advance limit. On Windows, we also return FALSE if we
2378 * can't rename the file into place because someone's got it open.
2379 * (Any other kind of failure causes ereport().)
2382 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2383 bool find_free, int *max_advance,
2386 char path[MAXPGPATH];
2387 struct stat stat_buf;
2389 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2392 * We want to be sure that only one process does this at a time.
2395 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2399 /* Force installation: get rid of any pre-existing segment file */
2404 /* Find a free slot to put it in */
2405 while (stat(path, &stat_buf) == 0)
2407 if (*max_advance <= 0)
2409 /* Failed to find a free slot within specified range */
2411 LWLockRelease(ControlFileLock);
2414 NextLogSeg(*log, *seg);
2416 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2421 * Prefer link() to rename() here just to be really sure that we don't
2422 * overwrite an existing logfile. However, there shouldn't be one, so
2423 * rename() is an acceptable substitute except for the truly paranoid.
2425 #if HAVE_WORKING_LINK
2426 if (link(tmppath, path) < 0)
2428 (errcode_for_file_access(),
2429 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2430 tmppath, path, *log, *seg)));
2433 if (rename(tmppath, path) < 0)
2436 #if !defined(__CYGWIN__)
2437 if (GetLastError() == ERROR_ACCESS_DENIED)
2439 if (errno == EACCES)
2443 LWLockRelease(ControlFileLock);
2449 (errcode_for_file_access(),
2450 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2451 tmppath, path, *log, *seg)));
2456 LWLockRelease(ControlFileLock);
2462 * Open a pre-existing logfile segment for writing.
2465 XLogFileOpen(uint32 log, uint32 seg)
2467 char path[MAXPGPATH];
2470 XLogFilePath(path, ThisTimeLineID, log, seg);
2472 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2476 (errcode_for_file_access(),
2477 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2484 * Open a logfile segment for reading (during recovery).
2487 XLogFileRead(uint32 log, uint32 seg, int emode)
2489 char path[MAXPGPATH];
2490 char xlogfname[MAXFNAMELEN];
2491 char activitymsg[MAXFNAMELEN + 16];
2496 * Loop looking for a suitable timeline ID: we might need to read any of
2497 * the timelines listed in expectedTLIs.
2499 * We expect curFileTLI on entry to be the TLI of the preceding file in
2500 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2501 * to go backwards; this prevents us from picking up the wrong file when a
2502 * parent timeline extends to higher segment numbers than the child we
2505 foreach(cell, expectedTLIs)
2507 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2509 if (tli < curFileTLI)
2510 break; /* don't bother looking at too-old TLIs */
2512 XLogFileName(xlogfname, tli, log, seg);
2514 if (InArchiveRecovery)
2516 /* Report recovery progress in PS display */
2517 snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
2519 set_ps_display(activitymsg, false);
2521 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2526 XLogFilePath(path, tli, log, seg);
2528 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2534 /* Report recovery progress in PS display */
2535 snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
2537 set_ps_display(activitymsg, false);
2541 if (errno != ENOENT) /* unexpected failure? */
2543 (errcode_for_file_access(),
2544 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2548 /* Couldn't find it. For simplicity, complain about front timeline */
2549 XLogFilePath(path, recoveryTargetTLI, log, seg);
2552 (errcode_for_file_access(),
2553 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2559 * Close the current logfile segment for writing.
2564 Assert(openLogFile >= 0);
2567 * WAL segment files will not be re-read in normal operation, so we advise
2568 * the OS to release any cached pages. But do not do so if WAL archiving
2569 * is active, because archiver process could use the cache to read the WAL
2570 * segment. Also, don't bother with it if we are using O_DIRECT, since
2571 * the kernel is presumably not caching in that case.
2573 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2574 if (!XLogArchivingActive() &&
2575 (get_sync_bit(sync_method) & PG_O_DIRECT) == 0)
2576 (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2579 if (close(openLogFile))
2581 (errcode_for_file_access(),
2582 errmsg("could not close log file %u, segment %u: %m",
2583 openLogId, openLogSeg)));
2588 * Attempt to retrieve the specified file from off-line archival storage.
2589 * If successful, fill "path" with its complete path (note that this will be
2590 * a temp file name that doesn't follow the normal naming convention), and
2593 * If not successful, fill "path" with the name of the normal on-line file
2594 * (which may or may not actually exist, but we'll try to use it), and return
2597 * For fixed-size files, the caller may pass the expected size as an
2598 * additional crosscheck on successful recovery. If the file size is not
2599 * known, set expectedSize = 0.
2602 RestoreArchivedFile(char *path, const char *xlogfname,
2603 const char *recovername, off_t expectedSize)
2605 char xlogpath[MAXPGPATH];
2606 char xlogRestoreCmd[MAXPGPATH];
2607 char lastRestartPointFname[MAXPGPATH];
2613 struct stat stat_buf;
2618 * When doing archive recovery, we always prefer an archived log file even
2619 * if a file of the same name exists in XLOGDIR. The reason is that the
2620 * file in XLOGDIR could be an old, un-filled or partly-filled version
2621 * that was copied and restored as part of backing up $PGDATA.
2623 * We could try to optimize this slightly by checking the local copy
2624 * lastchange timestamp against the archived copy, but we have no API to
2625 * do this, nor can we guarantee that the lastchange timestamp was
2626 * preserved correctly when we copied to archive. Our aim is robustness,
2627 * so we elect not to do this.
2629 * If we cannot obtain the log file from the archive, however, we will try
2630 * to use the XLOGDIR file if it exists. This is so that we can make use
2631 * of log segments that weren't yet transferred to the archive.
2633 * Notice that we don't actually overwrite any files when we copy back
2634 * from archive because the recoveryRestoreCommand may inadvertently
2635 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2636 * fallback to the segments remaining in current XLOGDIR later. The
2637 * copy-from-archive filename is always the same, ensuring that we don't
2638 * run out of disk space on long recoveries.
2640 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2643 * Make sure there is no existing file named recovername.
2645 if (stat(xlogpath, &stat_buf) != 0)
2647 if (errno != ENOENT)
2649 (errcode_for_file_access(),
2650 errmsg("could not stat file \"%s\": %m",
2655 if (unlink(xlogpath) != 0)
2657 (errcode_for_file_access(),
2658 errmsg("could not remove file \"%s\": %m",
2663 * Calculate the archive file cutoff point for use during log shipping
2664 * replication. All files earlier than this point can be deleted
2665 * from the archive, though there is no requirement to do so.
2667 * We initialise this with the filename of an InvalidXLogRecPtr, which
2668 * will prevent the deletion of any WAL files from the archive
2669 * because of the alphabetic sorting property of WAL filenames.
2671 * Once we have successfully located the redo pointer of the checkpoint
2672 * from which we start recovery we never request a file prior to the redo
2673 * pointer of the last restartpoint. When redo begins we know that we
2674 * have successfully located it, so there is no need for additional
2675 * status flags to signify the point when we can begin deleting WAL files
2680 XLByteToSeg(ControlFile->checkPointCopy.redo,
2681 restartLog, restartSeg);
2682 XLogFileName(lastRestartPointFname,
2683 ControlFile->checkPointCopy.ThisTimeLineID,
2684 restartLog, restartSeg);
2685 /* we shouldn't need anything earlier than last restart point */
2686 Assert(strcmp(lastRestartPointFname, xlogfname) <= 0);
2689 XLogFileName(lastRestartPointFname, 0, 0, 0);
2692 * construct the command to be executed
2694 dp = xlogRestoreCmd;
2695 endp = xlogRestoreCmd + MAXPGPATH - 1;
2698 for (sp = recoveryRestoreCommand; *sp; sp++)
2705 /* %p: relative path of target file */
2707 StrNCpy(dp, xlogpath, endp - dp);
2708 make_native_path(dp);
2712 /* %f: filename of desired file */
2714 StrNCpy(dp, xlogfname, endp - dp);
2718 /* %r: filename of last restartpoint */
2720 StrNCpy(dp, lastRestartPointFname, endp - dp);
2724 /* convert %% to a single % */
2730 /* otherwise treat the % as not special */
2745 (errmsg_internal("executing restore command \"%s\"",
2749 * Set in_restore_command to tell the signal handler that we should exit
2750 * right away on SIGTERM. We know that we're in a safe point to do that.
2751 * Check if we had already received the signal, so that we don't miss a
2752 * shutdown request received just before this.
2754 in_restore_command = true;
2755 if (shutdown_requested)
2759 * Copy xlog from archival storage to XLOGDIR
2761 rc = system(xlogRestoreCmd);
2763 in_restore_command = false;
2768 * command apparently succeeded, but let's make sure the file is
2769 * really there now and has the correct size.
2771 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2772 * it, but is that too strong? We could try to plow ahead with a
2773 * local copy of the file ... but the problem is that there probably
2774 * isn't one, and we'd incorrectly conclude we've reached the end of
2775 * WAL and we're done recovering ...
2777 if (stat(xlogpath, &stat_buf) == 0)
2779 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2781 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2783 (unsigned long) stat_buf.st_size,
2784 (unsigned long) expectedSize)));
2788 (errmsg("restored log file \"%s\" from archive",
2790 strcpy(path, xlogpath);
2797 if (errno != ENOENT)
2799 (errcode_for_file_access(),
2800 errmsg("could not stat file \"%s\": %m",
2806 * Remember, we rollforward UNTIL the restore fails so failure here is
2807 * just part of the process... that makes it difficult to determine
2808 * whether the restore failed because there isn't an archive to restore,
2809 * or because the administrator has specified the restore program
2810 * incorrectly. We have to assume the former.
2812 * However, if the failure was due to any sort of signal, it's best to
2813 * punt and abort recovery. (If we "return false" here, upper levels will
2814 * assume that recovery is complete and start up the database!) It's
2815 * essential to abort on child SIGINT and SIGQUIT, because per spec
2816 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2817 * those it's a good bet we should have gotten it too.
2819 * On SIGTERM, assume we have received a fast shutdown request, and exit
2820 * cleanly. It's pure chance whether we receive the SIGTERM first, or the
2821 * child process. If we receive it first, the signal handler will call
2822 * proc_exit, otherwise we do it here. If we or the child process
2823 * received SIGTERM for any other reason than a fast shutdown request,
2824 * postmaster will perform an immediate shutdown when it sees us exiting
2827 * Per the Single Unix Spec, shells report exit status > 128 when a called
2828 * command died on a signal. Also, 126 and 127 are used to report
2829 * problems such as an unfindable command; treat those as fatal errors
2832 if (WTERMSIG(rc) == SIGTERM)
2835 signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;
2837 ereport(signaled ? FATAL : DEBUG2,
2838 (errmsg("could not restore file \"%s\" from archive: return code %d",
2842 * if an archived file is not available, there might still be a version of
2843 * this file in XLOGDIR, so return that as the filename to open.
2845 * In many recovery scenarios we expect this to fail also, but if so that
2846 * just means we've reached the end of WAL.
2848 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2853 * Preallocate log files beyond the specified log endpoint.
2855 * XXX this is currently extremely conservative, since it forces only one
2856 * future log segment to exist, and even that only if we are 75% done with
2857 * the current one. This is only appropriate for very low-WAL-volume systems.
2858 * High-volume systems will be OK once they've built up a sufficient set of
2859 * recycled log segments, but the startup transient is likely to include
2860 * a lot of segment creations by foreground processes, which is not so good.
2863 PreallocXlogFiles(XLogRecPtr endptr)
2870 XLByteToPrevSeg(endptr, _logId, _logSeg);
2871 if ((endptr.xrecoff - 1) % XLogSegSize >=
2872 (uint32) (0.75 * XLogSegSize))
2874 NextLogSeg(_logId, _logSeg);
2875 use_existent = true;
2876 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2879 CheckpointStats.ckpt_segs_added++;
2884 * Recycle or remove all log files older or equal to passed log/seg#
2886 * endptr is current (or recent) end of xlog; this is used to determine
2887 * whether we want to recycle rather than delete no-longer-wanted log files.
2890 RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
2896 struct dirent *xlde;
2897 char lastoff[MAXFNAMELEN];
2898 char path[MAXPGPATH];
2901 * Initialize info about where to try to recycle to. We allow recycling
2902 * segments up to XLOGfileslop segments beyond the current XLOG location.
2904 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2905 max_advance = XLOGfileslop;
2907 xldir = AllocateDir(XLOGDIR);
2910 (errcode_for_file_access(),
2911 errmsg("could not open transaction log directory \"%s\": %m",
2914 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2916 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2919 * We ignore the timeline part of the XLOG segment identifiers in
2920 * deciding whether a segment is still needed. This ensures that we
2921 * won't prematurely remove a segment from a parent timeline. We could
2922 * probably be a little more proactive about removing segments of
2923 * non-parent timelines, but that would be a whole lot more
2926 * We use the alphanumeric sorting property of the filenames to decide
2927 * which ones are earlier than the lastoff segment.
2929 if (strlen(xlde->d_name) == 24 &&
2930 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2931 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2933 if (XLogArchiveCheckDone(xlde->d_name))
2935 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2938 * Before deleting the file, see if it can be recycled as a
2939 * future log segment.
2941 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2946 (errmsg("recycled transaction log file \"%s\"",
2948 CheckpointStats.ckpt_segs_recycled++;
2949 /* Needn't recheck that slot on future iterations */
2950 if (max_advance > 0)
2952 NextLogSeg(endlogId, endlogSeg);
2958 /* No need for any more future segments... */
2960 (errmsg("removing transaction log file \"%s\"",
2963 CheckpointStats.ckpt_segs_removed++;
2966 XLogArchiveCleanup(xlde->d_name);
2975 * Verify whether pg_xlog and pg_xlog/archive_status exist.
2976 * If the latter does not exist, recreate it.
2978 * It is not the goal of this function to verify the contents of these
2979 * directories, but to help in cases where someone has performed a cluster
2980 * copy for PITR purposes but omitted pg_xlog from the copy.
2982 * We could also recreate pg_xlog if it doesn't exist, but a deliberate
2983 * policy decision was made not to. It is fairly common for pg_xlog to be
2984 * a symlink, and if that was the DBA's intent then automatically making a
2985 * plain directory would result in degraded performance with no notice.
2988 ValidateXLOGDirectoryStructure(void)
2990 char path[MAXPGPATH];
2991 struct stat stat_buf;
2993 /* Check for pg_xlog; if it doesn't exist, error out */
2994 if (stat(XLOGDIR, &stat_buf) != 0 ||
2995 !S_ISDIR(stat_buf.st_mode))
2997 (errmsg("required WAL directory \"%s\" does not exist",
3000 /* Check for archive_status */
3001 snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
3002 if (stat(path, &stat_buf) == 0)
3004 /* Check for weird cases where it exists but isn't a directory */
3005 if (!S_ISDIR(stat_buf.st_mode))
3007 (errmsg("required WAL directory \"%s\" does not exist",
3013 (errmsg("creating missing WAL directory \"%s\"", path)));
3014 if (mkdir(path, 0700) < 0)
3016 (errmsg("could not create missing directory \"%s\": %m",
3022 * Remove previous backup history files. This also retries creation of
3023 * .ready files for any backup history files for which XLogArchiveNotify
3027 CleanupBackupHistory(void)
3030 struct dirent *xlde;
3031 char path[MAXPGPATH];
3033 xldir = AllocateDir(XLOGDIR);
3036 (errcode_for_file_access(),
3037 errmsg("could not open transaction log directory \"%s\": %m",
3040 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3042 if (strlen(xlde->d_name) > 24 &&
3043 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
3044 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
3047 if (XLogArchiveCheckDone(xlde->d_name))
3050 (errmsg("removing transaction log backup history file \"%s\"",
3052 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3054 XLogArchiveCleanup(xlde->d_name);
3063 * Restore the backup blocks present in an XLOG record, if any.
3065 * We assume all of the record has been read into memory at *record.
3067 * Note: when a backup block is available in XLOG, we restore it
3068 * unconditionally, even if the page in the database appears newer.
3069 * This is to protect ourselves against database pages that were partially
3070 * or incorrectly written during a crash. We assume that the XLOG data
3071 * must be good because it has passed a CRC check, while the database
3072 * page might not be. This will force us to replay all subsequent
3073 * modifications of the page that appear in XLOG, rather than possibly
3074 * ignoring them as already applied, but that's not a huge drawback.
3076 * If 'cleanup' is true, a cleanup lock is used when restoring blocks.
3077 * Otherwise, a normal exclusive lock is used. At the moment, that's just
3078 * pro forma, because there can't be any regular backends in the system
3079 * during recovery. The 'cleanup' argument applies to all backup blocks
3080 * in the WAL record, that suffices for now.
3083 RestoreBkpBlocks(XLogRecPtr lsn, XLogRecord *record, bool cleanup)
3091 if (!(record->xl_info & XLR_BKP_BLOCK_MASK))
3094 blk = (char *) XLogRecGetData(record) + record->xl_len;
3095 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3097 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3100 memcpy(&bkpb, blk, sizeof(BkpBlock));
3101 blk += sizeof(BkpBlock);
3103 buffer = XLogReadBufferExtended(bkpb.node, bkpb.fork, bkpb.block,
3105 Assert(BufferIsValid(buffer));
3107 LockBufferForCleanup(buffer);
3109 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3111 page = (Page) BufferGetPage(buffer);
3113 if (bkpb.hole_length == 0)
3115 memcpy((char *) page, blk, BLCKSZ);
3119 /* must zero-fill the hole */
3120 MemSet((char *) page, 0, BLCKSZ);
3121 memcpy((char *) page, blk, bkpb.hole_offset);
3122 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
3123 blk + bkpb.hole_offset,
3124 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
3127 PageSetLSN(page, lsn);
3128 PageSetTLI(page, ThisTimeLineID);
3129 MarkBufferDirty(buffer);
3130 UnlockReleaseBuffer(buffer);
3132 blk += BLCKSZ - bkpb.hole_length;
3137 * CRC-check an XLOG record. We do not believe the contents of an XLOG
3138 * record (other than to the minimal extent of computing the amount of
3139 * data to read in) until we've checked the CRCs.
3141 * We assume all of the record has been read into memory at *record.
3144 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
3148 uint32 len = record->xl_len;
3152 /* First the rmgr data */
3154 COMP_CRC32(crc, XLogRecGetData(record), len);
3156 /* Add in the backup blocks, if any */
3157 blk = (char *) XLogRecGetData(record) + len;
3158 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3162 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3165 memcpy(&bkpb, blk, sizeof(BkpBlock));
3166 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
3169 (errmsg("incorrect hole size in record at %X/%X",
3170 recptr.xlogid, recptr.xrecoff)));
3173 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
3174 COMP_CRC32(crc, blk, blen);
3178 /* Check that xl_tot_len agrees with our calculation */
3179 if (blk != (char *) record + record->xl_tot_len)
3182 (errmsg("incorrect total length in record at %X/%X",
3183 recptr.xlogid, recptr.xrecoff)));
3187 /* Finally include the record header */
3188 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
3189 SizeOfXLogRecord - sizeof(pg_crc32));
3192 if (!EQ_CRC32(record->xl_crc, crc))
3195 (errmsg("incorrect resource manager data checksum in record at %X/%X",
3196 recptr.xlogid, recptr.xrecoff)));
3204 * Attempt to read an XLOG record.
3206 * If RecPtr is not NULL, try to read a record at that position. Otherwise
3207 * try to read a record just after the last one previously read.
3209 * If no valid record is available, returns NULL, or fails if emode is PANIC.
3210 * (emode must be either PANIC or LOG.)
3212 * The record is copied into readRecordBuf, so that on successful return,
3213 * the returned record pointer always points there.
3216 ReadRecord(XLogRecPtr *RecPtr, int emode)
3220 XLogRecPtr tmpRecPtr = EndRecPtr;
3221 bool randAccess = false;
3224 uint32 targetPageOff;
3225 uint32 targetRecOff;
3226 uint32 pageHeaderSize;
3228 if (readBuf == NULL)
3231 * First time through, permanently allocate readBuf. We do it this
3232 * way, rather than just making a static array, for two reasons: (1)
3233 * no need to waste the storage in most instantiations of the backend;
3234 * (2) a static char array isn't guaranteed to have any particular
3235 * alignment, whereas malloc() will provide MAXALIGN'd storage.
3237 readBuf = (char *) malloc(XLOG_BLCKSZ);
3238 Assert(readBuf != NULL);
3243 RecPtr = &tmpRecPtr;
3244 /* fast case if next record is on same page */
3245 if (nextRecord != NULL)
3247 record = nextRecord;
3250 /* align old recptr to next page */
3251 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
3252 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
3253 if (tmpRecPtr.xrecoff >= XLogFileSize)
3255 (tmpRecPtr.xlogid)++;
3256 tmpRecPtr.xrecoff = 0;
3258 /* We will account for page header size below */
3262 if (!XRecOffIsValid(RecPtr->xrecoff))
3264 (errmsg("invalid record offset at %X/%X",
3265 RecPtr->xlogid, RecPtr->xrecoff)));
3268 * Since we are going to a random position in WAL, forget any prior
3269 * state about what timeline we were in, and allow it to be any
3270 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
3271 * to go backwards (but we can't reset that variable right here, since
3272 * we might not change files at all).
3274 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
3275 randAccess = true; /* allow curFileTLI to go backwards too */
3278 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
3283 XLByteToSeg(*RecPtr, readId, readSeg);
3286 /* Now it's okay to reset curFileTLI if random fetch */
3290 readFile = XLogFileRead(readId, readSeg, emode);
3292 goto next_record_is_invalid;
3295 * Whenever switching to a new WAL segment, we read the first page of
3296 * the file and validate its header, even if that's not where the
3297 * target record is. This is so that we can check the additional
3298 * identification info that is present in the first page's "long"
3302 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3305 (errcode_for_file_access(),
3306 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3307 readId, readSeg, readOff)));
3308 goto next_record_is_invalid;
3310 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3311 goto next_record_is_invalid;
3314 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
3315 if (readOff != targetPageOff)
3317 readOff = targetPageOff;
3318 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
3321 (errcode_for_file_access(),
3322 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
3323 readId, readSeg, readOff)));
3324 goto next_record_is_invalid;
3326 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3329 (errcode_for_file_access(),
3330 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3331 readId, readSeg, readOff)));
3332 goto next_record_is_invalid;
3334 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3335 goto next_record_is_invalid;
3337 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3338 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
3339 if (targetRecOff == 0)
3342 * Can only get here in the continuing-from-prev-page case, because
3343 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
3344 * to skip over the new page's header.
3346 tmpRecPtr.xrecoff += pageHeaderSize;
3347 targetRecOff = pageHeaderSize;
3349 else if (targetRecOff < pageHeaderSize)
3352 (errmsg("invalid record offset at %X/%X",
3353 RecPtr->xlogid, RecPtr->xrecoff)));
3354 goto next_record_is_invalid;
3356 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3357 targetRecOff == pageHeaderSize)
3360 (errmsg("contrecord is requested by %X/%X",
3361 RecPtr->xlogid, RecPtr->xrecoff)));
3362 goto next_record_is_invalid;
3364 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3369 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
3372 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3374 if (record->xl_len != 0)
3377 (errmsg("invalid xlog switch record at %X/%X",
3378 RecPtr->xlogid, RecPtr->xrecoff)));
3379 goto next_record_is_invalid;
3382 else if (record->xl_len == 0)
3385 (errmsg("record with zero length at %X/%X",
3386 RecPtr->xlogid, RecPtr->xrecoff)));
3387 goto next_record_is_invalid;
3389 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3390 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3391 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3394 (errmsg("invalid record length at %X/%X",
3395 RecPtr->xlogid, RecPtr->xrecoff)));
3396 goto next_record_is_invalid;
3398 if (record->xl_rmid > RM_MAX_ID)
3401 (errmsg("invalid resource manager ID %u at %X/%X",
3402 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3403 goto next_record_is_invalid;
3408 * We can't exactly verify the prev-link, but surely it should be less
3409 * than the record's own address.
3411 if (!XLByteLT(record->xl_prev, *RecPtr))
3414 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3415 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3416 RecPtr->xlogid, RecPtr->xrecoff)));
3417 goto next_record_is_invalid;
3423 * Record's prev-link should exactly match our previous location. This
3424 * check guards against torn WAL pages where a stale but valid-looking
3425 * WAL record starts on a sector boundary.
3427 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3430 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3431 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3432 RecPtr->xlogid, RecPtr->xrecoff)));
3433 goto next_record_is_invalid;
3438 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3439 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3440 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3441 * enough for all "normal" records, but very large commit or abort records
3442 * might need more space.)
3444 total_len = record->xl_tot_len;
3445 if (total_len > readRecordBufSize)
3447 uint32 newSize = total_len;
3449 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3450 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3452 free(readRecordBuf);
3453 readRecordBuf = (char *) malloc(newSize);
3456 readRecordBufSize = 0;
3457 /* We treat this as a "bogus data" condition */
3459 (errmsg("record length %u at %X/%X too long",
3460 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3461 goto next_record_is_invalid;
3463 readRecordBufSize = newSize;
3466 buffer = readRecordBuf;
3468 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3469 if (total_len > len)
3471 /* Need to reassemble record */
3472 XLogContRecord *contrecord;
3473 uint32 gotlen = len;
3475 memcpy(buffer, record, len);
3476 record = (XLogRecord *) buffer;
3480 readOff += XLOG_BLCKSZ;
3481 if (readOff >= XLogSegSize)
3485 NextLogSeg(readId, readSeg);
3486 readFile = XLogFileRead(readId, readSeg, emode);
3488 goto next_record_is_invalid;
3491 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3494 (errcode_for_file_access(),
3495 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3496 readId, readSeg, readOff)));
3497 goto next_record_is_invalid;
3499 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3500 goto next_record_is_invalid;
3501 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3504 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3505 readId, readSeg, readOff)));
3506 goto next_record_is_invalid;
3508 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3509 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3510 if (contrecord->xl_rem_len == 0 ||
3511 total_len != (contrecord->xl_rem_len + gotlen))
3514 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3515 contrecord->xl_rem_len,
3516 readId, readSeg, readOff)));
3517 goto next_record_is_invalid;
3519 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3520 if (contrecord->xl_rem_len > len)
3522 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3527 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3528 contrecord->xl_rem_len);
3531 if (!RecordIsValid(record, *RecPtr, emode))
3532 goto next_record_is_invalid;
3533 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3534 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3535 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3537 nextRecord = (XLogRecord *) ((char *) contrecord +
3538 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3540 EndRecPtr.xlogid = readId;
3541 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3543 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3544 ReadRecPtr = *RecPtr;
3545 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3549 /* Record does not cross a page boundary */
3550 if (!RecordIsValid(record, *RecPtr, emode))
3551 goto next_record_is_invalid;
3552 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3553 MAXALIGN(total_len))
3554 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3555 EndRecPtr.xlogid = RecPtr->xlogid;
3556 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3557 ReadRecPtr = *RecPtr;
3558 memcpy(buffer, record, total_len);
3561 * Special processing if it's an XLOG SWITCH record
3563 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3565 /* Pretend it extends to end of segment */
3566 EndRecPtr.xrecoff += XLogSegSize - 1;
3567 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3568 nextRecord = NULL; /* definitely not on same page */
3571 * Pretend that readBuf contains the last page of the segment. This is
3572 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3575 readOff = XLogSegSize - XLOG_BLCKSZ;
3577 return (XLogRecord *) buffer;
3579 next_record_is_invalid:;
3590 * Check whether the xlog header of a page just read in looks valid.
3592 * This is just a convenience subroutine to avoid duplicated code in
3593 * ReadRecord. It's not intended for use from anywhere else.
3596 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3600 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3603 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3604 hdr->xlp_magic, readId, readSeg, readOff)));
3607 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3610 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3611 hdr->xlp_info, readId, readSeg, readOff)));
3614 if (hdr->xlp_info & XLP_LONG_HEADER)
3616 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3618 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3620 char fhdrident_str[32];
3621 char sysident_str[32];
3624 * Format sysids separately to keep platform-dependent format code
3625 * out of the translatable message string.
3627 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3628 longhdr->xlp_sysid);
3629 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3630 ControlFile->system_identifier);
3632 (errmsg("WAL file is from different system"),
3633 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3634 fhdrident_str, sysident_str)));
3637 if (longhdr->xlp_seg_size != XLogSegSize)
3640 (errmsg("WAL file is from different system"),
3641 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3644 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3647 (errmsg("WAL file is from different system"),
3648 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3652 else if (readOff == 0)
3654 /* hmm, first page of file doesn't have a long header? */
3656 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3657 hdr->xlp_info, readId, readSeg, readOff)));
3661 recaddr.xlogid = readId;
3662 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3663 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3666 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3667 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3668 readId, readSeg, readOff)));
3673 * Check page TLI is one of the expected values.
3675 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3678 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3680 readId, readSeg, readOff)));
3685 * Since child timelines are always assigned a TLI greater than their
3686 * immediate parent's TLI, we should never see TLI go backwards across
3687 * successive pages of a consistent WAL sequence.
3689 * Of course this check should only be applied when advancing sequentially
3690 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3691 * going to a random page.
3693 if (hdr->xlp_tli < lastPageTLI)
3696 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3697 hdr->xlp_tli, lastPageTLI,
3698 readId, readSeg, readOff)));
3701 lastPageTLI = hdr->xlp_tli;
3706 * Try to read a timeline's history file.
3708 * If successful, return the list of component TLIs (the given TLI followed by
3709 * its ancestor TLIs). If we can't find the history file, assume that the
3710 * timeline has no parents, and return a list of just the specified timeline
3714 readTimeLineHistory(TimeLineID targetTLI)
3717 char path[MAXPGPATH];
3718 char histfname[MAXFNAMELEN];
3719 char fline[MAXPGPATH];
3722 if (InArchiveRecovery)
3724 TLHistoryFileName(histfname, targetTLI);
3725 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3728 TLHistoryFilePath(path, targetTLI);
3730 fd = AllocateFile(path, "r");
3733 if (errno != ENOENT)
3735 (errcode_for_file_access(),
3736 errmsg("could not open file \"%s\": %m", path)));
3737 /* Not there, so assume no parents */
3738 return list_make1_int((int) targetTLI);
3746 while (fgets(fline, sizeof(fline), fd) != NULL)
3748 /* skip leading whitespace and check for # comment */
3753 for (ptr = fline; *ptr; ptr++)
3755 if (!isspace((unsigned char) *ptr))
3758 if (*ptr == '\0' || *ptr == '#')
3761 /* expect a numeric timeline ID as first field of line */
3762 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3765 (errmsg("syntax error in history file: %s", fline),
3766 errhint("Expected a numeric timeline ID.")));
3769 tli <= (TimeLineID) linitial_int(result))
3771 (errmsg("invalid data in history file: %s", fline),
3772 errhint("Timeline IDs must be in increasing sequence.")));
3774 /* Build list with newest item first */
3775 result = lcons_int((int) tli, result);
3777 /* we ignore the remainder of each line */
3783 targetTLI <= (TimeLineID) linitial_int(result))
3785 (errmsg("invalid data in history file \"%s\"", path),
3786 errhint("Timeline IDs must be less than child timeline's ID.")));
3788 result = lcons_int((int) targetTLI, result);
3791 (errmsg_internal("history of timeline %u is %s",
3792 targetTLI, nodeToString(result))));
3798 * Probe whether a timeline history file exists for the given timeline ID
3801 existsTimeLineHistory(TimeLineID probeTLI)
3803 char path[MAXPGPATH];
3804 char histfname[MAXFNAMELEN];
3807 if (InArchiveRecovery)
3809 TLHistoryFileName(histfname, probeTLI);
3810 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3813 TLHistoryFilePath(path, probeTLI);
3815 fd = AllocateFile(path, "r");
3823 if (errno != ENOENT)
3825 (errcode_for_file_access(),
3826 errmsg("could not open file \"%s\": %m", path)));
3832 * Find the newest existing timeline, assuming that startTLI exists.
3834 * Note: while this is somewhat heuristic, it does positively guarantee
3835 * that (result + 1) is not a known timeline, and therefore it should
3836 * be safe to assign that ID to a new timeline.
3839 findNewestTimeLine(TimeLineID startTLI)
3841 TimeLineID newestTLI;
3842 TimeLineID probeTLI;
3845 * The algorithm is just to probe for the existence of timeline history
3846 * files. XXX is it useful to allow gaps in the sequence?
3848 newestTLI = startTLI;
3850 for (probeTLI = startTLI + 1;; probeTLI++)
3852 if (existsTimeLineHistory(probeTLI))
3854 newestTLI = probeTLI; /* probeTLI exists */
3858 /* doesn't exist, assume we're done */
3867 * Create a new timeline history file.
3869 * newTLI: ID of the new timeline
3870 * parentTLI: ID of its immediate parent
3871 * endTLI et al: ID of the last used WAL file, for annotation purposes
3873 * Currently this is only used during recovery, and so there are no locking
3874 * considerations. But we should be just as tense as XLogFileInit to avoid
3875 * emplacing a bogus file.
3878 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3879 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3881 char path[MAXPGPATH];
3882 char tmppath[MAXPGPATH];
3883 char histfname[MAXFNAMELEN];
3884 char xlogfname[MAXFNAMELEN];
3885 char buffer[BLCKSZ];
3890 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3893 * Write into a temp file name.
3895 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3899 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3900 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3904 (errcode_for_file_access(),
3905 errmsg("could not create file \"%s\": %m", tmppath)));
3908 * If a history file exists for the parent, copy it verbatim
3910 if (InArchiveRecovery)
3912 TLHistoryFileName(histfname, parentTLI);
3913 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3916 TLHistoryFilePath(path, parentTLI);
3918 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3921 if (errno != ENOENT)
3923 (errcode_for_file_access(),
3924 errmsg("could not open file \"%s\": %m", path)));
3925 /* Not there, so assume parent has no parents */
3932 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3933 if (nbytes < 0 || errno != 0)
3935 (errcode_for_file_access(),
3936 errmsg("could not read file \"%s\": %m", path)));
3940 if ((int) write(fd, buffer, nbytes) != nbytes)
3942 int save_errno = errno;
3945 * If we fail to make the file, delete it to release disk
3951 * if write didn't set errno, assume problem is no disk space
3953 errno = save_errno ? save_errno : ENOSPC;
3956 (errcode_for_file_access(),
3957 errmsg("could not write to file \"%s\": %m", tmppath)));
3964 * Append one line with the details of this timeline split.
3966 * If we did have a parent file, insert an extra newline just in case the
3967 * parent file failed to end with one.
3969 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3971 snprintf(buffer, sizeof(buffer),
3972 "%s%u\t%s\t%s transaction %u at %s\n",
3973 (srcfd < 0) ? "" : "\n",
3976 recoveryStopAfter ? "after" : "before",
3978 timestamptz_to_str(recoveryStopTime));
3980 nbytes = strlen(buffer);
3982 if ((int) write(fd, buffer, nbytes) != nbytes)
3984 int save_errno = errno;
3987 * If we fail to make the file, delete it to release disk space
3990 /* if write didn't set errno, assume problem is no disk space */
3991 errno = save_errno ? save_errno : ENOSPC;
3994 (errcode_for_file_access(),
3995 errmsg("could not write to file \"%s\": %m", tmppath)));
3998 if (pg_fsync(fd) != 0)
4000 (errcode_for_file_access(),
4001 errmsg("could not fsync file \"%s\": %m", tmppath)));
4005 (errcode_for_file_access(),
4006 errmsg("could not close file \"%s\": %m", tmppath)));
4010 * Now move the completed history file into place with its final name.
4012 TLHistoryFilePath(path, newTLI);
4015 * Prefer link() to rename() here just to be really sure that we don't
4016 * overwrite an existing logfile. However, there shouldn't be one, so
4017 * rename() is an acceptable substitute except for the truly paranoid.
4019 #if HAVE_WORKING_LINK
4020 if (link(tmppath, path) < 0)
4022 (errcode_for_file_access(),
4023 errmsg("could not link file \"%s\" to \"%s\": %m",
4027 if (rename(tmppath, path) < 0)
4029 (errcode_for_file_access(),
4030 errmsg("could not rename file \"%s\" to \"%s\": %m",
4034 /* The history file can be archived immediately. */
4035 TLHistoryFileName(histfname, newTLI);
4036 XLogArchiveNotify(histfname);
4040 * I/O routines for pg_control
4042 * *ControlFile is a buffer in shared memory that holds an image of the
4043 * contents of pg_control. WriteControlFile() initializes pg_control
4044 * given a preloaded buffer, ReadControlFile() loads the buffer from
4045 * the pg_control file (during postmaster or standalone-backend startup),
4046 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
4048 * For simplicity, WriteControlFile() initializes the fields of pg_control
4049 * that are related to checking backend/database compatibility, and
4050 * ReadControlFile() verifies they are correct. We could split out the
4051 * I/O and compatibility-check functions, but there seems no need currently.
4054 WriteControlFile(void)
4057 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
4060 * Initialize version and compatibility-check fields
4062 ControlFile->pg_control_version = PG_CONTROL_VERSION;
4063 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
4065 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
4066 ControlFile->floatFormat = FLOATFORMAT_VALUE;
4068 ControlFile->blcksz = BLCKSZ;
4069 ControlFile->relseg_size = RELSEG_SIZE;
4070 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4071 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
4073 ControlFile->nameDataLen = NAMEDATALEN;
4074 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
4076 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
4078 #ifdef HAVE_INT64_TIMESTAMP
4079 ControlFile->enableIntTimes = true;
4081 ControlFile->enableIntTimes = false;
4083 ControlFile->float4ByVal = FLOAT4PASSBYVAL;
4084 ControlFile->float8ByVal = FLOAT8PASSBYVAL;
4086 /* Contents are protected with a CRC */
4087 INIT_CRC32(ControlFile->crc);
4088 COMP_CRC32(ControlFile->crc,
4089 (char *) ControlFile,
4090 offsetof(ControlFileData, crc));
4091 FIN_CRC32(ControlFile->crc);
4094 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
4095 * excess over sizeof(ControlFileData). This reduces the odds of
4096 * premature-EOF errors when reading pg_control. We'll still fail when we
4097 * check the contents of the file, but hopefully with a more specific
4098 * error than "couldn't read pg_control".
4100 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
4101 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
4103 memset(buffer, 0, PG_CONTROL_SIZE);
4104 memcpy(buffer, ControlFile, sizeof(ControlFileData));
4106 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4107 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
4111 (errcode_for_file_access(),
4112 errmsg("could not create control file \"%s\": %m",
4113 XLOG_CONTROL_FILE)));
4116 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
4118 /* if write didn't set errno, assume problem is no disk space */
4122 (errcode_for_file_access(),
4123 errmsg("could not write to control file: %m")));
4126 if (pg_fsync(fd) != 0)
4128 (errcode_for_file_access(),
4129 errmsg("could not fsync control file: %m")));
4133 (errcode_for_file_access(),
4134 errmsg("could not close control file: %m")));
4138 ReadControlFile(void)
4146 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4151 (errcode_for_file_access(),
4152 errmsg("could not open control file \"%s\": %m",
4153 XLOG_CONTROL_FILE)));
4155 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4157 (errcode_for_file_access(),
4158 errmsg("could not read from control file: %m")));
4163 * Check for expected pg_control format version. If this is wrong, the
4164 * CRC check will likely fail because we'll be checking the wrong number
4165 * of bytes. Complaining about wrong version will probably be more
4166 * enlightening than complaining about wrong CRC.
4169 if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
4171 (errmsg("database files are incompatible with server"),
4172 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4173 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4174 ControlFile->pg_control_version, ControlFile->pg_control_version,
4175 PG_CONTROL_VERSION, PG_CONTROL_VERSION),
4176 errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4178 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
4180 (errmsg("database files are incompatible with server"),
4181 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4182 " but the server was compiled with PG_CONTROL_VERSION %d.",
4183 ControlFile->pg_control_version, PG_CONTROL_VERSION),
4184 errhint("It looks like you need to initdb.")));
4186 /* Now check the CRC. */
4189 (char *) ControlFile,
4190 offsetof(ControlFileData, crc));
4193 if (!EQ_CRC32(crc, ControlFile->crc))
4195 (errmsg("incorrect checksum in control file")));
4198 * Do compatibility checking immediately. If the database isn't
4199 * compatible with the backend executable, we want to abort before we
4200 * can possibly do any damage.
4202 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
4204 (errmsg("database files are incompatible with server"),
4205 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
4206 " but the server was compiled with CATALOG_VERSION_NO %d.",
4207 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
4208 errhint("It looks like you need to initdb.")));
4209 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4211 (errmsg("database files are incompatible with server"),
4212 errdetail("The database cluster was initialized with MAXALIGN %d,"
4213 " but the server was compiled with MAXALIGN %d.",
4214 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
4215 errhint("It looks like you need to initdb.")));
4216 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
4218 (errmsg("database files are incompatible with server"),
4219 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4220 errhint("It looks like you need to initdb.")));
4221 if (ControlFile->blcksz != BLCKSZ)
4223 (errmsg("database files are incompatible with server"),
4224 errdetail("The database cluster was initialized with BLCKSZ %d,"
4225 " but the server was compiled with BLCKSZ %d.",
4226 ControlFile->blcksz, BLCKSZ),
4227 errhint("It looks like you need to recompile or initdb.")));
4228 if (ControlFile->relseg_size != RELSEG_SIZE)
4230 (errmsg("database files are incompatible with server"),
4231 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
4232 " but the server was compiled with RELSEG_SIZE %d.",
4233 ControlFile->relseg_size, RELSEG_SIZE),
4234 errhint("It looks like you need to recompile or initdb.")));
4235 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4237 (errmsg("database files are incompatible with server"),
4238 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
4239 " but the server was compiled with XLOG_BLCKSZ %d.",
4240 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4241 errhint("It looks like you need to recompile or initdb.")));
4242 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
4244 (errmsg("database files are incompatible with server"),
4245 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
4246 " but the server was compiled with XLOG_SEG_SIZE %d.",
4247 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
4248 errhint("It looks like you need to recompile or initdb.")));
4249 if (ControlFile->nameDataLen != NAMEDATALEN)
4251 (errmsg("database files are incompatible with server"),
4252 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
4253 " but the server was compiled with NAMEDATALEN %d.",
4254 ControlFile->nameDataLen, NAMEDATALEN),
4255 errhint("It looks like you need to recompile or initdb.")));
4256 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4258 (errmsg("database files are incompatible with server"),
4259 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
4260 " but the server was compiled with INDEX_MAX_KEYS %d.",
4261 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
4262 errhint("It looks like you need to recompile or initdb.")));
4263 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
4265 (errmsg("database files are incompatible with server"),
4266 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
4267 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
4268 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4269 errhint("It looks like you need to recompile or initdb.")));
4271 #ifdef HAVE_INT64_TIMESTAMP
4272 if (ControlFile->enableIntTimes != true)
4274 (errmsg("database files are incompatible with server"),
4275 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
4276 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
4277 errhint("It looks like you need to recompile or initdb.")));
4279 if (ControlFile->enableIntTimes != false)
4281 (errmsg("database files are incompatible with server"),
4282 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
4283 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
4284 errhint("It looks like you need to recompile or initdb.")));
4287 #ifdef USE_FLOAT4_BYVAL
4288 if (ControlFile->float4ByVal != true)
4290 (errmsg("database files are incompatible with server"),
4291 errdetail("The database cluster was initialized without USE_FLOAT4_BYVAL"
4292 " but the server was compiled with USE_FLOAT4_BYVAL."),
4293 errhint("It looks like you need to recompile or initdb.")));
4295 if (ControlFile->float4ByVal != false)
4297 (errmsg("database files are incompatible with server"),
4298 errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
4299 " but the server was compiled without USE_FLOAT4_BYVAL."),
4300 errhint("It looks like you need to recompile or initdb.")));
4303 #ifdef USE_FLOAT8_BYVAL
4304 if (ControlFile->float8ByVal != true)
4306 (errmsg("database files are incompatible with server"),
4307 errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4308 " but the server was compiled with USE_FLOAT8_BYVAL."),
4309 errhint("It looks like you need to recompile or initdb.")));
4311 if (ControlFile->float8ByVal != false)
4313 (errmsg("database files are incompatible with server"),
4314 errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4315 " but the server was compiled without USE_FLOAT8_BYVAL."),
4316 errhint("It looks like you need to recompile or initdb.")));
4321 UpdateControlFile(void)
4325 INIT_CRC32(ControlFile->crc);
4326 COMP_CRC32(ControlFile->crc,
4327 (char *) ControlFile,
4328 offsetof(ControlFileData, crc));
4329 FIN_CRC32(ControlFile->crc);
4331 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4336 (errcode_for_file_access(),
4337 errmsg("could not open control file \"%s\": %m",
4338 XLOG_CONTROL_FILE)));
4341 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4343 /* if write didn't set errno, assume problem is no disk space */
4347 (errcode_for_file_access(),
4348 errmsg("could not write to control file: %m")));
4351 if (pg_fsync(fd) != 0)
4353 (errcode_for_file_access(),
4354 errmsg("could not fsync control file: %m")));
4358 (errcode_for_file_access(),
4359 errmsg("could not close control file: %m")));
4363 * Initialization of shared memory for XLOG
4371 size = sizeof(XLogCtlData);
4372 /* xlblocks array */
4373 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
4374 /* extra alignment padding for XLOG I/O buffers */
4375 size = add_size(size, ALIGNOF_XLOG_BUFFER);
4376 /* and the buffers themselves */
4377 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4380 * Note: we don't count ControlFileData, it comes out of the "slop factor"
4381 * added by CreateSharedMemoryAndSemaphores. This lets us use this
4382 * routine again below to compute the actual allocation size.
4395 ControlFile = (ControlFileData *)
4396 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4397 XLogCtl = (XLogCtlData *)
4398 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4400 if (foundCFile || foundXLog)
4402 /* both should be present or neither */
4403 Assert(foundCFile && foundXLog);
4407 memset(XLogCtl, 0, sizeof(XLogCtlData));
4410 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4411 * multiple of the alignment for same, so no extra alignment padding is
4414 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4415 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4416 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4417 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4420 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4422 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4423 XLogCtl->pages = allocptr;
4424 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4427 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4428 * in additional info.)
4430 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4431 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4432 SpinLockInit(&XLogCtl->info_lck);
4435 * If we are not in bootstrap mode, pg_control should already exist. Read
4436 * and validate it immediately (see comments in ReadControlFile() for the
4439 if (!IsBootstrapProcessingMode())
4444 * This func must be called ONCE on system install. It creates pg_control
4445 * and the initial XLOG segment.
4450 CheckPoint checkPoint;
4452 XLogPageHeader page;
4453 XLogLongPageHeader longpage;
4456 uint64 sysidentifier;
4461 * Select a hopefully-unique system identifier code for this installation.
4462 * We use the result of gettimeofday(), including the fractional seconds
4463 * field, as being about as unique as we can easily get. (Think not to
4464 * use random(), since it hasn't been seeded and there's no portable way
4465 * to seed it other than the system clock value...) The upper half of the
4466 * uint64 value is just the tv_sec part, while the lower half is the XOR
4467 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4468 * unnecessarily if "uint64" is really only 32 bits wide. A person
4469 * knowing this encoding can determine the initialization time of the
4470 * installation, which could perhaps be useful sometimes.
4472 gettimeofday(&tv, NULL);
4473 sysidentifier = ((uint64) tv.tv_sec) << 32;
4474 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4476 /* First timeline ID is always 1 */
4479 /* page buffer must be aligned suitably for O_DIRECT */
4480 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4481 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4482 memset(page, 0, XLOG_BLCKSZ);
4484 /* Set up information for the initial checkpoint record */
4485 checkPoint.redo.xlogid = 0;
4486 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4487 checkPoint.ThisTimeLineID = ThisTimeLineID;
4488 checkPoint.nextXidEpoch = 0;
4489 checkPoint.nextXid = FirstNormalTransactionId;
4490 checkPoint.nextOid = FirstBootstrapObjectId;
4491 checkPoint.nextMulti = FirstMultiXactId;
4492 checkPoint.nextMultiOffset = 0;
4493 checkPoint.time = (pg_time_t) time(NULL);
4495 ShmemVariableCache->nextXid = checkPoint.nextXid;
4496 ShmemVariableCache->nextOid = checkPoint.nextOid;
4497 ShmemVariableCache->oidCount = 0;
4498 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4500 /* Set up the XLOG page header */
4501 page->xlp_magic = XLOG_PAGE_MAGIC;
4502 page->xlp_info = XLP_LONG_HEADER;
4503 page->xlp_tli = ThisTimeLineID;
4504 page->xlp_pageaddr.xlogid = 0;
4505 page->xlp_pageaddr.xrecoff = 0;
4506 longpage = (XLogLongPageHeader) page;
4507 longpage->xlp_sysid = sysidentifier;
4508 longpage->xlp_seg_size = XLogSegSize;
4509 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4511 /* Insert the initial checkpoint record */
4512 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4513 record->xl_prev.xlogid = 0;
4514 record->xl_prev.xrecoff = 0;
4515 record->xl_xid = InvalidTransactionId;
4516 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4517 record->xl_len = sizeof(checkPoint);
4518 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4519 record->xl_rmid = RM_XLOG_ID;
4520 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4523 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4524 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4525 SizeOfXLogRecord - sizeof(pg_crc32));
4527 record->xl_crc = crc;
4529 /* Create first XLOG segment file */
4530 use_existent = false;
4531 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4533 /* Write the first page with the initial record */
4535 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4537 /* if write didn't set errno, assume problem is no disk space */
4541 (errcode_for_file_access(),
4542 errmsg("could not write bootstrap transaction log file: %m")));
4545 if (pg_fsync(openLogFile) != 0)
4547 (errcode_for_file_access(),
4548 errmsg("could not fsync bootstrap transaction log file: %m")));
4550 if (close(openLogFile))
4552 (errcode_for_file_access(),
4553 errmsg("could not close bootstrap transaction log file: %m")));
4557 /* Now create pg_control */
4559 memset(ControlFile, 0, sizeof(ControlFileData));
4560 /* Initialize pg_control status fields */
4561 ControlFile->system_identifier = sysidentifier;
4562 ControlFile->state = DB_SHUTDOWNED;
4563 ControlFile->time = checkPoint.time;
4564 ControlFile->checkPoint = checkPoint.redo;
4565 ControlFile->checkPointCopy = checkPoint;
4566 /* some additional ControlFile fields are set in WriteControlFile() */
4570 /* Bootstrap the commit log, too */
4572 BootStrapSUBTRANS();
4573 BootStrapMultiXact();
4579 str_time(pg_time_t tnow)
4581 static char buf[128];
4583 pg_strftime(buf, sizeof(buf),
4584 "%Y-%m-%d %H:%M:%S %Z",
4585 pg_localtime(&tnow, log_timezone));
4591 * See if there is a recovery command file (recovery.conf), and if so
4592 * read in parameters for archive recovery.
4594 * XXX longer term intention is to expand this to
4595 * cater for additional parameters and controls
4596 * possibly use a flex lexer similar to the GUC one
4599 readRecoveryCommandFile(void)
4602 char cmdline[MAXPGPATH];
4603 TimeLineID rtli = 0;
4604 bool rtliGiven = false;
4605 bool syntaxError = false;
4607 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4610 if (errno == ENOENT)
4611 return; /* not there, so no archive recovery */
4613 (errcode_for_file_access(),
4614 errmsg("could not open recovery command file \"%s\": %m",
4615 RECOVERY_COMMAND_FILE)));
4619 (errmsg("starting archive recovery")));
4624 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4626 /* skip leading whitespace and check for # comment */
4631 for (ptr = cmdline; *ptr; ptr++)
4633 if (!isspace((unsigned char) *ptr))
4636 if (*ptr == '\0' || *ptr == '#')
4639 /* identify the quoted parameter value */
4640 tok1 = strtok(ptr, "'");
4646 tok2 = strtok(NULL, "'");
4652 /* reparse to get just the parameter name */
4653 tok1 = strtok(ptr, " \t=");
4660 if (strcmp(tok1, "restore_command") == 0)
4662 recoveryRestoreCommand = pstrdup(tok2);
4664 (errmsg("restore_command = '%s'",
4665 recoveryRestoreCommand)));
4667 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4670 if (strcmp(tok2, "latest") == 0)
4675 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4676 if (errno == EINVAL || errno == ERANGE)
4678 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4683 (errmsg("recovery_target_timeline = %u", rtli)));
4686 (errmsg("recovery_target_timeline = latest")));
4688 else if (strcmp(tok1, "recovery_target_xid") == 0)
4691 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4692 if (errno == EINVAL || errno == ERANGE)
4694 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4697 (errmsg("recovery_target_xid = %u",
4698 recoveryTargetXid)));
4699 recoveryTarget = true;
4700 recoveryTargetExact = true;
4702 else if (strcmp(tok1, "recovery_target_time") == 0)
4705 * if recovery_target_xid specified, then this overrides
4706 * recovery_target_time
4708 if (recoveryTargetExact)
4710 recoveryTarget = true;
4711 recoveryTargetExact = false;
4714 * Convert the time string given by the user to TimestampTz form.
4716 recoveryTargetTime =
4717 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
4718 CStringGetDatum(tok2),
4719 ObjectIdGetDatum(InvalidOid),
4720 Int32GetDatum(-1)));
4722 (errmsg("recovery_target_time = '%s'",
4723 timestamptz_to_str(recoveryTargetTime))));
4725 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4728 * does nothing if a recovery_target is not also set
4730 if (!parse_bool(tok2, &recoveryTargetInclusive))
4732 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4733 errmsg("parameter \"recovery_target_inclusive\" requires a Boolean value")));
4735 (errmsg("recovery_target_inclusive = %s", tok2)));
4739 (errmsg("unrecognized recovery parameter \"%s\"",
4747 (errmsg("syntax error in recovery command file: %s",
4749 errhint("Lines should have the format parameter = 'value'.")));
4751 /* Check that required parameters were supplied */
4752 if (recoveryRestoreCommand == NULL)
4754 (errmsg("recovery command file \"%s\" did not specify restore_command",
4755 RECOVERY_COMMAND_FILE)));
4757 /* Enable fetching from archive recovery area */
4758 InArchiveRecovery = true;
4761 * If user specified recovery_target_timeline, validate it or compute the
4762 * "latest" value. We can't do this until after we've gotten the restore
4763 * command and set InArchiveRecovery, because we need to fetch timeline
4764 * history files from the archive.
4770 /* Timeline 1 does not have a history file, all else should */
4771 if (rtli != 1 && !existsTimeLineHistory(rtli))
4773 (errmsg("recovery target timeline %u does not exist",
4775 recoveryTargetTLI = rtli;
4779 /* We start the "latest" search from pg_control's timeline */
4780 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4786 * Exit archive-recovery state
4789 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4791 char recoveryPath[MAXPGPATH];
4792 char xlogpath[MAXPGPATH];
4795 * We are no longer in archive recovery state.
4797 InArchiveRecovery = false;
4800 * We should have the ending log segment currently open. Verify, and then
4801 * close it (to avoid problems on Windows with trying to rename or delete
4804 Assert(readFile >= 0);
4805 Assert(readId == endLogId);
4806 Assert(readSeg == endLogSeg);
4812 * If the segment was fetched from archival storage, we want to replace
4813 * the existing xlog segment (if any) with the archival version. This is
4814 * because whatever is in XLOGDIR is very possibly older than what we have
4815 * from the archives, since it could have come from restoring a PGDATA
4816 * backup. In any case, the archival version certainly is more
4817 * descriptive of what our current database state is, because that is what
4820 * Note that if we are establishing a new timeline, ThisTimeLineID is
4821 * already set to the new value, and so we will create a new file instead
4822 * of overwriting any existing file. (This is, in fact, always the case
4825 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4826 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4828 if (restoredFromArchive)
4831 (errmsg_internal("moving last restored xlog to \"%s\"",
4833 unlink(xlogpath); /* might or might not exist */
4834 if (rename(recoveryPath, xlogpath) != 0)
4836 (errcode_for_file_access(),
4837 errmsg("could not rename file \"%s\" to \"%s\": %m",
4838 recoveryPath, xlogpath)));
4839 /* XXX might we need to fix permissions on the file? */
4844 * If the latest segment is not archival, but there's still a
4845 * RECOVERYXLOG laying about, get rid of it.
4847 unlink(recoveryPath); /* ignore any error */
4850 * If we are establishing a new timeline, we have to copy data from
4851 * the last WAL segment of the old timeline to create a starting WAL
4852 * segment for the new timeline.
4854 if (endTLI != ThisTimeLineID)
4855 XLogFileCopy(endLogId, endLogSeg,
4856 endTLI, endLogId, endLogSeg);
4860 * Let's just make real sure there are not .ready or .done flags posted
4861 * for the new segment.
4863 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4864 XLogArchiveCleanup(xlogpath);
4866 /* Get rid of any remaining recovered timeline-history file, too */
4867 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4868 unlink(recoveryPath); /* ignore any error */
4871 * Rename the config file out of the way, so that we don't accidentally
4872 * re-enter archive recovery mode in a subsequent crash.
4874 unlink(RECOVERY_COMMAND_DONE);
4875 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4877 (errcode_for_file_access(),
4878 errmsg("could not rename file \"%s\" to \"%s\": %m",
4879 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4882 (errmsg("archive recovery complete")));
4886 * For point-in-time recovery, this function decides whether we want to
4887 * stop applying the XLOG at or after the current record.
4889 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4890 * *includeThis is set TRUE if we should apply this record before stopping.
4892 * We also track the timestamp of the latest applied COMMIT/ABORT record
4893 * in recoveryLastXTime, for logging purposes.
4894 * Also, some information is saved in recoveryStopXid et al for use in
4895 * annotating the new timeline's history file.
4898 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4902 TimestampTz recordXtime;
4904 /* We only consider stopping at COMMIT or ABORT records */
4905 if (record->xl_rmid != RM_XACT_ID)
4907 record_info = record->xl_info & ~XLR_INFO_MASK;
4908 if (record_info == XLOG_XACT_COMMIT)
4910 xl_xact_commit *recordXactCommitData;
4912 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4913 recordXtime = recordXactCommitData->xact_time;
4915 else if (record_info == XLOG_XACT_ABORT)
4917 xl_xact_abort *recordXactAbortData;
4919 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4920 recordXtime = recordXactAbortData->xact_time;
4925 /* Do we have a PITR target at all? */
4926 if (!recoveryTarget)
4928 recoveryLastXTime = recordXtime;
4932 if (recoveryTargetExact)
4935 * there can be only one transaction end record with this exact
4938 * when testing for an xid, we MUST test for equality only, since
4939 * transactions are numbered in the order they start, not the order
4940 * they complete. A higher numbered xid will complete before you about
4941 * 50% of the time...
4943 stopsHere = (record->xl_xid == recoveryTargetXid);
4945 *includeThis = recoveryTargetInclusive;
4950 * there can be many transactions that share the same commit time, so
4951 * we stop after the last one, if we are inclusive, or stop at the
4952 * first one if we are exclusive
4954 if (recoveryTargetInclusive)
4955 stopsHere = (recordXtime > recoveryTargetTime);
4957 stopsHere = (recordXtime >= recoveryTargetTime);
4959 *includeThis = false;
4964 recoveryStopXid = record->xl_xid;
4965 recoveryStopTime = recordXtime;
4966 recoveryStopAfter = *includeThis;
4968 if (record_info == XLOG_XACT_COMMIT)
4970 if (recoveryStopAfter)
4972 (errmsg("recovery stopping after commit of transaction %u, time %s",
4974 timestamptz_to_str(recoveryStopTime))));
4977 (errmsg("recovery stopping before commit of transaction %u, time %s",
4979 timestamptz_to_str(recoveryStopTime))));
4983 if (recoveryStopAfter)
4985 (errmsg("recovery stopping after abort of transaction %u, time %s",
4987 timestamptz_to_str(recoveryStopTime))));
4990 (errmsg("recovery stopping before abort of transaction %u, time %s",
4992 timestamptz_to_str(recoveryStopTime))));
4995 if (recoveryStopAfter)
4996 recoveryLastXTime = recordXtime;
4999 recoveryLastXTime = recordXtime;
5005 * This must be called ONCE during postmaster or standalone-backend startup
5010 XLogCtlInsert *Insert;
5011 CheckPoint checkPoint;
5013 bool reachedStopPoint = false;
5014 bool haveBackupLabel = false;
5024 TransactionId oldestActiveXID;
5026 XLogCtl->SharedRecoveryInProgress = true;
5029 * Read control file and check XLOG status looks valid.
5031 * Note: in most control paths, *ControlFile is already valid and we need
5032 * not do ReadControlFile() here, but might as well do it to be sure.
5036 if (ControlFile->state < DB_SHUTDOWNED ||
5037 ControlFile->state > DB_IN_PRODUCTION ||
5038 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
5040 (errmsg("control file contains invalid data")));
5042 if (ControlFile->state == DB_SHUTDOWNED)
5044 (errmsg("database system was shut down at %s",
5045 str_time(ControlFile->time))));
5046 else if (ControlFile->state == DB_SHUTDOWNING)
5048 (errmsg("database system shutdown was interrupted; last known up at %s",
5049 str_time(ControlFile->time))));
5050 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
5052 (errmsg("database system was interrupted while in recovery at %s",
5053 str_time(ControlFile->time)),
5054 errhint("This probably means that some data is corrupted and"
5055 " you will have to use the last backup for recovery.")));
5056 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
5058 (errmsg("database system was interrupted while in recovery at log time %s",
5059 str_time(ControlFile->checkPointCopy.time)),
5060 errhint("If this has occurred more than once some data might be corrupted"
5061 " and you might need to choose an earlier recovery target.")));
5062 else if (ControlFile->state == DB_IN_PRODUCTION)
5064 (errmsg("database system was interrupted; last known up at %s",
5065 str_time(ControlFile->time))));
5067 /* This is just to allow attaching to startup process with a debugger */
5068 #ifdef XLOG_REPLAY_DELAY
5069 if (ControlFile->state != DB_SHUTDOWNED)
5070 pg_usleep(60000000L);
5074 * Verify that pg_xlog and pg_xlog/archive_status exist. In cases where
5075 * someone has performed a copy for PITR, these directories may have
5076 * been excluded and need to be re-created.
5078 ValidateXLOGDirectoryStructure();
5081 * Initialize on the assumption we want to recover to the same timeline
5082 * that's active according to pg_control.
5084 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
5087 * Check for recovery control file, and if so set up state for offline
5090 readRecoveryCommandFile();
5092 /* Now we can determine the list of expected TLIs */
5093 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
5096 * If pg_control's timeline is not in expectedTLIs, then we cannot
5097 * proceed: the backup is not part of the history of the requested
5100 if (!list_member_int(expectedTLIs,
5101 (int) ControlFile->checkPointCopy.ThisTimeLineID))
5103 (errmsg("requested timeline %u is not a child of database system timeline %u",
5105 ControlFile->checkPointCopy.ThisTimeLineID)));
5107 if (read_backup_label(&checkPointLoc, &backupStopLoc))
5110 * When a backup_label file is present, we want to roll forward from
5111 * the checkpoint it identifies, rather than using pg_control.
5113 record = ReadCheckpointRecord(checkPointLoc, 0);
5117 (errmsg("checkpoint record is at %X/%X",
5118 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
5119 InRecovery = true; /* force recovery even if SHUTDOWNED */
5124 (errmsg("could not locate required checkpoint record"),
5125 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
5127 /* set flag to delete it later */
5128 haveBackupLabel = true;
5133 * Get the last valid checkpoint record. If the latest one according
5134 * to pg_control is broken, try the next-to-last one.
5136 checkPointLoc = ControlFile->checkPoint;
5137 record = ReadCheckpointRecord(checkPointLoc, 1);
5141 (errmsg("checkpoint record is at %X/%X",
5142 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
5146 checkPointLoc = ControlFile->prevCheckPoint;
5147 record = ReadCheckpointRecord(checkPointLoc, 2);
5151 (errmsg("using previous checkpoint record at %X/%X",
5152 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
5153 InRecovery = true; /* force recovery even if SHUTDOWNED */
5157 (errmsg("could not locate a valid checkpoint record")));
5161 LastRec = RecPtr = checkPointLoc;
5162 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5163 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
5166 (errmsg("redo record is at %X/%X; shutdown %s",
5167 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
5168 wasShutdown ? "TRUE" : "FALSE")));
5170 (errmsg("next transaction ID: %u/%u; next OID: %u",
5171 checkPoint.nextXidEpoch, checkPoint.nextXid,
5172 checkPoint.nextOid)));
5174 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
5175 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
5176 if (!TransactionIdIsNormal(checkPoint.nextXid))
5178 (errmsg("invalid next transaction ID")));
5180 ShmemVariableCache->nextXid = checkPoint.nextXid;
5181 ShmemVariableCache->nextOid = checkPoint.nextOid;
5182 ShmemVariableCache->oidCount = 0;
5183 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5186 * We must replay WAL entries using the same TimeLineID they were created
5187 * under, so temporarily adopt the TLI indicated by the checkpoint (see
5188 * also xlog_redo()).
5190 ThisTimeLineID = checkPoint.ThisTimeLineID;
5192 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
5194 if (XLByteLT(RecPtr, checkPoint.redo))
5196 (errmsg("invalid redo in checkpoint record")));
5199 * Check whether we need to force recovery from WAL. If it appears to
5200 * have been a clean shutdown and we did not have a recovery.conf file,
5201 * then assume no recovery needed.
5203 if (XLByteLT(checkPoint.redo, RecPtr))
5207 (errmsg("invalid redo record in shutdown checkpoint")));
5210 else if (ControlFile->state != DB_SHUTDOWNED)
5212 else if (InArchiveRecovery)
5214 /* force recovery due to presence of recovery.conf */
5224 * Update pg_control to show that we are recovering and to show the
5225 * selected checkpoint as the place we are starting from. We also mark
5226 * pg_control with any minimum recovery stop point obtained from a
5227 * backup history file.
5229 if (InArchiveRecovery)
5232 (errmsg("automatic recovery in progress")));
5233 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
5238 (errmsg("database system was not properly shut down; "
5239 "automatic recovery in progress")));
5240 ControlFile->state = DB_IN_CRASH_RECOVERY;
5242 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5243 ControlFile->checkPoint = checkPointLoc;
5244 ControlFile->checkPointCopy = checkPoint;
5245 if (backupStopLoc.xlogid != 0 || backupStopLoc.xrecoff != 0)
5247 if (XLByteLT(ControlFile->minRecoveryPoint, backupStopLoc))
5248 ControlFile->minRecoveryPoint = backupStopLoc;
5250 ControlFile->time = (pg_time_t) time(NULL);
5251 /* No need to hold ControlFileLock yet, we aren't up far enough */
5252 UpdateControlFile();
5254 /* update our local copy of minRecoveryPoint */
5255 minRecoveryPoint = ControlFile->minRecoveryPoint;
5258 * Reset pgstat data, because it may be invalid after recovery.
5263 * If there was a backup label file, it's done its job and the info
5264 * has now been propagated into pg_control. We must get rid of the
5265 * label file so that if we crash during recovery, we'll pick up at
5266 * the latest recovery restartpoint instead of going all the way back
5267 * to the backup start point. It seems prudent though to just rename
5268 * the file out of the way rather than delete it completely.
5270 if (haveBackupLabel)
5272 unlink(BACKUP_LABEL_OLD);
5273 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
5275 (errcode_for_file_access(),
5276 errmsg("could not rename file \"%s\" to \"%s\": %m",
5277 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
5280 /* Initialize resource managers */
5281 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5283 if (RmgrTable[rmid].rm_startup != NULL)
5284 RmgrTable[rmid].rm_startup();
5288 * Find the first record that logically follows the checkpoint --- it
5289 * might physically precede it, though.
5291 if (XLByteLT(checkPoint.redo, RecPtr))
5293 /* back up to find the record */
5294 record = ReadRecord(&(checkPoint.redo), PANIC);
5298 /* just have to read next record after CheckPoint */
5299 record = ReadRecord(NULL, LOG);
5304 bool recoveryContinue = true;
5305 bool recoveryApply = true;
5306 bool reachedMinRecoveryPoint = false;
5307 ErrorContextCallback errcontext;
5308 /* use volatile pointer to prevent code rearrangement */
5309 volatile XLogCtlData *xlogctl = XLogCtl;
5311 /* Update shared replayEndRecPtr */
5312 SpinLockAcquire(&xlogctl->info_lck);
5313 xlogctl->replayEndRecPtr = ReadRecPtr;
5314 SpinLockRelease(&xlogctl->info_lck);
5318 if (minRecoveryPoint.xlogid == 0 && minRecoveryPoint.xrecoff == 0)
5320 (errmsg("redo starts at %X/%X",
5321 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5324 (errmsg("redo starts at %X/%X, consistency will be reached at %X/%X",
5325 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
5326 minRecoveryPoint.xlogid, minRecoveryPoint.xrecoff)));
5329 * Let postmaster know we've started redo now, so that it can
5330 * launch bgwriter to perform restartpoints. We don't bother
5331 * during crash recovery as restartpoints can only be performed
5332 * during archive recovery. And we'd like to keep crash recovery
5333 * simple, to avoid introducing bugs that could you from
5334 * recovering after crash.
5336 * After this point, we can no longer assume that we're the only
5337 * process in addition to postmaster!
5339 if (InArchiveRecovery && IsUnderPostmaster)
5340 SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED);
5343 * main redo apply loop
5352 initStringInfo(&buf);
5353 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
5354 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
5355 EndRecPtr.xlogid, EndRecPtr.xrecoff);
5356 xlog_outrec(&buf, record);
5357 appendStringInfo(&buf, " - ");
5358 RmgrTable[record->xl_rmid].rm_desc(&buf,
5360 XLogRecGetData(record));
5361 elog(LOG, "%s", buf.data);
5367 * Check if we were requested to re-read config file.
5372 ProcessConfigFile(PGC_SIGHUP);
5376 * Check if we were requested to exit without finishing
5379 if (shutdown_requested)
5383 * Have we reached our safe starting point? If so, we can
5384 * tell postmaster that the database is consistent now.
5386 if (!reachedMinRecoveryPoint &&
5387 XLByteLE(minRecoveryPoint, EndRecPtr))
5389 reachedMinRecoveryPoint = true;
5390 if (InArchiveRecovery)
5393 (errmsg("consistent recovery state reached")));
5394 if (IsUnderPostmaster)
5395 SendPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT);
5400 * Have we reached our recovery target?
5402 if (recoveryStopsHere(record, &recoveryApply))
5404 reachedStopPoint = true; /* see below */
5405 recoveryContinue = false;
5410 /* Setup error traceback support for ereport() */
5411 errcontext.callback = rm_redo_error_callback;
5412 errcontext.arg = (void *) record;
5413 errcontext.previous = error_context_stack;
5414 error_context_stack = &errcontext;
5416 /* nextXid must be beyond record's xid */
5417 if (TransactionIdFollowsOrEquals(record->xl_xid,
5418 ShmemVariableCache->nextXid))
5420 ShmemVariableCache->nextXid = record->xl_xid;
5421 TransactionIdAdvance(ShmemVariableCache->nextXid);
5425 * Update shared replayEndRecPtr before replaying this
5426 * record, so that XLogFlush will update minRecoveryPoint
5429 SpinLockAcquire(&xlogctl->info_lck);
5430 xlogctl->replayEndRecPtr = EndRecPtr;
5431 SpinLockRelease(&xlogctl->info_lck);
5433 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
5435 /* Pop the error context stack */
5436 error_context_stack = errcontext.previous;
5438 LastRec = ReadRecPtr;
5440 record = ReadRecord(NULL, LOG);
5441 } while (record != NULL && recoveryContinue);
5444 * end of main redo apply loop
5448 (errmsg("redo done at %X/%X",
5449 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5450 if (recoveryLastXTime)
5452 (errmsg("last completed transaction was at log time %s",
5453 timestamptz_to_str(recoveryLastXTime))));
5458 /* there are no WAL records following the checkpoint */
5460 (errmsg("redo is not required")));
5465 * Re-fetch the last valid or last applied record, so we can identify the
5466 * exact endpoint of what we consider the valid portion of WAL.
5468 record = ReadRecord(&LastRec, PANIC);
5469 EndOfLog = EndRecPtr;
5470 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
5473 * Complain if we did not roll forward far enough to render the backup
5476 if (InRecovery && XLByteLT(EndOfLog, minRecoveryPoint))
5478 if (reachedStopPoint) /* stopped because of stop request */
5480 (errmsg("requested recovery stop point is before consistent recovery point")));
5481 else /* ran off end of WAL */
5483 (errmsg("WAL ends before consistent recovery point")));
5487 * Consider whether we need to assign a new timeline ID.
5489 * If we are doing an archive recovery, we always assign a new ID. This
5490 * handles a couple of issues. If we stopped short of the end of WAL
5491 * during recovery, then we are clearly generating a new timeline and must
5492 * assign it a unique new ID. Even if we ran to the end, modifying the
5493 * current last segment is problematic because it may result in trying to
5494 * overwrite an already-archived copy of that segment, and we encourage
5495 * DBAs to make their archive_commands reject that. We can dodge the
5496 * problem by making the new active segment have a new timeline ID.
5498 * In a normal crash recovery, we can just extend the timeline we were in.
5500 if (InArchiveRecovery)
5502 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5504 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5505 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5506 curFileTLI, endLogId, endLogSeg);
5509 /* Save the selected TimeLineID in shared memory, too */
5510 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5513 * We are now done reading the old WAL. Turn off archive fetching if it
5514 * was active, and make a writable copy of the last WAL segment. (Note
5515 * that we also have a copy of the last block of the old WAL in readBuf;
5516 * we will use that below.)
5518 if (InArchiveRecovery)
5519 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5522 * Prepare to write WAL starting at EndOfLog position, and init xlog
5523 * buffer cache using the block containing the last record from the
5524 * previous incarnation.
5526 openLogId = endLogId;
5527 openLogSeg = endLogSeg;
5528 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5530 Insert = &XLogCtl->Insert;
5531 Insert->PrevRecord = LastRec;
5532 XLogCtl->xlblocks[0].xlogid = openLogId;
5533 XLogCtl->xlblocks[0].xrecoff =
5534 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5537 * Tricky point here: readBuf contains the *last* block that the LastRec
5538 * record spans, not the one it starts in. The last block is indeed the
5539 * one we want to use.
5541 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5542 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5543 Insert->currpos = (char *) Insert->currpage +
5544 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5546 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5548 XLogCtl->Write.LogwrtResult = LogwrtResult;
5549 Insert->LogwrtResult = LogwrtResult;
5550 XLogCtl->LogwrtResult = LogwrtResult;
5552 XLogCtl->LogwrtRqst.Write = EndOfLog;
5553 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5555 freespace = INSERT_FREESPACE(Insert);
5558 /* Make sure rest of page is zero */
5559 MemSet(Insert->currpos, 0, freespace);
5560 XLogCtl->Write.curridx = 0;
5565 * Whenever Write.LogwrtResult points to exactly the end of a page,
5566 * Write.curridx must point to the *next* page (see XLogWrite()).
5568 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5569 * this is sufficient. The first actual attempt to insert a log
5570 * record will advance the insert state.
5572 XLogCtl->Write.curridx = NextBufIdx(0);
5575 /* Pre-scan prepared transactions to find out the range of XIDs present */
5576 oldestActiveXID = PrescanPreparedTransactions();
5579 * Allow writing WAL for us, so that we can create a checkpoint record.
5580 * But not yet for other backends!
5582 LocalRecoveryInProgress = false;
5589 * Allow resource managers to do any required cleanup.
5591 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5593 if (RmgrTable[rmid].rm_cleanup != NULL)
5594 RmgrTable[rmid].rm_cleanup();
5598 * Check to see if the XLOG sequence contained any unresolved
5599 * references to uninitialized pages.
5601 XLogCheckInvalidPages();
5604 * Perform a checkpoint to update all our recovery activity to disk.
5606 * Note that we write a shutdown checkpoint rather than an on-line
5607 * one. This is not particularly critical, but since we may be
5608 * assigning a new TLI, using a shutdown checkpoint allows us to have
5609 * the rule that TLI only changes in shutdown checkpoints, which
5610 * allows some extra error checking in xlog_redo.
5612 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5616 * Preallocate additional log files, if wanted.
5618 PreallocXlogFiles(EndOfLog);
5621 * Okay, we're officially UP.
5625 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5626 ControlFile->state = DB_IN_PRODUCTION;
5627 ControlFile->time = (pg_time_t) time(NULL);
5628 UpdateControlFile();
5629 LWLockRelease(ControlFileLock);
5631 /* start the archive_timeout timer running */
5632 XLogCtl->Write.lastSegSwitchTime = (pg_time_t) time(NULL);
5634 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5635 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5636 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5638 /* also initialize latestCompletedXid, to nextXid - 1 */
5639 ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
5640 TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);
5642 /* Start up the commit log and related stuff, too */
5644 StartupSUBTRANS(oldestActiveXID);
5647 /* Reload shared-memory state for prepared transactions */
5648 RecoverPreparedTransactions();
5650 /* Shut down readFile facility, free space */
5663 free(readRecordBuf);
5664 readRecordBuf = NULL;
5665 readRecordBufSize = 0;
5669 * All done. Allow others to write WAL.
5671 XLogCtl->SharedRecoveryInProgress = false;
5675 * Is the system still in recovery?
5677 * As a side-effect, we initialize the local TimeLineID and RedoRecPtr
5678 * variables the first time we see that recovery is finished.
5681 RecoveryInProgress(void)
5684 * We check shared state each time only until we leave recovery mode.
5685 * We can't re-enter recovery, so we rely on the local state variable
5688 if (!LocalRecoveryInProgress)
5692 /* use volatile pointer to prevent code rearrangement */
5693 volatile XLogCtlData *xlogctl = XLogCtl;
5695 LocalRecoveryInProgress = xlogctl->SharedRecoveryInProgress;
5698 * Initialize TimeLineID and RedoRecPtr the first time we see that
5699 * recovery is finished.
5701 if (!LocalRecoveryInProgress)
5704 return LocalRecoveryInProgress;
5709 * Subroutine to try to fetch and validate a prior checkpoint record.
5711 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5712 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5715 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5719 if (!XRecOffIsValid(RecPtr.xrecoff))
5725 (errmsg("invalid primary checkpoint link in control file")));
5729 (errmsg("invalid secondary checkpoint link in control file")));
5733 (errmsg("invalid checkpoint link in backup_label file")));
5739 record = ReadRecord(&RecPtr, LOG);
5747 (errmsg("invalid primary checkpoint record")));
5751 (errmsg("invalid secondary checkpoint record")));
5755 (errmsg("invalid checkpoint record")));
5760 if (record->xl_rmid != RM_XLOG_ID)
5766 (errmsg("invalid resource manager ID in primary checkpoint record")));
5770 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5774 (errmsg("invalid resource manager ID in checkpoint record")));
5779 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5780 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5786 (errmsg("invalid xl_info in primary checkpoint record")));
5790 (errmsg("invalid xl_info in secondary checkpoint record")));
5794 (errmsg("invalid xl_info in checkpoint record")));
5799 if (record->xl_len != sizeof(CheckPoint) ||
5800 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5806 (errmsg("invalid length of primary checkpoint record")));
5810 (errmsg("invalid length of secondary checkpoint record")));
5814 (errmsg("invalid length of checkpoint record")));
5823 * This must be called during startup of a backend process, except that
5824 * it need not be called in a standalone backend (which does StartupXLOG
5825 * instead). We need to initialize the local copies of ThisTimeLineID and
5828 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5829 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5830 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5833 InitXLOGAccess(void)
5835 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5836 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5837 Assert(ThisTimeLineID != 0);
5839 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5840 (void) GetRedoRecPtr();
5844 * Once spawned, a backend may update its local RedoRecPtr from
5845 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5846 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5851 /* use volatile pointer to prevent code rearrangement */
5852 volatile XLogCtlData *xlogctl = XLogCtl;
5854 SpinLockAcquire(&xlogctl->info_lck);
5855 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5856 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5857 SpinLockRelease(&xlogctl->info_lck);
5863 * GetInsertRecPtr -- Returns the current insert position.
5865 * NOTE: The value *actually* returned is the position of the last full
5866 * xlog page. It lags behind the real insert position by at most 1 page.
5867 * For that, we don't need to acquire WALInsertLock which can be quite
5868 * heavily contended, and an approximation is enough for the current
5869 * usage of this function.
5872 GetInsertRecPtr(void)
5874 /* use volatile pointer to prevent code rearrangement */
5875 volatile XLogCtlData *xlogctl = XLogCtl;
5878 SpinLockAcquire(&xlogctl->info_lck);
5879 recptr = xlogctl->LogwrtRqst.Write;
5880 SpinLockRelease(&xlogctl->info_lck);
5886 * Get the time of the last xlog segment switch
5889 GetLastSegSwitchTime(void)
5893 /* Need WALWriteLock, but shared lock is sufficient */
5894 LWLockAcquire(WALWriteLock, LW_SHARED);
5895 result = XLogCtl->Write.lastSegSwitchTime;
5896 LWLockRelease(WALWriteLock);
5902 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5904 * This is exported for use by code that would like to have 64-bit XIDs.
5905 * We don't really support such things, but all XIDs within the system
5906 * can be presumed "close to" the result, and thus the epoch associated
5907 * with them can be determined.
5910 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5912 uint32 ckptXidEpoch;
5913 TransactionId ckptXid;
5914 TransactionId nextXid;
5916 /* Must read checkpoint info first, else have race condition */
5918 /* use volatile pointer to prevent code rearrangement */
5919 volatile XLogCtlData *xlogctl = XLogCtl;
5921 SpinLockAcquire(&xlogctl->info_lck);
5922 ckptXidEpoch = xlogctl->ckptXidEpoch;
5923 ckptXid = xlogctl->ckptXid;
5924 SpinLockRelease(&xlogctl->info_lck);
5927 /* Now fetch current nextXid */
5928 nextXid = ReadNewTransactionId();
5931 * nextXid is certainly logically later than ckptXid. So if it's
5932 * numerically less, it must have wrapped into the next epoch.
5934 if (nextXid < ckptXid)
5938 *epoch = ckptXidEpoch;
5942 * This must be called ONCE during postmaster or standalone-backend shutdown
5945 ShutdownXLOG(int code, Datum arg)
5948 (errmsg("shutting down")));
5950 if (RecoveryInProgress())
5951 CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5953 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5956 ShutdownMultiXact();
5959 (errmsg("database system is shut down")));
5963 * Log start of a checkpoint.
5966 LogCheckpointStart(int flags, bool restartpoint)
5971 * XXX: This is hopelessly untranslatable. We could call gettext_noop
5972 * for the main message, but what about all the flags?
5975 msg = "restartpoint starting:%s%s%s%s%s%s";
5977 msg = "checkpoint starting:%s%s%s%s%s%s";
5980 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
5981 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
5982 (flags & CHECKPOINT_FORCE) ? " force" : "",
5983 (flags & CHECKPOINT_WAIT) ? " wait" : "",
5984 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
5985 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
5989 * Log end of a checkpoint.
5992 LogCheckpointEnd(bool restartpoint)
6001 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
6003 TimestampDifference(CheckpointStats.ckpt_start_t,
6004 CheckpointStats.ckpt_end_t,
6005 &total_secs, &total_usecs);
6007 TimestampDifference(CheckpointStats.ckpt_write_t,
6008 CheckpointStats.ckpt_sync_t,
6009 &write_secs, &write_usecs);
6011 TimestampDifference(CheckpointStats.ckpt_sync_t,
6012 CheckpointStats.ckpt_sync_end_t,
6013 &sync_secs, &sync_usecs);
6016 elog(LOG, "restartpoint complete: wrote %d buffers (%.1f%%); "
6017 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
6018 CheckpointStats.ckpt_bufs_written,
6019 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
6020 write_secs, write_usecs / 1000,
6021 sync_secs, sync_usecs / 1000,
6022 total_secs, total_usecs / 1000);
6024 elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
6025 "%d transaction log file(s) added, %d removed, %d recycled; "
6026 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
6027 CheckpointStats.ckpt_bufs_written,
6028 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
6029 CheckpointStats.ckpt_segs_added,
6030 CheckpointStats.ckpt_segs_removed,
6031 CheckpointStats.ckpt_segs_recycled,
6032 write_secs, write_usecs / 1000,
6033 sync_secs, sync_usecs / 1000,
6034 total_secs, total_usecs / 1000);
6038 * Perform a checkpoint --- either during shutdown, or on-the-fly
6040 * flags is a bitwise OR of the following:
6041 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
6042 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
6043 * ignoring checkpoint_completion_target parameter.
6044 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
6045 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
6047 * Note: flags contains other bits, of interest here only for logging purposes.
6048 * In particular note that this routine is synchronous and does not pay
6049 * attention to CHECKPOINT_WAIT.
6052 CreateCheckPoint(int flags)
6054 bool shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
6055 CheckPoint checkPoint;
6057 XLogCtlInsert *Insert = &XLogCtl->Insert;
6062 TransactionId *inCommitXids;
6065 /* shouldn't happen */
6066 if (RecoveryInProgress())
6067 elog(ERROR, "can't create a checkpoint during recovery");
6070 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
6071 * During normal operation, bgwriter is the only process that creates
6072 * checkpoints, but at the end of archive recovery, the bgwriter can be
6073 * busy creating a restartpoint while the startup process tries to perform
6074 * the startup checkpoint.
6076 if (!LWLockConditionalAcquire(CheckpointLock, LW_EXCLUSIVE))
6081 * A restartpoint is in progress. Wait until it finishes. This can
6082 * cause an extra restartpoint to be performed, but that's OK because
6083 * we're just about to perform a checkpoint anyway. Flushing the
6084 * buffers in this restartpoint can take some time, but that time is
6085 * saved from the upcoming checkpoint so the net effect is zero.
6087 ereport(DEBUG2, (errmsg("hurrying in-progress restartpoint")));
6088 RequestCheckpoint(CHECKPOINT_IMMEDIATE | CHECKPOINT_WAIT);
6090 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
6094 * Prepare to accumulate statistics.
6096 * Note: because it is possible for log_checkpoints to change while a
6097 * checkpoint proceeds, we always accumulate stats, even if
6098 * log_checkpoints is currently off.
6100 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
6101 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
6104 * Use a critical section to force system panic if we have trouble.
6106 START_CRIT_SECTION();
6110 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6111 ControlFile->state = DB_SHUTDOWNING;
6112 ControlFile->time = (pg_time_t) time(NULL);
6113 UpdateControlFile();
6114 LWLockRelease(ControlFileLock);
6118 * Let smgr prepare for checkpoint; this has to happen before we determine
6119 * the REDO pointer. Note that smgr must not do anything that'd have to
6120 * be undone if we decide no checkpoint is needed.
6124 /* Begin filling in the checkpoint WAL record */
6125 MemSet(&checkPoint, 0, sizeof(checkPoint));
6126 checkPoint.ThisTimeLineID = ThisTimeLineID;
6127 checkPoint.time = (pg_time_t) time(NULL);
6130 * We must hold WALInsertLock while examining insert state to determine
6131 * the checkpoint REDO pointer.
6133 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6136 * If this isn't a shutdown or forced checkpoint, and we have not inserted
6137 * any XLOG records since the start of the last checkpoint, skip the
6138 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
6139 * when the system is idle. That wastes log space, and more importantly it
6140 * exposes us to possible loss of both current and previous checkpoint
6141 * records if the machine crashes just as we're writing the update.
6142 * (Perhaps it'd make even more sense to checkpoint only when the previous
6143 * checkpoint record is in a different xlog page?)
6145 * We have to make two tests to determine that nothing has happened since
6146 * the start of the last checkpoint: current insertion point must match
6147 * the end of the last checkpoint record, and its redo pointer must point
6150 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
6152 XLogRecPtr curInsert;
6154 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
6155 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
6156 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
6157 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
6158 ControlFile->checkPoint.xlogid ==
6159 ControlFile->checkPointCopy.redo.xlogid &&
6160 ControlFile->checkPoint.xrecoff ==
6161 ControlFile->checkPointCopy.redo.xrecoff)
6163 LWLockRelease(WALInsertLock);
6164 LWLockRelease(CheckpointLock);
6171 * Compute new REDO record ptr = location of next XLOG record.
6173 * NB: this is NOT necessarily where the checkpoint record itself will be,
6174 * since other backends may insert more XLOG records while we're off doing
6175 * the buffer flush work. Those XLOG records are logically after the
6176 * checkpoint, even though physically before it. Got that?
6178 freespace = INSERT_FREESPACE(Insert);
6179 if (freespace < SizeOfXLogRecord)
6181 (void) AdvanceXLInsertBuffer(false);
6182 /* OK to ignore update return flag, since we will do flush anyway */
6183 freespace = INSERT_FREESPACE(Insert);
6185 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
6188 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
6189 * must be done while holding the insert lock AND the info_lck.
6191 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
6192 * pointing past where it really needs to point. This is okay; the only
6193 * consequence is that XLogInsert might back up whole buffers that it
6194 * didn't really need to. We can't postpone advancing RedoRecPtr because
6195 * XLogInserts that happen while we are dumping buffers must assume that
6196 * their buffer changes are not included in the checkpoint.
6199 /* use volatile pointer to prevent code rearrangement */
6200 volatile XLogCtlData *xlogctl = XLogCtl;
6202 SpinLockAcquire(&xlogctl->info_lck);
6203 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
6204 SpinLockRelease(&xlogctl->info_lck);
6208 * Now we can release WAL insert lock, allowing other xacts to proceed
6209 * while we are flushing disk buffers.
6211 LWLockRelease(WALInsertLock);
6214 * If enabled, log checkpoint start. We postpone this until now so as not
6215 * to log anything if we decided to skip the checkpoint.
6217 if (log_checkpoints)
6218 LogCheckpointStart(flags, false);
6220 TRACE_POSTGRESQL_CHECKPOINT_START(flags);
6223 * Before flushing data, we must wait for any transactions that are
6224 * currently in their commit critical sections. If an xact inserted its
6225 * commit record into XLOG just before the REDO point, then a crash
6226 * restart from the REDO point would not replay that record, which means
6227 * that our flushing had better include the xact's update of pg_clog. So
6228 * we wait till he's out of his commit critical section before proceeding.
6229 * See notes in RecordTransactionCommit().
6231 * Because we've already released WALInsertLock, this test is a bit fuzzy:
6232 * it is possible that we will wait for xacts we didn't really need to
6233 * wait for. But the delay should be short and it seems better to make
6234 * checkpoint take a bit longer than to hold locks longer than necessary.
6235 * (In fact, the whole reason we have this issue is that xact.c does
6236 * commit record XLOG insertion and clog update as two separate steps
6237 * protected by different locks, but again that seems best on grounds of
6238 * minimizing lock contention.)
6240 * A transaction that has not yet set inCommit when we look cannot be at
6241 * risk, since he's not inserted his commit record yet; and one that's
6242 * already cleared it is not at risk either, since he's done fixing clog
6243 * and we will correctly flush the update below. So we cannot miss any
6244 * xacts we need to wait for.
6246 nInCommit = GetTransactionsInCommit(&inCommitXids);
6251 pg_usleep(10000L); /* wait for 10 msec */
6252 } while (HaveTransactionsInCommit(inCommitXids, nInCommit));
6254 pfree(inCommitXids);
6257 * Get the other info we need for the checkpoint record.
6259 LWLockAcquire(XidGenLock, LW_SHARED);
6260 checkPoint.nextXid = ShmemVariableCache->nextXid;
6261 LWLockRelease(XidGenLock);
6263 /* Increase XID epoch if we've wrapped around since last checkpoint */
6264 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
6265 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
6266 checkPoint.nextXidEpoch++;
6268 LWLockAcquire(OidGenLock, LW_SHARED);
6269 checkPoint.nextOid = ShmemVariableCache->nextOid;
6271 checkPoint.nextOid += ShmemVariableCache->oidCount;
6272 LWLockRelease(OidGenLock);
6274 MultiXactGetCheckptMulti(shutdown,
6275 &checkPoint.nextMulti,
6276 &checkPoint.nextMultiOffset);
6279 * Having constructed the checkpoint record, ensure all shmem disk buffers
6280 * and commit-log buffers are flushed to disk.
6282 * This I/O could fail for various reasons. If so, we will fail to
6283 * complete the checkpoint, but there is no reason to force a system
6284 * panic. Accordingly, exit critical section while doing it.
6288 CheckPointGuts(checkPoint.redo, flags);
6290 START_CRIT_SECTION();
6293 * Now insert the checkpoint record into XLOG.
6295 rdata.data = (char *) (&checkPoint);
6296 rdata.len = sizeof(checkPoint);
6297 rdata.buffer = InvalidBuffer;
6300 recptr = XLogInsert(RM_XLOG_ID,
6301 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
6302 XLOG_CHECKPOINT_ONLINE,
6308 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
6309 * = end of actual checkpoint record.
6311 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
6313 (errmsg("concurrent transaction log activity while database system is shutting down")));
6316 * Select point at which we can truncate the log, which we base on the
6317 * prior checkpoint's earliest info.
6319 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
6322 * Update the control file.
6324 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6326 ControlFile->state = DB_SHUTDOWNED;
6327 ControlFile->prevCheckPoint = ControlFile->checkPoint;
6328 ControlFile->checkPoint = ProcLastRecPtr;
6329 ControlFile->checkPointCopy = checkPoint;
6330 ControlFile->time = (pg_time_t) time(NULL);
6331 UpdateControlFile();
6332 LWLockRelease(ControlFileLock);
6334 /* Update shared-memory copy of checkpoint XID/epoch */
6336 /* use volatile pointer to prevent code rearrangement */
6337 volatile XLogCtlData *xlogctl = XLogCtl;
6339 SpinLockAcquire(&xlogctl->info_lck);
6340 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
6341 xlogctl->ckptXid = checkPoint.nextXid;
6342 SpinLockRelease(&xlogctl->info_lck);
6346 * We are now done with critical updates; no need for system panic if we
6347 * have trouble while fooling with old log segments.
6352 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
6357 * Delete old log files (those no longer needed even for previous
6360 if (_logId || _logSeg)
6362 PrevLogSeg(_logId, _logSeg);
6363 RemoveOldXlogFiles(_logId, _logSeg, recptr);
6367 * Make more log segments if needed. (Do this after recycling old log
6368 * segments, since that may supply some of the needed files.)
6371 PreallocXlogFiles(recptr);
6374 * Truncate pg_subtrans if possible. We can throw away all data before
6375 * the oldest XMIN of any running transaction. No future transaction will
6376 * attempt to reference any pg_subtrans entry older than that (see Asserts
6377 * in subtrans.c). During recovery, though, we mustn't do this because
6378 * StartupSUBTRANS hasn't been called yet.
6381 TruncateSUBTRANS(GetOldestXmin(true, false));
6383 /* All real work is done, but log before releasing lock. */
6384 if (log_checkpoints)
6385 LogCheckpointEnd(false);
6387 TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
6388 NBuffers, CheckpointStats.ckpt_segs_added,
6389 CheckpointStats.ckpt_segs_removed,
6390 CheckpointStats.ckpt_segs_recycled);
6392 LWLockRelease(CheckpointLock);
6396 * Flush all data in shared memory to disk, and fsync
6398 * This is the common code shared between regular checkpoints and
6399 * recovery restartpoints.
6402 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
6405 CheckPointSUBTRANS();
6406 CheckPointMultiXact();
6407 CheckPointBuffers(flags); /* performs all required fsyncs */
6408 /* We deliberately delay 2PC checkpointing as long as possible */
6409 CheckPointTwoPhase(checkPointRedo);
6413 * This is used during WAL recovery to establish a point from which recovery
6414 * can roll forward without replaying the entire recovery log. This function
6415 * is called each time a checkpoint record is read from XLOG. It is stored
6416 * in shared memory, so that it can be used as a restartpoint later on.
6419 RecoveryRestartPoint(const CheckPoint *checkPoint)
6422 /* use volatile pointer to prevent code rearrangement */
6423 volatile XLogCtlData *xlogctl = XLogCtl;
6426 * Is it safe to checkpoint? We must ask each of the resource managers
6427 * whether they have any partial state information that might prevent a
6428 * correct restart from this point. If so, we skip this opportunity, but
6429 * return at the next checkpoint record for another try.
6431 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
6433 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
6434 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
6436 elog(DEBUG2, "RM %d not safe to record restart point at %X/%X",
6438 checkPoint->redo.xlogid,
6439 checkPoint->redo.xrecoff);
6445 * Copy the checkpoint record to shared memory, so that bgwriter can
6446 * use it the next time it wants to perform a restartpoint.
6448 SpinLockAcquire(&xlogctl->info_lck);
6449 XLogCtl->lastCheckPointRecPtr = ReadRecPtr;
6450 memcpy(&XLogCtl->lastCheckPoint, checkPoint, sizeof(CheckPoint));
6451 SpinLockRelease(&xlogctl->info_lck);
6455 * This is similar to CreateCheckPoint, but is used during WAL recovery
6456 * to establish a point from which recovery can roll forward without
6457 * replaying the entire recovery log.
6459 * Returns true if a new restartpoint was established. We can only establish
6460 * a restartpoint if we have replayed a checkpoint record since last
6464 CreateRestartPoint(int flags)
6466 XLogRecPtr lastCheckPointRecPtr;
6467 CheckPoint lastCheckPoint;
6468 /* use volatile pointer to prevent code rearrangement */
6469 volatile XLogCtlData *xlogctl = XLogCtl;
6472 * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
6473 * happens at a time.
6475 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
6477 /* Get the a local copy of the last checkpoint record. */
6478 SpinLockAcquire(&xlogctl->info_lck);
6479 lastCheckPointRecPtr = xlogctl->lastCheckPointRecPtr;
6480 memcpy(&lastCheckPoint, &XLogCtl->lastCheckPoint, sizeof(CheckPoint));
6481 SpinLockRelease(&xlogctl->info_lck);
6484 * Check that we're still in recovery mode. It's ok if we exit recovery
6485 * mode after this check, the restart point is valid anyway.
6487 if (!RecoveryInProgress())
6490 (errmsg("skipping restartpoint, recovery has already ended")));
6491 LWLockRelease(CheckpointLock);
6496 * If the last checkpoint record we've replayed is already our last
6497 * restartpoint, we can't perform a new restart point. We still update
6498 * minRecoveryPoint in that case, so that if this is a shutdown restart
6499 * point, we won't start up earlier than before. That's not strictly
6500 * necessary, but when we get hot standby capability, it would be rather
6501 * weird if the database opened up for read-only connections at a
6502 * point-in-time before the last shutdown. Such time travel is still
6503 * possible in case of immediate shutdown, though.
6505 * We don't explicitly advance minRecoveryPoint when we do create a
6506 * restartpoint. It's assumed that flushing the buffers will do that
6509 if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
6510 XLByteLE(lastCheckPoint.redo, ControlFile->checkPointCopy.redo))
6512 XLogRecPtr InvalidXLogRecPtr = {0, 0};
6514 (errmsg("skipping restartpoint, already performed at %X/%X",
6515 lastCheckPoint.redo.xlogid, lastCheckPoint.redo.xrecoff)));
6517 UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
6518 LWLockRelease(CheckpointLock);
6522 if (log_checkpoints)
6525 * Prepare to accumulate statistics.
6527 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
6528 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
6530 LogCheckpointStart(flags, true);
6533 CheckPointGuts(lastCheckPoint.redo, flags);
6536 * Update pg_control, using current time
6538 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6539 ControlFile->prevCheckPoint = ControlFile->checkPoint;
6540 ControlFile->checkPoint = lastCheckPointRecPtr;
6541 ControlFile->checkPointCopy = lastCheckPoint;
6542 ControlFile->time = (pg_time_t) time(NULL);
6543 UpdateControlFile();
6544 LWLockRelease(ControlFileLock);
6547 * Currently, there is no need to truncate pg_subtrans during recovery.
6548 * If we did do that, we will need to have called StartupSUBTRANS()
6549 * already and then TruncateSUBTRANS() would go here.
6552 /* All real work is done, but log before releasing lock. */
6553 if (log_checkpoints)
6554 LogCheckpointEnd(true);
6556 ereport((log_checkpoints ? LOG : DEBUG2),
6557 (errmsg("recovery restart point at %X/%X",
6558 lastCheckPoint.redo.xlogid, lastCheckPoint.redo.xrecoff)));
6560 if (recoveryLastXTime)
6561 ereport((log_checkpoints ? LOG : DEBUG2),
6562 (errmsg("last completed transaction was at log time %s",
6563 timestamptz_to_str(recoveryLastXTime))));
6565 LWLockRelease(CheckpointLock);
6570 * Write a NEXTOID log record
6573 XLogPutNextOid(Oid nextOid)
6577 rdata.data = (char *) (&nextOid);
6578 rdata.len = sizeof(Oid);
6579 rdata.buffer = InvalidBuffer;
6581 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
6584 * We need not flush the NEXTOID record immediately, because any of the
6585 * just-allocated OIDs could only reach disk as part of a tuple insert or
6586 * update that would have its own XLOG record that must follow the NEXTOID
6587 * record. Therefore, the standard buffer LSN interlock applied to those
6588 * records will ensure no such OID reaches disk before the NEXTOID record
6591 * Note, however, that the above statement only covers state "within" the
6592 * database. When we use a generated OID as a file or directory name, we
6593 * are in a sense violating the basic WAL rule, because that filesystem
6594 * change may reach disk before the NEXTOID WAL record does. The impact
6595 * of this is that if a database crash occurs immediately afterward, we
6596 * might after restart re-generate the same OID and find that it conflicts
6597 * with the leftover file or directory. But since for safety's sake we
6598 * always loop until finding a nonconflicting filename, this poses no real
6599 * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
6604 * Write an XLOG SWITCH record.
6606 * Here we just blindly issue an XLogInsert request for the record.
6607 * All the magic happens inside XLogInsert.
6609 * The return value is either the end+1 address of the switch record,
6610 * or the end+1 address of the prior segment if we did not need to
6611 * write a switch record because we are already at segment start.
6614 RequestXLogSwitch(void)
6619 /* XLOG SWITCH, alone among xlog record types, has no data */
6620 rdata.buffer = InvalidBuffer;
6625 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
6631 * XLOG resource manager's routines
6633 * Definitions of info values are in include/catalog/pg_control.h, though
6634 * not all records types are related to control file processing.
6637 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
6639 uint8 info = record->xl_info & ~XLR_INFO_MASK;
6641 /* Backup blocks are not used in xlog records */
6642 Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
6644 if (info == XLOG_NEXTOID)
6648 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
6649 if (ShmemVariableCache->nextOid < nextOid)
6651 ShmemVariableCache->nextOid = nextOid;
6652 ShmemVariableCache->oidCount = 0;
6655 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
6657 CheckPoint checkPoint;
6659 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6660 /* In a SHUTDOWN checkpoint, believe the counters exactly */
6661 ShmemVariableCache->nextXid = checkPoint.nextXid;
6662 ShmemVariableCache->nextOid = checkPoint.nextOid;
6663 ShmemVariableCache->oidCount = 0;
6664 MultiXactSetNextMXact(checkPoint.nextMulti,
6665 checkPoint.nextMultiOffset);
6667 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6668 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6669 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6672 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
6674 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6676 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
6677 !list_member_int(expectedTLIs,
6678 (int) checkPoint.ThisTimeLineID))
6680 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
6681 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6682 /* Following WAL records should be run with new TLI */
6683 ThisTimeLineID = checkPoint.ThisTimeLineID;
6686 RecoveryRestartPoint(&checkPoint);
6688 else if (info == XLOG_CHECKPOINT_ONLINE)
6690 CheckPoint checkPoint;
6692 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6693 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
6694 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
6695 checkPoint.nextXid))
6696 ShmemVariableCache->nextXid = checkPoint.nextXid;
6697 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
6699 ShmemVariableCache->nextOid = checkPoint.nextOid;
6700 ShmemVariableCache->oidCount = 0;
6702 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
6703 checkPoint.nextMultiOffset);
6705 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6706 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6707 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6709 /* TLI should not change in an on-line checkpoint */
6710 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6712 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
6713 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6715 RecoveryRestartPoint(&checkPoint);
6717 else if (info == XLOG_NOOP)
6719 /* nothing to do here */
6721 else if (info == XLOG_SWITCH)
6723 /* nothing to do here */
6728 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
6730 uint8 info = xl_info & ~XLR_INFO_MASK;
6732 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
6733 info == XLOG_CHECKPOINT_ONLINE)
6735 CheckPoint *checkpoint = (CheckPoint *) rec;
6737 appendStringInfo(buf, "checkpoint: redo %X/%X; "
6738 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
6739 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
6740 checkpoint->ThisTimeLineID,
6741 checkpoint->nextXidEpoch, checkpoint->nextXid,
6742 checkpoint->nextOid,
6743 checkpoint->nextMulti,
6744 checkpoint->nextMultiOffset,
6745 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
6747 else if (info == XLOG_NOOP)
6749 appendStringInfo(buf, "xlog no-op");
6751 else if (info == XLOG_NEXTOID)
6755 memcpy(&nextOid, rec, sizeof(Oid));
6756 appendStringInfo(buf, "nextOid: %u", nextOid);
6758 else if (info == XLOG_SWITCH)
6760 appendStringInfo(buf, "xlog switch");
6763 appendStringInfo(buf, "UNKNOWN");
6769 xlog_outrec(StringInfo buf, XLogRecord *record)
6773 appendStringInfo(buf, "prev %X/%X; xid %u",
6774 record->xl_prev.xlogid, record->xl_prev.xrecoff,
6777 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
6779 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
6780 appendStringInfo(buf, "; bkpb%d", i + 1);
6783 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
6785 #endif /* WAL_DEBUG */
6789 * Return the (possible) sync flag used for opening a file, depending on the
6790 * value of the GUC wal_sync_method.
6793 get_sync_bit(int method)
6795 /* If fsync is disabled, never open in sync mode */
6802 * enum values for all sync options are defined even if they are not
6803 * supported on the current platform. But if not, they are not
6804 * included in the enum option array, and therefore will never be seen
6807 case SYNC_METHOD_FSYNC:
6808 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6809 case SYNC_METHOD_FDATASYNC:
6811 #ifdef OPEN_SYNC_FLAG
6812 case SYNC_METHOD_OPEN:
6813 return OPEN_SYNC_FLAG;
6815 #ifdef OPEN_DATASYNC_FLAG
6816 case SYNC_METHOD_OPEN_DSYNC:
6817 return OPEN_DATASYNC_FLAG;
6820 /* can't happen (unless we are out of sync with option array) */
6821 elog(ERROR, "unrecognized wal_sync_method: %d", method);
6822 return 0; /* silence warning */
6830 assign_xlog_sync_method(int new_sync_method, bool doit, GucSource source)
6835 if (sync_method != new_sync_method)
6838 * To ensure that no blocks escape unsynced, force an fsync on the
6839 * currently open log segment (if any). Also, if the open flag is
6840 * changing, close the log file so it will be reopened (with new flag
6843 if (openLogFile >= 0)
6845 if (pg_fsync(openLogFile) != 0)
6847 (errcode_for_file_access(),
6848 errmsg("could not fsync log file %u, segment %u: %m",
6849 openLogId, openLogSeg)));
6850 if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
6860 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6863 issue_xlog_fsync(void)
6865 switch (sync_method)
6867 case SYNC_METHOD_FSYNC:
6868 if (pg_fsync_no_writethrough(openLogFile) != 0)
6870 (errcode_for_file_access(),
6871 errmsg("could not fsync log file %u, segment %u: %m",
6872 openLogId, openLogSeg)));
6874 #ifdef HAVE_FSYNC_WRITETHROUGH
6875 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6876 if (pg_fsync_writethrough(openLogFile) != 0)
6878 (errcode_for_file_access(),
6879 errmsg("could not fsync write-through log file %u, segment %u: %m",
6880 openLogId, openLogSeg)));
6883 #ifdef HAVE_FDATASYNC
6884 case SYNC_METHOD_FDATASYNC:
6885 if (pg_fdatasync(openLogFile) != 0)
6887 (errcode_for_file_access(),
6888 errmsg("could not fdatasync log file %u, segment %u: %m",
6889 openLogId, openLogSeg)));
6892 case SYNC_METHOD_OPEN:
6893 case SYNC_METHOD_OPEN_DSYNC:
6894 /* write synced it already */
6897 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6904 * pg_start_backup: set up for taking an on-line backup dump
6906 * Essentially what this does is to create a backup label file in $PGDATA,
6907 * where it will be archived as part of the backup dump. The label file
6908 * contains the user-supplied label string (typically this would be used
6909 * to tell where the backup dump will be stored) and the starting time and
6910 * starting WAL location for the dump.
6913 pg_start_backup(PG_FUNCTION_ARGS)
6915 text *backupid = PG_GETARG_TEXT_P(0);
6917 XLogRecPtr checkpointloc;
6918 XLogRecPtr startpoint;
6919 pg_time_t stamp_time;
6921 char xlogfilename[MAXFNAMELEN];
6924 struct stat stat_buf;
6929 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6930 errmsg("must be superuser to run a backup")));
6932 if (!XLogArchivingActive())
6934 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6935 errmsg("WAL archiving is not active"),
6936 errhint("archive_mode must be enabled at server start.")));
6938 if (!XLogArchiveCommandSet())
6940 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6941 errmsg("WAL archiving is not active"),
6942 errhint("archive_command must be defined before "
6943 "online backups can be made safely.")));
6945 backupidstr = text_to_cstring(backupid);
6948 * Mark backup active in shared memory. We must do full-page WAL writes
6949 * during an on-line backup even if not doing so at other times, because
6950 * it's quite possible for the backup dump to obtain a "torn" (partially
6951 * written) copy of a database page if it reads the page concurrently with
6952 * our write to the same page. This can be fixed as long as the first
6953 * write to the page in the WAL sequence is a full-page write. Hence, we
6954 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6955 * are no dirty pages in shared memory that might get dumped while the
6956 * backup is in progress without having a corresponding WAL record. (Once
6957 * the backup is complete, we need not force full-page writes anymore,
6958 * since we expect that any pages not modified during the backup interval
6959 * must have been correctly captured by the backup.)
6961 * We must hold WALInsertLock to change the value of forcePageWrites, to
6962 * ensure adequate interlocking against XLogInsert().
6964 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6965 if (XLogCtl->Insert.forcePageWrites)
6967 LWLockRelease(WALInsertLock);
6969 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6970 errmsg("a backup is already in progress"),
6971 errhint("Run pg_stop_backup() and try again.")));
6973 XLogCtl->Insert.forcePageWrites = true;
6974 LWLockRelease(WALInsertLock);
6976 /* Ensure we release forcePageWrites if fail below */
6977 PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
6980 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6981 * page problems, this guarantees that two successive backup runs will
6982 * have different checkpoint positions and hence different history
6983 * file names, even if nothing happened in between.
6985 * We don't use CHECKPOINT_IMMEDIATE, hence this can take awhile.
6987 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT);
6990 * Now we need to fetch the checkpoint record location, and also its
6991 * REDO pointer. The oldest point in WAL that would be needed to
6992 * restore starting from the checkpoint is precisely the REDO pointer.
6994 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6995 checkpointloc = ControlFile->checkPoint;
6996 startpoint = ControlFile->checkPointCopy.redo;
6997 LWLockRelease(ControlFileLock);
6999 XLByteToSeg(startpoint, _logId, _logSeg);
7000 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
7002 /* Use the log timezone here, not the session timezone */
7003 stamp_time = (pg_time_t) time(NULL);
7004 pg_strftime(strfbuf, sizeof(strfbuf),
7005 "%Y-%m-%d %H:%M:%S %Z",
7006 pg_localtime(&stamp_time, log_timezone));
7009 * Check for existing backup label --- implies a backup is already
7010 * running. (XXX given that we checked forcePageWrites above, maybe
7011 * it would be OK to just unlink any such label file?)
7013 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
7015 if (errno != ENOENT)
7017 (errcode_for_file_access(),
7018 errmsg("could not stat file \"%s\": %m",
7019 BACKUP_LABEL_FILE)));
7023 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7024 errmsg("a backup is already in progress"),
7025 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
7026 BACKUP_LABEL_FILE)));
7029 * Okay, write the file
7031 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
7034 (errcode_for_file_access(),
7035 errmsg("could not create file \"%s\": %m",
7036 BACKUP_LABEL_FILE)));
7037 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
7038 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
7039 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
7040 checkpointloc.xlogid, checkpointloc.xrecoff);
7041 fprintf(fp, "START TIME: %s\n", strfbuf);
7042 fprintf(fp, "LABEL: %s\n", backupidstr);
7043 if (fflush(fp) || ferror(fp) || FreeFile(fp))
7045 (errcode_for_file_access(),
7046 errmsg("could not write file \"%s\": %m",
7047 BACKUP_LABEL_FILE)));
7049 PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
7052 * We're done. As a convenience, return the starting WAL location.
7054 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
7055 startpoint.xlogid, startpoint.xrecoff);
7056 PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
7059 /* Error cleanup callback for pg_start_backup */
7061 pg_start_backup_callback(int code, Datum arg)
7063 /* Turn off forcePageWrites on failure */
7064 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
7065 XLogCtl->Insert.forcePageWrites = false;
7066 LWLockRelease(WALInsertLock);
7070 * pg_stop_backup: finish taking an on-line backup dump
7072 * We remove the backup label file created by pg_start_backup, and instead
7073 * create a backup history file in pg_xlog (whence it will immediately be
7074 * archived). The backup history file contains the same info found in
7075 * the label file, plus the backup-end time and WAL location.
7076 * Note: different from CancelBackup which just cancels online backup mode.
7079 pg_stop_backup(PG_FUNCTION_ARGS)
7081 XLogRecPtr startpoint;
7082 XLogRecPtr stoppoint;
7083 pg_time_t stamp_time;
7085 char histfilepath[MAXPGPATH];
7086 char startxlogfilename[MAXFNAMELEN];
7087 char stopxlogfilename[MAXFNAMELEN];
7088 char lastxlogfilename[MAXFNAMELEN];
7089 char histfilename[MAXFNAMELEN];
7096 int seconds_before_warning;
7101 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7102 (errmsg("must be superuser to run a backup"))));
7104 if (!XLogArchivingActive())
7106 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7107 errmsg("WAL archiving is not active"),
7108 errhint("archive_mode must be enabled at server start.")));
7111 * OK to clear forcePageWrites
7113 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
7114 XLogCtl->Insert.forcePageWrites = false;
7115 LWLockRelease(WALInsertLock);
7118 * Force a switch to a new xlog segment file, so that the backup is valid
7119 * as soon as archiver moves out the current segment file. We'll report
7120 * the end address of the XLOG SWITCH record as the backup stopping point.
7122 stoppoint = RequestXLogSwitch();
7124 XLByteToSeg(stoppoint, _logId, _logSeg);
7125 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
7127 /* Use the log timezone here, not the session timezone */
7128 stamp_time = (pg_time_t) time(NULL);
7129 pg_strftime(strfbuf, sizeof(strfbuf),
7130 "%Y-%m-%d %H:%M:%S %Z",
7131 pg_localtime(&stamp_time, log_timezone));
7134 * Open the existing label file
7136 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
7139 if (errno != ENOENT)
7141 (errcode_for_file_access(),
7142 errmsg("could not read file \"%s\": %m",
7143 BACKUP_LABEL_FILE)));
7145 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7146 errmsg("a backup is not in progress")));
7150 * Read and parse the START WAL LOCATION line (this code is pretty crude,
7151 * but we are not expecting any variability in the file format).
7153 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
7154 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
7155 &ch) != 4 || ch != '\n')
7157 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7158 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7161 * Write the backup history file
7163 XLByteToSeg(startpoint, _logId, _logSeg);
7164 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
7165 startpoint.xrecoff % XLogSegSize);
7166 fp = AllocateFile(histfilepath, "w");
7169 (errcode_for_file_access(),
7170 errmsg("could not create file \"%s\": %m",
7172 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
7173 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
7174 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
7175 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
7176 /* transfer remaining lines from label to history file */
7177 while ((ich = fgetc(lfp)) != EOF)
7179 fprintf(fp, "STOP TIME: %s\n", strfbuf);
7180 if (fflush(fp) || ferror(fp) || FreeFile(fp))
7182 (errcode_for_file_access(),
7183 errmsg("could not write file \"%s\": %m",
7187 * Close and remove the backup label file
7189 if (ferror(lfp) || FreeFile(lfp))
7191 (errcode_for_file_access(),
7192 errmsg("could not read file \"%s\": %m",
7193 BACKUP_LABEL_FILE)));
7194 if (unlink(BACKUP_LABEL_FILE) != 0)
7196 (errcode_for_file_access(),
7197 errmsg("could not remove file \"%s\": %m",
7198 BACKUP_LABEL_FILE)));
7201 * Clean out any no-longer-needed history files. As a side effect, this
7202 * will post a .ready file for the newly created history file, notifying
7203 * the archiver that history file may be archived immediately.
7205 CleanupBackupHistory();
7208 * Wait until both the last WAL file filled during backup and the history
7209 * file have been archived. We assume that the alphabetic sorting
7210 * property of the WAL files ensures any earlier WAL files are safely
7213 * We wait forever, since archive_command is supposed to work and
7214 * we assume the admin wanted his backup to work completely. If you
7215 * don't wish to wait, you can set statement_timeout.
7217 XLByteToPrevSeg(stoppoint, _logId, _logSeg);
7218 XLogFileName(lastxlogfilename, ThisTimeLineID, _logId, _logSeg);
7220 XLByteToSeg(startpoint, _logId, _logSeg);
7221 BackupHistoryFileName(histfilename, ThisTimeLineID, _logId, _logSeg,
7222 startpoint.xrecoff % XLogSegSize);
7224 seconds_before_warning = 60;
7227 while (XLogArchiveIsBusy(lastxlogfilename) ||
7228 XLogArchiveIsBusy(histfilename))
7230 CHECK_FOR_INTERRUPTS();
7232 pg_usleep(1000000L);
7234 if (++waits >= seconds_before_warning)
7236 seconds_before_warning *= 2; /* This wraps in >10 years... */
7238 (errmsg("pg_stop_backup still waiting for archive to complete (%d seconds elapsed)",
7244 * We're done. As a convenience, return the ending WAL location.
7246 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
7247 stoppoint.xlogid, stoppoint.xrecoff);
7248 PG_RETURN_TEXT_P(cstring_to_text(stopxlogfilename));
7252 * pg_switch_xlog: switch to next xlog file
7255 pg_switch_xlog(PG_FUNCTION_ARGS)
7257 XLogRecPtr switchpoint;
7258 char location[MAXFNAMELEN];
7262 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7263 (errmsg("must be superuser to switch transaction log files"))));
7265 switchpoint = RequestXLogSwitch();
7268 * As a convenience, return the WAL location of the switch record
7270 snprintf(location, sizeof(location), "%X/%X",
7271 switchpoint.xlogid, switchpoint.xrecoff);
7272 PG_RETURN_TEXT_P(cstring_to_text(location));
7276 * Report the current WAL write location (same format as pg_start_backup etc)
7278 * This is useful for determining how much of WAL is visible to an external
7279 * archiving process. Note that the data before this point is written out
7280 * to the kernel, but is not necessarily synced to disk.
7283 pg_current_xlog_location(PG_FUNCTION_ARGS)
7285 char location[MAXFNAMELEN];
7287 /* Make sure we have an up-to-date local LogwrtResult */
7289 /* use volatile pointer to prevent code rearrangement */
7290 volatile XLogCtlData *xlogctl = XLogCtl;
7292 SpinLockAcquire(&xlogctl->info_lck);
7293 LogwrtResult = xlogctl->LogwrtResult;
7294 SpinLockRelease(&xlogctl->info_lck);
7297 snprintf(location, sizeof(location), "%X/%X",
7298 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
7299 PG_RETURN_TEXT_P(cstring_to_text(location));
7303 * Report the current WAL insert location (same format as pg_start_backup etc)
7305 * This function is mostly for debugging purposes.
7308 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
7310 XLogCtlInsert *Insert = &XLogCtl->Insert;
7311 XLogRecPtr current_recptr;
7312 char location[MAXFNAMELEN];
7315 * Get the current end-of-WAL position ... shared lock is sufficient
7317 LWLockAcquire(WALInsertLock, LW_SHARED);
7318 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
7319 LWLockRelease(WALInsertLock);
7321 snprintf(location, sizeof(location), "%X/%X",
7322 current_recptr.xlogid, current_recptr.xrecoff);
7323 PG_RETURN_TEXT_P(cstring_to_text(location));
7327 * Compute an xlog file name and decimal byte offset given a WAL location,
7328 * such as is returned by pg_stop_backup() or pg_xlog_switch().
7330 * Note that a location exactly at a segment boundary is taken to be in
7331 * the previous segment. This is usually the right thing, since the
7332 * expected usage is to determine which xlog file(s) are ready to archive.
7335 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
7337 text *location = PG_GETARG_TEXT_P(0);
7339 unsigned int uxlogid;
7340 unsigned int uxrecoff;
7344 XLogRecPtr locationpoint;
7345 char xlogfilename[MAXFNAMELEN];
7348 TupleDesc resultTupleDesc;
7349 HeapTuple resultHeapTuple;
7353 * Read input and parse
7355 locationstr = text_to_cstring(location);
7357 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
7359 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7360 errmsg("could not parse transaction log location \"%s\"",
7363 locationpoint.xlogid = uxlogid;
7364 locationpoint.xrecoff = uxrecoff;
7367 * Construct a tuple descriptor for the result row. This must match this
7368 * function's pg_proc entry!
7370 resultTupleDesc = CreateTemplateTupleDesc(2, false);
7371 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
7373 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
7376 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
7381 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
7382 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
7384 values[0] = CStringGetTextDatum(xlogfilename);
7390 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
7392 values[1] = UInt32GetDatum(xrecoff);
7396 * Tuple jam: Having first prepared your Datums, then squash together
7398 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
7400 result = HeapTupleGetDatum(resultHeapTuple);
7402 PG_RETURN_DATUM(result);
7406 * Compute an xlog file name given a WAL location,
7407 * such as is returned by pg_stop_backup() or pg_xlog_switch().
7410 pg_xlogfile_name(PG_FUNCTION_ARGS)
7412 text *location = PG_GETARG_TEXT_P(0);
7414 unsigned int uxlogid;
7415 unsigned int uxrecoff;
7418 XLogRecPtr locationpoint;
7419 char xlogfilename[MAXFNAMELEN];
7421 locationstr = text_to_cstring(location);
7423 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
7425 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7426 errmsg("could not parse transaction log location \"%s\"",
7429 locationpoint.xlogid = uxlogid;
7430 locationpoint.xrecoff = uxrecoff;
7432 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
7433 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
7435 PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
7439 * read_backup_label: check to see if a backup_label file is present
7441 * If we see a backup_label during recovery, we assume that we are recovering
7442 * from a backup dump file, and we therefore roll forward from the checkpoint
7443 * identified by the label file, NOT what pg_control says. This avoids the
7444 * problem that pg_control might have been archived one or more checkpoints
7445 * later than the start of the dump, and so if we rely on it as the start
7446 * point, we will fail to restore a consistent database state.
7448 * We also attempt to retrieve the corresponding backup history file.
7449 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
7452 * Returns TRUE if a backup_label was found (and fills the checkpoint
7453 * location into *checkPointLoc); returns FALSE if not.
7456 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
7458 XLogRecPtr startpoint;
7459 XLogRecPtr stoppoint;
7460 char histfilename[MAXFNAMELEN];
7461 char histfilepath[MAXPGPATH];
7462 char startxlogfilename[MAXFNAMELEN];
7463 char stopxlogfilename[MAXFNAMELEN];
7471 /* Default is to not constrain recovery stop point */
7472 minRecoveryLoc->xlogid = 0;
7473 minRecoveryLoc->xrecoff = 0;
7476 * See if label file is present
7478 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
7481 if (errno != ENOENT)
7483 (errcode_for_file_access(),
7484 errmsg("could not read file \"%s\": %m",
7485 BACKUP_LABEL_FILE)));
7486 return false; /* it's not there, all is fine */
7490 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
7491 * is pretty crude, but we are not expecting any variability in the file
7494 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
7495 &startpoint.xlogid, &startpoint.xrecoff, &tli,
7496 startxlogfilename, &ch) != 5 || ch != '\n')
7498 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7499 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7500 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
7501 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
7502 &ch) != 3 || ch != '\n')
7504 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7505 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7506 if (ferror(lfp) || FreeFile(lfp))
7508 (errcode_for_file_access(),
7509 errmsg("could not read file \"%s\": %m",
7510 BACKUP_LABEL_FILE)));
7513 * Try to retrieve the backup history file (no error if we can't)
7515 XLByteToSeg(startpoint, _logId, _logSeg);
7516 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
7517 startpoint.xrecoff % XLogSegSize);
7519 if (InArchiveRecovery)
7520 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
7522 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
7523 startpoint.xrecoff % XLogSegSize);
7525 fp = AllocateFile(histfilepath, "r");
7529 * Parse history file to identify stop point.
7531 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
7532 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
7533 &ch) != 4 || ch != '\n')
7535 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7536 errmsg("invalid data in file \"%s\"", histfilename)));
7537 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
7538 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
7539 &ch) != 4 || ch != '\n')
7541 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7542 errmsg("invalid data in file \"%s\"", histfilename)));
7543 *minRecoveryLoc = stoppoint;
7544 if (ferror(fp) || FreeFile(fp))
7546 (errcode_for_file_access(),
7547 errmsg("could not read file \"%s\": %m",
7555 * Error context callback for errors occurring during rm_redo().
7558 rm_redo_error_callback(void *arg)
7560 XLogRecord *record = (XLogRecord *) arg;
7563 initStringInfo(&buf);
7564 RmgrTable[record->xl_rmid].rm_desc(&buf,
7566 XLogRecGetData(record));
7568 /* don't bother emitting empty description */
7570 errcontext("xlog redo %s", buf.data);
7576 * BackupInProgress: check if online backup mode is active
7578 * This is done by checking for existence of the "backup_label" file.
7581 BackupInProgress(void)
7583 struct stat stat_buf;
7585 return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
7589 * CancelBackup: rename the "backup_label" file to cancel backup mode
7591 * If the "backup_label" file exists, it will be renamed to "backup_label.old".
7592 * Note that this will render an online backup in progress useless.
7593 * To correctly finish an online backup, pg_stop_backup must be called.
7598 struct stat stat_buf;
7600 /* if the file is not there, return */
7601 if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
7604 /* remove leftover file from previously cancelled backup if it exists */
7605 unlink(BACKUP_LABEL_OLD);
7607 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) == 0)
7610 (errmsg("online backup mode cancelled"),
7611 errdetail("\"%s\" was renamed to \"%s\".",
7612 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
7617 (errcode_for_file_access(),
7618 errmsg("online backup mode was not cancelled"),
7619 errdetail("Could not rename \"%s\" to \"%s\": %m.",
7620 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
7624 /* ------------------------------------------------------
7625 * Startup Process main entry point and signal handlers
7626 * ------------------------------------------------------
7630 * startupproc_quickdie() occurs when signalled SIGQUIT by the postmaster.
7632 * Some backend has bought the farm,
7633 * so we need to stop what we're doing and exit.
7636 startupproc_quickdie(SIGNAL_ARGS)
7638 PG_SETMASK(&BlockSig);
7641 * DO NOT proc_exit() -- we're here because shared memory may be
7642 * corrupted, so we don't want to try to clean up our transaction. Just
7643 * nail the windows shut and get out of town.
7645 * Note we do exit(2) not exit(0). This is to force the postmaster into a
7646 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
7647 * backend. This is necessary precisely because we don't clean up our
7648 * shared memory state.
7654 /* SIGHUP: set flag to re-read config file at next convenient time */
7656 StartupProcSigHupHandler(SIGNAL_ARGS)
7661 /* SIGTERM: set flag to abort redo and exit */
7663 StartupProcShutdownHandler(SIGNAL_ARGS)
7665 if (in_restore_command)
7668 shutdown_requested = true;
7671 /* Main entry point for startup process */
7673 StartupProcessMain(void)
7676 * If possible, make this process a group leader, so that the postmaster
7677 * can signal any child processes too.
7681 elog(FATAL, "setsid() failed: %m");
7685 * Properly accept or ignore signals the postmaster might send us
7687 pqsignal(SIGHUP, StartupProcSigHupHandler); /* reload config file */
7688 pqsignal(SIGINT, SIG_IGN); /* ignore query cancel */
7689 pqsignal(SIGTERM, StartupProcShutdownHandler); /* request shutdown */
7690 pqsignal(SIGQUIT, startupproc_quickdie); /* hard crash time */
7691 pqsignal(SIGALRM, SIG_IGN);
7692 pqsignal(SIGPIPE, SIG_IGN);
7693 pqsignal(SIGUSR1, SIG_IGN);
7694 pqsignal(SIGUSR2, SIG_IGN);
7697 * Reset some signals that are accepted by postmaster but not here
7699 pqsignal(SIGCHLD, SIG_DFL);
7700 pqsignal(SIGTTIN, SIG_DFL);
7701 pqsignal(SIGTTOU, SIG_DFL);
7702 pqsignal(SIGCONT, SIG_DFL);
7703 pqsignal(SIGWINCH, SIG_DFL);
7706 * Unblock signals (they were blocked when the postmaster forked us)
7708 PG_SETMASK(&UnBlockSig);
7712 BuildFlatFiles(false);
7715 * Exit normally. Exit code 0 tells postmaster that we completed
7716 * recovery successfully.