1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/access/transam/xlog.c,v 1.280 2007/09/05 18:10:47 tgl Exp $
12 *-------------------------------------------------------------------------
26 #include "access/clog.h"
27 #include "access/heapam.h"
28 #include "access/multixact.h"
29 #include "access/subtrans.h"
30 #include "access/transam.h"
31 #include "access/tuptoaster.h"
32 #include "access/twophase.h"
33 #include "access/xact.h"
34 #include "access/xlog_internal.h"
35 #include "access/xlogdefs.h"
36 #include "access/xlogutils.h"
37 #include "catalog/catversion.h"
38 #include "catalog/pg_control.h"
39 #include "catalog/pg_type.h"
41 #include "miscadmin.h"
43 #include "postmaster/bgwriter.h"
44 #include "storage/bufpage.h"
45 #include "storage/fd.h"
46 #include "storage/pmsignal.h"
47 #include "storage/procarray.h"
48 #include "storage/spin.h"
49 #include "utils/builtins.h"
50 #include "utils/pg_locale.h"
54 /* File path names (all relative to $PGDATA) */
55 #define BACKUP_LABEL_FILE "backup_label"
56 #define BACKUP_LABEL_OLD "backup_label.old"
57 #define RECOVERY_COMMAND_FILE "recovery.conf"
58 #define RECOVERY_COMMAND_DONE "recovery.done"
61 /* User-settable parameters */
62 int CheckPointSegments = 3;
64 int XLogArchiveTimeout = 0;
65 char *XLogArchiveCommand = NULL;
66 char *XLOG_sync_method = NULL;
67 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
68 bool fullPageWrites = true;
69 bool log_checkpoints = false;
72 bool XLOG_DEBUG = false;
76 * XLOGfileslop is the maximum number of preallocated future XLOG segments.
77 * When we are done with an old XLOG segment file, we will recycle it as a
78 * future XLOG segment as long as there aren't already XLOGfileslop future
79 * segments; else we'll delete it. This could be made a separate GUC
80 * variable, but at present I think it's sufficient to hardwire it as
81 * 2*CheckPointSegments+1. Under normal conditions, a checkpoint will free
82 * no more than 2*CheckPointSegments log segments, and we want to recycle all
83 * of them; the +1 allows boundary cases to happen without wasting a
84 * delete/create-segment cycle.
86 #define XLOGfileslop (2*CheckPointSegments + 1)
89 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
90 int sync_method = DEFAULT_SYNC_METHOD;
91 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
93 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
97 * Statistics for current checkpoint are collected in this global struct.
98 * Because only the background writer or a stand-alone backend can perform
99 * checkpoints, this will be unused in normal backends.
101 CheckpointStatsData CheckpointStats;
104 * ThisTimeLineID will be same in all backends --- it identifies current
105 * WAL timeline for the database system.
107 TimeLineID ThisTimeLineID = 0;
109 /* Are we doing recovery from XLOG? */
110 bool InRecovery = false;
112 /* Are we recovering using offline XLOG archives? */
113 static bool InArchiveRecovery = false;
115 /* Was the last xlog file restored from archive, or local? */
116 static bool restoredFromArchive = false;
118 /* options taken from recovery.conf */
119 static char *recoveryRestoreCommand = NULL;
120 static bool recoveryTarget = false;
121 static bool recoveryTargetExact = false;
122 static bool recoveryTargetInclusive = true;
123 static TransactionId recoveryTargetXid;
124 static TimestampTz recoveryTargetTime;
126 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
127 static TransactionId recoveryStopXid;
128 static TimestampTz recoveryStopTime;
129 static bool recoveryStopAfter;
132 * During normal operation, the only timeline we care about is ThisTimeLineID.
133 * During recovery, however, things are more complicated. To simplify life
134 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
135 * scan through the WAL history (that is, it is the line that was active when
136 * the currently-scanned WAL record was generated). We also need these
139 * recoveryTargetTLI: the desired timeline that we want to end in.
141 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
142 * its known parents, newest first (so recoveryTargetTLI is always the
143 * first list member). Only these TLIs are expected to be seen in the WAL
144 * segments we read, and indeed only these TLIs will be considered as
145 * candidate WAL files to open at all.
147 * curFileTLI: the TLI appearing in the name of the current input WAL file.
148 * (This is not necessarily the same as ThisTimeLineID, because we could
149 * be scanning data that was copied from an ancestor timeline when the current
150 * file was created.) During a sequential scan we do not allow this value
153 static TimeLineID recoveryTargetTLI;
154 static List *expectedTLIs;
155 static TimeLineID curFileTLI;
158 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
159 * current backend. It is updated for all inserts. XactLastRecEnd points to
160 * end+1 of the last record, and is reset when we end a top-level transaction,
161 * or start a new one; so it can be used to tell if the current transaction has
162 * created any XLOG records.
164 static XLogRecPtr ProcLastRecPtr = {0, 0};
166 XLogRecPtr XactLastRecEnd = {0, 0};
169 * RedoRecPtr is this backend's local copy of the REDO record pointer
170 * (which is almost but not quite the same as a pointer to the most recent
171 * CHECKPOINT record). We update this from the shared-memory copy,
172 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
173 * hold the Insert lock). See XLogInsert for details. We are also allowed
174 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
175 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
178 static XLogRecPtr RedoRecPtr;
181 * Shared-memory data structures for XLOG control
183 * LogwrtRqst indicates a byte position that we need to write and/or fsync
184 * the log up to (all records before that point must be written or fsynced).
185 * LogwrtResult indicates the byte positions we have already written/fsynced.
186 * These structs are identical but are declared separately to indicate their
187 * slightly different functions.
189 * We do a lot of pushups to minimize the amount of access to lockable
190 * shared memory values. There are actually three shared-memory copies of
191 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
192 * XLogCtl->LogwrtResult is protected by info_lck
193 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
194 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
195 * One must hold the associated lock to read or write any of these, but
196 * of course no lock is needed to read/write the unshared LogwrtResult.
198 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
199 * right", since both are updated by a write or flush operation before
200 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
201 * is that it can be examined/modified by code that already holds WALWriteLock
202 * without needing to grab info_lck as well.
204 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
205 * but is updated when convenient. Again, it exists for the convenience of
206 * code that is already holding WALInsertLock but not the other locks.
208 * The unshared LogwrtResult may lag behind any or all of these, and again
209 * is updated when convenient.
211 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
212 * (protected by info_lck), but we don't need to cache any copies of it.
214 * Note that this all works because the request and result positions can only
215 * advance forward, never back up, and so we can easily determine which of two
216 * values is "more up to date".
218 * info_lck is only held long enough to read/update the protected variables,
219 * so it's a plain spinlock. The other locks are held longer (potentially
220 * over I/O operations), so we use LWLocks for them. These locks are:
222 * WALInsertLock: must be held to insert a record into the WAL buffers.
224 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
227 * ControlFileLock: must be held to read/update control file or create
230 * CheckpointLock: must be held to do a checkpoint (ensures only one
231 * checkpointer at a time; currently, with all checkpoints done by the
232 * bgwriter, this is just pro forma).
237 typedef struct XLogwrtRqst
239 XLogRecPtr Write; /* last byte + 1 to write out */
240 XLogRecPtr Flush; /* last byte + 1 to flush */
243 typedef struct XLogwrtResult
245 XLogRecPtr Write; /* last byte + 1 written out */
246 XLogRecPtr Flush; /* last byte + 1 flushed */
250 * Shared state data for XLogInsert.
252 typedef struct XLogCtlInsert
254 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
255 XLogRecPtr PrevRecord; /* start of previously-inserted record */
256 int curridx; /* current block index in cache */
257 XLogPageHeader currpage; /* points to header of block in cache */
258 char *currpos; /* current insertion point in cache */
259 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
260 bool forcePageWrites; /* forcing full-page writes for PITR? */
264 * Shared state data for XLogWrite/XLogFlush.
266 typedef struct XLogCtlWrite
268 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
269 int curridx; /* cache index of next block to write */
270 time_t lastSegSwitchTime; /* time of last xlog segment switch */
274 * Total shared-memory state for XLOG.
276 typedef struct XLogCtlData
278 /* Protected by WALInsertLock: */
279 XLogCtlInsert Insert;
281 /* Protected by info_lck: */
282 XLogwrtRqst LogwrtRqst;
283 XLogwrtResult LogwrtResult;
284 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
285 TransactionId ckptXid;
286 XLogRecPtr asyncCommitLSN; /* LSN of newest async commit */
288 /* Protected by WALWriteLock: */
292 * These values do not change after startup, although the pointed-to pages
293 * and xlblocks values certainly do. Permission to read/write the pages
294 * and xlblocks values depends on WALInsertLock and WALWriteLock.
296 char *pages; /* buffers for unwritten XLOG pages */
297 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
298 Size XLogCacheByte; /* # bytes in xlog buffers */
299 int XLogCacheBlck; /* highest allocated xlog buffer index */
300 TimeLineID ThisTimeLineID;
302 slock_t info_lck; /* locks shared variables shown above */
305 static XLogCtlData *XLogCtl = NULL;
308 * We maintain an image of pg_control in shared memory.
310 static ControlFileData *ControlFile = NULL;
313 * Macros for managing XLogInsert state. In most cases, the calling routine
314 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
315 * so these are passed as parameters instead of being fetched via XLogCtl.
318 /* Free space remaining in the current xlog page buffer */
319 #define INSERT_FREESPACE(Insert) \
320 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
322 /* Construct XLogRecPtr value for current insertion point */
323 #define INSERT_RECPTR(recptr,Insert,curridx) \
325 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
327 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
330 #define PrevBufIdx(idx) \
331 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
333 #define NextBufIdx(idx) \
334 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
337 * Private, possibly out-of-date copy of shared LogwrtResult.
338 * See discussion above.
340 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
343 * openLogFile is -1 or a kernel FD for an open log file segment.
344 * When it's open, openLogOff is the current seek offset in the file.
345 * openLogId/openLogSeg identify the segment. These variables are only
346 * used to write the XLOG, and so will normally refer to the active segment.
348 static int openLogFile = -1;
349 static uint32 openLogId = 0;
350 static uint32 openLogSeg = 0;
351 static uint32 openLogOff = 0;
354 * These variables are used similarly to the ones above, but for reading
355 * the XLOG. Note, however, that readOff generally represents the offset
356 * of the page just read, not the seek position of the FD itself, which
357 * will be just past that page.
359 static int readFile = -1;
360 static uint32 readId = 0;
361 static uint32 readSeg = 0;
362 static uint32 readOff = 0;
364 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
365 static char *readBuf = NULL;
367 /* Buffer for current ReadRecord result (expandable) */
368 static char *readRecordBuf = NULL;
369 static uint32 readRecordBufSize = 0;
371 /* State information for XLOG reading */
372 static XLogRecPtr ReadRecPtr; /* start of last record read */
373 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
374 static XLogRecord *nextRecord = NULL;
375 static TimeLineID lastPageTLI = 0;
377 static bool InRedo = false;
380 static void XLogArchiveNotify(const char *xlog);
381 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
382 static bool XLogArchiveCheckDone(const char *xlog);
383 static void XLogArchiveCleanup(const char *xlog);
384 static void readRecoveryCommandFile(void);
385 static void exitArchiveRecovery(TimeLineID endTLI,
386 uint32 endLogId, uint32 endLogSeg);
387 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
388 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
390 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
391 XLogRecPtr *lsn, BkpBlock *bkpb);
392 static bool AdvanceXLInsertBuffer(bool new_segment);
393 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
394 static int XLogFileInit(uint32 log, uint32 seg,
395 bool *use_existent, bool use_lock);
396 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
397 bool find_free, int *max_advance,
399 static int XLogFileOpen(uint32 log, uint32 seg);
400 static int XLogFileRead(uint32 log, uint32 seg, int emode);
401 static void XLogFileClose(void);
402 static bool RestoreArchivedFile(char *path, const char *xlogfname,
403 const char *recovername, off_t expectedSize);
404 static void PreallocXlogFiles(XLogRecPtr endptr);
405 static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
406 static void CleanupBackupHistory(void);
407 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
408 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
409 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
410 static List *readTimeLineHistory(TimeLineID targetTLI);
411 static bool existsTimeLineHistory(TimeLineID probeTLI);
412 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
413 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
415 uint32 endLogId, uint32 endLogSeg);
416 static void WriteControlFile(void);
417 static void ReadControlFile(void);
418 static char *str_time(pg_time_t tnow);
419 static void issue_xlog_fsync(void);
422 static void xlog_outrec(StringInfo buf, XLogRecord *record);
424 static bool read_backup_label(XLogRecPtr *checkPointLoc,
425 XLogRecPtr *minRecoveryLoc);
426 static void rm_redo_error_callback(void *arg);
430 * Insert an XLOG record having the specified RMID and info bytes,
431 * with the body of the record being the data chunk(s) described by
432 * the rdata chain (see xlog.h for notes about rdata).
434 * Returns XLOG pointer to end of record (beginning of next record).
435 * This can be used as LSN for data pages affected by the logged action.
436 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
437 * before the data page can be written out. This implements the basic
438 * WAL rule "write the log before the data".)
440 * NB: this routine feels free to scribble on the XLogRecData structs,
441 * though not on the data they reference. This is OK since the XLogRecData
442 * structs are always just temporaries in the calling code.
445 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
447 XLogCtlInsert *Insert = &XLogCtl->Insert;
449 XLogContRecord *contrecord;
451 XLogRecPtr WriteRqst;
455 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
456 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
457 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
458 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
459 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
460 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
461 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
468 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
470 /* info's high bits are reserved for use by me */
471 if (info & XLR_INFO_MASK)
472 elog(PANIC, "invalid xlog info mask %02X", info);
475 * In bootstrap mode, we don't actually log anything but XLOG resources;
476 * return a phony record pointer.
478 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
481 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
486 * Here we scan the rdata chain, determine which buffers must be backed
487 * up, and compute the CRC values for the data. Note that the record
488 * header isn't added into the CRC initially since we don't know the final
489 * length or info bits quite yet. Thus, the CRC will represent the CRC of
490 * the whole record in the order "rdata, then backup blocks, then record
493 * We may have to loop back to here if a race condition is detected below.
494 * We could prevent the race by doing all this work while holding the
495 * insert lock, but it seems better to avoid doing CRC calculations while
496 * holding the lock. This means we have to be careful about modifying the
497 * rdata chain until we know we aren't going to loop back again. The only
498 * change we allow ourselves to make earlier is to set rdt->data = NULL in
499 * chain items we have decided we will have to back up the whole buffer
500 * for. This is OK because we will certainly decide the same thing again
501 * for those items if we do it over; doing it here saves an extra pass
502 * over the chain later.
505 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
507 dtbuf[i] = InvalidBuffer;
508 dtbuf_bkp[i] = false;
512 * Decide if we need to do full-page writes in this XLOG record: true if
513 * full_page_writes is on or we have a PITR request for it. Since we
514 * don't yet have the insert lock, forcePageWrites could change under us,
515 * but we'll recheck it once we have the lock.
517 doPageWrites = fullPageWrites || Insert->forcePageWrites;
519 INIT_CRC32(rdata_crc);
523 if (rdt->buffer == InvalidBuffer)
525 /* Simple data, just include it */
527 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
531 /* Find info for buffer */
532 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
534 if (rdt->buffer == dtbuf[i])
536 /* Buffer already referenced by earlier chain item */
542 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
546 if (dtbuf[i] == InvalidBuffer)
548 /* OK, put it in this slot */
549 dtbuf[i] = rdt->buffer;
550 if (XLogCheckBuffer(rdt, doPageWrites,
551 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
559 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
564 if (i >= XLR_MAX_BKP_BLOCKS)
565 elog(PANIC, "can backup at most %d blocks per xlog record",
568 /* Break out of loop when rdt points to last chain item */
569 if (rdt->next == NULL)
575 * Now add the backup block headers and data into the CRC
577 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
581 BkpBlock *bkpb = &(dtbuf_xlg[i]);
584 COMP_CRC32(rdata_crc,
587 page = (char *) BufferGetBlock(dtbuf[i]);
588 if (bkpb->hole_length == 0)
590 COMP_CRC32(rdata_crc,
596 /* must skip the hole */
597 COMP_CRC32(rdata_crc,
600 COMP_CRC32(rdata_crc,
601 page + (bkpb->hole_offset + bkpb->hole_length),
602 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
608 * NOTE: We disallow len == 0 because it provides a useful bit of extra
609 * error checking in ReadRecord. This means that all callers of
610 * XLogInsert must supply at least some not-in-a-buffer data. However, we
611 * make an exception for XLOG SWITCH records because we don't want them to
612 * ever cross a segment boundary.
614 if (len == 0 && !isLogSwitch)
615 elog(PANIC, "invalid xlog record length %u", len);
617 START_CRIT_SECTION();
619 /* Now wait to get insert lock */
620 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
623 * Check to see if my RedoRecPtr is out of date. If so, may have to go
624 * back and recompute everything. This can only happen just after a
625 * checkpoint, so it's better to be slow in this case and fast otherwise.
627 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
628 * affect the contents of the XLOG record, so we'll update our local copy
629 * but not force a recomputation.
631 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
633 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
634 RedoRecPtr = Insert->RedoRecPtr;
638 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
640 if (dtbuf[i] == InvalidBuffer)
642 if (dtbuf_bkp[i] == false &&
643 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
646 * Oops, this buffer now needs to be backed up, but we
647 * didn't think so above. Start over.
649 LWLockRelease(WALInsertLock);
658 * Also check to see if forcePageWrites was just turned on; if we weren't
659 * already doing full-page writes then go back and recompute. (If it was
660 * just turned off, we could recompute the record without full pages, but
661 * we choose not to bother.)
663 if (Insert->forcePageWrites && !doPageWrites)
665 /* Oops, must redo it with full-page data */
666 LWLockRelease(WALInsertLock);
672 * Make additional rdata chain entries for the backup blocks, so that we
673 * don't need to special-case them in the write loop. Note that we have
674 * now irrevocably changed the input rdata chain. At the exit of this
675 * loop, write_len includes the backup block data.
677 * Also set the appropriate info bits to show which buffers were backed
678 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
679 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
682 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
690 info |= XLR_SET_BKP_BLOCK(i);
692 bkpb = &(dtbuf_xlg[i]);
693 page = (char *) BufferGetBlock(dtbuf[i]);
695 rdt->next = &(dtbuf_rdt1[i]);
698 rdt->data = (char *) bkpb;
699 rdt->len = sizeof(BkpBlock);
700 write_len += sizeof(BkpBlock);
702 rdt->next = &(dtbuf_rdt2[i]);
705 if (bkpb->hole_length == 0)
714 /* must skip the hole */
716 rdt->len = bkpb->hole_offset;
717 write_len += bkpb->hole_offset;
719 rdt->next = &(dtbuf_rdt3[i]);
722 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
723 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
724 write_len += rdt->len;
730 * If we backed up any full blocks and online backup is not in progress,
731 * mark the backup blocks as removable. This allows the WAL archiver to
732 * know whether it is safe to compress archived WAL data by transforming
733 * full-block records into the non-full-block format.
735 * Note: we could just set the flag whenever !forcePageWrites, but
736 * defining it like this leaves the info bit free for some potential
737 * other use in records without any backup blocks.
739 if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
740 info |= XLR_BKP_REMOVABLE;
743 * If there isn't enough space on the current XLOG page for a record
744 * header, advance to the next page (leaving the unused space as zeroes).
747 freespace = INSERT_FREESPACE(Insert);
748 if (freespace < SizeOfXLogRecord)
750 updrqst = AdvanceXLInsertBuffer(false);
751 freespace = INSERT_FREESPACE(Insert);
754 /* Compute record's XLOG location */
755 curridx = Insert->curridx;
756 INSERT_RECPTR(RecPtr, Insert, curridx);
759 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
760 * segment, we need not insert it (and don't want to because we'd like
761 * consecutive switch requests to be no-ops). Instead, make sure
762 * everything is written and flushed through the end of the prior segment,
763 * and return the prior segment's end address.
766 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
768 /* We can release insert lock immediately */
769 LWLockRelease(WALInsertLock);
771 RecPtr.xrecoff -= SizeOfXLogLongPHD;
772 if (RecPtr.xrecoff == 0)
774 /* crossing a logid boundary */
776 RecPtr.xrecoff = XLogFileSize;
779 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
780 LogwrtResult = XLogCtl->Write.LogwrtResult;
781 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
783 XLogwrtRqst FlushRqst;
785 FlushRqst.Write = RecPtr;
786 FlushRqst.Flush = RecPtr;
787 XLogWrite(FlushRqst, false, false);
789 LWLockRelease(WALWriteLock);
796 /* Insert record header */
798 record = (XLogRecord *) Insert->currpos;
799 record->xl_prev = Insert->PrevRecord;
800 record->xl_xid = GetCurrentTransactionIdIfAny();
801 record->xl_tot_len = SizeOfXLogRecord + write_len;
802 record->xl_len = len; /* doesn't include backup blocks */
803 record->xl_info = info;
804 record->xl_rmid = rmid;
806 /* Now we can finish computing the record's CRC */
807 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
808 SizeOfXLogRecord - sizeof(pg_crc32));
809 FIN_CRC32(rdata_crc);
810 record->xl_crc = rdata_crc;
817 initStringInfo(&buf);
818 appendStringInfo(&buf, "INSERT @ %X/%X: ",
819 RecPtr.xlogid, RecPtr.xrecoff);
820 xlog_outrec(&buf, record);
821 if (rdata->data != NULL)
823 appendStringInfo(&buf, " - ");
824 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
826 elog(LOG, "%s", buf.data);
831 /* Record begin of record in appropriate places */
832 ProcLastRecPtr = RecPtr;
833 Insert->PrevRecord = RecPtr;
835 Insert->currpos += SizeOfXLogRecord;
836 freespace -= SizeOfXLogRecord;
839 * Append the data, including backup blocks if any
843 while (rdata->data == NULL)
848 if (rdata->len > freespace)
850 memcpy(Insert->currpos, rdata->data, freespace);
851 rdata->data += freespace;
852 rdata->len -= freespace;
853 write_len -= freespace;
857 memcpy(Insert->currpos, rdata->data, rdata->len);
858 freespace -= rdata->len;
859 write_len -= rdata->len;
860 Insert->currpos += rdata->len;
866 /* Use next buffer */
867 updrqst = AdvanceXLInsertBuffer(false);
868 curridx = Insert->curridx;
869 /* Insert cont-record header */
870 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
871 contrecord = (XLogContRecord *) Insert->currpos;
872 contrecord->xl_rem_len = write_len;
873 Insert->currpos += SizeOfXLogContRecord;
874 freespace = INSERT_FREESPACE(Insert);
877 /* Ensure next record will be properly aligned */
878 Insert->currpos = (char *) Insert->currpage +
879 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
880 freespace = INSERT_FREESPACE(Insert);
883 * The recptr I return is the beginning of the *next* record. This will be
884 * stored as LSN for changed data pages...
886 INSERT_RECPTR(RecPtr, Insert, curridx);
889 * If the record is an XLOG_SWITCH, we must now write and flush all the
890 * existing data, and then forcibly advance to the start of the next
891 * segment. It's not good to do this I/O while holding the insert lock,
892 * but there seems too much risk of confusion if we try to release the
893 * lock sooner. Fortunately xlog switch needn't be a high-performance
894 * operation anyway...
898 XLogCtlWrite *Write = &XLogCtl->Write;
899 XLogwrtRqst FlushRqst;
900 XLogRecPtr OldSegEnd;
902 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
905 * Flush through the end of the page containing XLOG_SWITCH, and
906 * perform end-of-segment actions (eg, notifying archiver).
908 WriteRqst = XLogCtl->xlblocks[curridx];
909 FlushRqst.Write = WriteRqst;
910 FlushRqst.Flush = WriteRqst;
911 XLogWrite(FlushRqst, false, true);
913 /* Set up the next buffer as first page of next segment */
914 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
915 (void) AdvanceXLInsertBuffer(true);
917 /* There should be no unwritten data */
918 curridx = Insert->curridx;
919 Assert(curridx == Write->curridx);
921 /* Compute end address of old segment */
922 OldSegEnd = XLogCtl->xlblocks[curridx];
923 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
924 if (OldSegEnd.xrecoff == 0)
926 /* crossing a logid boundary */
927 OldSegEnd.xlogid -= 1;
928 OldSegEnd.xrecoff = XLogFileSize;
931 /* Make it look like we've written and synced all of old segment */
932 LogwrtResult.Write = OldSegEnd;
933 LogwrtResult.Flush = OldSegEnd;
936 * Update shared-memory status --- this code should match XLogWrite
939 /* use volatile pointer to prevent code rearrangement */
940 volatile XLogCtlData *xlogctl = XLogCtl;
942 SpinLockAcquire(&xlogctl->info_lck);
943 xlogctl->LogwrtResult = LogwrtResult;
944 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
945 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
946 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
947 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
948 SpinLockRelease(&xlogctl->info_lck);
951 Write->LogwrtResult = LogwrtResult;
953 LWLockRelease(WALWriteLock);
955 updrqst = false; /* done already */
959 /* normal case, ie not xlog switch */
961 /* Need to update shared LogwrtRqst if some block was filled up */
962 if (freespace < SizeOfXLogRecord)
964 /* curridx is filled and available for writing out */
969 /* if updrqst already set, write through end of previous buf */
970 curridx = PrevBufIdx(curridx);
972 WriteRqst = XLogCtl->xlblocks[curridx];
975 LWLockRelease(WALInsertLock);
979 /* use volatile pointer to prevent code rearrangement */
980 volatile XLogCtlData *xlogctl = XLogCtl;
982 SpinLockAcquire(&xlogctl->info_lck);
983 /* advance global request to include new block(s) */
984 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
985 xlogctl->LogwrtRqst.Write = WriteRqst;
986 /* update local result copy while I have the chance */
987 LogwrtResult = xlogctl->LogwrtResult;
988 SpinLockRelease(&xlogctl->info_lck);
991 XactLastRecEnd = RecPtr;
999 * Determine whether the buffer referenced by an XLogRecData item has to
1000 * be backed up, and if so fill a BkpBlock struct for it. In any case
1001 * save the buffer's LSN at *lsn.
1004 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1005 XLogRecPtr *lsn, BkpBlock *bkpb)
1009 page = (PageHeader) BufferGetBlock(rdata->buffer);
1012 * XXX We assume page LSN is first data on *every* page that can be passed
1013 * to XLogInsert, whether it otherwise has the standard page layout or
1016 *lsn = page->pd_lsn;
1019 XLByteLE(page->pd_lsn, RedoRecPtr))
1022 * The page needs to be backed up, so set up *bkpb
1024 bkpb->node = BufferGetFileNode(rdata->buffer);
1025 bkpb->block = BufferGetBlockNumber(rdata->buffer);
1027 if (rdata->buffer_std)
1029 /* Assume we can omit data between pd_lower and pd_upper */
1030 uint16 lower = page->pd_lower;
1031 uint16 upper = page->pd_upper;
1033 if (lower >= SizeOfPageHeaderData &&
1037 bkpb->hole_offset = lower;
1038 bkpb->hole_length = upper - lower;
1042 /* No "hole" to compress out */
1043 bkpb->hole_offset = 0;
1044 bkpb->hole_length = 0;
1049 /* Not a standard page header, don't try to eliminate "hole" */
1050 bkpb->hole_offset = 0;
1051 bkpb->hole_length = 0;
1054 return true; /* buffer requires backup */
1057 return false; /* buffer does not need to be backed up */
1063 * Create an archive notification file
1065 * The name of the notification file is the message that will be picked up
1066 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1067 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1068 * then when complete, rename it to 0000000100000001000000C6.done
1071 XLogArchiveNotify(const char *xlog)
1073 char archiveStatusPath[MAXPGPATH];
1076 /* insert an otherwise empty file called <XLOG>.ready */
1077 StatusFilePath(archiveStatusPath, xlog, ".ready");
1078 fd = AllocateFile(archiveStatusPath, "w");
1082 (errcode_for_file_access(),
1083 errmsg("could not create archive status file \"%s\": %m",
1084 archiveStatusPath)));
1090 (errcode_for_file_access(),
1091 errmsg("could not write archive status file \"%s\": %m",
1092 archiveStatusPath)));
1096 /* Notify archiver that it's got something to do */
1097 if (IsUnderPostmaster)
1098 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1102 * Convenience routine to notify using log/seg representation of filename
1105 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1107 char xlog[MAXFNAMELEN];
1109 XLogFileName(xlog, ThisTimeLineID, log, seg);
1110 XLogArchiveNotify(xlog);
1114 * XLogArchiveCheckDone
1116 * This is called when we are ready to delete or recycle an old XLOG segment
1117 * file or backup history file. If it is okay to delete it then return true.
1118 * If it is not time to delete it, make sure a .ready file exists, and return
1121 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1122 * then return false; else create <XLOG>.ready and return false.
1124 * The reason we do things this way is so that if the original attempt to
1125 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1128 XLogArchiveCheckDone(const char *xlog)
1130 char archiveStatusPath[MAXPGPATH];
1131 struct stat stat_buf;
1133 /* Always deletable if archiving is off */
1134 if (!XLogArchivingActive())
1137 /* First check for .done --- this means archiver is done with it */
1138 StatusFilePath(archiveStatusPath, xlog, ".done");
1139 if (stat(archiveStatusPath, &stat_buf) == 0)
1142 /* check for .ready --- this means archiver is still busy with it */
1143 StatusFilePath(archiveStatusPath, xlog, ".ready");
1144 if (stat(archiveStatusPath, &stat_buf) == 0)
1147 /* Race condition --- maybe archiver just finished, so recheck */
1148 StatusFilePath(archiveStatusPath, xlog, ".done");
1149 if (stat(archiveStatusPath, &stat_buf) == 0)
1152 /* Retry creation of the .ready file */
1153 XLogArchiveNotify(xlog);
1158 * XLogArchiveCleanup
1160 * Cleanup archive notification file(s) for a particular xlog segment
1163 XLogArchiveCleanup(const char *xlog)
1165 char archiveStatusPath[MAXPGPATH];
1167 /* Remove the .done file */
1168 StatusFilePath(archiveStatusPath, xlog, ".done");
1169 unlink(archiveStatusPath);
1170 /* should we complain about failure? */
1172 /* Remove the .ready file if present --- normally it shouldn't be */
1173 StatusFilePath(archiveStatusPath, xlog, ".ready");
1174 unlink(archiveStatusPath);
1175 /* should we complain about failure? */
1179 * Advance the Insert state to the next buffer page, writing out the next
1180 * buffer if it still contains unwritten data.
1182 * If new_segment is TRUE then we set up the next buffer page as the first
1183 * page of the next xlog segment file, possibly but not usually the next
1184 * consecutive file page.
1186 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1187 * just-filled page. If we can do this for free (without an extra lock),
1188 * we do so here. Otherwise the caller must do it. We return TRUE if the
1189 * request update still needs to be done, FALSE if we did it internally.
1191 * Must be called with WALInsertLock held.
1194 AdvanceXLInsertBuffer(bool new_segment)
1196 XLogCtlInsert *Insert = &XLogCtl->Insert;
1197 XLogCtlWrite *Write = &XLogCtl->Write;
1198 int nextidx = NextBufIdx(Insert->curridx);
1199 bool update_needed = true;
1200 XLogRecPtr OldPageRqstPtr;
1201 XLogwrtRqst WriteRqst;
1202 XLogRecPtr NewPageEndPtr;
1203 XLogPageHeader NewPage;
1205 /* Use Insert->LogwrtResult copy if it's more fresh */
1206 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1207 LogwrtResult = Insert->LogwrtResult;
1210 * Get ending-offset of the buffer page we need to replace (this may be
1211 * zero if the buffer hasn't been used yet). Fall through if it's already
1214 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1215 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1217 /* nope, got work to do... */
1218 XLogRecPtr FinishedPageRqstPtr;
1220 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1222 /* Before waiting, get info_lck and update LogwrtResult */
1224 /* use volatile pointer to prevent code rearrangement */
1225 volatile XLogCtlData *xlogctl = XLogCtl;
1227 SpinLockAcquire(&xlogctl->info_lck);
1228 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1229 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1230 LogwrtResult = xlogctl->LogwrtResult;
1231 SpinLockRelease(&xlogctl->info_lck);
1234 update_needed = false; /* Did the shared-request update */
1236 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1238 /* OK, someone wrote it already */
1239 Insert->LogwrtResult = LogwrtResult;
1243 /* Must acquire write lock */
1244 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1245 LogwrtResult = Write->LogwrtResult;
1246 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1248 /* OK, someone wrote it already */
1249 LWLockRelease(WALWriteLock);
1250 Insert->LogwrtResult = LogwrtResult;
1255 * Have to write buffers while holding insert lock. This is
1256 * not good, so only write as much as we absolutely must.
1258 WriteRqst.Write = OldPageRqstPtr;
1259 WriteRqst.Flush.xlogid = 0;
1260 WriteRqst.Flush.xrecoff = 0;
1261 XLogWrite(WriteRqst, false, false);
1262 LWLockRelease(WALWriteLock);
1263 Insert->LogwrtResult = LogwrtResult;
1269 * Now the next buffer slot is free and we can set it up to be the next
1272 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1276 /* force it to a segment start point */
1277 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1278 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1281 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1283 /* crossing a logid boundary */
1284 NewPageEndPtr.xlogid += 1;
1285 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1288 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1289 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1290 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1292 Insert->curridx = nextidx;
1293 Insert->currpage = NewPage;
1295 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1298 * Be sure to re-zero the buffer so that bytes beyond what we've written
1299 * will look like zeroes and not valid XLOG records...
1301 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1304 * Fill the new page's header
1306 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1308 /* NewPage->xlp_info = 0; */ /* done by memset */
1309 NewPage ->xlp_tli = ThisTimeLineID;
1310 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1311 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1314 * If first page of an XLOG segment file, make it a long header.
1316 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1318 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1320 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1321 NewLongPage->xlp_seg_size = XLogSegSize;
1322 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1323 NewPage ->xlp_info |= XLP_LONG_HEADER;
1325 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1328 return update_needed;
1332 * Write and/or fsync the log at least as far as WriteRqst indicates.
1334 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1335 * may stop at any convenient boundary (such as a cache or logfile boundary).
1336 * This option allows us to avoid uselessly issuing multiple writes when a
1337 * single one would do.
1339 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1340 * perform end-of-segment actions after writing the last page, even if
1341 * it's not physically the end of its segment. (NB: this will work properly
1342 * only if caller specifies WriteRqst == page-end and flexible == false,
1343 * and there is some data to write.)
1345 * Must be called with WALWriteLock held.
1348 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1350 XLogCtlWrite *Write = &XLogCtl->Write;
1352 bool last_iteration;
1360 /* We should always be inside a critical section here */
1361 Assert(CritSectionCount > 0);
1364 * Update local LogwrtResult (caller probably did this already, but...)
1366 LogwrtResult = Write->LogwrtResult;
1369 * Since successive pages in the xlog cache are consecutively allocated,
1370 * we can usually gather multiple pages together and issue just one
1371 * write() call. npages is the number of pages we have determined can be
1372 * written together; startidx is the cache block index of the first one,
1373 * and startoffset is the file offset at which it should go. The latter
1374 * two variables are only valid when npages > 0, but we must initialize
1375 * all of them to keep the compiler quiet.
1382 * Within the loop, curridx is the cache block index of the page to
1383 * consider writing. We advance Write->curridx only after successfully
1384 * writing pages. (Right now, this refinement is useless since we are
1385 * going to PANIC if any error occurs anyway; but someday it may come in
1388 curridx = Write->curridx;
1390 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1393 * Make sure we're not ahead of the insert process. This could happen
1394 * if we're passed a bogus WriteRqst.Write that is past the end of the
1395 * last page that's been initialized by AdvanceXLInsertBuffer.
1397 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1398 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1399 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1400 XLogCtl->xlblocks[curridx].xlogid,
1401 XLogCtl->xlblocks[curridx].xrecoff);
1403 /* Advance LogwrtResult.Write to end of current buffer page */
1404 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1405 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1407 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1410 * Switch to new logfile segment. We cannot have any pending
1411 * pages here (since we dump what we have at segment end).
1413 Assert(npages == 0);
1414 if (openLogFile >= 0)
1416 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1418 /* create/use new log file */
1419 use_existent = true;
1420 openLogFile = XLogFileInit(openLogId, openLogSeg,
1421 &use_existent, true);
1425 /* Make sure we have the current logfile open */
1426 if (openLogFile < 0)
1428 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1429 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1433 /* Add current page to the set of pending pages-to-dump */
1436 /* first of group */
1438 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1443 * Dump the set if this will be the last loop iteration, or if we are
1444 * at the last page of the cache area (since the next page won't be
1445 * contiguous in memory), or if we are at the end of the logfile
1448 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1450 finishing_seg = !ispartialpage &&
1451 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1453 if (last_iteration ||
1454 curridx == XLogCtl->XLogCacheBlck ||
1460 /* Need to seek in the file? */
1461 if (openLogOff != startoffset)
1463 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1465 (errcode_for_file_access(),
1466 errmsg("could not seek in log file %u, "
1467 "segment %u to offset %u: %m",
1468 openLogId, openLogSeg, startoffset)));
1469 openLogOff = startoffset;
1472 /* OK to write the page(s) */
1473 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1474 nbytes = npages * (Size) XLOG_BLCKSZ;
1476 if (write(openLogFile, from, nbytes) != nbytes)
1478 /* if write didn't set errno, assume no disk space */
1482 (errcode_for_file_access(),
1483 errmsg("could not write to log file %u, segment %u "
1484 "at offset %u, length %lu: %m",
1485 openLogId, openLogSeg,
1486 openLogOff, (unsigned long) nbytes)));
1489 /* Update state for write */
1490 openLogOff += nbytes;
1491 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1495 * If we just wrote the whole last page of a logfile segment,
1496 * fsync the segment immediately. This avoids having to go back
1497 * and re-open prior segments when an fsync request comes along
1498 * later. Doing it here ensures that one and only one backend will
1499 * perform this fsync.
1501 * We also do this if this is the last page written for an xlog
1504 * This is also the right place to notify the Archiver that the
1505 * segment is ready to copy to archival storage, and to update the
1506 * timer for archive_timeout, and to signal for a checkpoint if
1507 * too many logfile segments have been used since the last
1510 if (finishing_seg || (xlog_switch && last_iteration))
1513 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1515 if (XLogArchivingActive())
1516 XLogArchiveNotifySeg(openLogId, openLogSeg);
1518 Write->lastSegSwitchTime = time(NULL);
1521 * Signal bgwriter to start a checkpoint if we've consumed too
1522 * much xlog since the last one. (We look at local copy of
1523 * RedoRecPtr which might be a little out of date, but should
1524 * be close enough for this purpose.)
1526 * A straight computation of segment number could overflow 32
1527 * bits. Rather than assuming we have working 64-bit
1528 * arithmetic, we compare the highest-order bits separately,
1529 * and force a checkpoint immediately when they change.
1531 if (IsUnderPostmaster)
1535 uint32 old_highbits,
1538 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1539 (RedoRecPtr.xrecoff / XLogSegSize);
1540 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1541 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile +
1543 new_highbits = openLogId / XLogSegSize;
1544 if (new_highbits != old_highbits ||
1545 new_segno >= old_segno + (uint32) (CheckPointSegments-1))
1546 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1553 /* Only asked to write a partial page */
1554 LogwrtResult.Write = WriteRqst.Write;
1557 curridx = NextBufIdx(curridx);
1559 /* If flexible, break out of loop as soon as we wrote something */
1560 if (flexible && npages == 0)
1564 Assert(npages == 0);
1565 Assert(curridx == Write->curridx);
1568 * If asked to flush, do so
1570 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1571 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1574 * Could get here without iterating above loop, in which case we might
1575 * have no open file or the wrong one. However, we do not need to
1576 * fsync more than one file.
1578 if (sync_method != SYNC_METHOD_OPEN)
1580 if (openLogFile >= 0 &&
1581 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1583 if (openLogFile < 0)
1585 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1586 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1591 LogwrtResult.Flush = LogwrtResult.Write;
1595 * Update shared-memory status
1597 * We make sure that the shared 'request' values do not fall behind the
1598 * 'result' values. This is not absolutely essential, but it saves some
1599 * code in a couple of places.
1602 /* use volatile pointer to prevent code rearrangement */
1603 volatile XLogCtlData *xlogctl = XLogCtl;
1605 SpinLockAcquire(&xlogctl->info_lck);
1606 xlogctl->LogwrtResult = LogwrtResult;
1607 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1608 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1609 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1610 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1611 SpinLockRelease(&xlogctl->info_lck);
1614 Write->LogwrtResult = LogwrtResult;
1618 * Record the LSN for an asynchronous transaction commit.
1619 * (This should not be called for aborts, nor for synchronous commits.)
1622 XLogSetAsyncCommitLSN(XLogRecPtr asyncCommitLSN)
1624 /* use volatile pointer to prevent code rearrangement */
1625 volatile XLogCtlData *xlogctl = XLogCtl;
1627 SpinLockAcquire(&xlogctl->info_lck);
1628 if (XLByteLT(xlogctl->asyncCommitLSN, asyncCommitLSN))
1629 xlogctl->asyncCommitLSN = asyncCommitLSN;
1630 SpinLockRelease(&xlogctl->info_lck);
1634 * Ensure that all XLOG data through the given position is flushed to disk.
1636 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1637 * already held, and we try to avoid acquiring it if possible.
1640 XLogFlush(XLogRecPtr record)
1642 XLogRecPtr WriteRqstPtr;
1643 XLogwrtRqst WriteRqst;
1645 /* Disabled during REDO */
1649 /* Quick exit if already known flushed */
1650 if (XLByteLE(record, LogwrtResult.Flush))
1655 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1656 record.xlogid, record.xrecoff,
1657 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1658 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1661 START_CRIT_SECTION();
1664 * Since fsync is usually a horribly expensive operation, we try to
1665 * piggyback as much data as we can on each fsync: if we see any more data
1666 * entered into the xlog buffer, we'll write and fsync that too, so that
1667 * the final value of LogwrtResult.Flush is as large as possible. This
1668 * gives us some chance of avoiding another fsync immediately after.
1671 /* initialize to given target; may increase below */
1672 WriteRqstPtr = record;
1674 /* read LogwrtResult and update local state */
1676 /* use volatile pointer to prevent code rearrangement */
1677 volatile XLogCtlData *xlogctl = XLogCtl;
1679 SpinLockAcquire(&xlogctl->info_lck);
1680 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1681 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1682 LogwrtResult = xlogctl->LogwrtResult;
1683 SpinLockRelease(&xlogctl->info_lck);
1687 if (!XLByteLE(record, LogwrtResult.Flush))
1689 /* now wait for the write lock */
1690 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1691 LogwrtResult = XLogCtl->Write.LogwrtResult;
1692 if (!XLByteLE(record, LogwrtResult.Flush))
1694 /* try to write/flush later additions to XLOG as well */
1695 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1697 XLogCtlInsert *Insert = &XLogCtl->Insert;
1698 uint32 freespace = INSERT_FREESPACE(Insert);
1700 if (freespace < SizeOfXLogRecord) /* buffer is full */
1701 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1704 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1705 WriteRqstPtr.xrecoff -= freespace;
1707 LWLockRelease(WALInsertLock);
1708 WriteRqst.Write = WriteRqstPtr;
1709 WriteRqst.Flush = WriteRqstPtr;
1713 WriteRqst.Write = WriteRqstPtr;
1714 WriteRqst.Flush = record;
1716 XLogWrite(WriteRqst, false, false);
1718 LWLockRelease(WALWriteLock);
1724 * If we still haven't flushed to the request point then we have a
1725 * problem; most likely, the requested flush point is past end of XLOG.
1726 * This has been seen to occur when a disk page has a corrupted LSN.
1728 * Formerly we treated this as a PANIC condition, but that hurts the
1729 * system's robustness rather than helping it: we do not want to take down
1730 * the whole system due to corruption on one data page. In particular, if
1731 * the bad page is encountered again during recovery then we would be
1732 * unable to restart the database at all! (This scenario has actually
1733 * happened in the field several times with 7.1 releases. Note that we
1734 * cannot get here while InRedo is true, but if the bad page is brought in
1735 * and marked dirty during recovery then CreateCheckPoint will try to
1736 * flush it at the end of recovery.)
1738 * The current approach is to ERROR under normal conditions, but only
1739 * WARNING during recovery, so that the system can be brought up even if
1740 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1741 * be promoted to PANIC since xact.c calls this routine inside a critical
1742 * section. However, calls from bufmgr.c are not within critical sections
1743 * and so we will not force a restart for a bad LSN on a data page.
1745 if (XLByteLT(LogwrtResult.Flush, record))
1746 elog(InRecovery ? WARNING : ERROR,
1747 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1748 record.xlogid, record.xrecoff,
1749 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1753 * Flush xlog, but without specifying exactly where to flush to.
1755 * We normally flush only completed blocks; but if there is nothing to do on
1756 * that basis, we check for unflushed async commits in the current incomplete
1757 * block, and flush through the latest one of those. Thus, if async commits
1758 * are not being used, we will flush complete blocks only. We can guarantee
1759 * that async commits reach disk after at most three cycles; normally only
1760 * one or two. (We allow XLogWrite to write "flexibly", meaning it can stop
1761 * at the end of the buffer ring; this makes a difference only with very high
1762 * load or long wal_writer_delay, but imposes one extra cycle for the worst
1763 * case for async commits.)
1765 * This routine is invoked periodically by the background walwriter process.
1768 XLogBackgroundFlush(void)
1770 XLogRecPtr WriteRqstPtr;
1771 bool flexible = true;
1773 /* read LogwrtResult and update local state */
1775 /* use volatile pointer to prevent code rearrangement */
1776 volatile XLogCtlData *xlogctl = XLogCtl;
1778 SpinLockAcquire(&xlogctl->info_lck);
1779 LogwrtResult = xlogctl->LogwrtResult;
1780 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1781 SpinLockRelease(&xlogctl->info_lck);
1784 /* back off to last completed page boundary */
1785 WriteRqstPtr.xrecoff -= WriteRqstPtr.xrecoff % XLOG_BLCKSZ;
1787 /* if we have already flushed that far, consider async commit records */
1788 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1790 /* use volatile pointer to prevent code rearrangement */
1791 volatile XLogCtlData *xlogctl = XLogCtl;
1793 SpinLockAcquire(&xlogctl->info_lck);
1794 WriteRqstPtr = xlogctl->asyncCommitLSN;
1795 SpinLockRelease(&xlogctl->info_lck);
1796 flexible = false; /* ensure it all gets written */
1799 /* Done if already known flushed */
1800 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1805 elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
1806 WriteRqstPtr.xlogid, WriteRqstPtr.xrecoff,
1807 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1808 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1811 START_CRIT_SECTION();
1813 /* now wait for the write lock */
1814 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1815 LogwrtResult = XLogCtl->Write.LogwrtResult;
1816 if (!XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1818 XLogwrtRqst WriteRqst;
1820 WriteRqst.Write = WriteRqstPtr;
1821 WriteRqst.Flush = WriteRqstPtr;
1822 XLogWrite(WriteRqst, flexible, false);
1824 LWLockRelease(WALWriteLock);
1830 * Flush any previous asynchronously-committed transactions' commit records.
1832 * NOTE: it is unwise to assume that this provides any strong guarantees.
1833 * In particular, because of the inexact LSN bookkeeping used by clog.c,
1834 * we cannot assume that hint bits will be settable for these transactions.
1837 XLogAsyncCommitFlush(void)
1839 XLogRecPtr WriteRqstPtr;
1840 /* use volatile pointer to prevent code rearrangement */
1841 volatile XLogCtlData *xlogctl = XLogCtl;
1843 SpinLockAcquire(&xlogctl->info_lck);
1844 WriteRqstPtr = xlogctl->asyncCommitLSN;
1845 SpinLockRelease(&xlogctl->info_lck);
1847 XLogFlush(WriteRqstPtr);
1851 * Test whether XLOG data has been flushed up to (at least) the given position.
1853 * Returns true if a flush is still needed. (It may be that someone else
1854 * is already in process of flushing that far, however.)
1857 XLogNeedsFlush(XLogRecPtr record)
1859 /* Quick exit if already known flushed */
1860 if (XLByteLE(record, LogwrtResult.Flush))
1863 /* read LogwrtResult and update local state */
1865 /* use volatile pointer to prevent code rearrangement */
1866 volatile XLogCtlData *xlogctl = XLogCtl;
1868 SpinLockAcquire(&xlogctl->info_lck);
1869 LogwrtResult = xlogctl->LogwrtResult;
1870 SpinLockRelease(&xlogctl->info_lck);
1874 if (XLByteLE(record, LogwrtResult.Flush))
1881 * Create a new XLOG file segment, or open a pre-existing one.
1883 * log, seg: identify segment to be created/opened.
1885 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1886 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1889 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1890 * place. This should be TRUE except during bootstrap log creation. The
1891 * caller must *not* hold the lock at call.
1893 * Returns FD of opened file.
1895 * Note: errors here are ERROR not PANIC because we might or might not be
1896 * inside a critical section (eg, during checkpoint there is no reason to
1897 * take down the system on failure). They will promote to PANIC if we are
1898 * in a critical section.
1901 XLogFileInit(uint32 log, uint32 seg,
1902 bool *use_existent, bool use_lock)
1904 char path[MAXPGPATH];
1905 char tmppath[MAXPGPATH];
1907 uint32 installed_log;
1908 uint32 installed_seg;
1913 XLogFilePath(path, ThisTimeLineID, log, seg);
1916 * Try to use existent file (checkpoint maker may have created it already)
1920 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1924 if (errno != ENOENT)
1926 (errcode_for_file_access(),
1927 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1935 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
1936 * another process is doing the same thing. If so, we will end up
1937 * pre-creating an extra log segment. That seems OK, and better than
1938 * holding the lock throughout this lengthy process.
1940 elog(DEBUG2, "creating and filling new WAL file");
1942 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
1946 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1947 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1951 (errcode_for_file_access(),
1952 errmsg("could not create file \"%s\": %m", tmppath)));
1955 * Zero-fill the file. We have to do this the hard way to ensure that all
1956 * the file space has really been allocated --- on platforms that allow
1957 * "holes" in files, just seeking to the end doesn't allocate intermediate
1958 * space. This way, we know that we have all the space and (after the
1959 * fsync below) that all the indirect blocks are down on disk. Therefore,
1960 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
1963 * Note: palloc zbuffer, instead of just using a local char array, to
1964 * ensure it is reasonably well-aligned; this may save a few cycles
1965 * transferring data to the kernel.
1967 zbuffer = (char *) palloc0(XLOG_BLCKSZ);
1968 for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
1971 if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
1973 int save_errno = errno;
1976 * If we fail to make the file, delete it to release disk space
1979 /* if write didn't set errno, assume problem is no disk space */
1980 errno = save_errno ? save_errno : ENOSPC;
1983 (errcode_for_file_access(),
1984 errmsg("could not write to file \"%s\": %m", tmppath)));
1989 if (pg_fsync(fd) != 0)
1991 (errcode_for_file_access(),
1992 errmsg("could not fsync file \"%s\": %m", tmppath)));
1996 (errcode_for_file_access(),
1997 errmsg("could not close file \"%s\": %m", tmppath)));
2000 * Now move the segment into place with its final name.
2002 * If caller didn't want to use a pre-existing file, get rid of any
2003 * pre-existing file. Otherwise, cope with possibility that someone else
2004 * has created the file while we were filling ours: if so, use ours to
2005 * pre-create a future log segment.
2007 installed_log = log;
2008 installed_seg = seg;
2009 max_advance = XLOGfileslop;
2010 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
2011 *use_existent, &max_advance,
2014 /* No need for any more future segments... */
2018 elog(DEBUG2, "done creating and filling new WAL file");
2020 /* Set flag to tell caller there was no existent file */
2021 *use_existent = false;
2023 /* Now open original target segment (might not be file I just made) */
2024 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2028 (errcode_for_file_access(),
2029 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2036 * Create a new XLOG file segment by copying a pre-existing one.
2038 * log, seg: identify segment to be created.
2040 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
2041 * a different timeline)
2043 * Currently this is only used during recovery, and so there are no locking
2044 * considerations. But we should be just as tense as XLogFileInit to avoid
2045 * emplacing a bogus file.
2048 XLogFileCopy(uint32 log, uint32 seg,
2049 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
2051 char path[MAXPGPATH];
2052 char tmppath[MAXPGPATH];
2053 char buffer[XLOG_BLCKSZ];
2059 * Open the source file
2061 XLogFilePath(path, srcTLI, srclog, srcseg);
2062 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2065 (errcode_for_file_access(),
2066 errmsg("could not open file \"%s\": %m", path)));
2069 * Copy into a temp file name.
2071 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2075 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
2076 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2080 (errcode_for_file_access(),
2081 errmsg("could not create file \"%s\": %m", tmppath)));
2084 * Do the data copying.
2086 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2089 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2093 (errcode_for_file_access(),
2094 errmsg("could not read file \"%s\": %m", path)));
2097 (errmsg("not enough data in file \"%s\"", path)));
2100 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2102 int save_errno = errno;
2105 * If we fail to make the file, delete it to release disk space
2108 /* if write didn't set errno, assume problem is no disk space */
2109 errno = save_errno ? save_errno : ENOSPC;
2112 (errcode_for_file_access(),
2113 errmsg("could not write to file \"%s\": %m", tmppath)));
2117 if (pg_fsync(fd) != 0)
2119 (errcode_for_file_access(),
2120 errmsg("could not fsync file \"%s\": %m", tmppath)));
2124 (errcode_for_file_access(),
2125 errmsg("could not close file \"%s\": %m", tmppath)));
2130 * Now move the segment into place with its final name.
2132 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2133 elog(ERROR, "InstallXLogFileSegment should not have failed");
2137 * Install a new XLOG segment file as a current or future log segment.
2139 * This is used both to install a newly-created segment (which has a temp
2140 * filename while it's being created) and to recycle an old segment.
2142 * *log, *seg: identify segment to install as (or first possible target).
2143 * When find_free is TRUE, these are modified on return to indicate the
2144 * actual installation location or last segment searched.
2146 * tmppath: initial name of file to install. It will be renamed into place.
2148 * find_free: if TRUE, install the new segment at the first empty log/seg
2149 * number at or after the passed numbers. If FALSE, install the new segment
2150 * exactly where specified, deleting any existing segment file there.
2152 * *max_advance: maximum number of log/seg slots to advance past the starting
2153 * point. Fail if no free slot is found in this range. On return, reduced
2154 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2155 * when find_free is FALSE.)
2157 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2158 * place. This should be TRUE except during bootstrap log creation. The
2159 * caller must *not* hold the lock at call.
2161 * Returns TRUE if file installed, FALSE if not installed because of
2162 * exceeding max_advance limit. On Windows, we also return FALSE if we
2163 * can't rename the file into place because someone's got it open.
2164 * (Any other kind of failure causes ereport().)
2167 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2168 bool find_free, int *max_advance,
2171 char path[MAXPGPATH];
2172 struct stat stat_buf;
2174 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2177 * We want to be sure that only one process does this at a time.
2180 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2184 /* Force installation: get rid of any pre-existing segment file */
2189 /* Find a free slot to put it in */
2190 while (stat(path, &stat_buf) == 0)
2192 if (*max_advance <= 0)
2194 /* Failed to find a free slot within specified range */
2196 LWLockRelease(ControlFileLock);
2199 NextLogSeg(*log, *seg);
2201 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2206 * Prefer link() to rename() here just to be really sure that we don't
2207 * overwrite an existing logfile. However, there shouldn't be one, so
2208 * rename() is an acceptable substitute except for the truly paranoid.
2210 #if HAVE_WORKING_LINK
2211 if (link(tmppath, path) < 0)
2213 (errcode_for_file_access(),
2214 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2215 tmppath, path, *log, *seg)));
2218 if (rename(tmppath, path) < 0)
2221 #if !defined(__CYGWIN__)
2222 if (GetLastError() == ERROR_ACCESS_DENIED)
2224 if (errno == EACCES)
2228 LWLockRelease(ControlFileLock);
2234 (errcode_for_file_access(),
2235 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2236 tmppath, path, *log, *seg)));
2241 LWLockRelease(ControlFileLock);
2247 * Open a pre-existing logfile segment for writing.
2250 XLogFileOpen(uint32 log, uint32 seg)
2252 char path[MAXPGPATH];
2255 XLogFilePath(path, ThisTimeLineID, log, seg);
2257 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
2261 (errcode_for_file_access(),
2262 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2269 * Open a logfile segment for reading (during recovery).
2272 XLogFileRead(uint32 log, uint32 seg, int emode)
2274 char path[MAXPGPATH];
2275 char xlogfname[MAXFNAMELEN];
2280 * Loop looking for a suitable timeline ID: we might need to read any of
2281 * the timelines listed in expectedTLIs.
2283 * We expect curFileTLI on entry to be the TLI of the preceding file in
2284 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2285 * to go backwards; this prevents us from picking up the wrong file when a
2286 * parent timeline extends to higher segment numbers than the child we
2289 foreach(cell, expectedTLIs)
2291 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2293 if (tli < curFileTLI)
2294 break; /* don't bother looking at too-old TLIs */
2296 if (InArchiveRecovery)
2298 XLogFileName(xlogfname, tli, log, seg);
2299 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2304 XLogFilePath(path, tli, log, seg);
2306 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2313 if (errno != ENOENT) /* unexpected failure? */
2315 (errcode_for_file_access(),
2316 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2320 /* Couldn't find it. For simplicity, complain about front timeline */
2321 XLogFilePath(path, recoveryTargetTLI, log, seg);
2324 (errcode_for_file_access(),
2325 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2331 * Close the current logfile segment for writing.
2336 Assert(openLogFile >= 0);
2339 * posix_fadvise is problematic on many platforms: on older x86 Linux it
2340 * just dumps core, and there are reports of problems on PPC platforms as
2341 * well. The following is therefore disabled for the time being. We could
2342 * consider some kind of configure test to see if it's safe to use, but
2343 * since we lack hard evidence that there's any useful performance gain to
2344 * be had, spending time on that seems unprofitable for now.
2349 * WAL segment files will not be re-read in normal operation, so we advise
2350 * OS to release any cached pages. But do not do so if WAL archiving is
2351 * active, because archiver process could use the cache to read the WAL
2354 * While O_DIRECT works for O_SYNC, posix_fadvise() works for fsync() and
2355 * O_SYNC, and some platforms only have posix_fadvise().
2357 #if defined(HAVE_DECL_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2358 if (!XLogArchivingActive())
2359 posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2361 #endif /* NOT_USED */
2363 if (close(openLogFile))
2365 (errcode_for_file_access(),
2366 errmsg("could not close log file %u, segment %u: %m",
2367 openLogId, openLogSeg)));
2372 * Attempt to retrieve the specified file from off-line archival storage.
2373 * If successful, fill "path" with its complete path (note that this will be
2374 * a temp file name that doesn't follow the normal naming convention), and
2377 * If not successful, fill "path" with the name of the normal on-line file
2378 * (which may or may not actually exist, but we'll try to use it), and return
2381 * For fixed-size files, the caller may pass the expected size as an
2382 * additional crosscheck on successful recovery. If the file size is not
2383 * known, set expectedSize = 0.
2386 RestoreArchivedFile(char *path, const char *xlogfname,
2387 const char *recovername, off_t expectedSize)
2389 char xlogpath[MAXPGPATH];
2390 char xlogRestoreCmd[MAXPGPATH];
2396 struct stat stat_buf;
2399 * When doing archive recovery, we always prefer an archived log file even
2400 * if a file of the same name exists in XLOGDIR. The reason is that the
2401 * file in XLOGDIR could be an old, un-filled or partly-filled version
2402 * that was copied and restored as part of backing up $PGDATA.
2404 * We could try to optimize this slightly by checking the local copy
2405 * lastchange timestamp against the archived copy, but we have no API to
2406 * do this, nor can we guarantee that the lastchange timestamp was
2407 * preserved correctly when we copied to archive. Our aim is robustness,
2408 * so we elect not to do this.
2410 * If we cannot obtain the log file from the archive, however, we will try
2411 * to use the XLOGDIR file if it exists. This is so that we can make use
2412 * of log segments that weren't yet transferred to the archive.
2414 * Notice that we don't actually overwrite any files when we copy back
2415 * from archive because the recoveryRestoreCommand may inadvertently
2416 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2417 * fallback to the segments remaining in current XLOGDIR later. The
2418 * copy-from-archive filename is always the same, ensuring that we don't
2419 * run out of disk space on long recoveries.
2421 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2424 * Make sure there is no existing file named recovername.
2426 if (stat(xlogpath, &stat_buf) != 0)
2428 if (errno != ENOENT)
2430 (errcode_for_file_access(),
2431 errmsg("could not stat file \"%s\": %m",
2436 if (unlink(xlogpath) != 0)
2438 (errcode_for_file_access(),
2439 errmsg("could not remove file \"%s\": %m",
2444 * construct the command to be executed
2446 dp = xlogRestoreCmd;
2447 endp = xlogRestoreCmd + MAXPGPATH - 1;
2450 for (sp = recoveryRestoreCommand; *sp; sp++)
2457 /* %p: relative path of target file */
2459 StrNCpy(dp, xlogpath, endp - dp);
2460 make_native_path(dp);
2464 /* %f: filename of desired file */
2466 StrNCpy(dp, xlogfname, endp - dp);
2470 /* convert %% to a single % */
2476 /* otherwise treat the % as not special */
2491 (errmsg_internal("executing restore command \"%s\"",
2495 * Copy xlog from archival storage to XLOGDIR
2497 rc = system(xlogRestoreCmd);
2501 * command apparently succeeded, but let's make sure the file is
2502 * really there now and has the correct size.
2504 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2505 * it, but is that too strong? We could try to plow ahead with a
2506 * local copy of the file ... but the problem is that there probably
2507 * isn't one, and we'd incorrectly conclude we've reached the end of
2508 * WAL and we're done recovering ...
2510 if (stat(xlogpath, &stat_buf) == 0)
2512 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2514 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2516 (unsigned long) stat_buf.st_size,
2517 (unsigned long) expectedSize)));
2521 (errmsg("restored log file \"%s\" from archive",
2523 strcpy(path, xlogpath);
2530 if (errno != ENOENT)
2532 (errcode_for_file_access(),
2533 errmsg("could not stat file \"%s\": %m",
2539 * Remember, we rollforward UNTIL the restore fails so failure here is
2540 * just part of the process... that makes it difficult to determine
2541 * whether the restore failed because there isn't an archive to restore,
2542 * or because the administrator has specified the restore program
2543 * incorrectly. We have to assume the former.
2545 * However, if the failure was due to any sort of signal, it's best to
2546 * punt and abort recovery. (If we "return false" here, upper levels
2547 * will assume that recovery is complete and start up the database!)
2548 * It's essential to abort on child SIGINT and SIGQUIT, because per spec
2549 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2550 * those it's a good bet we should have gotten it too. Aborting on other
2551 * signals such as SIGTERM seems a good idea as well.
2553 * Per the Single Unix Spec, shells report exit status > 128 when
2554 * a called command died on a signal. Also, 126 and 127 are used to
2555 * report problems such as an unfindable command; treat those as fatal
2558 signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;
2560 ereport(signaled ? FATAL : DEBUG2,
2561 (errmsg("could not restore file \"%s\" from archive: return code %d",
2565 * if an archived file is not available, there might still be a version of
2566 * this file in XLOGDIR, so return that as the filename to open.
2568 * In many recovery scenarios we expect this to fail also, but if so that
2569 * just means we've reached the end of WAL.
2571 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2576 * Preallocate log files beyond the specified log endpoint.
2578 * XXX this is currently extremely conservative, since it forces only one
2579 * future log segment to exist, and even that only if we are 75% done with
2580 * the current one. This is only appropriate for very low-WAL-volume systems.
2581 * High-volume systems will be OK once they've built up a sufficient set of
2582 * recycled log segments, but the startup transient is likely to include
2583 * a lot of segment creations by foreground processes, which is not so good.
2586 PreallocXlogFiles(XLogRecPtr endptr)
2593 XLByteToPrevSeg(endptr, _logId, _logSeg);
2594 if ((endptr.xrecoff - 1) % XLogSegSize >=
2595 (uint32) (0.75 * XLogSegSize))
2597 NextLogSeg(_logId, _logSeg);
2598 use_existent = true;
2599 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2602 CheckpointStats.ckpt_segs_added++;
2607 * Recycle or remove all log files older or equal to passed log/seg#
2609 * endptr is current (or recent) end of xlog; this is used to determine
2610 * whether we want to recycle rather than delete no-longer-wanted log files.
2613 RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
2619 struct dirent *xlde;
2620 char lastoff[MAXFNAMELEN];
2621 char path[MAXPGPATH];
2624 * Initialize info about where to try to recycle to. We allow recycling
2625 * segments up to XLOGfileslop segments beyond the current XLOG location.
2627 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2628 max_advance = XLOGfileslop;
2630 xldir = AllocateDir(XLOGDIR);
2633 (errcode_for_file_access(),
2634 errmsg("could not open transaction log directory \"%s\": %m",
2637 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2639 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2642 * We ignore the timeline part of the XLOG segment identifiers in
2643 * deciding whether a segment is still needed. This ensures that we
2644 * won't prematurely remove a segment from a parent timeline. We could
2645 * probably be a little more proactive about removing segments of
2646 * non-parent timelines, but that would be a whole lot more
2649 * We use the alphanumeric sorting property of the filenames to decide
2650 * which ones are earlier than the lastoff segment.
2652 if (strlen(xlde->d_name) == 24 &&
2653 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2654 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2656 if (XLogArchiveCheckDone(xlde->d_name))
2658 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2661 * Before deleting the file, see if it can be recycled as a
2662 * future log segment.
2664 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2669 (errmsg("recycled transaction log file \"%s\"",
2671 CheckpointStats.ckpt_segs_recycled++;
2672 /* Needn't recheck that slot on future iterations */
2673 if (max_advance > 0)
2675 NextLogSeg(endlogId, endlogSeg);
2681 /* No need for any more future segments... */
2683 (errmsg("removing transaction log file \"%s\"",
2686 CheckpointStats.ckpt_segs_removed++;
2689 XLogArchiveCleanup(xlde->d_name);
2698 * Remove previous backup history files. This also retries creation of
2699 * .ready files for any backup history files for which XLogArchiveNotify
2703 CleanupBackupHistory(void)
2706 struct dirent *xlde;
2707 char path[MAXPGPATH];
2709 xldir = AllocateDir(XLOGDIR);
2712 (errcode_for_file_access(),
2713 errmsg("could not open transaction log directory \"%s\": %m",
2716 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2718 if (strlen(xlde->d_name) > 24 &&
2719 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2720 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
2723 if (XLogArchiveCheckDone(xlde->d_name))
2726 (errmsg("removing transaction log backup history file \"%s\"",
2728 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2730 XLogArchiveCleanup(xlde->d_name);
2739 * Restore the backup blocks present in an XLOG record, if any.
2741 * We assume all of the record has been read into memory at *record.
2743 * Note: when a backup block is available in XLOG, we restore it
2744 * unconditionally, even if the page in the database appears newer.
2745 * This is to protect ourselves against database pages that were partially
2746 * or incorrectly written during a crash. We assume that the XLOG data
2747 * must be good because it has passed a CRC check, while the database
2748 * page might not be. This will force us to replay all subsequent
2749 * modifications of the page that appear in XLOG, rather than possibly
2750 * ignoring them as already applied, but that's not a huge drawback.
2753 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
2762 blk = (char *) XLogRecGetData(record) + record->xl_len;
2763 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2765 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2768 memcpy(&bkpb, blk, sizeof(BkpBlock));
2769 blk += sizeof(BkpBlock);
2771 reln = XLogOpenRelation(bkpb.node);
2772 buffer = XLogReadBuffer(reln, bkpb.block, true);
2773 Assert(BufferIsValid(buffer));
2774 page = (Page) BufferGetPage(buffer);
2776 if (bkpb.hole_length == 0)
2778 memcpy((char *) page, blk, BLCKSZ);
2782 /* must zero-fill the hole */
2783 MemSet((char *) page, 0, BLCKSZ);
2784 memcpy((char *) page, blk, bkpb.hole_offset);
2785 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
2786 blk + bkpb.hole_offset,
2787 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
2790 PageSetLSN(page, lsn);
2791 PageSetTLI(page, ThisTimeLineID);
2792 MarkBufferDirty(buffer);
2793 UnlockReleaseBuffer(buffer);
2795 blk += BLCKSZ - bkpb.hole_length;
2800 * CRC-check an XLOG record. We do not believe the contents of an XLOG
2801 * record (other than to the minimal extent of computing the amount of
2802 * data to read in) until we've checked the CRCs.
2804 * We assume all of the record has been read into memory at *record.
2807 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
2811 uint32 len = record->xl_len;
2815 /* First the rmgr data */
2817 COMP_CRC32(crc, XLogRecGetData(record), len);
2819 /* Add in the backup blocks, if any */
2820 blk = (char *) XLogRecGetData(record) + len;
2821 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
2825 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
2828 memcpy(&bkpb, blk, sizeof(BkpBlock));
2829 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
2832 (errmsg("incorrect hole size in record at %X/%X",
2833 recptr.xlogid, recptr.xrecoff)));
2836 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
2837 COMP_CRC32(crc, blk, blen);
2841 /* Check that xl_tot_len agrees with our calculation */
2842 if (blk != (char *) record + record->xl_tot_len)
2845 (errmsg("incorrect total length in record at %X/%X",
2846 recptr.xlogid, recptr.xrecoff)));
2850 /* Finally include the record header */
2851 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
2852 SizeOfXLogRecord - sizeof(pg_crc32));
2855 if (!EQ_CRC32(record->xl_crc, crc))
2858 (errmsg("incorrect resource manager data checksum in record at %X/%X",
2859 recptr.xlogid, recptr.xrecoff)));
2867 * Attempt to read an XLOG record.
2869 * If RecPtr is not NULL, try to read a record at that position. Otherwise
2870 * try to read a record just after the last one previously read.
2872 * If no valid record is available, returns NULL, or fails if emode is PANIC.
2873 * (emode must be either PANIC or LOG.)
2875 * The record is copied into readRecordBuf, so that on successful return,
2876 * the returned record pointer always points there.
2879 ReadRecord(XLogRecPtr *RecPtr, int emode)
2883 XLogRecPtr tmpRecPtr = EndRecPtr;
2884 bool randAccess = false;
2887 uint32 targetPageOff;
2888 uint32 targetRecOff;
2889 uint32 pageHeaderSize;
2891 if (readBuf == NULL)
2894 * First time through, permanently allocate readBuf. We do it this
2895 * way, rather than just making a static array, for two reasons: (1)
2896 * no need to waste the storage in most instantiations of the backend;
2897 * (2) a static char array isn't guaranteed to have any particular
2898 * alignment, whereas malloc() will provide MAXALIGN'd storage.
2900 readBuf = (char *) malloc(XLOG_BLCKSZ);
2901 Assert(readBuf != NULL);
2906 RecPtr = &tmpRecPtr;
2907 /* fast case if next record is on same page */
2908 if (nextRecord != NULL)
2910 record = nextRecord;
2913 /* align old recptr to next page */
2914 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
2915 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
2916 if (tmpRecPtr.xrecoff >= XLogFileSize)
2918 (tmpRecPtr.xlogid)++;
2919 tmpRecPtr.xrecoff = 0;
2921 /* We will account for page header size below */
2925 if (!XRecOffIsValid(RecPtr->xrecoff))
2927 (errmsg("invalid record offset at %X/%X",
2928 RecPtr->xlogid, RecPtr->xrecoff)));
2931 * Since we are going to a random position in WAL, forget any prior
2932 * state about what timeline we were in, and allow it to be any
2933 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
2934 * to go backwards (but we can't reset that variable right here, since
2935 * we might not change files at all).
2937 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
2938 randAccess = true; /* allow curFileTLI to go backwards too */
2941 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
2946 XLByteToSeg(*RecPtr, readId, readSeg);
2949 /* Now it's okay to reset curFileTLI if random fetch */
2953 readFile = XLogFileRead(readId, readSeg, emode);
2955 goto next_record_is_invalid;
2958 * Whenever switching to a new WAL segment, we read the first page of
2959 * the file and validate its header, even if that's not where the
2960 * target record is. This is so that we can check the additional
2961 * identification info that is present in the first page's "long"
2965 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2968 (errcode_for_file_access(),
2969 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2970 readId, readSeg, readOff)));
2971 goto next_record_is_invalid;
2973 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2974 goto next_record_is_invalid;
2977 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
2978 if (readOff != targetPageOff)
2980 readOff = targetPageOff;
2981 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
2984 (errcode_for_file_access(),
2985 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
2986 readId, readSeg, readOff)));
2987 goto next_record_is_invalid;
2989 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
2992 (errcode_for_file_access(),
2993 errmsg("could not read from log file %u, segment %u, offset %u: %m",
2994 readId, readSeg, readOff)));
2995 goto next_record_is_invalid;
2997 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
2998 goto next_record_is_invalid;
3000 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3001 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
3002 if (targetRecOff == 0)
3005 * Can only get here in the continuing-from-prev-page case, because
3006 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
3007 * to skip over the new page's header.
3009 tmpRecPtr.xrecoff += pageHeaderSize;
3010 targetRecOff = pageHeaderSize;
3012 else if (targetRecOff < pageHeaderSize)
3015 (errmsg("invalid record offset at %X/%X",
3016 RecPtr->xlogid, RecPtr->xrecoff)));
3017 goto next_record_is_invalid;
3019 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3020 targetRecOff == pageHeaderSize)
3023 (errmsg("contrecord is requested by %X/%X",
3024 RecPtr->xlogid, RecPtr->xrecoff)));
3025 goto next_record_is_invalid;
3027 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3032 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
3035 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3037 if (record->xl_len != 0)
3040 (errmsg("invalid xlog switch record at %X/%X",
3041 RecPtr->xlogid, RecPtr->xrecoff)));
3042 goto next_record_is_invalid;
3045 else if (record->xl_len == 0)
3048 (errmsg("record with zero length at %X/%X",
3049 RecPtr->xlogid, RecPtr->xrecoff)));
3050 goto next_record_is_invalid;
3052 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3053 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3054 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3057 (errmsg("invalid record length at %X/%X",
3058 RecPtr->xlogid, RecPtr->xrecoff)));
3059 goto next_record_is_invalid;
3061 if (record->xl_rmid > RM_MAX_ID)
3064 (errmsg("invalid resource manager ID %u at %X/%X",
3065 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3066 goto next_record_is_invalid;
3071 * We can't exactly verify the prev-link, but surely it should be less
3072 * than the record's own address.
3074 if (!XLByteLT(record->xl_prev, *RecPtr))
3077 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3078 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3079 RecPtr->xlogid, RecPtr->xrecoff)));
3080 goto next_record_is_invalid;
3086 * Record's prev-link should exactly match our previous location. This
3087 * check guards against torn WAL pages where a stale but valid-looking
3088 * WAL record starts on a sector boundary.
3090 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3093 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3094 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3095 RecPtr->xlogid, RecPtr->xrecoff)));
3096 goto next_record_is_invalid;
3101 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3102 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3103 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3104 * enough for all "normal" records, but very large commit or abort records
3105 * might need more space.)
3107 total_len = record->xl_tot_len;
3108 if (total_len > readRecordBufSize)
3110 uint32 newSize = total_len;
3112 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3113 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3115 free(readRecordBuf);
3116 readRecordBuf = (char *) malloc(newSize);
3119 readRecordBufSize = 0;
3120 /* We treat this as a "bogus data" condition */
3122 (errmsg("record length %u at %X/%X too long",
3123 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3124 goto next_record_is_invalid;
3126 readRecordBufSize = newSize;
3129 buffer = readRecordBuf;
3131 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3132 if (total_len > len)
3134 /* Need to reassemble record */
3135 XLogContRecord *contrecord;
3136 uint32 gotlen = len;
3138 memcpy(buffer, record, len);
3139 record = (XLogRecord *) buffer;
3143 readOff += XLOG_BLCKSZ;
3144 if (readOff >= XLogSegSize)
3148 NextLogSeg(readId, readSeg);
3149 readFile = XLogFileRead(readId, readSeg, emode);
3151 goto next_record_is_invalid;
3154 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3157 (errcode_for_file_access(),
3158 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3159 readId, readSeg, readOff)));
3160 goto next_record_is_invalid;
3162 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3163 goto next_record_is_invalid;
3164 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3167 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3168 readId, readSeg, readOff)));
3169 goto next_record_is_invalid;
3171 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3172 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3173 if (contrecord->xl_rem_len == 0 ||
3174 total_len != (contrecord->xl_rem_len + gotlen))
3177 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3178 contrecord->xl_rem_len,
3179 readId, readSeg, readOff)));
3180 goto next_record_is_invalid;
3182 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3183 if (contrecord->xl_rem_len > len)
3185 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3190 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3191 contrecord->xl_rem_len);
3194 if (!RecordIsValid(record, *RecPtr, emode))
3195 goto next_record_is_invalid;
3196 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3197 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3198 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3200 nextRecord = (XLogRecord *) ((char *) contrecord +
3201 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3203 EndRecPtr.xlogid = readId;
3204 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3206 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3207 ReadRecPtr = *RecPtr;
3208 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3212 /* Record does not cross a page boundary */
3213 if (!RecordIsValid(record, *RecPtr, emode))
3214 goto next_record_is_invalid;
3215 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3216 MAXALIGN(total_len))
3217 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3218 EndRecPtr.xlogid = RecPtr->xlogid;
3219 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3220 ReadRecPtr = *RecPtr;
3221 memcpy(buffer, record, total_len);
3224 * Special processing if it's an XLOG SWITCH record
3226 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3228 /* Pretend it extends to end of segment */
3229 EndRecPtr.xrecoff += XLogSegSize - 1;
3230 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3231 nextRecord = NULL; /* definitely not on same page */
3234 * Pretend that readBuf contains the last page of the segment. This is
3235 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3238 readOff = XLogSegSize - XLOG_BLCKSZ;
3240 return (XLogRecord *) buffer;
3242 next_record_is_invalid:;
3250 * Check whether the xlog header of a page just read in looks valid.
3252 * This is just a convenience subroutine to avoid duplicated code in
3253 * ReadRecord. It's not intended for use from anywhere else.
3256 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3260 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3263 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3264 hdr->xlp_magic, readId, readSeg, readOff)));
3267 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3270 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3271 hdr->xlp_info, readId, readSeg, readOff)));
3274 if (hdr->xlp_info & XLP_LONG_HEADER)
3276 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3278 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3280 char fhdrident_str[32];
3281 char sysident_str[32];
3284 * Format sysids separately to keep platform-dependent format code
3285 * out of the translatable message string.
3287 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3288 longhdr->xlp_sysid);
3289 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3290 ControlFile->system_identifier);
3292 (errmsg("WAL file is from different system"),
3293 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3294 fhdrident_str, sysident_str)));
3297 if (longhdr->xlp_seg_size != XLogSegSize)
3300 (errmsg("WAL file is from different system"),
3301 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3304 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3307 (errmsg("WAL file is from different system"),
3308 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3312 else if (readOff == 0)
3314 /* hmm, first page of file doesn't have a long header? */
3316 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3317 hdr->xlp_info, readId, readSeg, readOff)));
3321 recaddr.xlogid = readId;
3322 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3323 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3326 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3327 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3328 readId, readSeg, readOff)));
3333 * Check page TLI is one of the expected values.
3335 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3338 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3340 readId, readSeg, readOff)));
3345 * Since child timelines are always assigned a TLI greater than their
3346 * immediate parent's TLI, we should never see TLI go backwards across
3347 * successive pages of a consistent WAL sequence.
3349 * Of course this check should only be applied when advancing sequentially
3350 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3351 * going to a random page.
3353 if (hdr->xlp_tli < lastPageTLI)
3356 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3357 hdr->xlp_tli, lastPageTLI,
3358 readId, readSeg, readOff)));
3361 lastPageTLI = hdr->xlp_tli;
3366 * Try to read a timeline's history file.
3368 * If successful, return the list of component TLIs (the given TLI followed by
3369 * its ancestor TLIs). If we can't find the history file, assume that the
3370 * timeline has no parents, and return a list of just the specified timeline
3374 readTimeLineHistory(TimeLineID targetTLI)
3377 char path[MAXPGPATH];
3378 char histfname[MAXFNAMELEN];
3379 char fline[MAXPGPATH];
3382 if (InArchiveRecovery)
3384 TLHistoryFileName(histfname, targetTLI);
3385 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3388 TLHistoryFilePath(path, targetTLI);
3390 fd = AllocateFile(path, "r");
3393 if (errno != ENOENT)
3395 (errcode_for_file_access(),
3396 errmsg("could not open file \"%s\": %m", path)));
3397 /* Not there, so assume no parents */
3398 return list_make1_int((int) targetTLI);
3406 while (fgets(fline, sizeof(fline), fd) != NULL)
3408 /* skip leading whitespace and check for # comment */
3413 for (ptr = fline; *ptr; ptr++)
3415 if (!isspace((unsigned char) *ptr))
3418 if (*ptr == '\0' || *ptr == '#')
3421 /* expect a numeric timeline ID as first field of line */
3422 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3425 (errmsg("syntax error in history file: %s", fline),
3426 errhint("Expected a numeric timeline ID.")));
3429 tli <= (TimeLineID) linitial_int(result))
3431 (errmsg("invalid data in history file: %s", fline),
3432 errhint("Timeline IDs must be in increasing sequence.")));
3434 /* Build list with newest item first */
3435 result = lcons_int((int) tli, result);
3437 /* we ignore the remainder of each line */
3443 targetTLI <= (TimeLineID) linitial_int(result))
3445 (errmsg("invalid data in history file \"%s\"", path),
3446 errhint("Timeline IDs must be less than child timeline's ID.")));
3448 result = lcons_int((int) targetTLI, result);
3451 (errmsg_internal("history of timeline %u is %s",
3452 targetTLI, nodeToString(result))));
3458 * Probe whether a timeline history file exists for the given timeline ID
3461 existsTimeLineHistory(TimeLineID probeTLI)
3463 char path[MAXPGPATH];
3464 char histfname[MAXFNAMELEN];
3467 if (InArchiveRecovery)
3469 TLHistoryFileName(histfname, probeTLI);
3470 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3473 TLHistoryFilePath(path, probeTLI);
3475 fd = AllocateFile(path, "r");
3483 if (errno != ENOENT)
3485 (errcode_for_file_access(),
3486 errmsg("could not open file \"%s\": %m", path)));
3492 * Find the newest existing timeline, assuming that startTLI exists.
3494 * Note: while this is somewhat heuristic, it does positively guarantee
3495 * that (result + 1) is not a known timeline, and therefore it should
3496 * be safe to assign that ID to a new timeline.
3499 findNewestTimeLine(TimeLineID startTLI)
3501 TimeLineID newestTLI;
3502 TimeLineID probeTLI;
3505 * The algorithm is just to probe for the existence of timeline history
3506 * files. XXX is it useful to allow gaps in the sequence?
3508 newestTLI = startTLI;
3510 for (probeTLI = startTLI + 1;; probeTLI++)
3512 if (existsTimeLineHistory(probeTLI))
3514 newestTLI = probeTLI; /* probeTLI exists */
3518 /* doesn't exist, assume we're done */
3527 * Create a new timeline history file.
3529 * newTLI: ID of the new timeline
3530 * parentTLI: ID of its immediate parent
3531 * endTLI et al: ID of the last used WAL file, for annotation purposes
3533 * Currently this is only used during recovery, and so there are no locking
3534 * considerations. But we should be just as tense as XLogFileInit to avoid
3535 * emplacing a bogus file.
3538 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3539 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3541 char path[MAXPGPATH];
3542 char tmppath[MAXPGPATH];
3543 char histfname[MAXFNAMELEN];
3544 char xlogfname[MAXFNAMELEN];
3545 char buffer[BLCKSZ];
3550 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3553 * Write into a temp file name.
3555 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3559 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
3560 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3564 (errcode_for_file_access(),
3565 errmsg("could not create file \"%s\": %m", tmppath)));
3568 * If a history file exists for the parent, copy it verbatim
3570 if (InArchiveRecovery)
3572 TLHistoryFileName(histfname, parentTLI);
3573 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3576 TLHistoryFilePath(path, parentTLI);
3578 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3581 if (errno != ENOENT)
3583 (errcode_for_file_access(),
3584 errmsg("could not open file \"%s\": %m", path)));
3585 /* Not there, so assume parent has no parents */
3592 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3593 if (nbytes < 0 || errno != 0)
3595 (errcode_for_file_access(),
3596 errmsg("could not read file \"%s\": %m", path)));
3600 if ((int) write(fd, buffer, nbytes) != nbytes)
3602 int save_errno = errno;
3605 * If we fail to make the file, delete it to release disk
3611 * if write didn't set errno, assume problem is no disk space
3613 errno = save_errno ? save_errno : ENOSPC;
3616 (errcode_for_file_access(),
3617 errmsg("could not write to file \"%s\": %m", tmppath)));
3624 * Append one line with the details of this timeline split.
3626 * If we did have a parent file, insert an extra newline just in case the
3627 * parent file failed to end with one.
3629 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3631 snprintf(buffer, sizeof(buffer),
3632 "%s%u\t%s\t%s transaction %u at %s\n",
3633 (srcfd < 0) ? "" : "\n",
3636 recoveryStopAfter ? "after" : "before",
3638 timestamptz_to_str(recoveryStopTime));
3640 nbytes = strlen(buffer);
3642 if ((int) write(fd, buffer, nbytes) != nbytes)
3644 int save_errno = errno;
3647 * If we fail to make the file, delete it to release disk space
3650 /* if write didn't set errno, assume problem is no disk space */
3651 errno = save_errno ? save_errno : ENOSPC;
3654 (errcode_for_file_access(),
3655 errmsg("could not write to file \"%s\": %m", tmppath)));
3658 if (pg_fsync(fd) != 0)
3660 (errcode_for_file_access(),
3661 errmsg("could not fsync file \"%s\": %m", tmppath)));
3665 (errcode_for_file_access(),
3666 errmsg("could not close file \"%s\": %m", tmppath)));
3670 * Now move the completed history file into place with its final name.
3672 TLHistoryFilePath(path, newTLI);
3675 * Prefer link() to rename() here just to be really sure that we don't
3676 * overwrite an existing logfile. However, there shouldn't be one, so
3677 * rename() is an acceptable substitute except for the truly paranoid.
3679 #if HAVE_WORKING_LINK
3680 if (link(tmppath, path) < 0)
3682 (errcode_for_file_access(),
3683 errmsg("could not link file \"%s\" to \"%s\": %m",
3687 if (rename(tmppath, path) < 0)
3689 (errcode_for_file_access(),
3690 errmsg("could not rename file \"%s\" to \"%s\": %m",
3694 /* The history file can be archived immediately. */
3695 TLHistoryFileName(histfname, newTLI);
3696 XLogArchiveNotify(histfname);
3700 * I/O routines for pg_control
3702 * *ControlFile is a buffer in shared memory that holds an image of the
3703 * contents of pg_control. WriteControlFile() initializes pg_control
3704 * given a preloaded buffer, ReadControlFile() loads the buffer from
3705 * the pg_control file (during postmaster or standalone-backend startup),
3706 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
3708 * For simplicity, WriteControlFile() initializes the fields of pg_control
3709 * that are related to checking backend/database compatibility, and
3710 * ReadControlFile() verifies they are correct. We could split out the
3711 * I/O and compatibility-check functions, but there seems no need currently.
3714 WriteControlFile(void)
3717 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
3721 * Initialize version and compatibility-check fields
3723 ControlFile->pg_control_version = PG_CONTROL_VERSION;
3724 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
3726 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
3727 ControlFile->floatFormat = FLOATFORMAT_VALUE;
3729 ControlFile->blcksz = BLCKSZ;
3730 ControlFile->relseg_size = RELSEG_SIZE;
3731 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
3732 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
3734 ControlFile->nameDataLen = NAMEDATALEN;
3735 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
3737 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
3739 #ifdef HAVE_INT64_TIMESTAMP
3740 ControlFile->enableIntTimes = TRUE;
3742 ControlFile->enableIntTimes = FALSE;
3745 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
3746 localeptr = setlocale(LC_COLLATE, NULL);
3749 (errmsg("invalid LC_COLLATE setting")));
3750 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
3751 localeptr = setlocale(LC_CTYPE, NULL);
3754 (errmsg("invalid LC_CTYPE setting")));
3755 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
3757 /* Contents are protected with a CRC */
3758 INIT_CRC32(ControlFile->crc);
3759 COMP_CRC32(ControlFile->crc,
3760 (char *) ControlFile,
3761 offsetof(ControlFileData, crc));
3762 FIN_CRC32(ControlFile->crc);
3765 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
3766 * excess over sizeof(ControlFileData). This reduces the odds of
3767 * premature-EOF errors when reading pg_control. We'll still fail when we
3768 * check the contents of the file, but hopefully with a more specific
3769 * error than "couldn't read pg_control".
3771 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
3772 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
3774 memset(buffer, 0, PG_CONTROL_SIZE);
3775 memcpy(buffer, ControlFile, sizeof(ControlFileData));
3777 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3778 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
3782 (errcode_for_file_access(),
3783 errmsg("could not create control file \"%s\": %m",
3784 XLOG_CONTROL_FILE)));
3787 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
3789 /* if write didn't set errno, assume problem is no disk space */
3793 (errcode_for_file_access(),
3794 errmsg("could not write to control file: %m")));
3797 if (pg_fsync(fd) != 0)
3799 (errcode_for_file_access(),
3800 errmsg("could not fsync control file: %m")));
3804 (errcode_for_file_access(),
3805 errmsg("could not close control file: %m")));
3809 ReadControlFile(void)
3817 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3822 (errcode_for_file_access(),
3823 errmsg("could not open control file \"%s\": %m",
3824 XLOG_CONTROL_FILE)));
3826 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
3828 (errcode_for_file_access(),
3829 errmsg("could not read from control file: %m")));
3834 * Check for expected pg_control format version. If this is wrong, the
3835 * CRC check will likely fail because we'll be checking the wrong number
3836 * of bytes. Complaining about wrong version will probably be more
3837 * enlightening than complaining about wrong CRC.
3839 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
3841 (errmsg("database files are incompatible with server"),
3842 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
3843 " but the server was compiled with PG_CONTROL_VERSION %d.",
3844 ControlFile->pg_control_version, PG_CONTROL_VERSION),
3845 errhint("It looks like you need to initdb.")));
3846 /* Now check the CRC. */
3849 (char *) ControlFile,
3850 offsetof(ControlFileData, crc));
3853 if (!EQ_CRC32(crc, ControlFile->crc))
3855 (errmsg("incorrect checksum in control file")));
3858 * Do compatibility checking immediately. We do this here for 2 reasons:
3860 * (1) if the database isn't compatible with the backend executable, we
3861 * want to abort before we can possibly do any damage;
3863 * (2) this code is executed in the postmaster, so the setlocale() will
3864 * propagate to forked backends, which aren't going to read this file for
3865 * themselves. (These locale settings are considered critical
3866 * compatibility items because they can affect sort order of indexes.)
3868 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
3870 (errmsg("database files are incompatible with server"),
3871 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
3872 " but the server was compiled with CATALOG_VERSION_NO %d.",
3873 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
3874 errhint("It looks like you need to initdb.")));
3875 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
3877 (errmsg("database files are incompatible with server"),
3878 errdetail("The database cluster was initialized with MAXALIGN %d,"
3879 " but the server was compiled with MAXALIGN %d.",
3880 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
3881 errhint("It looks like you need to initdb.")));
3882 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
3884 (errmsg("database files are incompatible with server"),
3885 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
3886 errhint("It looks like you need to initdb.")));
3887 if (ControlFile->blcksz != BLCKSZ)
3889 (errmsg("database files are incompatible with server"),
3890 errdetail("The database cluster was initialized with BLCKSZ %d,"
3891 " but the server was compiled with BLCKSZ %d.",
3892 ControlFile->blcksz, BLCKSZ),
3893 errhint("It looks like you need to recompile or initdb.")));
3894 if (ControlFile->relseg_size != RELSEG_SIZE)
3896 (errmsg("database files are incompatible with server"),
3897 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
3898 " but the server was compiled with RELSEG_SIZE %d.",
3899 ControlFile->relseg_size, RELSEG_SIZE),
3900 errhint("It looks like you need to recompile or initdb.")));
3901 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
3903 (errmsg("database files are incompatible with server"),
3904 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
3905 " but the server was compiled with XLOG_BLCKSZ %d.",
3906 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
3907 errhint("It looks like you need to recompile or initdb.")));
3908 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
3910 (errmsg("database files are incompatible with server"),
3911 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
3912 " but the server was compiled with XLOG_SEG_SIZE %d.",
3913 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
3914 errhint("It looks like you need to recompile or initdb.")));
3915 if (ControlFile->nameDataLen != NAMEDATALEN)
3917 (errmsg("database files are incompatible with server"),
3918 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
3919 " but the server was compiled with NAMEDATALEN %d.",
3920 ControlFile->nameDataLen, NAMEDATALEN),
3921 errhint("It looks like you need to recompile or initdb.")));
3922 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
3924 (errmsg("database files are incompatible with server"),
3925 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
3926 " but the server was compiled with INDEX_MAX_KEYS %d.",
3927 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
3928 errhint("It looks like you need to recompile or initdb.")));
3929 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
3931 (errmsg("database files are incompatible with server"),
3932 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
3933 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
3934 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
3935 errhint("It looks like you need to recompile or initdb.")));
3937 #ifdef HAVE_INT64_TIMESTAMP
3938 if (ControlFile->enableIntTimes != TRUE)
3940 (errmsg("database files are incompatible with server"),
3941 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
3942 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
3943 errhint("It looks like you need to recompile or initdb.")));
3945 if (ControlFile->enableIntTimes != FALSE)
3947 (errmsg("database files are incompatible with server"),
3948 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
3949 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
3950 errhint("It looks like you need to recompile or initdb.")));
3953 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
3955 (errmsg("database files are incompatible with server"),
3956 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
3957 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
3958 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
3959 errhint("It looks like you need to recompile or initdb.")));
3960 if (pg_perm_setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
3962 (errmsg("database files are incompatible with operating system"),
3963 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
3964 " which is not recognized by setlocale().",
3965 ControlFile->lc_collate),
3966 errhint("It looks like you need to initdb or install locale support.")));
3967 if (pg_perm_setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
3969 (errmsg("database files are incompatible with operating system"),
3970 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
3971 " which is not recognized by setlocale().",
3972 ControlFile->lc_ctype),
3973 errhint("It looks like you need to initdb or install locale support.")));
3975 /* Make the fixed locale settings visible as GUC variables, too */
3976 SetConfigOption("lc_collate", ControlFile->lc_collate,
3977 PGC_INTERNAL, PGC_S_OVERRIDE);
3978 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
3979 PGC_INTERNAL, PGC_S_OVERRIDE);
3983 UpdateControlFile(void)
3987 INIT_CRC32(ControlFile->crc);
3988 COMP_CRC32(ControlFile->crc,
3989 (char *) ControlFile,
3990 offsetof(ControlFileData, crc));
3991 FIN_CRC32(ControlFile->crc);
3993 fd = BasicOpenFile(XLOG_CONTROL_FILE,
3998 (errcode_for_file_access(),
3999 errmsg("could not open control file \"%s\": %m",
4000 XLOG_CONTROL_FILE)));
4003 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4005 /* if write didn't set errno, assume problem is no disk space */
4009 (errcode_for_file_access(),
4010 errmsg("could not write to control file: %m")));
4013 if (pg_fsync(fd) != 0)
4015 (errcode_for_file_access(),
4016 errmsg("could not fsync control file: %m")));
4020 (errcode_for_file_access(),
4021 errmsg("could not close control file: %m")));
4025 * Initialization of shared memory for XLOG
4033 size = sizeof(XLogCtlData);
4034 /* xlblocks array */
4035 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
4036 /* extra alignment padding for XLOG I/O buffers */
4037 size = add_size(size, ALIGNOF_XLOG_BUFFER);
4038 /* and the buffers themselves */
4039 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4042 * Note: we don't count ControlFileData, it comes out of the "slop factor"
4043 * added by CreateSharedMemoryAndSemaphores. This lets us use this
4044 * routine again below to compute the actual allocation size.
4057 ControlFile = (ControlFileData *)
4058 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4059 XLogCtl = (XLogCtlData *)
4060 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4062 if (foundCFile || foundXLog)
4064 /* both should be present or neither */
4065 Assert(foundCFile && foundXLog);
4069 memset(XLogCtl, 0, sizeof(XLogCtlData));
4072 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4073 * multiple of the alignment for same, so no extra alignment padding is
4076 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4077 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4078 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4079 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4082 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4084 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4085 XLogCtl->pages = allocptr;
4086 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4089 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4090 * in additional info.)
4092 XLogCtl->XLogCacheByte = (Size) XLOG_BLCKSZ *XLOGbuffers;
4094 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4095 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4096 SpinLockInit(&XLogCtl->info_lck);
4099 * If we are not in bootstrap mode, pg_control should already exist. Read
4100 * and validate it immediately (see comments in ReadControlFile() for the
4103 if (!IsBootstrapProcessingMode())
4108 * This func must be called ONCE on system install. It creates pg_control
4109 * and the initial XLOG segment.
4114 CheckPoint checkPoint;
4116 XLogPageHeader page;
4117 XLogLongPageHeader longpage;
4120 uint64 sysidentifier;
4125 * Select a hopefully-unique system identifier code for this installation.
4126 * We use the result of gettimeofday(), including the fractional seconds
4127 * field, as being about as unique as we can easily get. (Think not to
4128 * use random(), since it hasn't been seeded and there's no portable way
4129 * to seed it other than the system clock value...) The upper half of the
4130 * uint64 value is just the tv_sec part, while the lower half is the XOR
4131 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4132 * unnecessarily if "uint64" is really only 32 bits wide. A person
4133 * knowing this encoding can determine the initialization time of the
4134 * installation, which could perhaps be useful sometimes.
4136 gettimeofday(&tv, NULL);
4137 sysidentifier = ((uint64) tv.tv_sec) << 32;
4138 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4140 /* First timeline ID is always 1 */
4143 /* page buffer must be aligned suitably for O_DIRECT */
4144 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4145 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4146 memset(page, 0, XLOG_BLCKSZ);
4148 /* Set up information for the initial checkpoint record */
4149 checkPoint.redo.xlogid = 0;
4150 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4151 checkPoint.ThisTimeLineID = ThisTimeLineID;
4152 checkPoint.nextXidEpoch = 0;
4153 checkPoint.nextXid = FirstNormalTransactionId;
4154 checkPoint.nextOid = FirstBootstrapObjectId;
4155 checkPoint.nextMulti = FirstMultiXactId;
4156 checkPoint.nextMultiOffset = 0;
4157 checkPoint.time = time(NULL);
4159 ShmemVariableCache->nextXid = checkPoint.nextXid;
4160 ShmemVariableCache->nextOid = checkPoint.nextOid;
4161 ShmemVariableCache->oidCount = 0;
4162 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4164 /* Set up the XLOG page header */
4165 page->xlp_magic = XLOG_PAGE_MAGIC;
4166 page->xlp_info = XLP_LONG_HEADER;
4167 page->xlp_tli = ThisTimeLineID;
4168 page->xlp_pageaddr.xlogid = 0;
4169 page->xlp_pageaddr.xrecoff = 0;
4170 longpage = (XLogLongPageHeader) page;
4171 longpage->xlp_sysid = sysidentifier;
4172 longpage->xlp_seg_size = XLogSegSize;
4173 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4175 /* Insert the initial checkpoint record */
4176 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4177 record->xl_prev.xlogid = 0;
4178 record->xl_prev.xrecoff = 0;
4179 record->xl_xid = InvalidTransactionId;
4180 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4181 record->xl_len = sizeof(checkPoint);
4182 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4183 record->xl_rmid = RM_XLOG_ID;
4184 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4187 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4188 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4189 SizeOfXLogRecord - sizeof(pg_crc32));
4191 record->xl_crc = crc;
4193 /* Create first XLOG segment file */
4194 use_existent = false;
4195 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4197 /* Write the first page with the initial record */
4199 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4201 /* if write didn't set errno, assume problem is no disk space */
4205 (errcode_for_file_access(),
4206 errmsg("could not write bootstrap transaction log file: %m")));
4209 if (pg_fsync(openLogFile) != 0)
4211 (errcode_for_file_access(),
4212 errmsg("could not fsync bootstrap transaction log file: %m")));
4214 if (close(openLogFile))
4216 (errcode_for_file_access(),
4217 errmsg("could not close bootstrap transaction log file: %m")));
4221 /* Now create pg_control */
4223 memset(ControlFile, 0, sizeof(ControlFileData));
4224 /* Initialize pg_control status fields */
4225 ControlFile->system_identifier = sysidentifier;
4226 ControlFile->state = DB_SHUTDOWNED;
4227 ControlFile->time = checkPoint.time;
4228 ControlFile->checkPoint = checkPoint.redo;
4229 ControlFile->checkPointCopy = checkPoint;
4230 /* some additional ControlFile fields are set in WriteControlFile() */
4234 /* Bootstrap the commit log, too */
4236 BootStrapSUBTRANS();
4237 BootStrapMultiXact();
4243 str_time(pg_time_t tnow)
4245 static char buf[128];
4247 pg_strftime(buf, sizeof(buf),
4248 "%Y-%m-%d %H:%M:%S %Z",
4249 pg_localtime(&tnow, log_timezone));
4255 * See if there is a recovery command file (recovery.conf), and if so
4256 * read in parameters for archive recovery.
4258 * XXX longer term intention is to expand this to
4259 * cater for additional parameters and controls
4260 * possibly use a flex lexer similar to the GUC one
4263 readRecoveryCommandFile(void)
4266 char cmdline[MAXPGPATH];
4267 TimeLineID rtli = 0;
4268 bool rtliGiven = false;
4269 bool syntaxError = false;
4271 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4274 if (errno == ENOENT)
4275 return; /* not there, so no archive recovery */
4277 (errcode_for_file_access(),
4278 errmsg("could not open recovery command file \"%s\": %m",
4279 RECOVERY_COMMAND_FILE)));
4283 (errmsg("starting archive recovery")));
4288 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4290 /* skip leading whitespace and check for # comment */
4295 for (ptr = cmdline; *ptr; ptr++)
4297 if (!isspace((unsigned char) *ptr))
4300 if (*ptr == '\0' || *ptr == '#')
4303 /* identify the quoted parameter value */
4304 tok1 = strtok(ptr, "'");
4310 tok2 = strtok(NULL, "'");
4316 /* reparse to get just the parameter name */
4317 tok1 = strtok(ptr, " \t=");
4324 if (strcmp(tok1, "restore_command") == 0)
4326 recoveryRestoreCommand = pstrdup(tok2);
4328 (errmsg("restore_command = \"%s\"",
4329 recoveryRestoreCommand)));
4331 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4334 if (strcmp(tok2, "latest") == 0)
4339 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4340 if (errno == EINVAL || errno == ERANGE)
4342 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4347 (errmsg("recovery_target_timeline = %u", rtli)));
4350 (errmsg("recovery_target_timeline = latest")));
4352 else if (strcmp(tok1, "recovery_target_xid") == 0)
4355 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4356 if (errno == EINVAL || errno == ERANGE)
4358 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4361 (errmsg("recovery_target_xid = %u",
4362 recoveryTargetXid)));
4363 recoveryTarget = true;
4364 recoveryTargetExact = true;
4366 else if (strcmp(tok1, "recovery_target_time") == 0)
4369 * if recovery_target_xid specified, then this overrides
4370 * recovery_target_time
4372 if (recoveryTargetExact)
4374 recoveryTarget = true;
4375 recoveryTargetExact = false;
4378 * Convert the time string given by the user to TimestampTz form.
4380 recoveryTargetTime =
4381 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
4382 CStringGetDatum(tok2),
4383 ObjectIdGetDatum(InvalidOid),
4384 Int32GetDatum(-1)));
4386 (errmsg("recovery_target_time = %s",
4387 timestamptz_to_str(recoveryTargetTime))));
4389 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4392 * does nothing if a recovery_target is not also set
4394 if (strcmp(tok2, "true") == 0)
4395 recoveryTargetInclusive = true;
4398 recoveryTargetInclusive = false;
4402 (errmsg("recovery_target_inclusive = %s", tok2)));
4406 (errmsg("unrecognized recovery parameter \"%s\"",
4414 (errmsg("syntax error in recovery command file: %s",
4416 errhint("Lines should have the format parameter = 'value'.")));
4418 /* Check that required parameters were supplied */
4419 if (recoveryRestoreCommand == NULL)
4421 (errmsg("recovery command file \"%s\" did not specify restore_command",
4422 RECOVERY_COMMAND_FILE)));
4424 /* Enable fetching from archive recovery area */
4425 InArchiveRecovery = true;
4428 * If user specified recovery_target_timeline, validate it or compute the
4429 * "latest" value. We can't do this until after we've gotten the restore
4430 * command and set InArchiveRecovery, because we need to fetch timeline
4431 * history files from the archive.
4437 /* Timeline 1 does not have a history file, all else should */
4438 if (rtli != 1 && !existsTimeLineHistory(rtli))
4440 (errmsg("recovery_target_timeline %u does not exist",
4442 recoveryTargetTLI = rtli;
4446 /* We start the "latest" search from pg_control's timeline */
4447 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4453 * Exit archive-recovery state
4456 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4458 char recoveryPath[MAXPGPATH];
4459 char xlogpath[MAXPGPATH];
4462 * We are no longer in archive recovery state.
4464 InArchiveRecovery = false;
4467 * We should have the ending log segment currently open. Verify, and then
4468 * close it (to avoid problems on Windows with trying to rename or delete
4471 Assert(readFile >= 0);
4472 Assert(readId == endLogId);
4473 Assert(readSeg == endLogSeg);
4479 * If the segment was fetched from archival storage, we want to replace
4480 * the existing xlog segment (if any) with the archival version. This is
4481 * because whatever is in XLOGDIR is very possibly older than what we have
4482 * from the archives, since it could have come from restoring a PGDATA
4483 * backup. In any case, the archival version certainly is more
4484 * descriptive of what our current database state is, because that is what
4487 * Note that if we are establishing a new timeline, ThisTimeLineID is
4488 * already set to the new value, and so we will create a new file instead
4489 * of overwriting any existing file.
4491 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4492 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4494 if (restoredFromArchive)
4497 (errmsg_internal("moving last restored xlog to \"%s\"",
4499 unlink(xlogpath); /* might or might not exist */
4500 if (rename(recoveryPath, xlogpath) != 0)
4502 (errcode_for_file_access(),
4503 errmsg("could not rename file \"%s\" to \"%s\": %m",
4504 recoveryPath, xlogpath)));
4505 /* XXX might we need to fix permissions on the file? */
4510 * If the latest segment is not archival, but there's still a
4511 * RECOVERYXLOG laying about, get rid of it.
4513 unlink(recoveryPath); /* ignore any error */
4516 * If we are establishing a new timeline, we have to copy data from
4517 * the last WAL segment of the old timeline to create a starting WAL
4518 * segment for the new timeline.
4520 if (endTLI != ThisTimeLineID)
4521 XLogFileCopy(endLogId, endLogSeg,
4522 endTLI, endLogId, endLogSeg);
4526 * Let's just make real sure there are not .ready or .done flags posted
4527 * for the new segment.
4529 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4530 XLogArchiveCleanup(xlogpath);
4532 /* Get rid of any remaining recovered timeline-history file, too */
4533 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4534 unlink(recoveryPath); /* ignore any error */
4537 * Rename the config file out of the way, so that we don't accidentally
4538 * re-enter archive recovery mode in a subsequent crash.
4540 unlink(RECOVERY_COMMAND_DONE);
4541 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4543 (errcode_for_file_access(),
4544 errmsg("could not rename file \"%s\" to \"%s\": %m",
4545 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4548 (errmsg("archive recovery complete")));
4552 * For point-in-time recovery, this function decides whether we want to
4553 * stop applying the XLOG at or after the current record.
4555 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4556 * *includeThis is set TRUE if we should apply this record before stopping.
4557 * Also, some information is saved in recoveryStopXid et al for use in
4558 * annotating the new timeline's history file.
4561 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4565 TimestampTz recordXtime;
4567 /* Do we have a PITR target at all? */
4568 if (!recoveryTarget)
4571 /* We only consider stopping at COMMIT or ABORT records */
4572 if (record->xl_rmid != RM_XACT_ID)
4574 record_info = record->xl_info & ~XLR_INFO_MASK;
4575 if (record_info == XLOG_XACT_COMMIT)
4577 xl_xact_commit *recordXactCommitData;
4579 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4580 recordXtime = recordXactCommitData->xact_time;
4582 else if (record_info == XLOG_XACT_ABORT)
4584 xl_xact_abort *recordXactAbortData;
4586 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4587 recordXtime = recordXactAbortData->xact_time;
4592 if (recoveryTargetExact)
4595 * there can be only one transaction end record with this exact
4598 * when testing for an xid, we MUST test for equality only, since
4599 * transactions are numbered in the order they start, not the order
4600 * they complete. A higher numbered xid will complete before you about
4601 * 50% of the time...
4603 stopsHere = (record->xl_xid == recoveryTargetXid);
4605 *includeThis = recoveryTargetInclusive;
4610 * there can be many transactions that share the same commit time, so
4611 * we stop after the last one, if we are inclusive, or stop at the
4612 * first one if we are exclusive
4614 if (recoveryTargetInclusive)
4615 stopsHere = (recordXtime > recoveryTargetTime);
4617 stopsHere = (recordXtime >= recoveryTargetTime);
4619 *includeThis = false;
4624 recoveryStopXid = record->xl_xid;
4625 recoveryStopTime = recordXtime;
4626 recoveryStopAfter = *includeThis;
4628 if (record_info == XLOG_XACT_COMMIT)
4630 if (recoveryStopAfter)
4632 (errmsg("recovery stopping after commit of transaction %u, time %s",
4634 timestamptz_to_str(recoveryStopTime))));
4637 (errmsg("recovery stopping before commit of transaction %u, time %s",
4639 timestamptz_to_str(recoveryStopTime))));
4643 if (recoveryStopAfter)
4645 (errmsg("recovery stopping after abort of transaction %u, time %s",
4647 timestamptz_to_str(recoveryStopTime))));
4650 (errmsg("recovery stopping before abort of transaction %u, time %s",
4652 timestamptz_to_str(recoveryStopTime))));
4660 * This must be called ONCE during postmaster or standalone-backend startup
4665 XLogCtlInsert *Insert;
4666 CheckPoint checkPoint;
4668 bool needNewTimeLine = false;
4669 bool haveBackupLabel = false;
4679 TransactionId oldestActiveXID;
4682 * Read control file and check XLOG status looks valid.
4684 * Note: in most control paths, *ControlFile is already valid and we need
4685 * not do ReadControlFile() here, but might as well do it to be sure.
4689 if (ControlFile->state < DB_SHUTDOWNED ||
4690 ControlFile->state > DB_IN_PRODUCTION ||
4691 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
4693 (errmsg("control file contains invalid data")));
4695 if (ControlFile->state == DB_SHUTDOWNED)
4697 (errmsg("database system was shut down at %s",
4698 str_time(ControlFile->time))));
4699 else if (ControlFile->state == DB_SHUTDOWNING)
4701 (errmsg("database system shutdown was interrupted; last known up at %s",
4702 str_time(ControlFile->time))));
4703 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
4705 (errmsg("database system was interrupted while in recovery at %s",
4706 str_time(ControlFile->time)),
4707 errhint("This probably means that some data is corrupted and"
4708 " you will have to use the last backup for recovery.")));
4709 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
4711 (errmsg("database system was interrupted while in recovery at log time %s",
4712 str_time(ControlFile->checkPointCopy.time)),
4713 errhint("If this has occurred more than once some data might be corrupted"
4714 " and you might need to choose an earlier recovery target.")));
4715 else if (ControlFile->state == DB_IN_PRODUCTION)
4717 (errmsg("database system was interrupted; last known up at %s",
4718 str_time(ControlFile->time))));
4720 /* This is just to allow attaching to startup process with a debugger */
4721 #ifdef XLOG_REPLAY_DELAY
4722 if (ControlFile->state != DB_SHUTDOWNED)
4723 pg_usleep(60000000L);
4727 * Initialize on the assumption we want to recover to the same timeline
4728 * that's active according to pg_control.
4730 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
4733 * Check for recovery control file, and if so set up state for offline
4736 readRecoveryCommandFile();
4738 /* Now we can determine the list of expected TLIs */
4739 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
4742 * If pg_control's timeline is not in expectedTLIs, then we cannot
4743 * proceed: the backup is not part of the history of the requested
4746 if (!list_member_int(expectedTLIs,
4747 (int) ControlFile->checkPointCopy.ThisTimeLineID))
4749 (errmsg("requested timeline %u is not a child of database system timeline %u",
4751 ControlFile->checkPointCopy.ThisTimeLineID)));
4753 if (read_backup_label(&checkPointLoc, &minRecoveryLoc))
4756 * When a backup_label file is present, we want to roll forward from
4757 * the checkpoint it identifies, rather than using pg_control.
4759 record = ReadCheckpointRecord(checkPointLoc, 0);
4763 (errmsg("checkpoint record is at %X/%X",
4764 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4765 InRecovery = true; /* force recovery even if SHUTDOWNED */
4770 (errmsg("could not locate required checkpoint record"),
4771 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
4773 /* set flag to delete it later */
4774 haveBackupLabel = true;
4779 * Get the last valid checkpoint record. If the latest one according
4780 * to pg_control is broken, try the next-to-last one.
4782 checkPointLoc = ControlFile->checkPoint;
4783 record = ReadCheckpointRecord(checkPointLoc, 1);
4787 (errmsg("checkpoint record is at %X/%X",
4788 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4792 checkPointLoc = ControlFile->prevCheckPoint;
4793 record = ReadCheckpointRecord(checkPointLoc, 2);
4797 (errmsg("using previous checkpoint record at %X/%X",
4798 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
4799 InRecovery = true; /* force recovery even if SHUTDOWNED */
4803 (errmsg("could not locate a valid checkpoint record")));
4807 LastRec = RecPtr = checkPointLoc;
4808 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
4809 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
4812 (errmsg("redo record is at %X/%X; shutdown %s",
4813 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
4814 wasShutdown ? "TRUE" : "FALSE")));
4816 (errmsg("next transaction ID: %u/%u; next OID: %u",
4817 checkPoint.nextXidEpoch, checkPoint.nextXid,
4818 checkPoint.nextOid)));
4820 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
4821 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
4822 if (!TransactionIdIsNormal(checkPoint.nextXid))
4824 (errmsg("invalid next transaction ID")));
4826 ShmemVariableCache->nextXid = checkPoint.nextXid;
4827 ShmemVariableCache->nextOid = checkPoint.nextOid;
4828 ShmemVariableCache->oidCount = 0;
4829 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4832 * We must replay WAL entries using the same TimeLineID they were created
4833 * under, so temporarily adopt the TLI indicated by the checkpoint (see
4834 * also xlog_redo()).
4836 ThisTimeLineID = checkPoint.ThisTimeLineID;
4838 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
4840 if (XLByteLT(RecPtr, checkPoint.redo))
4842 (errmsg("invalid redo in checkpoint record")));
4845 * Check whether we need to force recovery from WAL. If it appears to
4846 * have been a clean shutdown and we did not have a recovery.conf file,
4847 * then assume no recovery needed.
4849 if (XLByteLT(checkPoint.redo, RecPtr))
4853 (errmsg("invalid redo record in shutdown checkpoint")));
4856 else if (ControlFile->state != DB_SHUTDOWNED)
4858 else if (InArchiveRecovery)
4860 /* force recovery due to presence of recovery.conf */
4870 * Update pg_control to show that we are recovering and to show the
4871 * selected checkpoint as the place we are starting from. We also mark
4872 * pg_control with any minimum recovery stop point obtained from a
4873 * backup history file.
4875 if (InArchiveRecovery)
4878 (errmsg("automatic recovery in progress")));
4879 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
4884 (errmsg("database system was not properly shut down; "
4885 "automatic recovery in progress")));
4886 ControlFile->state = DB_IN_CRASH_RECOVERY;
4888 ControlFile->prevCheckPoint = ControlFile->checkPoint;
4889 ControlFile->checkPoint = checkPointLoc;
4890 ControlFile->checkPointCopy = checkPoint;
4891 if (minRecoveryLoc.xlogid != 0 || minRecoveryLoc.xrecoff != 0)
4892 ControlFile->minRecoveryPoint = minRecoveryLoc;
4893 ControlFile->time = time(NULL);
4894 UpdateControlFile();
4897 * If there was a backup label file, it's done its job and the info
4898 * has now been propagated into pg_control. We must get rid of the
4899 * label file so that if we crash during recovery, we'll pick up at
4900 * the latest recovery restartpoint instead of going all the way back
4901 * to the backup start point. It seems prudent though to just rename
4902 * the file out of the way rather than delete it completely.
4904 if (haveBackupLabel)
4906 unlink(BACKUP_LABEL_OLD);
4907 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
4909 (errcode_for_file_access(),
4910 errmsg("could not rename file \"%s\" to \"%s\": %m",
4911 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
4914 /* Start up the recovery environment */
4915 XLogInitRelationCache();
4917 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
4919 if (RmgrTable[rmid].rm_startup != NULL)
4920 RmgrTable[rmid].rm_startup();
4924 * Find the first record that logically follows the checkpoint --- it
4925 * might physically precede it, though.
4927 if (XLByteLT(checkPoint.redo, RecPtr))
4929 /* back up to find the record */
4930 record = ReadRecord(&(checkPoint.redo), PANIC);
4934 /* just have to read next record after CheckPoint */
4935 record = ReadRecord(NULL, LOG);
4940 bool recoveryContinue = true;
4941 bool recoveryApply = true;
4942 ErrorContextCallback errcontext;
4946 (errmsg("redo starts at %X/%X",
4947 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
4950 * main redo apply loop
4959 initStringInfo(&buf);
4960 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
4961 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
4962 EndRecPtr.xlogid, EndRecPtr.xrecoff);
4963 xlog_outrec(&buf, record);
4964 appendStringInfo(&buf, " - ");
4965 RmgrTable[record->xl_rmid].rm_desc(&buf,
4967 XLogRecGetData(record));
4968 elog(LOG, "%s", buf.data);
4974 * Have we reached our recovery target?
4976 if (recoveryStopsHere(record, &recoveryApply))
4978 needNewTimeLine = true; /* see below */
4979 recoveryContinue = false;
4984 /* Setup error traceback support for ereport() */
4985 errcontext.callback = rm_redo_error_callback;
4986 errcontext.arg = (void *) record;
4987 errcontext.previous = error_context_stack;
4988 error_context_stack = &errcontext;
4990 /* nextXid must be beyond record's xid */
4991 if (TransactionIdFollowsOrEquals(record->xl_xid,
4992 ShmemVariableCache->nextXid))
4994 ShmemVariableCache->nextXid = record->xl_xid;
4995 TransactionIdAdvance(ShmemVariableCache->nextXid);
4998 if (record->xl_info & XLR_BKP_BLOCK_MASK)
4999 RestoreBkpBlocks(record, EndRecPtr);
5001 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
5003 /* Pop the error context stack */
5004 error_context_stack = errcontext.previous;
5006 LastRec = ReadRecPtr;
5008 record = ReadRecord(NULL, LOG);
5009 } while (record != NULL && recoveryContinue);
5012 * end of main redo apply loop
5016 (errmsg("redo done at %X/%X",
5017 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5022 /* there are no WAL records following the checkpoint */
5024 (errmsg("redo is not required")));
5029 * Re-fetch the last valid or last applied record, so we can identify the
5030 * exact endpoint of what we consider the valid portion of WAL.
5032 record = ReadRecord(&LastRec, PANIC);
5033 EndOfLog = EndRecPtr;
5034 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
5037 * Complain if we did not roll forward far enough to render the backup
5040 if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
5042 if (needNewTimeLine) /* stopped because of stop request */
5044 (errmsg("requested recovery stop point is before end time of backup dump")));
5046 /* ran off end of WAL */
5048 (errmsg("WAL ends before end time of backup dump")));
5052 * Consider whether we need to assign a new timeline ID.
5054 * If we stopped short of the end of WAL during recovery, then we are
5055 * generating a new timeline and must assign it a unique new ID.
5056 * Otherwise, we can just extend the timeline we were in when we ran out
5059 if (needNewTimeLine)
5061 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5063 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5064 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5065 curFileTLI, endLogId, endLogSeg);
5068 /* Save the selected TimeLineID in shared memory, too */
5069 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5072 * We are now done reading the old WAL. Turn off archive fetching if it
5073 * was active, and make a writable copy of the last WAL segment. (Note
5074 * that we also have a copy of the last block of the old WAL in readBuf;
5075 * we will use that below.)
5077 if (InArchiveRecovery)
5078 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5081 * Prepare to write WAL starting at EndOfLog position, and init xlog
5082 * buffer cache using the block containing the last record from the
5083 * previous incarnation.
5085 openLogId = endLogId;
5086 openLogSeg = endLogSeg;
5087 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5089 Insert = &XLogCtl->Insert;
5090 Insert->PrevRecord = LastRec;
5091 XLogCtl->xlblocks[0].xlogid = openLogId;
5092 XLogCtl->xlblocks[0].xrecoff =
5093 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5096 * Tricky point here: readBuf contains the *last* block that the LastRec
5097 * record spans, not the one it starts in. The last block is indeed the
5098 * one we want to use.
5100 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5101 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5102 Insert->currpos = (char *) Insert->currpage +
5103 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5105 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5107 XLogCtl->Write.LogwrtResult = LogwrtResult;
5108 Insert->LogwrtResult = LogwrtResult;
5109 XLogCtl->LogwrtResult = LogwrtResult;
5111 XLogCtl->LogwrtRqst.Write = EndOfLog;
5112 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5114 freespace = INSERT_FREESPACE(Insert);
5117 /* Make sure rest of page is zero */
5118 MemSet(Insert->currpos, 0, freespace);
5119 XLogCtl->Write.curridx = 0;
5124 * Whenever Write.LogwrtResult points to exactly the end of a page,
5125 * Write.curridx must point to the *next* page (see XLogWrite()).
5127 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5128 * this is sufficient. The first actual attempt to insert a log
5129 * record will advance the insert state.
5131 XLogCtl->Write.curridx = NextBufIdx(0);
5134 /* Pre-scan prepared transactions to find out the range of XIDs present */
5135 oldestActiveXID = PrescanPreparedTransactions();
5142 * Allow resource managers to do any required cleanup.
5144 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5146 if (RmgrTable[rmid].rm_cleanup != NULL)
5147 RmgrTable[rmid].rm_cleanup();
5151 * Check to see if the XLOG sequence contained any unresolved
5152 * references to uninitialized pages.
5154 XLogCheckInvalidPages();
5157 * Reset pgstat data, because it may be invalid after recovery.
5162 * Perform a checkpoint to update all our recovery activity to disk.
5164 * Note that we write a shutdown checkpoint rather than an on-line
5165 * one. This is not particularly critical, but since we may be
5166 * assigning a new TLI, using a shutdown checkpoint allows us to have
5167 * the rule that TLI only changes in shutdown checkpoints, which
5168 * allows some extra error checking in xlog_redo.
5170 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5173 * Close down recovery environment
5175 XLogCloseRelationCache();
5179 * Preallocate additional log files, if wanted.
5181 PreallocXlogFiles(EndOfLog);
5184 * Okay, we're officially UP.
5188 ControlFile->state = DB_IN_PRODUCTION;
5189 ControlFile->time = time(NULL);
5190 UpdateControlFile();
5192 /* start the archive_timeout timer running */
5193 XLogCtl->Write.lastSegSwitchTime = ControlFile->time;
5195 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5196 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5197 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5199 /* Start up the commit log and related stuff, too */
5201 StartupSUBTRANS(oldestActiveXID);
5204 /* Reload shared-memory state for prepared transactions */
5205 RecoverPreparedTransactions();
5207 /* Shut down readFile facility, free space */
5220 free(readRecordBuf);
5221 readRecordBuf = NULL;
5222 readRecordBufSize = 0;
5227 * Subroutine to try to fetch and validate a prior checkpoint record.
5229 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5230 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5233 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5237 if (!XRecOffIsValid(RecPtr.xrecoff))
5243 (errmsg("invalid primary checkpoint link in control file")));
5247 (errmsg("invalid secondary checkpoint link in control file")));
5251 (errmsg("invalid checkpoint link in backup_label file")));
5257 record = ReadRecord(&RecPtr, LOG);
5265 (errmsg("invalid primary checkpoint record")));
5269 (errmsg("invalid secondary checkpoint record")));
5273 (errmsg("invalid checkpoint record")));
5278 if (record->xl_rmid != RM_XLOG_ID)
5284 (errmsg("invalid resource manager ID in primary checkpoint record")));
5288 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5292 (errmsg("invalid resource manager ID in checkpoint record")));
5297 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5298 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5304 (errmsg("invalid xl_info in primary checkpoint record")));
5308 (errmsg("invalid xl_info in secondary checkpoint record")));
5312 (errmsg("invalid xl_info in checkpoint record")));
5317 if (record->xl_len != sizeof(CheckPoint) ||
5318 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5324 (errmsg("invalid length of primary checkpoint record")));
5328 (errmsg("invalid length of secondary checkpoint record")));
5332 (errmsg("invalid length of checkpoint record")));
5341 * This must be called during startup of a backend process, except that
5342 * it need not be called in a standalone backend (which does StartupXLOG
5343 * instead). We need to initialize the local copies of ThisTimeLineID and
5346 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5347 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5348 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5351 InitXLOGAccess(void)
5353 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5354 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5355 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5356 (void) GetRedoRecPtr();
5360 * Once spawned, a backend may update its local RedoRecPtr from
5361 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5362 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5367 /* use volatile pointer to prevent code rearrangement */
5368 volatile XLogCtlData *xlogctl = XLogCtl;
5370 SpinLockAcquire(&xlogctl->info_lck);
5371 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5372 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5373 SpinLockRelease(&xlogctl->info_lck);
5379 * GetInsertRecPtr -- Returns the current insert position.
5381 * NOTE: The value *actually* returned is the position of the last full
5382 * xlog page. It lags behind the real insert position by at most 1 page.
5383 * For that, we don't need to acquire WALInsertLock which can be quite
5384 * heavily contended, and an approximation is enough for the current
5385 * usage of this function.
5388 GetInsertRecPtr(void)
5390 /* use volatile pointer to prevent code rearrangement */
5391 volatile XLogCtlData *xlogctl = XLogCtl;
5394 SpinLockAcquire(&xlogctl->info_lck);
5395 recptr = xlogctl->LogwrtRqst.Write;
5396 SpinLockRelease(&xlogctl->info_lck);
5402 * Get the time of the last xlog segment switch
5405 GetLastSegSwitchTime(void)
5409 /* Need WALWriteLock, but shared lock is sufficient */
5410 LWLockAcquire(WALWriteLock, LW_SHARED);
5411 result = XLogCtl->Write.lastSegSwitchTime;
5412 LWLockRelease(WALWriteLock);
5418 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5420 * This is exported for use by code that would like to have 64-bit XIDs.
5421 * We don't really support such things, but all XIDs within the system
5422 * can be presumed "close to" the result, and thus the epoch associated
5423 * with them can be determined.
5426 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5428 uint32 ckptXidEpoch;
5429 TransactionId ckptXid;
5430 TransactionId nextXid;
5432 /* Must read checkpoint info first, else have race condition */
5434 /* use volatile pointer to prevent code rearrangement */
5435 volatile XLogCtlData *xlogctl = XLogCtl;
5437 SpinLockAcquire(&xlogctl->info_lck);
5438 ckptXidEpoch = xlogctl->ckptXidEpoch;
5439 ckptXid = xlogctl->ckptXid;
5440 SpinLockRelease(&xlogctl->info_lck);
5443 /* Now fetch current nextXid */
5444 nextXid = ReadNewTransactionId();
5447 * nextXid is certainly logically later than ckptXid. So if it's
5448 * numerically less, it must have wrapped into the next epoch.
5450 if (nextXid < ckptXid)
5454 *epoch = ckptXidEpoch;
5458 * This must be called ONCE during postmaster or standalone-backend shutdown
5461 ShutdownXLOG(int code, Datum arg)
5464 (errmsg("shutting down")));
5466 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5469 ShutdownMultiXact();
5472 (errmsg("database system is shut down")));
5476 * Log start of a checkpoint.
5479 LogCheckpointStart(int flags)
5481 elog(LOG, "checkpoint starting:%s%s%s%s%s%s",
5482 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
5483 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
5484 (flags & CHECKPOINT_FORCE) ? " force" : "",
5485 (flags & CHECKPOINT_WAIT) ? " wait" : "",
5486 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
5487 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
5491 * Log end of a checkpoint.
5494 LogCheckpointEnd(void)
5496 long write_secs, sync_secs, total_secs;
5497 int write_usecs, sync_usecs, total_usecs;
5499 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
5501 TimestampDifference(CheckpointStats.ckpt_start_t,
5502 CheckpointStats.ckpt_end_t,
5503 &total_secs, &total_usecs);
5505 TimestampDifference(CheckpointStats.ckpt_write_t,
5506 CheckpointStats.ckpt_sync_t,
5507 &write_secs, &write_usecs);
5509 TimestampDifference(CheckpointStats.ckpt_sync_t,
5510 CheckpointStats.ckpt_sync_end_t,
5511 &sync_secs, &sync_usecs);
5513 elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
5514 "%d transaction log file(s) added, %d removed, %d recycled; "
5515 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
5516 CheckpointStats.ckpt_bufs_written,
5517 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
5518 CheckpointStats.ckpt_segs_added,
5519 CheckpointStats.ckpt_segs_removed,
5520 CheckpointStats.ckpt_segs_recycled,
5521 write_secs, write_usecs/1000,
5522 sync_secs, sync_usecs/1000,
5523 total_secs, total_usecs/1000);
5527 * Perform a checkpoint --- either during shutdown, or on-the-fly
5529 * flags is a bitwise OR of the following:
5530 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
5531 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
5532 * ignoring checkpoint_completion_target parameter.
5533 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
5534 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
5536 * Note: flags contains other bits, of interest here only for logging purposes.
5537 * In particular note that this routine is synchronous and does not pay
5538 * attention to CHECKPOINT_WAIT.
5541 CreateCheckPoint(int flags)
5543 bool shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
5544 CheckPoint checkPoint;
5546 XLogCtlInsert *Insert = &XLogCtl->Insert;
5551 TransactionId *inCommitXids;
5555 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
5556 * (This is just pro forma, since in the present system structure there is
5557 * only one process that is allowed to issue checkpoints at any given
5560 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
5563 * Prepare to accumulate statistics.
5565 * Note: because it is possible for log_checkpoints to change while a
5566 * checkpoint proceeds, we always accumulate stats, even if
5567 * log_checkpoints is currently off.
5569 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
5570 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
5573 * Use a critical section to force system panic if we have trouble.
5575 START_CRIT_SECTION();
5579 ControlFile->state = DB_SHUTDOWNING;
5580 ControlFile->time = time(NULL);
5581 UpdateControlFile();
5584 MemSet(&checkPoint, 0, sizeof(checkPoint));
5585 checkPoint.ThisTimeLineID = ThisTimeLineID;
5586 checkPoint.time = time(NULL);
5589 * We must hold WALInsertLock while examining insert state to determine
5590 * the checkpoint REDO pointer.
5592 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
5595 * If this isn't a shutdown or forced checkpoint, and we have not inserted
5596 * any XLOG records since the start of the last checkpoint, skip the
5597 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
5598 * when the system is idle. That wastes log space, and more importantly it
5599 * exposes us to possible loss of both current and previous checkpoint
5600 * records if the machine crashes just as we're writing the update.
5601 * (Perhaps it'd make even more sense to checkpoint only when the previous
5602 * checkpoint record is in a different xlog page?)
5604 * We have to make two tests to determine that nothing has happened since
5605 * the start of the last checkpoint: current insertion point must match
5606 * the end of the last checkpoint record, and its redo pointer must point
5609 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
5611 XLogRecPtr curInsert;
5613 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
5614 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
5615 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
5616 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
5617 ControlFile->checkPoint.xlogid ==
5618 ControlFile->checkPointCopy.redo.xlogid &&
5619 ControlFile->checkPoint.xrecoff ==
5620 ControlFile->checkPointCopy.redo.xrecoff)
5622 LWLockRelease(WALInsertLock);
5623 LWLockRelease(CheckpointLock);
5630 * Compute new REDO record ptr = location of next XLOG record.
5632 * NB: this is NOT necessarily where the checkpoint record itself will be,
5633 * since other backends may insert more XLOG records while we're off doing
5634 * the buffer flush work. Those XLOG records are logically after the
5635 * checkpoint, even though physically before it. Got that?
5637 freespace = INSERT_FREESPACE(Insert);
5638 if (freespace < SizeOfXLogRecord)
5640 (void) AdvanceXLInsertBuffer(false);
5641 /* OK to ignore update return flag, since we will do flush anyway */
5642 freespace = INSERT_FREESPACE(Insert);
5644 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
5647 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
5648 * must be done while holding the insert lock AND the info_lck.
5650 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
5651 * pointing past where it really needs to point. This is okay; the only
5652 * consequence is that XLogInsert might back up whole buffers that it
5653 * didn't really need to. We can't postpone advancing RedoRecPtr because
5654 * XLogInserts that happen while we are dumping buffers must assume that
5655 * their buffer changes are not included in the checkpoint.
5658 /* use volatile pointer to prevent code rearrangement */
5659 volatile XLogCtlData *xlogctl = XLogCtl;
5661 SpinLockAcquire(&xlogctl->info_lck);
5662 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
5663 SpinLockRelease(&xlogctl->info_lck);
5667 * Now we can release WAL insert lock, allowing other xacts to proceed
5668 * while we are flushing disk buffers.
5670 LWLockRelease(WALInsertLock);
5673 * If enabled, log checkpoint start. We postpone this until now
5674 * so as not to log anything if we decided to skip the checkpoint.
5676 if (log_checkpoints)
5677 LogCheckpointStart(flags);
5680 * Before flushing data, we must wait for any transactions that are
5681 * currently in their commit critical sections. If an xact inserted its
5682 * commit record into XLOG just before the REDO point, then a crash
5683 * restart from the REDO point would not replay that record, which means
5684 * that our flushing had better include the xact's update of pg_clog. So
5685 * we wait till he's out of his commit critical section before proceeding.
5686 * See notes in RecordTransactionCommit().
5688 * Because we've already released WALInsertLock, this test is a bit fuzzy:
5689 * it is possible that we will wait for xacts we didn't really need to
5690 * wait for. But the delay should be short and it seems better to make
5691 * checkpoint take a bit longer than to hold locks longer than necessary.
5692 * (In fact, the whole reason we have this issue is that xact.c does
5693 * commit record XLOG insertion and clog update as two separate steps
5694 * protected by different locks, but again that seems best on grounds
5695 * of minimizing lock contention.)
5697 * A transaction that has not yet set inCommit when we look cannot be
5698 * at risk, since he's not inserted his commit record yet; and one that's
5699 * already cleared it is not at risk either, since he's done fixing clog
5700 * and we will correctly flush the update below. So we cannot miss any
5701 * xacts we need to wait for.
5703 nInCommit = GetTransactionsInCommit(&inCommitXids);
5707 pg_usleep(10000L); /* wait for 10 msec */
5708 } while (HaveTransactionsInCommit(inCommitXids, nInCommit));
5710 pfree(inCommitXids);
5713 * Get the other info we need for the checkpoint record.
5715 LWLockAcquire(XidGenLock, LW_SHARED);
5716 checkPoint.nextXid = ShmemVariableCache->nextXid;
5717 LWLockRelease(XidGenLock);
5719 /* Increase XID epoch if we've wrapped around since last checkpoint */
5720 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5721 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
5722 checkPoint.nextXidEpoch++;
5724 LWLockAcquire(OidGenLock, LW_SHARED);
5725 checkPoint.nextOid = ShmemVariableCache->nextOid;
5727 checkPoint.nextOid += ShmemVariableCache->oidCount;
5728 LWLockRelease(OidGenLock);
5730 MultiXactGetCheckptMulti(shutdown,
5731 &checkPoint.nextMulti,
5732 &checkPoint.nextMultiOffset);
5735 * Having constructed the checkpoint record, ensure all shmem disk buffers
5736 * and commit-log buffers are flushed to disk.
5738 * This I/O could fail for various reasons. If so, we will fail to
5739 * complete the checkpoint, but there is no reason to force a system
5740 * panic. Accordingly, exit critical section while doing it.
5744 CheckPointGuts(checkPoint.redo, flags);
5746 START_CRIT_SECTION();
5749 * Now insert the checkpoint record into XLOG.
5751 rdata.data = (char *) (&checkPoint);
5752 rdata.len = sizeof(checkPoint);
5753 rdata.buffer = InvalidBuffer;
5756 recptr = XLogInsert(RM_XLOG_ID,
5757 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
5758 XLOG_CHECKPOINT_ONLINE,
5764 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
5765 * = end of actual checkpoint record.
5767 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
5769 (errmsg("concurrent transaction log activity while database system is shutting down")));
5772 * Select point at which we can truncate the log, which we base on the
5773 * prior checkpoint's earliest info.
5775 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
5778 * Update the control file.
5780 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5782 ControlFile->state = DB_SHUTDOWNED;
5783 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5784 ControlFile->checkPoint = ProcLastRecPtr;
5785 ControlFile->checkPointCopy = checkPoint;
5786 ControlFile->time = time(NULL);
5787 UpdateControlFile();
5788 LWLockRelease(ControlFileLock);
5790 /* Update shared-memory copy of checkpoint XID/epoch */
5792 /* use volatile pointer to prevent code rearrangement */
5793 volatile XLogCtlData *xlogctl = XLogCtl;
5795 SpinLockAcquire(&xlogctl->info_lck);
5796 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
5797 xlogctl->ckptXid = checkPoint.nextXid;
5798 SpinLockRelease(&xlogctl->info_lck);
5802 * We are now done with critical updates; no need for system panic if we
5803 * have trouble while fooling with old log segments.
5808 * Delete old log files (those no longer needed even for previous
5811 if (_logId || _logSeg)
5813 PrevLogSeg(_logId, _logSeg);
5814 RemoveOldXlogFiles(_logId, _logSeg, recptr);
5818 * Make more log segments if needed. (Do this after recycling old log
5819 * segments, since that may supply some of the needed files.)
5822 PreallocXlogFiles(recptr);
5825 * Truncate pg_subtrans if possible. We can throw away all data before
5826 * the oldest XMIN of any running transaction. No future transaction will
5827 * attempt to reference any pg_subtrans entry older than that (see Asserts
5828 * in subtrans.c). During recovery, though, we mustn't do this because
5829 * StartupSUBTRANS hasn't been called yet.
5832 TruncateSUBTRANS(GetOldestXmin(true, false));
5834 /* All real work is done, but log before releasing lock. */
5835 if (log_checkpoints)
5838 LWLockRelease(CheckpointLock);
5842 * Flush all data in shared memory to disk, and fsync
5844 * This is the common code shared between regular checkpoints and
5845 * recovery restartpoints.
5848 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
5851 CheckPointSUBTRANS();
5852 CheckPointMultiXact();
5853 CheckPointBuffers(flags); /* performs all required fsyncs */
5854 /* We deliberately delay 2PC checkpointing as long as possible */
5855 CheckPointTwoPhase(checkPointRedo);
5859 * Set a recovery restart point if appropriate
5861 * This is similar to CreateCheckPoint, but is used during WAL recovery
5862 * to establish a point from which recovery can roll forward without
5863 * replaying the entire recovery log. This function is called each time
5864 * a checkpoint record is read from XLOG; it must determine whether a
5865 * restartpoint is needed or not.
5868 RecoveryRestartPoint(const CheckPoint *checkPoint)
5874 * Do nothing if the elapsed time since the last restartpoint is less than
5875 * half of checkpoint_timeout. (We use a value less than
5876 * checkpoint_timeout so that variations in the timing of checkpoints on
5877 * the master, or speed of transmission of WAL segments to a slave, won't
5878 * make the slave skip a restartpoint once it's synced with the master.)
5879 * Checking true elapsed time keeps us from doing restartpoints too often
5880 * while rapidly scanning large amounts of WAL.
5882 elapsed_secs = time(NULL) - ControlFile->time;
5883 if (elapsed_secs < CheckPointTimeout / 2)
5887 * Is it safe to checkpoint? We must ask each of the resource managers
5888 * whether they have any partial state information that might prevent a
5889 * correct restart from this point. If so, we skip this opportunity, but
5890 * return at the next checkpoint record for another try.
5892 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5894 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
5895 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
5897 elog(DEBUG2, "RM %d not safe to record restart point at %X/%X",
5899 checkPoint->redo.xlogid,
5900 checkPoint->redo.xrecoff);
5906 * OK, force data out to disk
5908 CheckPointGuts(checkPoint->redo, CHECKPOINT_IMMEDIATE);
5911 * Update pg_control so that any subsequent crash will restart from this
5912 * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
5915 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5916 ControlFile->checkPoint = ReadRecPtr;
5917 ControlFile->checkPointCopy = *checkPoint;
5918 ControlFile->time = time(NULL);
5919 UpdateControlFile();
5922 (errmsg("recovery restart point at %X/%X",
5923 checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
5927 * Write a NEXTOID log record
5930 XLogPutNextOid(Oid nextOid)
5934 rdata.data = (char *) (&nextOid);
5935 rdata.len = sizeof(Oid);
5936 rdata.buffer = InvalidBuffer;
5938 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
5941 * We need not flush the NEXTOID record immediately, because any of the
5942 * just-allocated OIDs could only reach disk as part of a tuple insert or
5943 * update that would have its own XLOG record that must follow the NEXTOID
5944 * record. Therefore, the standard buffer LSN interlock applied to those
5945 * records will ensure no such OID reaches disk before the NEXTOID record
5948 * Note, however, that the above statement only covers state "within" the
5949 * database. When we use a generated OID as a file or directory name,
5950 * we are in a sense violating the basic WAL rule, because that filesystem
5951 * change may reach disk before the NEXTOID WAL record does. The impact
5952 * of this is that if a database crash occurs immediately afterward,
5953 * we might after restart re-generate the same OID and find that it
5954 * conflicts with the leftover file or directory. But since for safety's
5955 * sake we always loop until finding a nonconflicting filename, this poses
5956 * no real problem in practice. See pgsql-hackers discussion 27-Sep-2006.
5961 * Write an XLOG SWITCH record.
5963 * Here we just blindly issue an XLogInsert request for the record.
5964 * All the magic happens inside XLogInsert.
5966 * The return value is either the end+1 address of the switch record,
5967 * or the end+1 address of the prior segment if we did not need to
5968 * write a switch record because we are already at segment start.
5971 RequestXLogSwitch(void)
5976 /* XLOG SWITCH, alone among xlog record types, has no data */
5977 rdata.buffer = InvalidBuffer;
5982 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
5988 * XLOG resource manager's routines
5991 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
5993 uint8 info = record->xl_info & ~XLR_INFO_MASK;
5995 if (info == XLOG_NEXTOID)
5999 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
6000 if (ShmemVariableCache->nextOid < nextOid)
6002 ShmemVariableCache->nextOid = nextOid;
6003 ShmemVariableCache->oidCount = 0;
6006 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
6008 CheckPoint checkPoint;
6010 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6011 /* In a SHUTDOWN checkpoint, believe the counters exactly */
6012 ShmemVariableCache->nextXid = checkPoint.nextXid;
6013 ShmemVariableCache->nextOid = checkPoint.nextOid;
6014 ShmemVariableCache->oidCount = 0;
6015 MultiXactSetNextMXact(checkPoint.nextMulti,
6016 checkPoint.nextMultiOffset);
6018 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6019 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6020 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6023 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
6025 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6027 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
6028 !list_member_int(expectedTLIs,
6029 (int) checkPoint.ThisTimeLineID))
6031 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
6032 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6033 /* Following WAL records should be run with new TLI */
6034 ThisTimeLineID = checkPoint.ThisTimeLineID;
6037 RecoveryRestartPoint(&checkPoint);
6039 else if (info == XLOG_CHECKPOINT_ONLINE)
6041 CheckPoint checkPoint;
6043 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6044 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
6045 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
6046 checkPoint.nextXid))
6047 ShmemVariableCache->nextXid = checkPoint.nextXid;
6048 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
6050 ShmemVariableCache->nextOid = checkPoint.nextOid;
6051 ShmemVariableCache->oidCount = 0;
6053 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
6054 checkPoint.nextMultiOffset);
6056 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6057 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6058 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6060 /* TLI should not change in an on-line checkpoint */
6061 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6063 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
6064 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6066 RecoveryRestartPoint(&checkPoint);
6068 else if (info == XLOG_NOOP)
6070 /* nothing to do here */
6072 else if (info == XLOG_SWITCH)
6074 /* nothing to do here */
6079 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
6081 uint8 info = xl_info & ~XLR_INFO_MASK;
6083 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
6084 info == XLOG_CHECKPOINT_ONLINE)
6086 CheckPoint *checkpoint = (CheckPoint *) rec;
6088 appendStringInfo(buf, "checkpoint: redo %X/%X; "
6089 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
6090 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
6091 checkpoint->ThisTimeLineID,
6092 checkpoint->nextXidEpoch, checkpoint->nextXid,
6093 checkpoint->nextOid,
6094 checkpoint->nextMulti,
6095 checkpoint->nextMultiOffset,
6096 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
6098 else if (info == XLOG_NOOP)
6100 appendStringInfo(buf, "xlog no-op");
6102 else if (info == XLOG_NEXTOID)
6106 memcpy(&nextOid, rec, sizeof(Oid));
6107 appendStringInfo(buf, "nextOid: %u", nextOid);
6109 else if (info == XLOG_SWITCH)
6111 appendStringInfo(buf, "xlog switch");
6114 appendStringInfo(buf, "UNKNOWN");
6120 xlog_outrec(StringInfo buf, XLogRecord *record)
6124 appendStringInfo(buf, "prev %X/%X; xid %u",
6125 record->xl_prev.xlogid, record->xl_prev.xrecoff,
6128 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
6130 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
6131 appendStringInfo(buf, "; bkpb%d", i + 1);
6134 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
6136 #endif /* WAL_DEBUG */
6143 assign_xlog_sync_method(const char *method, bool doit, GucSource source)
6145 int new_sync_method;
6148 if (pg_strcasecmp(method, "fsync") == 0)
6150 new_sync_method = SYNC_METHOD_FSYNC;
6153 #ifdef HAVE_FSYNC_WRITETHROUGH
6154 else if (pg_strcasecmp(method, "fsync_writethrough") == 0)
6156 new_sync_method = SYNC_METHOD_FSYNC_WRITETHROUGH;
6160 #ifdef HAVE_FDATASYNC
6161 else if (pg_strcasecmp(method, "fdatasync") == 0)
6163 new_sync_method = SYNC_METHOD_FDATASYNC;
6167 #ifdef OPEN_SYNC_FLAG
6168 else if (pg_strcasecmp(method, "open_sync") == 0)
6170 new_sync_method = SYNC_METHOD_OPEN;
6171 new_sync_bit = OPEN_SYNC_FLAG;
6174 #ifdef OPEN_DATASYNC_FLAG
6175 else if (pg_strcasecmp(method, "open_datasync") == 0)
6177 new_sync_method = SYNC_METHOD_OPEN;
6178 new_sync_bit = OPEN_DATASYNC_FLAG;
6187 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
6190 * To ensure that no blocks escape unsynced, force an fsync on the
6191 * currently open log segment (if any). Also, if the open flag is
6192 * changing, close the log file so it will be reopened (with new flag
6195 if (openLogFile >= 0)
6197 if (pg_fsync(openLogFile) != 0)
6199 (errcode_for_file_access(),
6200 errmsg("could not fsync log file %u, segment %u: %m",
6201 openLogId, openLogSeg)));
6202 if (open_sync_bit != new_sync_bit)
6205 sync_method = new_sync_method;
6206 open_sync_bit = new_sync_bit;
6214 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6217 issue_xlog_fsync(void)
6219 switch (sync_method)
6221 case SYNC_METHOD_FSYNC:
6222 if (pg_fsync_no_writethrough(openLogFile) != 0)
6224 (errcode_for_file_access(),
6225 errmsg("could not fsync log file %u, segment %u: %m",
6226 openLogId, openLogSeg)));
6228 #ifdef HAVE_FSYNC_WRITETHROUGH
6229 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6230 if (pg_fsync_writethrough(openLogFile) != 0)
6232 (errcode_for_file_access(),
6233 errmsg("could not fsync write-through log file %u, segment %u: %m",
6234 openLogId, openLogSeg)));
6237 #ifdef HAVE_FDATASYNC
6238 case SYNC_METHOD_FDATASYNC:
6239 if (pg_fdatasync(openLogFile) != 0)
6241 (errcode_for_file_access(),
6242 errmsg("could not fdatasync log file %u, segment %u: %m",
6243 openLogId, openLogSeg)));
6246 case SYNC_METHOD_OPEN:
6247 /* write synced it already */
6250 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6257 * pg_start_backup: set up for taking an on-line backup dump
6259 * Essentially what this does is to create a backup label file in $PGDATA,
6260 * where it will be archived as part of the backup dump. The label file
6261 * contains the user-supplied label string (typically this would be used
6262 * to tell where the backup dump will be stored) and the starting time and
6263 * starting WAL location for the dump.
6266 pg_start_backup(PG_FUNCTION_ARGS)
6268 text *backupid = PG_GETARG_TEXT_P(0);
6271 XLogRecPtr checkpointloc;
6272 XLogRecPtr startpoint;
6273 pg_time_t stamp_time;
6275 char xlogfilename[MAXFNAMELEN];
6278 struct stat stat_buf;
6283 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6284 (errmsg("must be superuser to run a backup"))));
6286 if (!XLogArchivingActive())
6288 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6289 (errmsg("WAL archiving is not active"),
6290 (errhint("archive_command must be defined before "
6291 "online backups can be made safely.")))));
6293 backupidstr = DatumGetCString(DirectFunctionCall1(textout,
6294 PointerGetDatum(backupid)));
6297 * Mark backup active in shared memory. We must do full-page WAL writes
6298 * during an on-line backup even if not doing so at other times, because
6299 * it's quite possible for the backup dump to obtain a "torn" (partially
6300 * written) copy of a database page if it reads the page concurrently with
6301 * our write to the same page. This can be fixed as long as the first
6302 * write to the page in the WAL sequence is a full-page write. Hence, we
6303 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6304 * are no dirty pages in shared memory that might get dumped while the
6305 * backup is in progress without having a corresponding WAL record. (Once
6306 * the backup is complete, we need not force full-page writes anymore,
6307 * since we expect that any pages not modified during the backup interval
6308 * must have been correctly captured by the backup.)
6310 * We must hold WALInsertLock to change the value of forcePageWrites, to
6311 * ensure adequate interlocking against XLogInsert().
6313 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6314 if (XLogCtl->Insert.forcePageWrites)
6316 LWLockRelease(WALInsertLock);
6318 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6319 errmsg("a backup is already in progress"),
6320 errhint("Run pg_stop_backup() and try again.")));
6322 XLogCtl->Insert.forcePageWrites = true;
6323 LWLockRelease(WALInsertLock);
6325 /* Use a TRY block to ensure we release forcePageWrites if fail below */
6329 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6330 * page problems, this guarantees that two successive backup runs will
6331 * have different checkpoint positions and hence different history
6332 * file names, even if nothing happened in between.
6334 * We don't use CHECKPOINT_IMMEDIATE, hence this can take awhile.
6336 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT);
6339 * Now we need to fetch the checkpoint record location, and also its
6340 * REDO pointer. The oldest point in WAL that would be needed to
6341 * restore starting from the checkpoint is precisely the REDO pointer.
6343 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6344 checkpointloc = ControlFile->checkPoint;
6345 startpoint = ControlFile->checkPointCopy.redo;
6346 LWLockRelease(ControlFileLock);
6348 XLByteToSeg(startpoint, _logId, _logSeg);
6349 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
6351 /* Use the log timezone here, not the session timezone */
6352 stamp_time = (pg_time_t) time(NULL);
6353 pg_strftime(strfbuf, sizeof(strfbuf),
6354 "%Y-%m-%d %H:%M:%S %Z",
6355 pg_localtime(&stamp_time, log_timezone));
6358 * Check for existing backup label --- implies a backup is already
6359 * running. (XXX given that we checked forcePageWrites above, maybe
6360 * it would be OK to just unlink any such label file?)
6362 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
6364 if (errno != ENOENT)
6366 (errcode_for_file_access(),
6367 errmsg("could not stat file \"%s\": %m",
6368 BACKUP_LABEL_FILE)));
6372 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6373 errmsg("a backup is already in progress"),
6374 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
6375 BACKUP_LABEL_FILE)));
6378 * Okay, write the file
6380 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
6383 (errcode_for_file_access(),
6384 errmsg("could not create file \"%s\": %m",
6385 BACKUP_LABEL_FILE)));
6386 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6387 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
6388 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
6389 checkpointloc.xlogid, checkpointloc.xrecoff);
6390 fprintf(fp, "START TIME: %s\n", strfbuf);
6391 fprintf(fp, "LABEL: %s\n", backupidstr);
6392 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6394 (errcode_for_file_access(),
6395 errmsg("could not write file \"%s\": %m",
6396 BACKUP_LABEL_FILE)));
6400 /* Turn off forcePageWrites on failure */
6401 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6402 XLogCtl->Insert.forcePageWrites = false;
6403 LWLockRelease(WALInsertLock);
6410 * We're done. As a convenience, return the starting WAL location.
6412 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
6413 startpoint.xlogid, startpoint.xrecoff);
6414 result = DatumGetTextP(DirectFunctionCall1(textin,
6415 CStringGetDatum(xlogfilename)));
6416 PG_RETURN_TEXT_P(result);
6420 * pg_stop_backup: finish taking an on-line backup dump
6422 * We remove the backup label file created by pg_start_backup, and instead
6423 * create a backup history file in pg_xlog (whence it will immediately be
6424 * archived). The backup history file contains the same info found in
6425 * the label file, plus the backup-end time and WAL location.
6428 pg_stop_backup(PG_FUNCTION_ARGS)
6431 XLogRecPtr startpoint;
6432 XLogRecPtr stoppoint;
6433 pg_time_t stamp_time;
6435 char histfilepath[MAXPGPATH];
6436 char startxlogfilename[MAXFNAMELEN];
6437 char stopxlogfilename[MAXFNAMELEN];
6447 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6448 (errmsg("must be superuser to run a backup"))));
6451 * OK to clear forcePageWrites
6453 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6454 XLogCtl->Insert.forcePageWrites = false;
6455 LWLockRelease(WALInsertLock);
6458 * Force a switch to a new xlog segment file, so that the backup is valid
6459 * as soon as archiver moves out the current segment file. We'll report
6460 * the end address of the XLOG SWITCH record as the backup stopping point.
6462 stoppoint = RequestXLogSwitch();
6464 XLByteToSeg(stoppoint, _logId, _logSeg);
6465 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
6467 /* Use the log timezone here, not the session timezone */
6468 stamp_time = (pg_time_t) time(NULL);
6469 pg_strftime(strfbuf, sizeof(strfbuf),
6470 "%Y-%m-%d %H:%M:%S %Z",
6471 pg_localtime(&stamp_time, log_timezone));
6474 * Open the existing label file
6476 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6479 if (errno != ENOENT)
6481 (errcode_for_file_access(),
6482 errmsg("could not read file \"%s\": %m",
6483 BACKUP_LABEL_FILE)));
6485 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6486 errmsg("a backup is not in progress")));
6490 * Read and parse the START WAL LOCATION line (this code is pretty crude,
6491 * but we are not expecting any variability in the file format).
6493 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
6494 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6495 &ch) != 4 || ch != '\n')
6497 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6498 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6501 * Write the backup history file
6503 XLByteToSeg(startpoint, _logId, _logSeg);
6504 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
6505 startpoint.xrecoff % XLogSegSize);
6506 fp = AllocateFile(histfilepath, "w");
6509 (errcode_for_file_access(),
6510 errmsg("could not create file \"%s\": %m",
6512 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
6513 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
6514 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
6515 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
6516 /* transfer remaining lines from label to history file */
6517 while ((ich = fgetc(lfp)) != EOF)
6519 fprintf(fp, "STOP TIME: %s\n", strfbuf);
6520 if (fflush(fp) || ferror(fp) || FreeFile(fp))
6522 (errcode_for_file_access(),
6523 errmsg("could not write file \"%s\": %m",
6527 * Close and remove the backup label file
6529 if (ferror(lfp) || FreeFile(lfp))
6531 (errcode_for_file_access(),
6532 errmsg("could not read file \"%s\": %m",
6533 BACKUP_LABEL_FILE)));
6534 if (unlink(BACKUP_LABEL_FILE) != 0)
6536 (errcode_for_file_access(),
6537 errmsg("could not remove file \"%s\": %m",
6538 BACKUP_LABEL_FILE)));
6541 * Clean out any no-longer-needed history files. As a side effect, this
6542 * will post a .ready file for the newly created history file, notifying
6543 * the archiver that history file may be archived immediately.
6545 CleanupBackupHistory();
6548 * We're done. As a convenience, return the ending WAL location.
6550 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
6551 stoppoint.xlogid, stoppoint.xrecoff);
6552 result = DatumGetTextP(DirectFunctionCall1(textin,
6553 CStringGetDatum(stopxlogfilename)));
6554 PG_RETURN_TEXT_P(result);
6558 * pg_switch_xlog: switch to next xlog file
6561 pg_switch_xlog(PG_FUNCTION_ARGS)
6564 XLogRecPtr switchpoint;
6565 char location[MAXFNAMELEN];
6569 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6570 (errmsg("must be superuser to switch transaction log files"))));
6572 switchpoint = RequestXLogSwitch();
6575 * As a convenience, return the WAL location of the switch record
6577 snprintf(location, sizeof(location), "%X/%X",
6578 switchpoint.xlogid, switchpoint.xrecoff);
6579 result = DatumGetTextP(DirectFunctionCall1(textin,
6580 CStringGetDatum(location)));
6581 PG_RETURN_TEXT_P(result);
6585 * Report the current WAL write location (same format as pg_start_backup etc)
6587 * This is useful for determining how much of WAL is visible to an external
6588 * archiving process. Note that the data before this point is written out
6589 * to the kernel, but is not necessarily synced to disk.
6592 pg_current_xlog_location(PG_FUNCTION_ARGS)
6595 char location[MAXFNAMELEN];
6597 /* Make sure we have an up-to-date local LogwrtResult */
6599 /* use volatile pointer to prevent code rearrangement */
6600 volatile XLogCtlData *xlogctl = XLogCtl;
6602 SpinLockAcquire(&xlogctl->info_lck);
6603 LogwrtResult = xlogctl->LogwrtResult;
6604 SpinLockRelease(&xlogctl->info_lck);
6607 snprintf(location, sizeof(location), "%X/%X",
6608 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
6610 result = DatumGetTextP(DirectFunctionCall1(textin,
6611 CStringGetDatum(location)));
6612 PG_RETURN_TEXT_P(result);
6616 * Report the current WAL insert location (same format as pg_start_backup etc)
6618 * This function is mostly for debugging purposes.
6621 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
6624 XLogCtlInsert *Insert = &XLogCtl->Insert;
6625 XLogRecPtr current_recptr;
6626 char location[MAXFNAMELEN];
6629 * Get the current end-of-WAL position ... shared lock is sufficient
6631 LWLockAcquire(WALInsertLock, LW_SHARED);
6632 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
6633 LWLockRelease(WALInsertLock);
6635 snprintf(location, sizeof(location), "%X/%X",
6636 current_recptr.xlogid, current_recptr.xrecoff);
6638 result = DatumGetTextP(DirectFunctionCall1(textin,
6639 CStringGetDatum(location)));
6640 PG_RETURN_TEXT_P(result);
6644 * Compute an xlog file name and decimal byte offset given a WAL location,
6645 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6647 * Note that a location exactly at a segment boundary is taken to be in
6648 * the previous segment. This is usually the right thing, since the
6649 * expected usage is to determine which xlog file(s) are ready to archive.
6652 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
6654 text *location = PG_GETARG_TEXT_P(0);
6656 unsigned int uxlogid;
6657 unsigned int uxrecoff;
6661 XLogRecPtr locationpoint;
6662 char xlogfilename[MAXFNAMELEN];
6665 TupleDesc resultTupleDesc;
6666 HeapTuple resultHeapTuple;
6670 * Read input and parse
6672 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6673 PointerGetDatum(location)));
6675 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6677 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6678 errmsg("could not parse transaction log location \"%s\"",
6681 locationpoint.xlogid = uxlogid;
6682 locationpoint.xrecoff = uxrecoff;
6685 * Construct a tuple descriptor for the result row. This must match this
6686 * function's pg_proc entry!
6688 resultTupleDesc = CreateTemplateTupleDesc(2, false);
6689 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
6691 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
6694 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
6699 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6700 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6702 values[0] = DirectFunctionCall1(textin,
6703 CStringGetDatum(xlogfilename));
6709 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
6711 values[1] = UInt32GetDatum(xrecoff);
6715 * Tuple jam: Having first prepared your Datums, then squash together
6717 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
6719 result = HeapTupleGetDatum(resultHeapTuple);
6721 PG_RETURN_DATUM(result);
6725 * Compute an xlog file name given a WAL location,
6726 * such as is returned by pg_stop_backup() or pg_xlog_switch().
6729 pg_xlogfile_name(PG_FUNCTION_ARGS)
6731 text *location = PG_GETARG_TEXT_P(0);
6734 unsigned int uxlogid;
6735 unsigned int uxrecoff;
6738 XLogRecPtr locationpoint;
6739 char xlogfilename[MAXFNAMELEN];
6741 locationstr = DatumGetCString(DirectFunctionCall1(textout,
6742 PointerGetDatum(location)));
6744 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
6746 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6747 errmsg("could not parse transaction log location \"%s\"",
6750 locationpoint.xlogid = uxlogid;
6751 locationpoint.xrecoff = uxrecoff;
6753 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
6754 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
6756 result = DatumGetTextP(DirectFunctionCall1(textin,
6757 CStringGetDatum(xlogfilename)));
6758 PG_RETURN_TEXT_P(result);
6762 * read_backup_label: check to see if a backup_label file is present
6764 * If we see a backup_label during recovery, we assume that we are recovering
6765 * from a backup dump file, and we therefore roll forward from the checkpoint
6766 * identified by the label file, NOT what pg_control says. This avoids the
6767 * problem that pg_control might have been archived one or more checkpoints
6768 * later than the start of the dump, and so if we rely on it as the start
6769 * point, we will fail to restore a consistent database state.
6771 * We also attempt to retrieve the corresponding backup history file.
6772 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
6775 * Returns TRUE if a backup_label was found (and fills the checkpoint
6776 * location into *checkPointLoc); returns FALSE if not.
6779 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
6781 XLogRecPtr startpoint;
6782 XLogRecPtr stoppoint;
6783 char histfilename[MAXFNAMELEN];
6784 char histfilepath[MAXPGPATH];
6785 char startxlogfilename[MAXFNAMELEN];
6786 char stopxlogfilename[MAXFNAMELEN];
6794 /* Default is to not constrain recovery stop point */
6795 minRecoveryLoc->xlogid = 0;
6796 minRecoveryLoc->xrecoff = 0;
6799 * See if label file is present
6801 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
6804 if (errno != ENOENT)
6806 (errcode_for_file_access(),
6807 errmsg("could not read file \"%s\": %m",
6808 BACKUP_LABEL_FILE)));
6809 return false; /* it's not there, all is fine */
6813 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
6814 * is pretty crude, but we are not expecting any variability in the file
6817 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
6818 &startpoint.xlogid, &startpoint.xrecoff, &tli,
6819 startxlogfilename, &ch) != 5 || ch != '\n')
6821 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6822 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6823 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
6824 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
6825 &ch) != 3 || ch != '\n')
6827 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6828 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
6829 if (ferror(lfp) || FreeFile(lfp))
6831 (errcode_for_file_access(),
6832 errmsg("could not read file \"%s\": %m",
6833 BACKUP_LABEL_FILE)));
6836 * Try to retrieve the backup history file (no error if we can't)
6838 XLByteToSeg(startpoint, _logId, _logSeg);
6839 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
6840 startpoint.xrecoff % XLogSegSize);
6842 if (InArchiveRecovery)
6843 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
6845 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
6846 startpoint.xrecoff % XLogSegSize);
6848 fp = AllocateFile(histfilepath, "r");
6852 * Parse history file to identify stop point.
6854 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
6855 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
6856 &ch) != 4 || ch != '\n')
6858 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6859 errmsg("invalid data in file \"%s\"", histfilename)));
6860 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
6861 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
6862 &ch) != 4 || ch != '\n')
6864 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6865 errmsg("invalid data in file \"%s\"", histfilename)));
6866 *minRecoveryLoc = stoppoint;
6867 if (ferror(fp) || FreeFile(fp))
6869 (errcode_for_file_access(),
6870 errmsg("could not read file \"%s\": %m",
6878 * Error context callback for errors occurring during rm_redo().
6881 rm_redo_error_callback(void *arg)
6883 XLogRecord *record = (XLogRecord *) arg;
6886 initStringInfo(&buf);
6887 RmgrTable[record->xl_rmid].rm_desc(&buf,
6889 XLogRecGetData(record));
6891 /* don't bother emitting empty description */
6893 errcontext("xlog redo %s", buf.data);