After archive recovery, mark the last WAL segment from the parent timeline
[PostgreSQL.git] / src / backend / access / transam / xlog.c
blob820b4398fe0a4ebcd5e691d3435040b1612d2804
1 /*-------------------------------------------------------------------------
3 * xlog.c
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL$
12 *-------------------------------------------------------------------------
15 #include "postgres.h"
17 #include <ctype.h>
18 #include <signal.h>
19 #include <time.h>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <sys/time.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
26 #include "access/clog.h"
27 #include "access/multixact.h"
28 #include "access/subtrans.h"
29 #include "access/transam.h"
30 #include "access/tuptoaster.h"
31 #include "access/twophase.h"
32 #include "access/xact.h"
33 #include "access/xlog_internal.h"
34 #include "access/xlogutils.h"
35 #include "catalog/catversion.h"
36 #include "catalog/pg_control.h"
37 #include "catalog/pg_type.h"
38 #include "funcapi.h"
39 #include "libpq/pqsignal.h"
40 #include "miscadmin.h"
41 #include "pgstat.h"
42 #include "postmaster/bgwriter.h"
43 #include "storage/bufmgr.h"
44 #include "storage/fd.h"
45 #include "storage/ipc.h"
46 #include "storage/pmsignal.h"
47 #include "storage/procarray.h"
48 #include "storage/smgr.h"
49 #include "storage/spin.h"
50 #include "utils/builtins.h"
51 #include "utils/flatfiles.h"
52 #include "utils/guc.h"
53 #include "utils/ps_status.h"
54 #include "pg_trace.h"
57 /* File path names (all relative to $PGDATA) */
58 #define BACKUP_LABEL_FILE "backup_label"
59 #define BACKUP_LABEL_OLD "backup_label.old"
60 #define RECOVERY_COMMAND_FILE "recovery.conf"
61 #define RECOVERY_COMMAND_DONE "recovery.done"
64 /* User-settable parameters */
65 int CheckPointSegments = 3;
66 int XLOGbuffers = 8;
67 int XLogArchiveTimeout = 0;
68 bool XLogArchiveMode = false;
69 char *XLogArchiveCommand = NULL;
70 bool fullPageWrites = true;
71 bool log_checkpoints = false;
72 int sync_method = DEFAULT_SYNC_METHOD;
74 #ifdef WAL_DEBUG
75 bool XLOG_DEBUG = false;
76 #endif
79 * XLOGfileslop is the maximum number of preallocated future XLOG segments.
80 * When we are done with an old XLOG segment file, we will recycle it as a
81 * future XLOG segment as long as there aren't already XLOGfileslop future
82 * segments; else we'll delete it. This could be made a separate GUC
83 * variable, but at present I think it's sufficient to hardwire it as
84 * 2*CheckPointSegments+1. Under normal conditions, a checkpoint will free
85 * no more than 2*CheckPointSegments log segments, and we want to recycle all
86 * of them; the +1 allows boundary cases to happen without wasting a
87 * delete/create-segment cycle.
89 #define XLOGfileslop (2*CheckPointSegments + 1)
92 * GUC support
94 const struct config_enum_entry sync_method_options[] = {
95 {"fsync", SYNC_METHOD_FSYNC, false},
96 #ifdef HAVE_FSYNC_WRITETHROUGH
97 {"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
98 #endif
99 #ifdef HAVE_FDATASYNC
100 {"fdatasync", SYNC_METHOD_FDATASYNC, false},
101 #endif
102 #ifdef OPEN_SYNC_FLAG
103 {"open_sync", SYNC_METHOD_OPEN, false},
104 #endif
105 #ifdef OPEN_DATASYNC_FLAG
106 {"open_datasync", SYNC_METHOD_OPEN_DSYNC, false},
107 #endif
108 {NULL, 0, false}
112 * Statistics for current checkpoint are collected in this global struct.
113 * Because only the background writer or a stand-alone backend can perform
114 * checkpoints, this will be unused in normal backends.
116 CheckpointStatsData CheckpointStats;
119 * ThisTimeLineID will be same in all backends --- it identifies current
120 * WAL timeline for the database system.
122 TimeLineID ThisTimeLineID = 0;
125 * Are we doing recovery from XLOG?
127 * This is only ever true in the startup process, even if the system is still
128 * in recovery. Prior to 8.4, all activity during recovery were carried out
129 * by Startup process. This local variable continues to be used in functions
130 * that need to act differently when called from a redo function (e.g skip
131 * WAL logging). To check whether the system is in recovery regardless of what
132 * process you're running in, use RecoveryInProgress().
134 bool InRecovery = false;
136 /* Are we recovering using offline XLOG archives? */
137 static bool InArchiveRecovery = false;
140 * Local copy of SharedRecoveryInProgress variable. True actually means "not
141 * known, need to check the shared state"
143 static bool LocalRecoveryInProgress = true;
145 /* Was the last xlog file restored from archive, or local? */
146 static bool restoredFromArchive = false;
148 /* options taken from recovery.conf */
149 static char *recoveryRestoreCommand = NULL;
150 static bool recoveryTarget = false;
151 static bool recoveryTargetExact = false;
152 static bool recoveryTargetInclusive = true;
153 static TransactionId recoveryTargetXid;
154 static TimestampTz recoveryTargetTime;
155 static TimestampTz recoveryLastXTime = 0;
157 /* if recoveryStopsHere returns true, it saves actual stop xid/time here */
158 static TransactionId recoveryStopXid;
159 static TimestampTz recoveryStopTime;
160 static bool recoveryStopAfter;
163 * During normal operation, the only timeline we care about is ThisTimeLineID.
164 * During recovery, however, things are more complicated. To simplify life
165 * for rmgr code, we keep ThisTimeLineID set to the "current" timeline as we
166 * scan through the WAL history (that is, it is the line that was active when
167 * the currently-scanned WAL record was generated). We also need these
168 * timeline values:
170 * recoveryTargetTLI: the desired timeline that we want to end in.
172 * expectedTLIs: an integer list of recoveryTargetTLI and the TLIs of
173 * its known parents, newest first (so recoveryTargetTLI is always the
174 * first list member). Only these TLIs are expected to be seen in the WAL
175 * segments we read, and indeed only these TLIs will be considered as
176 * candidate WAL files to open at all.
178 * curFileTLI: the TLI appearing in the name of the current input WAL file.
179 * (This is not necessarily the same as ThisTimeLineID, because we could
180 * be scanning data that was copied from an ancestor timeline when the current
181 * file was created.) During a sequential scan we do not allow this value
182 * to decrease.
184 static TimeLineID recoveryTargetTLI;
185 static List *expectedTLIs;
186 static TimeLineID curFileTLI;
189 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
190 * current backend. It is updated for all inserts. XactLastRecEnd points to
191 * end+1 of the last record, and is reset when we end a top-level transaction,
192 * or start a new one; so it can be used to tell if the current transaction has
193 * created any XLOG records.
195 static XLogRecPtr ProcLastRecPtr = {0, 0};
197 XLogRecPtr XactLastRecEnd = {0, 0};
200 * RedoRecPtr is this backend's local copy of the REDO record pointer
201 * (which is almost but not quite the same as a pointer to the most recent
202 * CHECKPOINT record). We update this from the shared-memory copy,
203 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
204 * hold the Insert lock). See XLogInsert for details. We are also allowed
205 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
206 * see GetRedoRecPtr. A freshly spawned backend obtains the value during
207 * InitXLOGAccess.
209 static XLogRecPtr RedoRecPtr;
211 /*----------
212 * Shared-memory data structures for XLOG control
214 * LogwrtRqst indicates a byte position that we need to write and/or fsync
215 * the log up to (all records before that point must be written or fsynced).
216 * LogwrtResult indicates the byte positions we have already written/fsynced.
217 * These structs are identical but are declared separately to indicate their
218 * slightly different functions.
220 * We do a lot of pushups to minimize the amount of access to lockable
221 * shared memory values. There are actually three shared-memory copies of
222 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
223 * XLogCtl->LogwrtResult is protected by info_lck
224 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
225 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
226 * One must hold the associated lock to read or write any of these, but
227 * of course no lock is needed to read/write the unshared LogwrtResult.
229 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
230 * right", since both are updated by a write or flush operation before
231 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
232 * is that it can be examined/modified by code that already holds WALWriteLock
233 * without needing to grab info_lck as well.
235 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
236 * but is updated when convenient. Again, it exists for the convenience of
237 * code that is already holding WALInsertLock but not the other locks.
239 * The unshared LogwrtResult may lag behind any or all of these, and again
240 * is updated when convenient.
242 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
243 * (protected by info_lck), but we don't need to cache any copies of it.
245 * Note that this all works because the request and result positions can only
246 * advance forward, never back up, and so we can easily determine which of two
247 * values is "more up to date".
249 * info_lck is only held long enough to read/update the protected variables,
250 * so it's a plain spinlock. The other locks are held longer (potentially
251 * over I/O operations), so we use LWLocks for them. These locks are:
253 * WALInsertLock: must be held to insert a record into the WAL buffers.
255 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
256 * XLogFlush).
258 * ControlFileLock: must be held to read/update control file or create
259 * new log file.
261 * CheckpointLock: must be held to do a checkpoint or restartpoint (ensures
262 * only one checkpointer at a time)
264 *----------
267 typedef struct XLogwrtRqst
269 XLogRecPtr Write; /* last byte + 1 to write out */
270 XLogRecPtr Flush; /* last byte + 1 to flush */
271 } XLogwrtRqst;
273 typedef struct XLogwrtResult
275 XLogRecPtr Write; /* last byte + 1 written out */
276 XLogRecPtr Flush; /* last byte + 1 flushed */
277 } XLogwrtResult;
280 * Shared state data for XLogInsert.
282 typedef struct XLogCtlInsert
284 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
285 XLogRecPtr PrevRecord; /* start of previously-inserted record */
286 int curridx; /* current block index in cache */
287 XLogPageHeader currpage; /* points to header of block in cache */
288 char *currpos; /* current insertion point in cache */
289 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
290 bool forcePageWrites; /* forcing full-page writes for PITR? */
291 } XLogCtlInsert;
294 * Shared state data for XLogWrite/XLogFlush.
296 typedef struct XLogCtlWrite
298 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
299 int curridx; /* cache index of next block to write */
300 pg_time_t lastSegSwitchTime; /* time of last xlog segment switch */
301 } XLogCtlWrite;
304 * Total shared-memory state for XLOG.
306 typedef struct XLogCtlData
308 /* Protected by WALInsertLock: */
309 XLogCtlInsert Insert;
311 /* Protected by info_lck: */
312 XLogwrtRqst LogwrtRqst;
313 XLogwrtResult LogwrtResult;
314 uint32 ckptXidEpoch; /* nextXID & epoch of latest checkpoint */
315 TransactionId ckptXid;
316 XLogRecPtr asyncCommitLSN; /* LSN of newest async commit */
318 /* Protected by WALWriteLock: */
319 XLogCtlWrite Write;
322 * These values do not change after startup, although the pointed-to pages
323 * and xlblocks values certainly do. Permission to read/write the pages
324 * and xlblocks values depends on WALInsertLock and WALWriteLock.
326 char *pages; /* buffers for unwritten XLOG pages */
327 XLogRecPtr *xlblocks; /* 1st byte ptr-s + XLOG_BLCKSZ */
328 int XLogCacheBlck; /* highest allocated xlog buffer index */
329 TimeLineID ThisTimeLineID;
332 * SharedRecoveryInProgress indicates if we're still in crash or archive
333 * recovery. It's checked by RecoveryInProgress().
335 bool SharedRecoveryInProgress;
338 * During recovery, we keep a copy of the latest checkpoint record
339 * here. Used by the background writer when it wants to create
340 * a restartpoint.
342 * Protected by info_lck.
344 XLogRecPtr lastCheckPointRecPtr;
345 CheckPoint lastCheckPoint;
347 /* end+1 of the last record replayed (or being replayed) */
348 XLogRecPtr replayEndRecPtr;
350 slock_t info_lck; /* locks shared variables shown above */
351 } XLogCtlData;
353 static XLogCtlData *XLogCtl = NULL;
356 * We maintain an image of pg_control in shared memory.
358 static ControlFileData *ControlFile = NULL;
361 * Macros for managing XLogInsert state. In most cases, the calling routine
362 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
363 * so these are passed as parameters instead of being fetched via XLogCtl.
366 /* Free space remaining in the current xlog page buffer */
367 #define INSERT_FREESPACE(Insert) \
368 (XLOG_BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
370 /* Construct XLogRecPtr value for current insertion point */
371 #define INSERT_RECPTR(recptr,Insert,curridx) \
373 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
374 (recptr).xrecoff = \
375 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
378 #define PrevBufIdx(idx) \
379 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
381 #define NextBufIdx(idx) \
382 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
385 * Private, possibly out-of-date copy of shared LogwrtResult.
386 * See discussion above.
388 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
391 * openLogFile is -1 or a kernel FD for an open log file segment.
392 * When it's open, openLogOff is the current seek offset in the file.
393 * openLogId/openLogSeg identify the segment. These variables are only
394 * used to write the XLOG, and so will normally refer to the active segment.
396 static int openLogFile = -1;
397 static uint32 openLogId = 0;
398 static uint32 openLogSeg = 0;
399 static uint32 openLogOff = 0;
402 * These variables are used similarly to the ones above, but for reading
403 * the XLOG. Note, however, that readOff generally represents the offset
404 * of the page just read, not the seek position of the FD itself, which
405 * will be just past that page.
407 static int readFile = -1;
408 static uint32 readId = 0;
409 static uint32 readSeg = 0;
410 static uint32 readOff = 0;
412 /* Buffer for currently read page (XLOG_BLCKSZ bytes) */
413 static char *readBuf = NULL;
415 /* Buffer for current ReadRecord result (expandable) */
416 static char *readRecordBuf = NULL;
417 static uint32 readRecordBufSize = 0;
419 /* State information for XLOG reading */
420 static XLogRecPtr ReadRecPtr; /* start of last record read */
421 static XLogRecPtr EndRecPtr; /* end+1 of last record read */
422 static XLogRecord *nextRecord = NULL;
423 static TimeLineID lastPageTLI = 0;
424 static XLogRecPtr minRecoveryPoint; /* local copy of ControlFile->minRecoveryPoint */
425 static bool updateMinRecoveryPoint = true;
427 static bool InRedo = false;
430 * Flag set by interrupt handlers for later service in the redo loop.
432 static volatile sig_atomic_t got_SIGHUP = false;
433 static volatile sig_atomic_t shutdown_requested = false;
435 * Flag set when executing a restore command, to tell SIGTERM signal handler
436 * that it's safe to just proc_exit.
438 static volatile sig_atomic_t in_restore_command = false;
441 static void XLogArchiveNotify(const char *xlog);
442 static void XLogArchiveNotifySeg(uint32 log, uint32 seg);
443 static bool XLogArchiveCheckDone(const char *xlog);
444 static bool XLogArchiveIsBusy(const char *xlog);
445 static void XLogArchiveCleanup(const char *xlog);
446 static void readRecoveryCommandFile(void);
447 static void exitArchiveRecovery(TimeLineID endTLI,
448 uint32 endLogId, uint32 endLogSeg);
449 static bool recoveryStopsHere(XLogRecord *record, bool *includeThis);
450 static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags);
452 static bool XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
453 XLogRecPtr *lsn, BkpBlock *bkpb);
454 static bool AdvanceXLInsertBuffer(bool new_segment);
455 static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch);
456 static int XLogFileInit(uint32 log, uint32 seg,
457 bool *use_existent, bool use_lock);
458 static bool InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
459 bool find_free, int *max_advance,
460 bool use_lock);
461 static int XLogFileOpen(uint32 log, uint32 seg);
462 static int XLogFileRead(uint32 log, uint32 seg, int emode);
463 static void XLogFileClose(void);
464 static bool RestoreArchivedFile(char *path, const char *xlogfname,
465 const char *recovername, off_t expectedSize);
466 static void PreallocXlogFiles(XLogRecPtr endptr);
467 static void RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr);
468 static void ValidateXLOGDirectoryStructure(void);
469 static void CleanupBackupHistory(void);
470 static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force);
471 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode);
472 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode);
473 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt);
474 static List *readTimeLineHistory(TimeLineID targetTLI);
475 static bool existsTimeLineHistory(TimeLineID probeTLI);
476 static TimeLineID findNewestTimeLine(TimeLineID startTLI);
477 static void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
478 TimeLineID endTLI,
479 uint32 endLogId, uint32 endLogSeg);
480 static void WriteControlFile(void);
481 static void ReadControlFile(void);
482 static char *str_time(pg_time_t tnow);
483 #ifdef WAL_DEBUG
484 static void xlog_outrec(StringInfo buf, XLogRecord *record);
485 #endif
486 static void issue_xlog_fsync(void);
487 static void pg_start_backup_callback(int code, Datum arg);
488 static bool read_backup_label(XLogRecPtr *checkPointLoc,
489 XLogRecPtr *minRecoveryLoc);
490 static void rm_redo_error_callback(void *arg);
491 static int get_sync_bit(int method);
495 * Insert an XLOG record having the specified RMID and info bytes,
496 * with the body of the record being the data chunk(s) described by
497 * the rdata chain (see xlog.h for notes about rdata).
499 * Returns XLOG pointer to end of record (beginning of next record).
500 * This can be used as LSN for data pages affected by the logged action.
501 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
502 * before the data page can be written out. This implements the basic
503 * WAL rule "write the log before the data".)
505 * NB: this routine feels free to scribble on the XLogRecData structs,
506 * though not on the data they reference. This is OK since the XLogRecData
507 * structs are always just temporaries in the calling code.
509 XLogRecPtr
510 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
512 XLogCtlInsert *Insert = &XLogCtl->Insert;
513 XLogRecord *record;
514 XLogContRecord *contrecord;
515 XLogRecPtr RecPtr;
516 XLogRecPtr WriteRqst;
517 uint32 freespace;
518 int curridx;
519 XLogRecData *rdt;
520 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
521 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
522 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
523 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
524 XLogRecData dtbuf_rdt1[XLR_MAX_BKP_BLOCKS];
525 XLogRecData dtbuf_rdt2[XLR_MAX_BKP_BLOCKS];
526 XLogRecData dtbuf_rdt3[XLR_MAX_BKP_BLOCKS];
527 pg_crc32 rdata_crc;
528 uint32 len,
529 write_len;
530 unsigned i;
531 bool updrqst;
532 bool doPageWrites;
533 bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);
535 /* cross-check on whether we should be here or not */
536 if (RecoveryInProgress())
537 elog(FATAL, "cannot make new WAL entries during recovery");
539 /* info's high bits are reserved for use by me */
540 if (info & XLR_INFO_MASK)
541 elog(PANIC, "invalid xlog info mask %02X", info);
543 TRACE_POSTGRESQL_XLOG_INSERT(rmid, info);
546 * In bootstrap mode, we don't actually log anything but XLOG resources;
547 * return a phony record pointer.
549 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
551 RecPtr.xlogid = 0;
552 RecPtr.xrecoff = SizeOfXLogLongPHD; /* start of 1st chkpt record */
553 return RecPtr;
557 * Here we scan the rdata chain, determine which buffers must be backed
558 * up, and compute the CRC values for the data. Note that the record
559 * header isn't added into the CRC initially since we don't know the final
560 * length or info bits quite yet. Thus, the CRC will represent the CRC of
561 * the whole record in the order "rdata, then backup blocks, then record
562 * header".
564 * We may have to loop back to here if a race condition is detected below.
565 * We could prevent the race by doing all this work while holding the
566 * insert lock, but it seems better to avoid doing CRC calculations while
567 * holding the lock. This means we have to be careful about modifying the
568 * rdata chain until we know we aren't going to loop back again. The only
569 * change we allow ourselves to make earlier is to set rdt->data = NULL in
570 * chain items we have decided we will have to back up the whole buffer
571 * for. This is OK because we will certainly decide the same thing again
572 * for those items if we do it over; doing it here saves an extra pass
573 * over the chain later.
575 begin:;
576 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
578 dtbuf[i] = InvalidBuffer;
579 dtbuf_bkp[i] = false;
583 * Decide if we need to do full-page writes in this XLOG record: true if
584 * full_page_writes is on or we have a PITR request for it. Since we
585 * don't yet have the insert lock, forcePageWrites could change under us,
586 * but we'll recheck it once we have the lock.
588 doPageWrites = fullPageWrites || Insert->forcePageWrites;
590 INIT_CRC32(rdata_crc);
591 len = 0;
592 for (rdt = rdata;;)
594 if (rdt->buffer == InvalidBuffer)
596 /* Simple data, just include it */
597 len += rdt->len;
598 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
600 else
602 /* Find info for buffer */
603 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
605 if (rdt->buffer == dtbuf[i])
607 /* Buffer already referenced by earlier chain item */
608 if (dtbuf_bkp[i])
609 rdt->data = NULL;
610 else if (rdt->data)
612 len += rdt->len;
613 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
615 break;
617 if (dtbuf[i] == InvalidBuffer)
619 /* OK, put it in this slot */
620 dtbuf[i] = rdt->buffer;
621 if (XLogCheckBuffer(rdt, doPageWrites,
622 &(dtbuf_lsn[i]), &(dtbuf_xlg[i])))
624 dtbuf_bkp[i] = true;
625 rdt->data = NULL;
627 else if (rdt->data)
629 len += rdt->len;
630 COMP_CRC32(rdata_crc, rdt->data, rdt->len);
632 break;
635 if (i >= XLR_MAX_BKP_BLOCKS)
636 elog(PANIC, "can backup at most %d blocks per xlog record",
637 XLR_MAX_BKP_BLOCKS);
639 /* Break out of loop when rdt points to last chain item */
640 if (rdt->next == NULL)
641 break;
642 rdt = rdt->next;
646 * Now add the backup block headers and data into the CRC
648 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
650 if (dtbuf_bkp[i])
652 BkpBlock *bkpb = &(dtbuf_xlg[i]);
653 char *page;
655 COMP_CRC32(rdata_crc,
656 (char *) bkpb,
657 sizeof(BkpBlock));
658 page = (char *) BufferGetBlock(dtbuf[i]);
659 if (bkpb->hole_length == 0)
661 COMP_CRC32(rdata_crc,
662 page,
663 BLCKSZ);
665 else
667 /* must skip the hole */
668 COMP_CRC32(rdata_crc,
669 page,
670 bkpb->hole_offset);
671 COMP_CRC32(rdata_crc,
672 page + (bkpb->hole_offset + bkpb->hole_length),
673 BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
679 * NOTE: We disallow len == 0 because it provides a useful bit of extra
680 * error checking in ReadRecord. This means that all callers of
681 * XLogInsert must supply at least some not-in-a-buffer data. However, we
682 * make an exception for XLOG SWITCH records because we don't want them to
683 * ever cross a segment boundary.
685 if (len == 0 && !isLogSwitch)
686 elog(PANIC, "invalid xlog record length %u", len);
688 START_CRIT_SECTION();
690 /* Now wait to get insert lock */
691 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
694 * Check to see if my RedoRecPtr is out of date. If so, may have to go
695 * back and recompute everything. This can only happen just after a
696 * checkpoint, so it's better to be slow in this case and fast otherwise.
698 * If we aren't doing full-page writes then RedoRecPtr doesn't actually
699 * affect the contents of the XLOG record, so we'll update our local copy
700 * but not force a recomputation.
702 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
704 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
705 RedoRecPtr = Insert->RedoRecPtr;
707 if (doPageWrites)
709 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
711 if (dtbuf[i] == InvalidBuffer)
712 continue;
713 if (dtbuf_bkp[i] == false &&
714 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
717 * Oops, this buffer now needs to be backed up, but we
718 * didn't think so above. Start over.
720 LWLockRelease(WALInsertLock);
721 END_CRIT_SECTION();
722 goto begin;
729 * Also check to see if forcePageWrites was just turned on; if we weren't
730 * already doing full-page writes then go back and recompute. (If it was
731 * just turned off, we could recompute the record without full pages, but
732 * we choose not to bother.)
734 if (Insert->forcePageWrites && !doPageWrites)
736 /* Oops, must redo it with full-page data */
737 LWLockRelease(WALInsertLock);
738 END_CRIT_SECTION();
739 goto begin;
743 * Make additional rdata chain entries for the backup blocks, so that we
744 * don't need to special-case them in the write loop. Note that we have
745 * now irrevocably changed the input rdata chain. At the exit of this
746 * loop, write_len includes the backup block data.
748 * Also set the appropriate info bits to show which buffers were backed
749 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th distinct
750 * buffer value (ignoring InvalidBuffer) appearing in the rdata chain.
752 write_len = len;
753 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
755 BkpBlock *bkpb;
756 char *page;
758 if (!dtbuf_bkp[i])
759 continue;
761 info |= XLR_SET_BKP_BLOCK(i);
763 bkpb = &(dtbuf_xlg[i]);
764 page = (char *) BufferGetBlock(dtbuf[i]);
766 rdt->next = &(dtbuf_rdt1[i]);
767 rdt = rdt->next;
769 rdt->data = (char *) bkpb;
770 rdt->len = sizeof(BkpBlock);
771 write_len += sizeof(BkpBlock);
773 rdt->next = &(dtbuf_rdt2[i]);
774 rdt = rdt->next;
776 if (bkpb->hole_length == 0)
778 rdt->data = page;
779 rdt->len = BLCKSZ;
780 write_len += BLCKSZ;
781 rdt->next = NULL;
783 else
785 /* must skip the hole */
786 rdt->data = page;
787 rdt->len = bkpb->hole_offset;
788 write_len += bkpb->hole_offset;
790 rdt->next = &(dtbuf_rdt3[i]);
791 rdt = rdt->next;
793 rdt->data = page + (bkpb->hole_offset + bkpb->hole_length);
794 rdt->len = BLCKSZ - (bkpb->hole_offset + bkpb->hole_length);
795 write_len += rdt->len;
796 rdt->next = NULL;
801 * If we backed up any full blocks and online backup is not in progress,
802 * mark the backup blocks as removable. This allows the WAL archiver to
803 * know whether it is safe to compress archived WAL data by transforming
804 * full-block records into the non-full-block format.
806 * Note: we could just set the flag whenever !forcePageWrites, but
807 * defining it like this leaves the info bit free for some potential other
808 * use in records without any backup blocks.
810 if ((info & XLR_BKP_BLOCK_MASK) && !Insert->forcePageWrites)
811 info |= XLR_BKP_REMOVABLE;
814 * If there isn't enough space on the current XLOG page for a record
815 * header, advance to the next page (leaving the unused space as zeroes).
817 updrqst = false;
818 freespace = INSERT_FREESPACE(Insert);
819 if (freespace < SizeOfXLogRecord)
821 updrqst = AdvanceXLInsertBuffer(false);
822 freespace = INSERT_FREESPACE(Insert);
825 /* Compute record's XLOG location */
826 curridx = Insert->curridx;
827 INSERT_RECPTR(RecPtr, Insert, curridx);
830 * If the record is an XLOG_SWITCH, and we are exactly at the start of a
831 * segment, we need not insert it (and don't want to because we'd like
832 * consecutive switch requests to be no-ops). Instead, make sure
833 * everything is written and flushed through the end of the prior segment,
834 * and return the prior segment's end address.
836 if (isLogSwitch &&
837 (RecPtr.xrecoff % XLogSegSize) == SizeOfXLogLongPHD)
839 /* We can release insert lock immediately */
840 LWLockRelease(WALInsertLock);
842 RecPtr.xrecoff -= SizeOfXLogLongPHD;
843 if (RecPtr.xrecoff == 0)
845 /* crossing a logid boundary */
846 RecPtr.xlogid -= 1;
847 RecPtr.xrecoff = XLogFileSize;
850 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
851 LogwrtResult = XLogCtl->Write.LogwrtResult;
852 if (!XLByteLE(RecPtr, LogwrtResult.Flush))
854 XLogwrtRqst FlushRqst;
856 FlushRqst.Write = RecPtr;
857 FlushRqst.Flush = RecPtr;
858 XLogWrite(FlushRqst, false, false);
860 LWLockRelease(WALWriteLock);
862 END_CRIT_SECTION();
864 return RecPtr;
867 /* Insert record header */
869 record = (XLogRecord *) Insert->currpos;
870 record->xl_prev = Insert->PrevRecord;
871 record->xl_xid = GetCurrentTransactionIdIfAny();
872 record->xl_tot_len = SizeOfXLogRecord + write_len;
873 record->xl_len = len; /* doesn't include backup blocks */
874 record->xl_info = info;
875 record->xl_rmid = rmid;
877 /* Now we can finish computing the record's CRC */
878 COMP_CRC32(rdata_crc, (char *) record + sizeof(pg_crc32),
879 SizeOfXLogRecord - sizeof(pg_crc32));
880 FIN_CRC32(rdata_crc);
881 record->xl_crc = rdata_crc;
883 #ifdef WAL_DEBUG
884 if (XLOG_DEBUG)
886 StringInfoData buf;
888 initStringInfo(&buf);
889 appendStringInfo(&buf, "INSERT @ %X/%X: ",
890 RecPtr.xlogid, RecPtr.xrecoff);
891 xlog_outrec(&buf, record);
892 if (rdata->data != NULL)
894 appendStringInfo(&buf, " - ");
895 RmgrTable[record->xl_rmid].rm_desc(&buf, record->xl_info, rdata->data);
897 elog(LOG, "%s", buf.data);
898 pfree(buf.data);
900 #endif
902 /* Record begin of record in appropriate places */
903 ProcLastRecPtr = RecPtr;
904 Insert->PrevRecord = RecPtr;
906 Insert->currpos += SizeOfXLogRecord;
907 freespace -= SizeOfXLogRecord;
910 * Append the data, including backup blocks if any
912 while (write_len)
914 while (rdata->data == NULL)
915 rdata = rdata->next;
917 if (freespace > 0)
919 if (rdata->len > freespace)
921 memcpy(Insert->currpos, rdata->data, freespace);
922 rdata->data += freespace;
923 rdata->len -= freespace;
924 write_len -= freespace;
926 else
928 memcpy(Insert->currpos, rdata->data, rdata->len);
929 freespace -= rdata->len;
930 write_len -= rdata->len;
931 Insert->currpos += rdata->len;
932 rdata = rdata->next;
933 continue;
937 /* Use next buffer */
938 updrqst = AdvanceXLInsertBuffer(false);
939 curridx = Insert->curridx;
940 /* Insert cont-record header */
941 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
942 contrecord = (XLogContRecord *) Insert->currpos;
943 contrecord->xl_rem_len = write_len;
944 Insert->currpos += SizeOfXLogContRecord;
945 freespace = INSERT_FREESPACE(Insert);
948 /* Ensure next record will be properly aligned */
949 Insert->currpos = (char *) Insert->currpage +
950 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
951 freespace = INSERT_FREESPACE(Insert);
954 * The recptr I return is the beginning of the *next* record. This will be
955 * stored as LSN for changed data pages...
957 INSERT_RECPTR(RecPtr, Insert, curridx);
960 * If the record is an XLOG_SWITCH, we must now write and flush all the
961 * existing data, and then forcibly advance to the start of the next
962 * segment. It's not good to do this I/O while holding the insert lock,
963 * but there seems too much risk of confusion if we try to release the
964 * lock sooner. Fortunately xlog switch needn't be a high-performance
965 * operation anyway...
967 if (isLogSwitch)
969 XLogCtlWrite *Write = &XLogCtl->Write;
970 XLogwrtRqst FlushRqst;
971 XLogRecPtr OldSegEnd;
973 TRACE_POSTGRESQL_XLOG_SWITCH();
975 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
978 * Flush through the end of the page containing XLOG_SWITCH, and
979 * perform end-of-segment actions (eg, notifying archiver).
981 WriteRqst = XLogCtl->xlblocks[curridx];
982 FlushRqst.Write = WriteRqst;
983 FlushRqst.Flush = WriteRqst;
984 XLogWrite(FlushRqst, false, true);
986 /* Set up the next buffer as first page of next segment */
987 /* Note: AdvanceXLInsertBuffer cannot need to do I/O here */
988 (void) AdvanceXLInsertBuffer(true);
990 /* There should be no unwritten data */
991 curridx = Insert->curridx;
992 Assert(curridx == Write->curridx);
994 /* Compute end address of old segment */
995 OldSegEnd = XLogCtl->xlblocks[curridx];
996 OldSegEnd.xrecoff -= XLOG_BLCKSZ;
997 if (OldSegEnd.xrecoff == 0)
999 /* crossing a logid boundary */
1000 OldSegEnd.xlogid -= 1;
1001 OldSegEnd.xrecoff = XLogFileSize;
1004 /* Make it look like we've written and synced all of old segment */
1005 LogwrtResult.Write = OldSegEnd;
1006 LogwrtResult.Flush = OldSegEnd;
1009 * Update shared-memory status --- this code should match XLogWrite
1012 /* use volatile pointer to prevent code rearrangement */
1013 volatile XLogCtlData *xlogctl = XLogCtl;
1015 SpinLockAcquire(&xlogctl->info_lck);
1016 xlogctl->LogwrtResult = LogwrtResult;
1017 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1018 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1019 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1020 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1021 SpinLockRelease(&xlogctl->info_lck);
1024 Write->LogwrtResult = LogwrtResult;
1026 LWLockRelease(WALWriteLock);
1028 updrqst = false; /* done already */
1030 else
1032 /* normal case, ie not xlog switch */
1034 /* Need to update shared LogwrtRqst if some block was filled up */
1035 if (freespace < SizeOfXLogRecord)
1037 /* curridx is filled and available for writing out */
1038 updrqst = true;
1040 else
1042 /* if updrqst already set, write through end of previous buf */
1043 curridx = PrevBufIdx(curridx);
1045 WriteRqst = XLogCtl->xlblocks[curridx];
1048 LWLockRelease(WALInsertLock);
1050 if (updrqst)
1052 /* use volatile pointer to prevent code rearrangement */
1053 volatile XLogCtlData *xlogctl = XLogCtl;
1055 SpinLockAcquire(&xlogctl->info_lck);
1056 /* advance global request to include new block(s) */
1057 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
1058 xlogctl->LogwrtRqst.Write = WriteRqst;
1059 /* update local result copy while I have the chance */
1060 LogwrtResult = xlogctl->LogwrtResult;
1061 SpinLockRelease(&xlogctl->info_lck);
1064 XactLastRecEnd = RecPtr;
1066 END_CRIT_SECTION();
1068 return RecPtr;
1072 * Determine whether the buffer referenced by an XLogRecData item has to
1073 * be backed up, and if so fill a BkpBlock struct for it. In any case
1074 * save the buffer's LSN at *lsn.
1076 static bool
1077 XLogCheckBuffer(XLogRecData *rdata, bool doPageWrites,
1078 XLogRecPtr *lsn, BkpBlock *bkpb)
1080 Page page;
1082 page = BufferGetPage(rdata->buffer);
1085 * XXX We assume page LSN is first data on *every* page that can be passed
1086 * to XLogInsert, whether it otherwise has the standard page layout or
1087 * not.
1089 *lsn = PageGetLSN(page);
1091 if (doPageWrites &&
1092 XLByteLE(PageGetLSN(page), RedoRecPtr))
1095 * The page needs to be backed up, so set up *bkpb
1097 BufferGetTag(rdata->buffer, &bkpb->node, &bkpb->fork, &bkpb->block);
1099 if (rdata->buffer_std)
1101 /* Assume we can omit data between pd_lower and pd_upper */
1102 uint16 lower = ((PageHeader) page)->pd_lower;
1103 uint16 upper = ((PageHeader) page)->pd_upper;
1105 if (lower >= SizeOfPageHeaderData &&
1106 upper > lower &&
1107 upper <= BLCKSZ)
1109 bkpb->hole_offset = lower;
1110 bkpb->hole_length = upper - lower;
1112 else
1114 /* No "hole" to compress out */
1115 bkpb->hole_offset = 0;
1116 bkpb->hole_length = 0;
1119 else
1121 /* Not a standard page header, don't try to eliminate "hole" */
1122 bkpb->hole_offset = 0;
1123 bkpb->hole_length = 0;
1126 return true; /* buffer requires backup */
1129 return false; /* buffer does not need to be backed up */
1133 * XLogArchiveNotify
1135 * Create an archive notification file
1137 * The name of the notification file is the message that will be picked up
1138 * by the archiver, e.g. we write 0000000100000001000000C6.ready
1139 * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
1140 * then when complete, rename it to 0000000100000001000000C6.done
1142 static void
1143 XLogArchiveNotify(const char *xlog)
1145 char archiveStatusPath[MAXPGPATH];
1146 FILE *fd;
1148 /* insert an otherwise empty file called <XLOG>.ready */
1149 StatusFilePath(archiveStatusPath, xlog, ".ready");
1150 fd = AllocateFile(archiveStatusPath, "w");
1151 if (fd == NULL)
1153 ereport(LOG,
1154 (errcode_for_file_access(),
1155 errmsg("could not create archive status file \"%s\": %m",
1156 archiveStatusPath)));
1157 return;
1159 if (FreeFile(fd))
1161 ereport(LOG,
1162 (errcode_for_file_access(),
1163 errmsg("could not write archive status file \"%s\": %m",
1164 archiveStatusPath)));
1165 return;
1168 /* Notify archiver that it's got something to do */
1169 if (IsUnderPostmaster)
1170 SendPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER);
1174 * Convenience routine to notify using log/seg representation of filename
1176 static void
1177 XLogArchiveNotifySeg(uint32 log, uint32 seg)
1179 char xlog[MAXFNAMELEN];
1181 XLogFileName(xlog, ThisTimeLineID, log, seg);
1182 XLogArchiveNotify(xlog);
1186 * XLogArchiveCheckDone
1188 * This is called when we are ready to delete or recycle an old XLOG segment
1189 * file or backup history file. If it is okay to delete it then return true.
1190 * If it is not time to delete it, make sure a .ready file exists, and return
1191 * false.
1193 * If <XLOG>.done exists, then return true; else if <XLOG>.ready exists,
1194 * then return false; else create <XLOG>.ready and return false.
1196 * The reason we do things this way is so that if the original attempt to
1197 * create <XLOG>.ready fails, we'll retry during subsequent checkpoints.
1199 static bool
1200 XLogArchiveCheckDone(const char *xlog)
1202 char archiveStatusPath[MAXPGPATH];
1203 struct stat stat_buf;
1205 /* Always deletable if archiving is off */
1206 if (!XLogArchivingActive())
1207 return true;
1209 /* First check for .done --- this means archiver is done with it */
1210 StatusFilePath(archiveStatusPath, xlog, ".done");
1211 if (stat(archiveStatusPath, &stat_buf) == 0)
1212 return true;
1214 /* check for .ready --- this means archiver is still busy with it */
1215 StatusFilePath(archiveStatusPath, xlog, ".ready");
1216 if (stat(archiveStatusPath, &stat_buf) == 0)
1217 return false;
1219 /* Race condition --- maybe archiver just finished, so recheck */
1220 StatusFilePath(archiveStatusPath, xlog, ".done");
1221 if (stat(archiveStatusPath, &stat_buf) == 0)
1222 return true;
1224 /* Retry creation of the .ready file */
1225 XLogArchiveNotify(xlog);
1226 return false;
1230 * XLogArchiveIsBusy
1232 * Check to see if an XLOG segment file is still unarchived.
1233 * This is almost but not quite the inverse of XLogArchiveCheckDone: in
1234 * the first place we aren't chartered to recreate the .ready file, and
1235 * in the second place we should consider that if the file is already gone
1236 * then it's not busy. (This check is needed to handle the race condition
1237 * that a checkpoint already deleted the no-longer-needed file.)
1239 static bool
1240 XLogArchiveIsBusy(const char *xlog)
1242 char archiveStatusPath[MAXPGPATH];
1243 struct stat stat_buf;
1245 /* First check for .done --- this means archiver is done with it */
1246 StatusFilePath(archiveStatusPath, xlog, ".done");
1247 if (stat(archiveStatusPath, &stat_buf) == 0)
1248 return false;
1250 /* check for .ready --- this means archiver is still busy with it */
1251 StatusFilePath(archiveStatusPath, xlog, ".ready");
1252 if (stat(archiveStatusPath, &stat_buf) == 0)
1253 return true;
1255 /* Race condition --- maybe archiver just finished, so recheck */
1256 StatusFilePath(archiveStatusPath, xlog, ".done");
1257 if (stat(archiveStatusPath, &stat_buf) == 0)
1258 return false;
1261 * Check to see if the WAL file has been removed by checkpoint,
1262 * which implies it has already been archived, and explains why we
1263 * can't see a status file for it.
1265 snprintf(archiveStatusPath, MAXPGPATH, XLOGDIR "/%s", xlog);
1266 if (stat(archiveStatusPath, &stat_buf) != 0 &&
1267 errno == ENOENT)
1268 return false;
1270 return true;
1274 * XLogArchiveCleanup
1276 * Cleanup archive notification file(s) for a particular xlog segment
1278 static void
1279 XLogArchiveCleanup(const char *xlog)
1281 char archiveStatusPath[MAXPGPATH];
1283 /* Remove the .done file */
1284 StatusFilePath(archiveStatusPath, xlog, ".done");
1285 unlink(archiveStatusPath);
1286 /* should we complain about failure? */
1288 /* Remove the .ready file if present --- normally it shouldn't be */
1289 StatusFilePath(archiveStatusPath, xlog, ".ready");
1290 unlink(archiveStatusPath);
1291 /* should we complain about failure? */
1295 * Advance the Insert state to the next buffer page, writing out the next
1296 * buffer if it still contains unwritten data.
1298 * If new_segment is TRUE then we set up the next buffer page as the first
1299 * page of the next xlog segment file, possibly but not usually the next
1300 * consecutive file page.
1302 * The global LogwrtRqst.Write pointer needs to be advanced to include the
1303 * just-filled page. If we can do this for free (without an extra lock),
1304 * we do so here. Otherwise the caller must do it. We return TRUE if the
1305 * request update still needs to be done, FALSE if we did it internally.
1307 * Must be called with WALInsertLock held.
1309 static bool
1310 AdvanceXLInsertBuffer(bool new_segment)
1312 XLogCtlInsert *Insert = &XLogCtl->Insert;
1313 XLogCtlWrite *Write = &XLogCtl->Write;
1314 int nextidx = NextBufIdx(Insert->curridx);
1315 bool update_needed = true;
1316 XLogRecPtr OldPageRqstPtr;
1317 XLogwrtRqst WriteRqst;
1318 XLogRecPtr NewPageEndPtr;
1319 XLogPageHeader NewPage;
1321 /* Use Insert->LogwrtResult copy if it's more fresh */
1322 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
1323 LogwrtResult = Insert->LogwrtResult;
1326 * Get ending-offset of the buffer page we need to replace (this may be
1327 * zero if the buffer hasn't been used yet). Fall through if it's already
1328 * written out.
1330 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
1331 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1333 /* nope, got work to do... */
1334 XLogRecPtr FinishedPageRqstPtr;
1336 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1338 /* Before waiting, get info_lck and update LogwrtResult */
1340 /* use volatile pointer to prevent code rearrangement */
1341 volatile XLogCtlData *xlogctl = XLogCtl;
1343 SpinLockAcquire(&xlogctl->info_lck);
1344 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
1345 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
1346 LogwrtResult = xlogctl->LogwrtResult;
1347 SpinLockRelease(&xlogctl->info_lck);
1350 update_needed = false; /* Did the shared-request update */
1352 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1354 /* OK, someone wrote it already */
1355 Insert->LogwrtResult = LogwrtResult;
1357 else
1359 /* Must acquire write lock */
1360 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1361 LogwrtResult = Write->LogwrtResult;
1362 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
1364 /* OK, someone wrote it already */
1365 LWLockRelease(WALWriteLock);
1366 Insert->LogwrtResult = LogwrtResult;
1368 else
1371 * Have to write buffers while holding insert lock. This is
1372 * not good, so only write as much as we absolutely must.
1374 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
1375 WriteRqst.Write = OldPageRqstPtr;
1376 WriteRqst.Flush.xlogid = 0;
1377 WriteRqst.Flush.xrecoff = 0;
1378 XLogWrite(WriteRqst, false, false);
1379 LWLockRelease(WALWriteLock);
1380 Insert->LogwrtResult = LogwrtResult;
1381 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
1387 * Now the next buffer slot is free and we can set it up to be the next
1388 * output page.
1390 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
1392 if (new_segment)
1394 /* force it to a segment start point */
1395 NewPageEndPtr.xrecoff += XLogSegSize - 1;
1396 NewPageEndPtr.xrecoff -= NewPageEndPtr.xrecoff % XLogSegSize;
1399 if (NewPageEndPtr.xrecoff >= XLogFileSize)
1401 /* crossing a logid boundary */
1402 NewPageEndPtr.xlogid += 1;
1403 NewPageEndPtr.xrecoff = XLOG_BLCKSZ;
1405 else
1406 NewPageEndPtr.xrecoff += XLOG_BLCKSZ;
1407 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
1408 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
1410 Insert->curridx = nextidx;
1411 Insert->currpage = NewPage;
1413 Insert->currpos = ((char *) NewPage) +SizeOfXLogShortPHD;
1416 * Be sure to re-zero the buffer so that bytes beyond what we've written
1417 * will look like zeroes and not valid XLOG records...
1419 MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
1422 * Fill the new page's header
1424 NewPage ->xlp_magic = XLOG_PAGE_MAGIC;
1426 /* NewPage->xlp_info = 0; */ /* done by memset */
1427 NewPage ->xlp_tli = ThisTimeLineID;
1428 NewPage ->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
1429 NewPage ->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - XLOG_BLCKSZ;
1432 * If first page of an XLOG segment file, make it a long header.
1434 if ((NewPage->xlp_pageaddr.xrecoff % XLogSegSize) == 0)
1436 XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
1438 NewLongPage->xlp_sysid = ControlFile->system_identifier;
1439 NewLongPage->xlp_seg_size = XLogSegSize;
1440 NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
1441 NewPage ->xlp_info |= XLP_LONG_HEADER;
1443 Insert->currpos = ((char *) NewPage) +SizeOfXLogLongPHD;
1446 return update_needed;
1450 * Check whether we've consumed enough xlog space that a checkpoint is needed.
1452 * Caller must have just finished filling the open log file (so that
1453 * openLogId/openLogSeg are valid). We measure the distance from RedoRecPtr
1454 * to the open log file and see if that exceeds CheckPointSegments.
1456 * Note: it is caller's responsibility that RedoRecPtr is up-to-date.
1458 static bool
1459 XLogCheckpointNeeded(void)
1462 * A straight computation of segment number could overflow 32 bits. Rather
1463 * than assuming we have working 64-bit arithmetic, we compare the
1464 * highest-order bits separately, and force a checkpoint immediately when
1465 * they change.
1467 uint32 old_segno,
1468 new_segno;
1469 uint32 old_highbits,
1470 new_highbits;
1472 old_segno = (RedoRecPtr.xlogid % XLogSegSize) * XLogSegsPerFile +
1473 (RedoRecPtr.xrecoff / XLogSegSize);
1474 old_highbits = RedoRecPtr.xlogid / XLogSegSize;
1475 new_segno = (openLogId % XLogSegSize) * XLogSegsPerFile + openLogSeg;
1476 new_highbits = openLogId / XLogSegSize;
1477 if (new_highbits != old_highbits ||
1478 new_segno >= old_segno + (uint32) (CheckPointSegments - 1))
1479 return true;
1480 return false;
1484 * Write and/or fsync the log at least as far as WriteRqst indicates.
1486 * If flexible == TRUE, we don't have to write as far as WriteRqst, but
1487 * may stop at any convenient boundary (such as a cache or logfile boundary).
1488 * This option allows us to avoid uselessly issuing multiple writes when a
1489 * single one would do.
1491 * If xlog_switch == TRUE, we are intending an xlog segment switch, so
1492 * perform end-of-segment actions after writing the last page, even if
1493 * it's not physically the end of its segment. (NB: this will work properly
1494 * only if caller specifies WriteRqst == page-end and flexible == false,
1495 * and there is some data to write.)
1497 * Must be called with WALWriteLock held.
1499 static void
1500 XLogWrite(XLogwrtRqst WriteRqst, bool flexible, bool xlog_switch)
1502 XLogCtlWrite *Write = &XLogCtl->Write;
1503 bool ispartialpage;
1504 bool last_iteration;
1505 bool finishing_seg;
1506 bool use_existent;
1507 int curridx;
1508 int npages;
1509 int startidx;
1510 uint32 startoffset;
1512 /* We should always be inside a critical section here */
1513 Assert(CritSectionCount > 0);
1516 * Update local LogwrtResult (caller probably did this already, but...)
1518 LogwrtResult = Write->LogwrtResult;
1521 * Since successive pages in the xlog cache are consecutively allocated,
1522 * we can usually gather multiple pages together and issue just one
1523 * write() call. npages is the number of pages we have determined can be
1524 * written together; startidx is the cache block index of the first one,
1525 * and startoffset is the file offset at which it should go. The latter
1526 * two variables are only valid when npages > 0, but we must initialize
1527 * all of them to keep the compiler quiet.
1529 npages = 0;
1530 startidx = 0;
1531 startoffset = 0;
1534 * Within the loop, curridx is the cache block index of the page to
1535 * consider writing. We advance Write->curridx only after successfully
1536 * writing pages. (Right now, this refinement is useless since we are
1537 * going to PANIC if any error occurs anyway; but someday it may come in
1538 * useful.)
1540 curridx = Write->curridx;
1542 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1545 * Make sure we're not ahead of the insert process. This could happen
1546 * if we're passed a bogus WriteRqst.Write that is past the end of the
1547 * last page that's been initialized by AdvanceXLInsertBuffer.
1549 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[curridx]))
1550 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1551 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1552 XLogCtl->xlblocks[curridx].xlogid,
1553 XLogCtl->xlblocks[curridx].xrecoff);
1555 /* Advance LogwrtResult.Write to end of current buffer page */
1556 LogwrtResult.Write = XLogCtl->xlblocks[curridx];
1557 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1559 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1562 * Switch to new logfile segment. We cannot have any pending
1563 * pages here (since we dump what we have at segment end).
1565 Assert(npages == 0);
1566 if (openLogFile >= 0)
1567 XLogFileClose();
1568 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1570 /* create/use new log file */
1571 use_existent = true;
1572 openLogFile = XLogFileInit(openLogId, openLogSeg,
1573 &use_existent, true);
1574 openLogOff = 0;
1577 /* Make sure we have the current logfile open */
1578 if (openLogFile < 0)
1580 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1581 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1582 openLogOff = 0;
1585 /* Add current page to the set of pending pages-to-dump */
1586 if (npages == 0)
1588 /* first of group */
1589 startidx = curridx;
1590 startoffset = (LogwrtResult.Write.xrecoff - XLOG_BLCKSZ) % XLogSegSize;
1592 npages++;
1595 * Dump the set if this will be the last loop iteration, or if we are
1596 * at the last page of the cache area (since the next page won't be
1597 * contiguous in memory), or if we are at the end of the logfile
1598 * segment.
1600 last_iteration = !XLByteLT(LogwrtResult.Write, WriteRqst.Write);
1602 finishing_seg = !ispartialpage &&
1603 (startoffset + npages * XLOG_BLCKSZ) >= XLogSegSize;
1605 if (last_iteration ||
1606 curridx == XLogCtl->XLogCacheBlck ||
1607 finishing_seg)
1609 char *from;
1610 Size nbytes;
1612 /* Need to seek in the file? */
1613 if (openLogOff != startoffset)
1615 if (lseek(openLogFile, (off_t) startoffset, SEEK_SET) < 0)
1616 ereport(PANIC,
1617 (errcode_for_file_access(),
1618 errmsg("could not seek in log file %u, "
1619 "segment %u to offset %u: %m",
1620 openLogId, openLogSeg, startoffset)));
1621 openLogOff = startoffset;
1624 /* OK to write the page(s) */
1625 from = XLogCtl->pages + startidx * (Size) XLOG_BLCKSZ;
1626 nbytes = npages * (Size) XLOG_BLCKSZ;
1627 errno = 0;
1628 if (write(openLogFile, from, nbytes) != nbytes)
1630 /* if write didn't set errno, assume no disk space */
1631 if (errno == 0)
1632 errno = ENOSPC;
1633 ereport(PANIC,
1634 (errcode_for_file_access(),
1635 errmsg("could not write to log file %u, segment %u "
1636 "at offset %u, length %lu: %m",
1637 openLogId, openLogSeg,
1638 openLogOff, (unsigned long) nbytes)));
1641 /* Update state for write */
1642 openLogOff += nbytes;
1643 Write->curridx = ispartialpage ? curridx : NextBufIdx(curridx);
1644 npages = 0;
1647 * If we just wrote the whole last page of a logfile segment,
1648 * fsync the segment immediately. This avoids having to go back
1649 * and re-open prior segments when an fsync request comes along
1650 * later. Doing it here ensures that one and only one backend will
1651 * perform this fsync.
1653 * We also do this if this is the last page written for an xlog
1654 * switch.
1656 * This is also the right place to notify the Archiver that the
1657 * segment is ready to copy to archival storage, and to update the
1658 * timer for archive_timeout, and to signal for a checkpoint if
1659 * too many logfile segments have been used since the last
1660 * checkpoint.
1662 if (finishing_seg || (xlog_switch && last_iteration))
1664 issue_xlog_fsync();
1665 LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
1667 if (XLogArchivingActive())
1668 XLogArchiveNotifySeg(openLogId, openLogSeg);
1670 Write->lastSegSwitchTime = (pg_time_t) time(NULL);
1673 * Signal bgwriter to start a checkpoint if we've consumed too
1674 * much xlog since the last one. For speed, we first check
1675 * using the local copy of RedoRecPtr, which might be out of
1676 * date; if it looks like a checkpoint is needed, forcibly
1677 * update RedoRecPtr and recheck.
1679 if (IsUnderPostmaster &&
1680 XLogCheckpointNeeded())
1682 (void) GetRedoRecPtr();
1683 if (XLogCheckpointNeeded())
1684 RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
1689 if (ispartialpage)
1691 /* Only asked to write a partial page */
1692 LogwrtResult.Write = WriteRqst.Write;
1693 break;
1695 curridx = NextBufIdx(curridx);
1697 /* If flexible, break out of loop as soon as we wrote something */
1698 if (flexible && npages == 0)
1699 break;
1702 Assert(npages == 0);
1703 Assert(curridx == Write->curridx);
1706 * If asked to flush, do so
1708 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1709 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1712 * Could get here without iterating above loop, in which case we might
1713 * have no open file or the wrong one. However, we do not need to
1714 * fsync more than one file.
1716 if (sync_method != SYNC_METHOD_OPEN &&
1717 sync_method != SYNC_METHOD_OPEN_DSYNC)
1719 if (openLogFile >= 0 &&
1720 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1721 XLogFileClose();
1722 if (openLogFile < 0)
1724 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1725 openLogFile = XLogFileOpen(openLogId, openLogSeg);
1726 openLogOff = 0;
1728 issue_xlog_fsync();
1730 LogwrtResult.Flush = LogwrtResult.Write;
1734 * Update shared-memory status
1736 * We make sure that the shared 'request' values do not fall behind the
1737 * 'result' values. This is not absolutely essential, but it saves some
1738 * code in a couple of places.
1741 /* use volatile pointer to prevent code rearrangement */
1742 volatile XLogCtlData *xlogctl = XLogCtl;
1744 SpinLockAcquire(&xlogctl->info_lck);
1745 xlogctl->LogwrtResult = LogwrtResult;
1746 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1747 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1748 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1749 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1750 SpinLockRelease(&xlogctl->info_lck);
1753 Write->LogwrtResult = LogwrtResult;
1757 * Record the LSN for an asynchronous transaction commit.
1758 * (This should not be called for aborts, nor for synchronous commits.)
1760 void
1761 XLogSetAsyncCommitLSN(XLogRecPtr asyncCommitLSN)
1763 /* use volatile pointer to prevent code rearrangement */
1764 volatile XLogCtlData *xlogctl = XLogCtl;
1766 SpinLockAcquire(&xlogctl->info_lck);
1767 if (XLByteLT(xlogctl->asyncCommitLSN, asyncCommitLSN))
1768 xlogctl->asyncCommitLSN = asyncCommitLSN;
1769 SpinLockRelease(&xlogctl->info_lck);
1773 * Advance minRecoveryPoint in control file.
1775 * If we crash during recovery, we must reach this point again before the
1776 * database is consistent.
1778 * If 'force' is true, 'lsn' argument is ignored. Otherwise, minRecoveryPoint
1779 * is is only updated if it's not already greater than or equal to 'lsn'.
1781 static void
1782 UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
1784 /* Quick check using our local copy of the variable */
1785 if (!updateMinRecoveryPoint || (!force && XLByteLE(lsn, minRecoveryPoint)))
1786 return;
1788 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1790 /* update local copy */
1791 minRecoveryPoint = ControlFile->minRecoveryPoint;
1794 * An invalid minRecoveryPoint means that we need to recover all the WAL,
1795 * ie. crash recovery. Don't update the control file in that case.
1797 if (minRecoveryPoint.xlogid == 0 && minRecoveryPoint.xrecoff == 0)
1798 updateMinRecoveryPoint = false;
1799 else if (force || XLByteLT(minRecoveryPoint, lsn))
1801 /* use volatile pointer to prevent code rearrangement */
1802 volatile XLogCtlData *xlogctl = XLogCtl;
1803 XLogRecPtr newMinRecoveryPoint;
1806 * To avoid having to update the control file too often, we update it
1807 * all the way to the last record being replayed, even though 'lsn'
1808 * would suffice for correctness.
1810 SpinLockAcquire(&xlogctl->info_lck);
1811 newMinRecoveryPoint = xlogctl->replayEndRecPtr;
1812 SpinLockRelease(&xlogctl->info_lck);
1814 /* update control file */
1815 if (XLByteLT(ControlFile->minRecoveryPoint, newMinRecoveryPoint))
1817 ControlFile->minRecoveryPoint = newMinRecoveryPoint;
1818 UpdateControlFile();
1819 minRecoveryPoint = newMinRecoveryPoint;
1821 ereport(DEBUG2,
1822 (errmsg("updated min recovery point to %X/%X",
1823 minRecoveryPoint.xlogid, minRecoveryPoint.xrecoff)));
1826 LWLockRelease(ControlFileLock);
1830 * Ensure that all XLOG data through the given position is flushed to disk.
1832 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1833 * already held, and we try to avoid acquiring it if possible.
1835 void
1836 XLogFlush(XLogRecPtr record)
1838 XLogRecPtr WriteRqstPtr;
1839 XLogwrtRqst WriteRqst;
1842 * During REDO, we don't try to flush the WAL, but update minRecoveryPoint
1843 * instead.
1845 if (RecoveryInProgress())
1847 UpdateMinRecoveryPoint(record, false);
1848 return;
1851 /* Quick exit if already known flushed */
1852 if (XLByteLE(record, LogwrtResult.Flush))
1853 return;
1855 #ifdef WAL_DEBUG
1856 if (XLOG_DEBUG)
1857 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1858 record.xlogid, record.xrecoff,
1859 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1860 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1861 #endif
1863 START_CRIT_SECTION();
1866 * Since fsync is usually a horribly expensive operation, we try to
1867 * piggyback as much data as we can on each fsync: if we see any more data
1868 * entered into the xlog buffer, we'll write and fsync that too, so that
1869 * the final value of LogwrtResult.Flush is as large as possible. This
1870 * gives us some chance of avoiding another fsync immediately after.
1873 /* initialize to given target; may increase below */
1874 WriteRqstPtr = record;
1876 /* read LogwrtResult and update local state */
1878 /* use volatile pointer to prevent code rearrangement */
1879 volatile XLogCtlData *xlogctl = XLogCtl;
1881 SpinLockAcquire(&xlogctl->info_lck);
1882 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1883 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1884 LogwrtResult = xlogctl->LogwrtResult;
1885 SpinLockRelease(&xlogctl->info_lck);
1888 /* done already? */
1889 if (!XLByteLE(record, LogwrtResult.Flush))
1891 /* now wait for the write lock */
1892 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1893 LogwrtResult = XLogCtl->Write.LogwrtResult;
1894 if (!XLByteLE(record, LogwrtResult.Flush))
1896 /* try to write/flush later additions to XLOG as well */
1897 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1899 XLogCtlInsert *Insert = &XLogCtl->Insert;
1900 uint32 freespace = INSERT_FREESPACE(Insert);
1902 if (freespace < SizeOfXLogRecord) /* buffer is full */
1903 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1904 else
1906 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1907 WriteRqstPtr.xrecoff -= freespace;
1909 LWLockRelease(WALInsertLock);
1910 WriteRqst.Write = WriteRqstPtr;
1911 WriteRqst.Flush = WriteRqstPtr;
1913 else
1915 WriteRqst.Write = WriteRqstPtr;
1916 WriteRqst.Flush = record;
1918 XLogWrite(WriteRqst, false, false);
1920 LWLockRelease(WALWriteLock);
1923 END_CRIT_SECTION();
1926 * If we still haven't flushed to the request point then we have a
1927 * problem; most likely, the requested flush point is past end of XLOG.
1928 * This has been seen to occur when a disk page has a corrupted LSN.
1930 * Formerly we treated this as a PANIC condition, but that hurts the
1931 * system's robustness rather than helping it: we do not want to take down
1932 * the whole system due to corruption on one data page. In particular, if
1933 * the bad page is encountered again during recovery then we would be
1934 * unable to restart the database at all! (This scenario has actually
1935 * happened in the field several times with 7.1 releases. Note that we
1936 * cannot get here while RecoveryInProgress(), but if the bad page is
1937 * brought in and marked dirty during recovery then if a checkpoint were
1938 * performed at the end of recovery it will try to flush it.
1940 * The current approach is to ERROR under normal conditions, but only
1941 * WARNING during recovery, so that the system can be brought up even if
1942 * there's a corrupt LSN. Note that for calls from xact.c, the ERROR will
1943 * be promoted to PANIC since xact.c calls this routine inside a critical
1944 * section. However, calls from bufmgr.c are not within critical sections
1945 * and so we will not force a restart for a bad LSN on a data page.
1947 if (XLByteLT(LogwrtResult.Flush, record))
1948 elog(InRecovery ? WARNING : ERROR,
1949 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1950 record.xlogid, record.xrecoff,
1951 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1955 * Flush xlog, but without specifying exactly where to flush to.
1957 * We normally flush only completed blocks; but if there is nothing to do on
1958 * that basis, we check for unflushed async commits in the current incomplete
1959 * block, and flush through the latest one of those. Thus, if async commits
1960 * are not being used, we will flush complete blocks only. We can guarantee
1961 * that async commits reach disk after at most three cycles; normally only
1962 * one or two. (We allow XLogWrite to write "flexibly", meaning it can stop
1963 * at the end of the buffer ring; this makes a difference only with very high
1964 * load or long wal_writer_delay, but imposes one extra cycle for the worst
1965 * case for async commits.)
1967 * This routine is invoked periodically by the background walwriter process.
1969 void
1970 XLogBackgroundFlush(void)
1972 XLogRecPtr WriteRqstPtr;
1973 bool flexible = true;
1975 /* XLOG doesn't need flushing during recovery */
1976 if (RecoveryInProgress())
1977 return;
1979 /* read LogwrtResult and update local state */
1981 /* use volatile pointer to prevent code rearrangement */
1982 volatile XLogCtlData *xlogctl = XLogCtl;
1984 SpinLockAcquire(&xlogctl->info_lck);
1985 LogwrtResult = xlogctl->LogwrtResult;
1986 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1987 SpinLockRelease(&xlogctl->info_lck);
1990 /* back off to last completed page boundary */
1991 WriteRqstPtr.xrecoff -= WriteRqstPtr.xrecoff % XLOG_BLCKSZ;
1993 /* if we have already flushed that far, consider async commit records */
1994 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
1996 /* use volatile pointer to prevent code rearrangement */
1997 volatile XLogCtlData *xlogctl = XLogCtl;
1999 SpinLockAcquire(&xlogctl->info_lck);
2000 WriteRqstPtr = xlogctl->asyncCommitLSN;
2001 SpinLockRelease(&xlogctl->info_lck);
2002 flexible = false; /* ensure it all gets written */
2005 /* Done if already known flushed */
2006 if (XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
2007 return;
2009 #ifdef WAL_DEBUG
2010 if (XLOG_DEBUG)
2011 elog(LOG, "xlog bg flush request %X/%X; write %X/%X; flush %X/%X",
2012 WriteRqstPtr.xlogid, WriteRqstPtr.xrecoff,
2013 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
2014 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
2015 #endif
2017 START_CRIT_SECTION();
2019 /* now wait for the write lock */
2020 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2021 LogwrtResult = XLogCtl->Write.LogwrtResult;
2022 if (!XLByteLE(WriteRqstPtr, LogwrtResult.Flush))
2024 XLogwrtRqst WriteRqst;
2026 WriteRqst.Write = WriteRqstPtr;
2027 WriteRqst.Flush = WriteRqstPtr;
2028 XLogWrite(WriteRqst, flexible, false);
2030 LWLockRelease(WALWriteLock);
2032 END_CRIT_SECTION();
2036 * Flush any previous asynchronously-committed transactions' commit records.
2038 * NOTE: it is unwise to assume that this provides any strong guarantees.
2039 * In particular, because of the inexact LSN bookkeeping used by clog.c,
2040 * we cannot assume that hint bits will be settable for these transactions.
2042 void
2043 XLogAsyncCommitFlush(void)
2045 XLogRecPtr WriteRqstPtr;
2047 /* use volatile pointer to prevent code rearrangement */
2048 volatile XLogCtlData *xlogctl = XLogCtl;
2050 /* There's no asynchronously committed transactions during recovery */
2051 if (RecoveryInProgress())
2052 return;
2054 SpinLockAcquire(&xlogctl->info_lck);
2055 WriteRqstPtr = xlogctl->asyncCommitLSN;
2056 SpinLockRelease(&xlogctl->info_lck);
2058 XLogFlush(WriteRqstPtr);
2062 * Test whether XLOG data has been flushed up to (at least) the given position.
2064 * Returns true if a flush is still needed. (It may be that someone else
2065 * is already in process of flushing that far, however.)
2067 bool
2068 XLogNeedsFlush(XLogRecPtr record)
2070 /* XLOG doesn't need flushing during recovery */
2071 if (RecoveryInProgress())
2072 return false;
2074 /* Quick exit if already known flushed */
2075 if (XLByteLE(record, LogwrtResult.Flush))
2076 return false;
2078 /* read LogwrtResult and update local state */
2080 /* use volatile pointer to prevent code rearrangement */
2081 volatile XLogCtlData *xlogctl = XLogCtl;
2083 SpinLockAcquire(&xlogctl->info_lck);
2084 LogwrtResult = xlogctl->LogwrtResult;
2085 SpinLockRelease(&xlogctl->info_lck);
2088 /* check again */
2089 if (XLByteLE(record, LogwrtResult.Flush))
2090 return false;
2092 return true;
2096 * Create a new XLOG file segment, or open a pre-existing one.
2098 * log, seg: identify segment to be created/opened.
2100 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
2101 * pre-existing file will be deleted). On return, TRUE if a pre-existing
2102 * file was used.
2104 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2105 * place. This should be TRUE except during bootstrap log creation. The
2106 * caller must *not* hold the lock at call.
2108 * Returns FD of opened file.
2110 * Note: errors here are ERROR not PANIC because we might or might not be
2111 * inside a critical section (eg, during checkpoint there is no reason to
2112 * take down the system on failure). They will promote to PANIC if we are
2113 * in a critical section.
2115 static int
2116 XLogFileInit(uint32 log, uint32 seg,
2117 bool *use_existent, bool use_lock)
2119 char path[MAXPGPATH];
2120 char tmppath[MAXPGPATH];
2121 char *zbuffer;
2122 uint32 installed_log;
2123 uint32 installed_seg;
2124 int max_advance;
2125 int fd;
2126 int nbytes;
2128 XLogFilePath(path, ThisTimeLineID, log, seg);
2131 * Try to use existent file (checkpoint maker may have created it already)
2133 if (*use_existent)
2135 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2136 S_IRUSR | S_IWUSR);
2137 if (fd < 0)
2139 if (errno != ENOENT)
2140 ereport(ERROR,
2141 (errcode_for_file_access(),
2142 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2143 path, log, seg)));
2145 else
2146 return fd;
2150 * Initialize an empty (all zeroes) segment. NOTE: it is possible that
2151 * another process is doing the same thing. If so, we will end up
2152 * pre-creating an extra log segment. That seems OK, and better than
2153 * holding the lock throughout this lengthy process.
2155 elog(DEBUG2, "creating and filling new WAL file");
2157 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2159 unlink(tmppath);
2161 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
2162 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2163 S_IRUSR | S_IWUSR);
2164 if (fd < 0)
2165 ereport(ERROR,
2166 (errcode_for_file_access(),
2167 errmsg("could not create file \"%s\": %m", tmppath)));
2170 * Zero-fill the file. We have to do this the hard way to ensure that all
2171 * the file space has really been allocated --- on platforms that allow
2172 * "holes" in files, just seeking to the end doesn't allocate intermediate
2173 * space. This way, we know that we have all the space and (after the
2174 * fsync below) that all the indirect blocks are down on disk. Therefore,
2175 * fdatasync(2) or O_DSYNC will be sufficient to sync future writes to the
2176 * log file.
2178 * Note: palloc zbuffer, instead of just using a local char array, to
2179 * ensure it is reasonably well-aligned; this may save a few cycles
2180 * transferring data to the kernel.
2182 zbuffer = (char *) palloc0(XLOG_BLCKSZ);
2183 for (nbytes = 0; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
2185 errno = 0;
2186 if ((int) write(fd, zbuffer, XLOG_BLCKSZ) != (int) XLOG_BLCKSZ)
2188 int save_errno = errno;
2191 * If we fail to make the file, delete it to release disk space
2193 unlink(tmppath);
2194 /* if write didn't set errno, assume problem is no disk space */
2195 errno = save_errno ? save_errno : ENOSPC;
2197 ereport(ERROR,
2198 (errcode_for_file_access(),
2199 errmsg("could not write to file \"%s\": %m", tmppath)));
2202 pfree(zbuffer);
2204 if (pg_fsync(fd) != 0)
2205 ereport(ERROR,
2206 (errcode_for_file_access(),
2207 errmsg("could not fsync file \"%s\": %m", tmppath)));
2209 if (close(fd))
2210 ereport(ERROR,
2211 (errcode_for_file_access(),
2212 errmsg("could not close file \"%s\": %m", tmppath)));
2215 * Now move the segment into place with its final name.
2217 * If caller didn't want to use a pre-existing file, get rid of any
2218 * pre-existing file. Otherwise, cope with possibility that someone else
2219 * has created the file while we were filling ours: if so, use ours to
2220 * pre-create a future log segment.
2222 installed_log = log;
2223 installed_seg = seg;
2224 max_advance = XLOGfileslop;
2225 if (!InstallXLogFileSegment(&installed_log, &installed_seg, tmppath,
2226 *use_existent, &max_advance,
2227 use_lock))
2229 /* No need for any more future segments... */
2230 unlink(tmppath);
2233 elog(DEBUG2, "done creating and filling new WAL file");
2235 /* Set flag to tell caller there was no existent file */
2236 *use_existent = false;
2238 /* Now open original target segment (might not be file I just made) */
2239 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2240 S_IRUSR | S_IWUSR);
2241 if (fd < 0)
2242 ereport(ERROR,
2243 (errcode_for_file_access(),
2244 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2245 path, log, seg)));
2247 return fd;
2251 * Create a new XLOG file segment by copying a pre-existing one.
2253 * log, seg: identify segment to be created.
2255 * srcTLI, srclog, srcseg: identify segment to be copied (could be from
2256 * a different timeline)
2258 * Currently this is only used during recovery, and so there are no locking
2259 * considerations. But we should be just as tense as XLogFileInit to avoid
2260 * emplacing a bogus file.
2262 static void
2263 XLogFileCopy(uint32 log, uint32 seg,
2264 TimeLineID srcTLI, uint32 srclog, uint32 srcseg)
2266 char path[MAXPGPATH];
2267 char tmppath[MAXPGPATH];
2268 char buffer[XLOG_BLCKSZ];
2269 int srcfd;
2270 int fd;
2271 int nbytes;
2274 * Open the source file
2276 XLogFilePath(path, srcTLI, srclog, srcseg);
2277 srcfd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2278 if (srcfd < 0)
2279 ereport(ERROR,
2280 (errcode_for_file_access(),
2281 errmsg("could not open file \"%s\": %m", path)));
2284 * Copy into a temp file name.
2286 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
2288 unlink(tmppath);
2290 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
2291 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2292 S_IRUSR | S_IWUSR);
2293 if (fd < 0)
2294 ereport(ERROR,
2295 (errcode_for_file_access(),
2296 errmsg("could not create file \"%s\": %m", tmppath)));
2299 * Do the data copying.
2301 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(buffer))
2303 errno = 0;
2304 if ((int) read(srcfd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2306 if (errno != 0)
2307 ereport(ERROR,
2308 (errcode_for_file_access(),
2309 errmsg("could not read file \"%s\": %m", path)));
2310 else
2311 ereport(ERROR,
2312 (errmsg("not enough data in file \"%s\"", path)));
2314 errno = 0;
2315 if ((int) write(fd, buffer, sizeof(buffer)) != (int) sizeof(buffer))
2317 int save_errno = errno;
2320 * If we fail to make the file, delete it to release disk space
2322 unlink(tmppath);
2323 /* if write didn't set errno, assume problem is no disk space */
2324 errno = save_errno ? save_errno : ENOSPC;
2326 ereport(ERROR,
2327 (errcode_for_file_access(),
2328 errmsg("could not write to file \"%s\": %m", tmppath)));
2332 if (pg_fsync(fd) != 0)
2333 ereport(ERROR,
2334 (errcode_for_file_access(),
2335 errmsg("could not fsync file \"%s\": %m", tmppath)));
2337 if (close(fd))
2338 ereport(ERROR,
2339 (errcode_for_file_access(),
2340 errmsg("could not close file \"%s\": %m", tmppath)));
2342 close(srcfd);
2345 * Now move the segment into place with its final name.
2347 if (!InstallXLogFileSegment(&log, &seg, tmppath, false, NULL, false))
2348 elog(ERROR, "InstallXLogFileSegment should not have failed");
2352 * Install a new XLOG segment file as a current or future log segment.
2354 * This is used both to install a newly-created segment (which has a temp
2355 * filename while it's being created) and to recycle an old segment.
2357 * *log, *seg: identify segment to install as (or first possible target).
2358 * When find_free is TRUE, these are modified on return to indicate the
2359 * actual installation location or last segment searched.
2361 * tmppath: initial name of file to install. It will be renamed into place.
2363 * find_free: if TRUE, install the new segment at the first empty log/seg
2364 * number at or after the passed numbers. If FALSE, install the new segment
2365 * exactly where specified, deleting any existing segment file there.
2367 * *max_advance: maximum number of log/seg slots to advance past the starting
2368 * point. Fail if no free slot is found in this range. On return, reduced
2369 * by the number of slots skipped over. (Irrelevant, and may be NULL,
2370 * when find_free is FALSE.)
2372 * use_lock: if TRUE, acquire ControlFileLock while moving file into
2373 * place. This should be TRUE except during bootstrap log creation. The
2374 * caller must *not* hold the lock at call.
2376 * Returns TRUE if file installed, FALSE if not installed because of
2377 * exceeding max_advance limit. On Windows, we also return FALSE if we
2378 * can't rename the file into place because someone's got it open.
2379 * (Any other kind of failure causes ereport().)
2381 static bool
2382 InstallXLogFileSegment(uint32 *log, uint32 *seg, char *tmppath,
2383 bool find_free, int *max_advance,
2384 bool use_lock)
2386 char path[MAXPGPATH];
2387 struct stat stat_buf;
2389 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2392 * We want to be sure that only one process does this at a time.
2394 if (use_lock)
2395 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
2397 if (!find_free)
2399 /* Force installation: get rid of any pre-existing segment file */
2400 unlink(path);
2402 else
2404 /* Find a free slot to put it in */
2405 while (stat(path, &stat_buf) == 0)
2407 if (*max_advance <= 0)
2409 /* Failed to find a free slot within specified range */
2410 if (use_lock)
2411 LWLockRelease(ControlFileLock);
2412 return false;
2414 NextLogSeg(*log, *seg);
2415 (*max_advance)--;
2416 XLogFilePath(path, ThisTimeLineID, *log, *seg);
2421 * Prefer link() to rename() here just to be really sure that we don't
2422 * overwrite an existing logfile. However, there shouldn't be one, so
2423 * rename() is an acceptable substitute except for the truly paranoid.
2425 #if HAVE_WORKING_LINK
2426 if (link(tmppath, path) < 0)
2427 ereport(ERROR,
2428 (errcode_for_file_access(),
2429 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2430 tmppath, path, *log, *seg)));
2431 unlink(tmppath);
2432 #else
2433 if (rename(tmppath, path) < 0)
2435 #ifdef WIN32
2436 #if !defined(__CYGWIN__)
2437 if (GetLastError() == ERROR_ACCESS_DENIED)
2438 #else
2439 if (errno == EACCES)
2440 #endif
2442 if (use_lock)
2443 LWLockRelease(ControlFileLock);
2444 return false;
2446 #endif /* WIN32 */
2448 ereport(ERROR,
2449 (errcode_for_file_access(),
2450 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file %u, segment %u): %m",
2451 tmppath, path, *log, *seg)));
2453 #endif
2455 if (use_lock)
2456 LWLockRelease(ControlFileLock);
2458 return true;
2462 * Open a pre-existing logfile segment for writing.
2464 static int
2465 XLogFileOpen(uint32 log, uint32 seg)
2467 char path[MAXPGPATH];
2468 int fd;
2470 XLogFilePath(path, ThisTimeLineID, log, seg);
2472 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | get_sync_bit(sync_method),
2473 S_IRUSR | S_IWUSR);
2474 if (fd < 0)
2475 ereport(PANIC,
2476 (errcode_for_file_access(),
2477 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2478 path, log, seg)));
2480 return fd;
2484 * Open a logfile segment for reading (during recovery).
2486 static int
2487 XLogFileRead(uint32 log, uint32 seg, int emode)
2489 char path[MAXPGPATH];
2490 char xlogfname[MAXFNAMELEN];
2491 char activitymsg[MAXFNAMELEN + 16];
2492 ListCell *cell;
2493 int fd;
2496 * Loop looking for a suitable timeline ID: we might need to read any of
2497 * the timelines listed in expectedTLIs.
2499 * We expect curFileTLI on entry to be the TLI of the preceding file in
2500 * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
2501 * to go backwards; this prevents us from picking up the wrong file when a
2502 * parent timeline extends to higher segment numbers than the child we
2503 * want to read.
2505 foreach(cell, expectedTLIs)
2507 TimeLineID tli = (TimeLineID) lfirst_int(cell);
2509 if (tli < curFileTLI)
2510 break; /* don't bother looking at too-old TLIs */
2512 XLogFileName(xlogfname, tli, log, seg);
2514 if (InArchiveRecovery)
2516 /* Report recovery progress in PS display */
2517 snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
2518 xlogfname);
2519 set_ps_display(activitymsg, false);
2521 restoredFromArchive = RestoreArchivedFile(path, xlogfname,
2522 "RECOVERYXLOG",
2523 XLogSegSize);
2525 else
2526 XLogFilePath(path, tli, log, seg);
2528 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
2529 if (fd >= 0)
2531 /* Success! */
2532 curFileTLI = tli;
2534 /* Report recovery progress in PS display */
2535 snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
2536 xlogfname);
2537 set_ps_display(activitymsg, false);
2539 return fd;
2541 if (errno != ENOENT) /* unexpected failure? */
2542 ereport(PANIC,
2543 (errcode_for_file_access(),
2544 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2545 path, log, seg)));
2548 /* Couldn't find it. For simplicity, complain about front timeline */
2549 XLogFilePath(path, recoveryTargetTLI, log, seg);
2550 errno = ENOENT;
2551 ereport(emode,
2552 (errcode_for_file_access(),
2553 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
2554 path, log, seg)));
2555 return -1;
2559 * Close the current logfile segment for writing.
2561 static void
2562 XLogFileClose(void)
2564 Assert(openLogFile >= 0);
2567 * WAL segment files will not be re-read in normal operation, so we advise
2568 * the OS to release any cached pages. But do not do so if WAL archiving
2569 * is active, because archiver process could use the cache to read the WAL
2570 * segment. Also, don't bother with it if we are using O_DIRECT, since
2571 * the kernel is presumably not caching in that case.
2573 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
2574 if (!XLogArchivingActive() &&
2575 (get_sync_bit(sync_method) & PG_O_DIRECT) == 0)
2576 (void) posix_fadvise(openLogFile, 0, 0, POSIX_FADV_DONTNEED);
2577 #endif
2579 if (close(openLogFile))
2580 ereport(PANIC,
2581 (errcode_for_file_access(),
2582 errmsg("could not close log file %u, segment %u: %m",
2583 openLogId, openLogSeg)));
2584 openLogFile = -1;
2588 * Attempt to retrieve the specified file from off-line archival storage.
2589 * If successful, fill "path" with its complete path (note that this will be
2590 * a temp file name that doesn't follow the normal naming convention), and
2591 * return TRUE.
2593 * If not successful, fill "path" with the name of the normal on-line file
2594 * (which may or may not actually exist, but we'll try to use it), and return
2595 * FALSE.
2597 * For fixed-size files, the caller may pass the expected size as an
2598 * additional crosscheck on successful recovery. If the file size is not
2599 * known, set expectedSize = 0.
2601 static bool
2602 RestoreArchivedFile(char *path, const char *xlogfname,
2603 const char *recovername, off_t expectedSize)
2605 char xlogpath[MAXPGPATH];
2606 char xlogRestoreCmd[MAXPGPATH];
2607 char lastRestartPointFname[MAXPGPATH];
2608 char *dp;
2609 char *endp;
2610 const char *sp;
2611 int rc;
2612 bool signaled;
2613 struct stat stat_buf;
2614 uint32 restartLog;
2615 uint32 restartSeg;
2618 * When doing archive recovery, we always prefer an archived log file even
2619 * if a file of the same name exists in XLOGDIR. The reason is that the
2620 * file in XLOGDIR could be an old, un-filled or partly-filled version
2621 * that was copied and restored as part of backing up $PGDATA.
2623 * We could try to optimize this slightly by checking the local copy
2624 * lastchange timestamp against the archived copy, but we have no API to
2625 * do this, nor can we guarantee that the lastchange timestamp was
2626 * preserved correctly when we copied to archive. Our aim is robustness,
2627 * so we elect not to do this.
2629 * If we cannot obtain the log file from the archive, however, we will try
2630 * to use the XLOGDIR file if it exists. This is so that we can make use
2631 * of log segments that weren't yet transferred to the archive.
2633 * Notice that we don't actually overwrite any files when we copy back
2634 * from archive because the recoveryRestoreCommand may inadvertently
2635 * restore inappropriate xlogs, or they may be corrupt, so we may wish to
2636 * fallback to the segments remaining in current XLOGDIR later. The
2637 * copy-from-archive filename is always the same, ensuring that we don't
2638 * run out of disk space on long recoveries.
2640 snprintf(xlogpath, MAXPGPATH, XLOGDIR "/%s", recovername);
2643 * Make sure there is no existing file named recovername.
2645 if (stat(xlogpath, &stat_buf) != 0)
2647 if (errno != ENOENT)
2648 ereport(FATAL,
2649 (errcode_for_file_access(),
2650 errmsg("could not stat file \"%s\": %m",
2651 xlogpath)));
2653 else
2655 if (unlink(xlogpath) != 0)
2656 ereport(FATAL,
2657 (errcode_for_file_access(),
2658 errmsg("could not remove file \"%s\": %m",
2659 xlogpath)));
2663 * Calculate the archive file cutoff point for use during log shipping
2664 * replication. All files earlier than this point can be deleted
2665 * from the archive, though there is no requirement to do so.
2667 * We initialise this with the filename of an InvalidXLogRecPtr, which
2668 * will prevent the deletion of any WAL files from the archive
2669 * because of the alphabetic sorting property of WAL filenames.
2671 * Once we have successfully located the redo pointer of the checkpoint
2672 * from which we start recovery we never request a file prior to the redo
2673 * pointer of the last restartpoint. When redo begins we know that we
2674 * have successfully located it, so there is no need for additional
2675 * status flags to signify the point when we can begin deleting WAL files
2676 * from the archive.
2678 if (InRedo)
2680 XLByteToSeg(ControlFile->checkPointCopy.redo,
2681 restartLog, restartSeg);
2682 XLogFileName(lastRestartPointFname,
2683 ControlFile->checkPointCopy.ThisTimeLineID,
2684 restartLog, restartSeg);
2685 /* we shouldn't need anything earlier than last restart point */
2686 Assert(strcmp(lastRestartPointFname, xlogfname) <= 0);
2688 else
2689 XLogFileName(lastRestartPointFname, 0, 0, 0);
2692 * construct the command to be executed
2694 dp = xlogRestoreCmd;
2695 endp = xlogRestoreCmd + MAXPGPATH - 1;
2696 *endp = '\0';
2698 for (sp = recoveryRestoreCommand; *sp; sp++)
2700 if (*sp == '%')
2702 switch (sp[1])
2704 case 'p':
2705 /* %p: relative path of target file */
2706 sp++;
2707 StrNCpy(dp, xlogpath, endp - dp);
2708 make_native_path(dp);
2709 dp += strlen(dp);
2710 break;
2711 case 'f':
2712 /* %f: filename of desired file */
2713 sp++;
2714 StrNCpy(dp, xlogfname, endp - dp);
2715 dp += strlen(dp);
2716 break;
2717 case 'r':
2718 /* %r: filename of last restartpoint */
2719 sp++;
2720 StrNCpy(dp, lastRestartPointFname, endp - dp);
2721 dp += strlen(dp);
2722 break;
2723 case '%':
2724 /* convert %% to a single % */
2725 sp++;
2726 if (dp < endp)
2727 *dp++ = *sp;
2728 break;
2729 default:
2730 /* otherwise treat the % as not special */
2731 if (dp < endp)
2732 *dp++ = *sp;
2733 break;
2736 else
2738 if (dp < endp)
2739 *dp++ = *sp;
2742 *dp = '\0';
2744 ereport(DEBUG3,
2745 (errmsg_internal("executing restore command \"%s\"",
2746 xlogRestoreCmd)));
2749 * Set in_restore_command to tell the signal handler that we should exit
2750 * right away on SIGTERM. We know that we're in a safe point to do that.
2751 * Check if we had already received the signal, so that we don't miss a
2752 * shutdown request received just before this.
2754 in_restore_command = true;
2755 if (shutdown_requested)
2756 proc_exit(1);
2759 * Copy xlog from archival storage to XLOGDIR
2761 rc = system(xlogRestoreCmd);
2763 in_restore_command = false;
2765 if (rc == 0)
2768 * command apparently succeeded, but let's make sure the file is
2769 * really there now and has the correct size.
2771 * XXX I made wrong-size a fatal error to ensure the DBA would notice
2772 * it, but is that too strong? We could try to plow ahead with a
2773 * local copy of the file ... but the problem is that there probably
2774 * isn't one, and we'd incorrectly conclude we've reached the end of
2775 * WAL and we're done recovering ...
2777 if (stat(xlogpath, &stat_buf) == 0)
2779 if (expectedSize > 0 && stat_buf.st_size != expectedSize)
2780 ereport(FATAL,
2781 (errmsg("archive file \"%s\" has wrong size: %lu instead of %lu",
2782 xlogfname,
2783 (unsigned long) stat_buf.st_size,
2784 (unsigned long) expectedSize)));
2785 else
2787 ereport(LOG,
2788 (errmsg("restored log file \"%s\" from archive",
2789 xlogfname)));
2790 strcpy(path, xlogpath);
2791 return true;
2794 else
2796 /* stat failed */
2797 if (errno != ENOENT)
2798 ereport(FATAL,
2799 (errcode_for_file_access(),
2800 errmsg("could not stat file \"%s\": %m",
2801 xlogpath)));
2806 * Remember, we rollforward UNTIL the restore fails so failure here is
2807 * just part of the process... that makes it difficult to determine
2808 * whether the restore failed because there isn't an archive to restore,
2809 * or because the administrator has specified the restore program
2810 * incorrectly. We have to assume the former.
2812 * However, if the failure was due to any sort of signal, it's best to
2813 * punt and abort recovery. (If we "return false" here, upper levels will
2814 * assume that recovery is complete and start up the database!) It's
2815 * essential to abort on child SIGINT and SIGQUIT, because per spec
2816 * system() ignores SIGINT and SIGQUIT while waiting; if we see one of
2817 * those it's a good bet we should have gotten it too.
2819 * On SIGTERM, assume we have received a fast shutdown request, and exit
2820 * cleanly. It's pure chance whether we receive the SIGTERM first, or the
2821 * child process. If we receive it first, the signal handler will call
2822 * proc_exit, otherwise we do it here. If we or the child process
2823 * received SIGTERM for any other reason than a fast shutdown request,
2824 * postmaster will perform an immediate shutdown when it sees us exiting
2825 * unexpectedly.
2827 * Per the Single Unix Spec, shells report exit status > 128 when a called
2828 * command died on a signal. Also, 126 and 127 are used to report
2829 * problems such as an unfindable command; treat those as fatal errors
2830 * too.
2832 if (WTERMSIG(rc) == SIGTERM)
2833 proc_exit(1);
2835 signaled = WIFSIGNALED(rc) || WEXITSTATUS(rc) > 125;
2837 ereport(signaled ? FATAL : DEBUG2,
2838 (errmsg("could not restore file \"%s\" from archive: return code %d",
2839 xlogfname, rc)));
2842 * if an archived file is not available, there might still be a version of
2843 * this file in XLOGDIR, so return that as the filename to open.
2845 * In many recovery scenarios we expect this to fail also, but if so that
2846 * just means we've reached the end of WAL.
2848 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
2849 return false;
2853 * Preallocate log files beyond the specified log endpoint.
2855 * XXX this is currently extremely conservative, since it forces only one
2856 * future log segment to exist, and even that only if we are 75% done with
2857 * the current one. This is only appropriate for very low-WAL-volume systems.
2858 * High-volume systems will be OK once they've built up a sufficient set of
2859 * recycled log segments, but the startup transient is likely to include
2860 * a lot of segment creations by foreground processes, which is not so good.
2862 static void
2863 PreallocXlogFiles(XLogRecPtr endptr)
2865 uint32 _logId;
2866 uint32 _logSeg;
2867 int lf;
2868 bool use_existent;
2870 XLByteToPrevSeg(endptr, _logId, _logSeg);
2871 if ((endptr.xrecoff - 1) % XLogSegSize >=
2872 (uint32) (0.75 * XLogSegSize))
2874 NextLogSeg(_logId, _logSeg);
2875 use_existent = true;
2876 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
2877 close(lf);
2878 if (!use_existent)
2879 CheckpointStats.ckpt_segs_added++;
2884 * Recycle or remove all log files older or equal to passed log/seg#
2886 * endptr is current (or recent) end of xlog; this is used to determine
2887 * whether we want to recycle rather than delete no-longer-wanted log files.
2889 static void
2890 RemoveOldXlogFiles(uint32 log, uint32 seg, XLogRecPtr endptr)
2892 uint32 endlogId;
2893 uint32 endlogSeg;
2894 int max_advance;
2895 DIR *xldir;
2896 struct dirent *xlde;
2897 char lastoff[MAXFNAMELEN];
2898 char path[MAXPGPATH];
2901 * Initialize info about where to try to recycle to. We allow recycling
2902 * segments up to XLOGfileslop segments beyond the current XLOG location.
2904 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
2905 max_advance = XLOGfileslop;
2907 xldir = AllocateDir(XLOGDIR);
2908 if (xldir == NULL)
2909 ereport(ERROR,
2910 (errcode_for_file_access(),
2911 errmsg("could not open transaction log directory \"%s\": %m",
2912 XLOGDIR)));
2914 XLogFileName(lastoff, ThisTimeLineID, log, seg);
2916 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
2919 * We ignore the timeline part of the XLOG segment identifiers in
2920 * deciding whether a segment is still needed. This ensures that we
2921 * won't prematurely remove a segment from a parent timeline. We could
2922 * probably be a little more proactive about removing segments of
2923 * non-parent timelines, but that would be a whole lot more
2924 * complicated.
2926 * We use the alphanumeric sorting property of the filenames to decide
2927 * which ones are earlier than the lastoff segment.
2929 if (strlen(xlde->d_name) == 24 &&
2930 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
2931 strcmp(xlde->d_name + 8, lastoff + 8) <= 0)
2933 if (XLogArchiveCheckDone(xlde->d_name))
2935 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
2938 * Before deleting the file, see if it can be recycled as a
2939 * future log segment.
2941 if (InstallXLogFileSegment(&endlogId, &endlogSeg, path,
2942 true, &max_advance,
2943 true))
2945 ereport(DEBUG2,
2946 (errmsg("recycled transaction log file \"%s\"",
2947 xlde->d_name)));
2948 CheckpointStats.ckpt_segs_recycled++;
2949 /* Needn't recheck that slot on future iterations */
2950 if (max_advance > 0)
2952 NextLogSeg(endlogId, endlogSeg);
2953 max_advance--;
2956 else
2958 /* No need for any more future segments... */
2959 ereport(DEBUG2,
2960 (errmsg("removing transaction log file \"%s\"",
2961 xlde->d_name)));
2962 unlink(path);
2963 CheckpointStats.ckpt_segs_removed++;
2966 XLogArchiveCleanup(xlde->d_name);
2971 FreeDir(xldir);
2975 * Verify whether pg_xlog and pg_xlog/archive_status exist.
2976 * If the latter does not exist, recreate it.
2978 * It is not the goal of this function to verify the contents of these
2979 * directories, but to help in cases where someone has performed a cluster
2980 * copy for PITR purposes but omitted pg_xlog from the copy.
2982 * We could also recreate pg_xlog if it doesn't exist, but a deliberate
2983 * policy decision was made not to. It is fairly common for pg_xlog to be
2984 * a symlink, and if that was the DBA's intent then automatically making a
2985 * plain directory would result in degraded performance with no notice.
2987 static void
2988 ValidateXLOGDirectoryStructure(void)
2990 char path[MAXPGPATH];
2991 struct stat stat_buf;
2993 /* Check for pg_xlog; if it doesn't exist, error out */
2994 if (stat(XLOGDIR, &stat_buf) != 0 ||
2995 !S_ISDIR(stat_buf.st_mode))
2996 ereport(FATAL,
2997 (errmsg("required WAL directory \"%s\" does not exist",
2998 XLOGDIR)));
3000 /* Check for archive_status */
3001 snprintf(path, MAXPGPATH, XLOGDIR "/archive_status");
3002 if (stat(path, &stat_buf) == 0)
3004 /* Check for weird cases where it exists but isn't a directory */
3005 if (!S_ISDIR(stat_buf.st_mode))
3006 ereport(FATAL,
3007 (errmsg("required WAL directory \"%s\" does not exist",
3008 path)));
3010 else
3012 ereport(LOG,
3013 (errmsg("creating missing WAL directory \"%s\"", path)));
3014 if (mkdir(path, 0700) < 0)
3015 ereport(FATAL,
3016 (errmsg("could not create missing directory \"%s\": %m",
3017 path)));
3022 * Remove previous backup history files. This also retries creation of
3023 * .ready files for any backup history files for which XLogArchiveNotify
3024 * failed earlier.
3026 static void
3027 CleanupBackupHistory(void)
3029 DIR *xldir;
3030 struct dirent *xlde;
3031 char path[MAXPGPATH];
3033 xldir = AllocateDir(XLOGDIR);
3034 if (xldir == NULL)
3035 ereport(ERROR,
3036 (errcode_for_file_access(),
3037 errmsg("could not open transaction log directory \"%s\": %m",
3038 XLOGDIR)));
3040 while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
3042 if (strlen(xlde->d_name) > 24 &&
3043 strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
3044 strcmp(xlde->d_name + strlen(xlde->d_name) - strlen(".backup"),
3045 ".backup") == 0)
3047 if (XLogArchiveCheckDone(xlde->d_name))
3049 ereport(DEBUG2,
3050 (errmsg("removing transaction log backup history file \"%s\"",
3051 xlde->d_name)));
3052 snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlde->d_name);
3053 unlink(path);
3054 XLogArchiveCleanup(xlde->d_name);
3059 FreeDir(xldir);
3063 * Restore the backup blocks present in an XLOG record, if any.
3065 * We assume all of the record has been read into memory at *record.
3067 * Note: when a backup block is available in XLOG, we restore it
3068 * unconditionally, even if the page in the database appears newer.
3069 * This is to protect ourselves against database pages that were partially
3070 * or incorrectly written during a crash. We assume that the XLOG data
3071 * must be good because it has passed a CRC check, while the database
3072 * page might not be. This will force us to replay all subsequent
3073 * modifications of the page that appear in XLOG, rather than possibly
3074 * ignoring them as already applied, but that's not a huge drawback.
3076 * If 'cleanup' is true, a cleanup lock is used when restoring blocks.
3077 * Otherwise, a normal exclusive lock is used. At the moment, that's just
3078 * pro forma, because there can't be any regular backends in the system
3079 * during recovery. The 'cleanup' argument applies to all backup blocks
3080 * in the WAL record, that suffices for now.
3082 void
3083 RestoreBkpBlocks(XLogRecPtr lsn, XLogRecord *record, bool cleanup)
3085 Buffer buffer;
3086 Page page;
3087 BkpBlock bkpb;
3088 char *blk;
3089 int i;
3091 if (!(record->xl_info & XLR_BKP_BLOCK_MASK))
3092 return;
3094 blk = (char *) XLogRecGetData(record) + record->xl_len;
3095 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3097 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3098 continue;
3100 memcpy(&bkpb, blk, sizeof(BkpBlock));
3101 blk += sizeof(BkpBlock);
3103 buffer = XLogReadBufferExtended(bkpb.node, bkpb.fork, bkpb.block,
3104 RBM_ZERO);
3105 Assert(BufferIsValid(buffer));
3106 if (cleanup)
3107 LockBufferForCleanup(buffer);
3108 else
3109 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3111 page = (Page) BufferGetPage(buffer);
3113 if (bkpb.hole_length == 0)
3115 memcpy((char *) page, blk, BLCKSZ);
3117 else
3119 /* must zero-fill the hole */
3120 MemSet((char *) page, 0, BLCKSZ);
3121 memcpy((char *) page, blk, bkpb.hole_offset);
3122 memcpy((char *) page + (bkpb.hole_offset + bkpb.hole_length),
3123 blk + bkpb.hole_offset,
3124 BLCKSZ - (bkpb.hole_offset + bkpb.hole_length));
3127 PageSetLSN(page, lsn);
3128 PageSetTLI(page, ThisTimeLineID);
3129 MarkBufferDirty(buffer);
3130 UnlockReleaseBuffer(buffer);
3132 blk += BLCKSZ - bkpb.hole_length;
3137 * CRC-check an XLOG record. We do not believe the contents of an XLOG
3138 * record (other than to the minimal extent of computing the amount of
3139 * data to read in) until we've checked the CRCs.
3141 * We assume all of the record has been read into memory at *record.
3143 static bool
3144 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
3146 pg_crc32 crc;
3147 int i;
3148 uint32 len = record->xl_len;
3149 BkpBlock bkpb;
3150 char *blk;
3152 /* First the rmgr data */
3153 INIT_CRC32(crc);
3154 COMP_CRC32(crc, XLogRecGetData(record), len);
3156 /* Add in the backup blocks, if any */
3157 blk = (char *) XLogRecGetData(record) + len;
3158 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3160 uint32 blen;
3162 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
3163 continue;
3165 memcpy(&bkpb, blk, sizeof(BkpBlock));
3166 if (bkpb.hole_offset + bkpb.hole_length > BLCKSZ)
3168 ereport(emode,
3169 (errmsg("incorrect hole size in record at %X/%X",
3170 recptr.xlogid, recptr.xrecoff)));
3171 return false;
3173 blen = sizeof(BkpBlock) + BLCKSZ - bkpb.hole_length;
3174 COMP_CRC32(crc, blk, blen);
3175 blk += blen;
3178 /* Check that xl_tot_len agrees with our calculation */
3179 if (blk != (char *) record + record->xl_tot_len)
3181 ereport(emode,
3182 (errmsg("incorrect total length in record at %X/%X",
3183 recptr.xlogid, recptr.xrecoff)));
3184 return false;
3187 /* Finally include the record header */
3188 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
3189 SizeOfXLogRecord - sizeof(pg_crc32));
3190 FIN_CRC32(crc);
3192 if (!EQ_CRC32(record->xl_crc, crc))
3194 ereport(emode,
3195 (errmsg("incorrect resource manager data checksum in record at %X/%X",
3196 recptr.xlogid, recptr.xrecoff)));
3197 return false;
3200 return true;
3204 * Attempt to read an XLOG record.
3206 * If RecPtr is not NULL, try to read a record at that position. Otherwise
3207 * try to read a record just after the last one previously read.
3209 * If no valid record is available, returns NULL, or fails if emode is PANIC.
3210 * (emode must be either PANIC or LOG.)
3212 * The record is copied into readRecordBuf, so that on successful return,
3213 * the returned record pointer always points there.
3215 static XLogRecord *
3216 ReadRecord(XLogRecPtr *RecPtr, int emode)
3218 XLogRecord *record;
3219 char *buffer;
3220 XLogRecPtr tmpRecPtr = EndRecPtr;
3221 bool randAccess = false;
3222 uint32 len,
3223 total_len;
3224 uint32 targetPageOff;
3225 uint32 targetRecOff;
3226 uint32 pageHeaderSize;
3228 if (readBuf == NULL)
3231 * First time through, permanently allocate readBuf. We do it this
3232 * way, rather than just making a static array, for two reasons: (1)
3233 * no need to waste the storage in most instantiations of the backend;
3234 * (2) a static char array isn't guaranteed to have any particular
3235 * alignment, whereas malloc() will provide MAXALIGN'd storage.
3237 readBuf = (char *) malloc(XLOG_BLCKSZ);
3238 Assert(readBuf != NULL);
3241 if (RecPtr == NULL)
3243 RecPtr = &tmpRecPtr;
3244 /* fast case if next record is on same page */
3245 if (nextRecord != NULL)
3247 record = nextRecord;
3248 goto got_record;
3250 /* align old recptr to next page */
3251 if (tmpRecPtr.xrecoff % XLOG_BLCKSZ != 0)
3252 tmpRecPtr.xrecoff += (XLOG_BLCKSZ - tmpRecPtr.xrecoff % XLOG_BLCKSZ);
3253 if (tmpRecPtr.xrecoff >= XLogFileSize)
3255 (tmpRecPtr.xlogid)++;
3256 tmpRecPtr.xrecoff = 0;
3258 /* We will account for page header size below */
3260 else
3262 if (!XRecOffIsValid(RecPtr->xrecoff))
3263 ereport(PANIC,
3264 (errmsg("invalid record offset at %X/%X",
3265 RecPtr->xlogid, RecPtr->xrecoff)));
3268 * Since we are going to a random position in WAL, forget any prior
3269 * state about what timeline we were in, and allow it to be any
3270 * timeline in expectedTLIs. We also set a flag to allow curFileTLI
3271 * to go backwards (but we can't reset that variable right here, since
3272 * we might not change files at all).
3274 lastPageTLI = 0; /* see comment in ValidXLOGHeader */
3275 randAccess = true; /* allow curFileTLI to go backwards too */
3278 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
3280 close(readFile);
3281 readFile = -1;
3283 XLByteToSeg(*RecPtr, readId, readSeg);
3284 if (readFile < 0)
3286 /* Now it's okay to reset curFileTLI if random fetch */
3287 if (randAccess)
3288 curFileTLI = 0;
3290 readFile = XLogFileRead(readId, readSeg, emode);
3291 if (readFile < 0)
3292 goto next_record_is_invalid;
3295 * Whenever switching to a new WAL segment, we read the first page of
3296 * the file and validate its header, even if that's not where the
3297 * target record is. This is so that we can check the additional
3298 * identification info that is present in the first page's "long"
3299 * header.
3301 readOff = 0;
3302 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3304 ereport(emode,
3305 (errcode_for_file_access(),
3306 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3307 readId, readSeg, readOff)));
3308 goto next_record_is_invalid;
3310 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3311 goto next_record_is_invalid;
3314 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / XLOG_BLCKSZ) * XLOG_BLCKSZ;
3315 if (readOff != targetPageOff)
3317 readOff = targetPageOff;
3318 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
3320 ereport(emode,
3321 (errcode_for_file_access(),
3322 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
3323 readId, readSeg, readOff)));
3324 goto next_record_is_invalid;
3326 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3328 ereport(emode,
3329 (errcode_for_file_access(),
3330 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3331 readId, readSeg, readOff)));
3332 goto next_record_is_invalid;
3334 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3335 goto next_record_is_invalid;
3337 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3338 targetRecOff = RecPtr->xrecoff % XLOG_BLCKSZ;
3339 if (targetRecOff == 0)
3342 * Can only get here in the continuing-from-prev-page case, because
3343 * XRecOffIsValid eliminated the zero-page-offset case otherwise. Need
3344 * to skip over the new page's header.
3346 tmpRecPtr.xrecoff += pageHeaderSize;
3347 targetRecOff = pageHeaderSize;
3349 else if (targetRecOff < pageHeaderSize)
3351 ereport(emode,
3352 (errmsg("invalid record offset at %X/%X",
3353 RecPtr->xlogid, RecPtr->xrecoff)));
3354 goto next_record_is_invalid;
3356 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
3357 targetRecOff == pageHeaderSize)
3359 ereport(emode,
3360 (errmsg("contrecord is requested by %X/%X",
3361 RecPtr->xlogid, RecPtr->xrecoff)));
3362 goto next_record_is_invalid;
3364 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % XLOG_BLCKSZ);
3366 got_record:;
3369 * xl_len == 0 is bad data for everything except XLOG SWITCH, where it is
3370 * required.
3372 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3374 if (record->xl_len != 0)
3376 ereport(emode,
3377 (errmsg("invalid xlog switch record at %X/%X",
3378 RecPtr->xlogid, RecPtr->xrecoff)));
3379 goto next_record_is_invalid;
3382 else if (record->xl_len == 0)
3384 ereport(emode,
3385 (errmsg("record with zero length at %X/%X",
3386 RecPtr->xlogid, RecPtr->xrecoff)));
3387 goto next_record_is_invalid;
3389 if (record->xl_tot_len < SizeOfXLogRecord + record->xl_len ||
3390 record->xl_tot_len > SizeOfXLogRecord + record->xl_len +
3391 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
3393 ereport(emode,
3394 (errmsg("invalid record length at %X/%X",
3395 RecPtr->xlogid, RecPtr->xrecoff)));
3396 goto next_record_is_invalid;
3398 if (record->xl_rmid > RM_MAX_ID)
3400 ereport(emode,
3401 (errmsg("invalid resource manager ID %u at %X/%X",
3402 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
3403 goto next_record_is_invalid;
3405 if (randAccess)
3408 * We can't exactly verify the prev-link, but surely it should be less
3409 * than the record's own address.
3411 if (!XLByteLT(record->xl_prev, *RecPtr))
3413 ereport(emode,
3414 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3415 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3416 RecPtr->xlogid, RecPtr->xrecoff)));
3417 goto next_record_is_invalid;
3420 else
3423 * Record's prev-link should exactly match our previous location. This
3424 * check guards against torn WAL pages where a stale but valid-looking
3425 * WAL record starts on a sector boundary.
3427 if (!XLByteEQ(record->xl_prev, ReadRecPtr))
3429 ereport(emode,
3430 (errmsg("record with incorrect prev-link %X/%X at %X/%X",
3431 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3432 RecPtr->xlogid, RecPtr->xrecoff)));
3433 goto next_record_is_invalid;
3438 * Allocate or enlarge readRecordBuf as needed. To avoid useless small
3439 * increases, round its size to a multiple of XLOG_BLCKSZ, and make sure
3440 * it's at least 4*Max(BLCKSZ, XLOG_BLCKSZ) to start with. (That is
3441 * enough for all "normal" records, but very large commit or abort records
3442 * might need more space.)
3444 total_len = record->xl_tot_len;
3445 if (total_len > readRecordBufSize)
3447 uint32 newSize = total_len;
3449 newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
3450 newSize = Max(newSize, 4 * Max(BLCKSZ, XLOG_BLCKSZ));
3451 if (readRecordBuf)
3452 free(readRecordBuf);
3453 readRecordBuf = (char *) malloc(newSize);
3454 if (!readRecordBuf)
3456 readRecordBufSize = 0;
3457 /* We treat this as a "bogus data" condition */
3458 ereport(emode,
3459 (errmsg("record length %u at %X/%X too long",
3460 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
3461 goto next_record_is_invalid;
3463 readRecordBufSize = newSize;
3466 buffer = readRecordBuf;
3467 nextRecord = NULL;
3468 len = XLOG_BLCKSZ - RecPtr->xrecoff % XLOG_BLCKSZ;
3469 if (total_len > len)
3471 /* Need to reassemble record */
3472 XLogContRecord *contrecord;
3473 uint32 gotlen = len;
3475 memcpy(buffer, record, len);
3476 record = (XLogRecord *) buffer;
3477 buffer += len;
3478 for (;;)
3480 readOff += XLOG_BLCKSZ;
3481 if (readOff >= XLogSegSize)
3483 close(readFile);
3484 readFile = -1;
3485 NextLogSeg(readId, readSeg);
3486 readFile = XLogFileRead(readId, readSeg, emode);
3487 if (readFile < 0)
3488 goto next_record_is_invalid;
3489 readOff = 0;
3491 if (read(readFile, readBuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
3493 ereport(emode,
3494 (errcode_for_file_access(),
3495 errmsg("could not read from log file %u, segment %u, offset %u: %m",
3496 readId, readSeg, readOff)));
3497 goto next_record_is_invalid;
3499 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode))
3500 goto next_record_is_invalid;
3501 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
3503 ereport(emode,
3504 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
3505 readId, readSeg, readOff)));
3506 goto next_record_is_invalid;
3508 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3509 contrecord = (XLogContRecord *) ((char *) readBuf + pageHeaderSize);
3510 if (contrecord->xl_rem_len == 0 ||
3511 total_len != (contrecord->xl_rem_len + gotlen))
3513 ereport(emode,
3514 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
3515 contrecord->xl_rem_len,
3516 readId, readSeg, readOff)));
3517 goto next_record_is_invalid;
3519 len = XLOG_BLCKSZ - pageHeaderSize - SizeOfXLogContRecord;
3520 if (contrecord->xl_rem_len > len)
3522 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
3523 gotlen += len;
3524 buffer += len;
3525 continue;
3527 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
3528 contrecord->xl_rem_len);
3529 break;
3531 if (!RecordIsValid(record, *RecPtr, emode))
3532 goto next_record_is_invalid;
3533 pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) readBuf);
3534 if (XLOG_BLCKSZ - SizeOfXLogRecord >= pageHeaderSize +
3535 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len))
3537 nextRecord = (XLogRecord *) ((char *) contrecord +
3538 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len));
3540 EndRecPtr.xlogid = readId;
3541 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
3542 pageHeaderSize +
3543 MAXALIGN(SizeOfXLogContRecord + contrecord->xl_rem_len);
3544 ReadRecPtr = *RecPtr;
3545 /* needn't worry about XLOG SWITCH, it can't cross page boundaries */
3546 return record;
3549 /* Record does not cross a page boundary */
3550 if (!RecordIsValid(record, *RecPtr, emode))
3551 goto next_record_is_invalid;
3552 if (XLOG_BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % XLOG_BLCKSZ +
3553 MAXALIGN(total_len))
3554 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
3555 EndRecPtr.xlogid = RecPtr->xlogid;
3556 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
3557 ReadRecPtr = *RecPtr;
3558 memcpy(buffer, record, total_len);
3561 * Special processing if it's an XLOG SWITCH record
3563 if (record->xl_rmid == RM_XLOG_ID && record->xl_info == XLOG_SWITCH)
3565 /* Pretend it extends to end of segment */
3566 EndRecPtr.xrecoff += XLogSegSize - 1;
3567 EndRecPtr.xrecoff -= EndRecPtr.xrecoff % XLogSegSize;
3568 nextRecord = NULL; /* definitely not on same page */
3571 * Pretend that readBuf contains the last page of the segment. This is
3572 * just to avoid Assert failure in StartupXLOG if XLOG ends with this
3573 * segment.
3575 readOff = XLogSegSize - XLOG_BLCKSZ;
3577 return (XLogRecord *) buffer;
3579 next_record_is_invalid:;
3580 if (readFile >= 0)
3582 close(readFile);
3583 readFile = -1;
3585 nextRecord = NULL;
3586 return NULL;
3590 * Check whether the xlog header of a page just read in looks valid.
3592 * This is just a convenience subroutine to avoid duplicated code in
3593 * ReadRecord. It's not intended for use from anywhere else.
3595 static bool
3596 ValidXLOGHeader(XLogPageHeader hdr, int emode)
3598 XLogRecPtr recaddr;
3600 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
3602 ereport(emode,
3603 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
3604 hdr->xlp_magic, readId, readSeg, readOff)));
3605 return false;
3607 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
3609 ereport(emode,
3610 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3611 hdr->xlp_info, readId, readSeg, readOff)));
3612 return false;
3614 if (hdr->xlp_info & XLP_LONG_HEADER)
3616 XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
3618 if (longhdr->xlp_sysid != ControlFile->system_identifier)
3620 char fhdrident_str[32];
3621 char sysident_str[32];
3624 * Format sysids separately to keep platform-dependent format code
3625 * out of the translatable message string.
3627 snprintf(fhdrident_str, sizeof(fhdrident_str), UINT64_FORMAT,
3628 longhdr->xlp_sysid);
3629 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
3630 ControlFile->system_identifier);
3631 ereport(emode,
3632 (errmsg("WAL file is from different system"),
3633 errdetail("WAL file SYSID is %s, pg_control SYSID is %s",
3634 fhdrident_str, sysident_str)));
3635 return false;
3637 if (longhdr->xlp_seg_size != XLogSegSize)
3639 ereport(emode,
3640 (errmsg("WAL file is from different system"),
3641 errdetail("Incorrect XLOG_SEG_SIZE in page header.")));
3642 return false;
3644 if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
3646 ereport(emode,
3647 (errmsg("WAL file is from different system"),
3648 errdetail("Incorrect XLOG_BLCKSZ in page header.")));
3649 return false;
3652 else if (readOff == 0)
3654 /* hmm, first page of file doesn't have a long header? */
3655 ereport(emode,
3656 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
3657 hdr->xlp_info, readId, readSeg, readOff)));
3658 return false;
3661 recaddr.xlogid = readId;
3662 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
3663 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
3665 ereport(emode,
3666 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
3667 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
3668 readId, readSeg, readOff)));
3669 return false;
3673 * Check page TLI is one of the expected values.
3675 if (!list_member_int(expectedTLIs, (int) hdr->xlp_tli))
3677 ereport(emode,
3678 (errmsg("unexpected timeline ID %u in log file %u, segment %u, offset %u",
3679 hdr->xlp_tli,
3680 readId, readSeg, readOff)));
3681 return false;
3685 * Since child timelines are always assigned a TLI greater than their
3686 * immediate parent's TLI, we should never see TLI go backwards across
3687 * successive pages of a consistent WAL sequence.
3689 * Of course this check should only be applied when advancing sequentially
3690 * across pages; therefore ReadRecord resets lastPageTLI to zero when
3691 * going to a random page.
3693 if (hdr->xlp_tli < lastPageTLI)
3695 ereport(emode,
3696 (errmsg("out-of-sequence timeline ID %u (after %u) in log file %u, segment %u, offset %u",
3697 hdr->xlp_tli, lastPageTLI,
3698 readId, readSeg, readOff)));
3699 return false;
3701 lastPageTLI = hdr->xlp_tli;
3702 return true;
3706 * Try to read a timeline's history file.
3708 * If successful, return the list of component TLIs (the given TLI followed by
3709 * its ancestor TLIs). If we can't find the history file, assume that the
3710 * timeline has no parents, and return a list of just the specified timeline
3711 * ID.
3713 static List *
3714 readTimeLineHistory(TimeLineID targetTLI)
3716 List *result;
3717 char path[MAXPGPATH];
3718 char histfname[MAXFNAMELEN];
3719 char fline[MAXPGPATH];
3720 FILE *fd;
3722 if (InArchiveRecovery)
3724 TLHistoryFileName(histfname, targetTLI);
3725 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3727 else
3728 TLHistoryFilePath(path, targetTLI);
3730 fd = AllocateFile(path, "r");
3731 if (fd == NULL)
3733 if (errno != ENOENT)
3734 ereport(FATAL,
3735 (errcode_for_file_access(),
3736 errmsg("could not open file \"%s\": %m", path)));
3737 /* Not there, so assume no parents */
3738 return list_make1_int((int) targetTLI);
3741 result = NIL;
3744 * Parse the file...
3746 while (fgets(fline, sizeof(fline), fd) != NULL)
3748 /* skip leading whitespace and check for # comment */
3749 char *ptr;
3750 char *endptr;
3751 TimeLineID tli;
3753 for (ptr = fline; *ptr; ptr++)
3755 if (!isspace((unsigned char) *ptr))
3756 break;
3758 if (*ptr == '\0' || *ptr == '#')
3759 continue;
3761 /* expect a numeric timeline ID as first field of line */
3762 tli = (TimeLineID) strtoul(ptr, &endptr, 0);
3763 if (endptr == ptr)
3764 ereport(FATAL,
3765 (errmsg("syntax error in history file: %s", fline),
3766 errhint("Expected a numeric timeline ID.")));
3768 if (result &&
3769 tli <= (TimeLineID) linitial_int(result))
3770 ereport(FATAL,
3771 (errmsg("invalid data in history file: %s", fline),
3772 errhint("Timeline IDs must be in increasing sequence.")));
3774 /* Build list with newest item first */
3775 result = lcons_int((int) tli, result);
3777 /* we ignore the remainder of each line */
3780 FreeFile(fd);
3782 if (result &&
3783 targetTLI <= (TimeLineID) linitial_int(result))
3784 ereport(FATAL,
3785 (errmsg("invalid data in history file \"%s\"", path),
3786 errhint("Timeline IDs must be less than child timeline's ID.")));
3788 result = lcons_int((int) targetTLI, result);
3790 ereport(DEBUG3,
3791 (errmsg_internal("history of timeline %u is %s",
3792 targetTLI, nodeToString(result))));
3794 return result;
3798 * Probe whether a timeline history file exists for the given timeline ID
3800 static bool
3801 existsTimeLineHistory(TimeLineID probeTLI)
3803 char path[MAXPGPATH];
3804 char histfname[MAXFNAMELEN];
3805 FILE *fd;
3807 if (InArchiveRecovery)
3809 TLHistoryFileName(histfname, probeTLI);
3810 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3812 else
3813 TLHistoryFilePath(path, probeTLI);
3815 fd = AllocateFile(path, "r");
3816 if (fd != NULL)
3818 FreeFile(fd);
3819 return true;
3821 else
3823 if (errno != ENOENT)
3824 ereport(FATAL,
3825 (errcode_for_file_access(),
3826 errmsg("could not open file \"%s\": %m", path)));
3827 return false;
3832 * Find the newest existing timeline, assuming that startTLI exists.
3834 * Note: while this is somewhat heuristic, it does positively guarantee
3835 * that (result + 1) is not a known timeline, and therefore it should
3836 * be safe to assign that ID to a new timeline.
3838 static TimeLineID
3839 findNewestTimeLine(TimeLineID startTLI)
3841 TimeLineID newestTLI;
3842 TimeLineID probeTLI;
3845 * The algorithm is just to probe for the existence of timeline history
3846 * files. XXX is it useful to allow gaps in the sequence?
3848 newestTLI = startTLI;
3850 for (probeTLI = startTLI + 1;; probeTLI++)
3852 if (existsTimeLineHistory(probeTLI))
3854 newestTLI = probeTLI; /* probeTLI exists */
3856 else
3858 /* doesn't exist, assume we're done */
3859 break;
3863 return newestTLI;
3867 * Create a new timeline history file.
3869 * newTLI: ID of the new timeline
3870 * parentTLI: ID of its immediate parent
3871 * endTLI et al: ID of the last used WAL file, for annotation purposes
3873 * Currently this is only used during recovery, and so there are no locking
3874 * considerations. But we should be just as tense as XLogFileInit to avoid
3875 * emplacing a bogus file.
3877 static void
3878 writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
3879 TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
3881 char path[MAXPGPATH];
3882 char tmppath[MAXPGPATH];
3883 char histfname[MAXFNAMELEN];
3884 char xlogfname[MAXFNAMELEN];
3885 char buffer[BLCKSZ];
3886 int srcfd;
3887 int fd;
3888 int nbytes;
3890 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
3893 * Write into a temp file name.
3895 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
3897 unlink(tmppath);
3899 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
3900 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL,
3901 S_IRUSR | S_IWUSR);
3902 if (fd < 0)
3903 ereport(ERROR,
3904 (errcode_for_file_access(),
3905 errmsg("could not create file \"%s\": %m", tmppath)));
3908 * If a history file exists for the parent, copy it verbatim
3910 if (InArchiveRecovery)
3912 TLHistoryFileName(histfname, parentTLI);
3913 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0);
3915 else
3916 TLHistoryFilePath(path, parentTLI);
3918 srcfd = BasicOpenFile(path, O_RDONLY, 0);
3919 if (srcfd < 0)
3921 if (errno != ENOENT)
3922 ereport(ERROR,
3923 (errcode_for_file_access(),
3924 errmsg("could not open file \"%s\": %m", path)));
3925 /* Not there, so assume parent has no parents */
3927 else
3929 for (;;)
3931 errno = 0;
3932 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
3933 if (nbytes < 0 || errno != 0)
3934 ereport(ERROR,
3935 (errcode_for_file_access(),
3936 errmsg("could not read file \"%s\": %m", path)));
3937 if (nbytes == 0)
3938 break;
3939 errno = 0;
3940 if ((int) write(fd, buffer, nbytes) != nbytes)
3942 int save_errno = errno;
3945 * If we fail to make the file, delete it to release disk
3946 * space
3948 unlink(tmppath);
3951 * if write didn't set errno, assume problem is no disk space
3953 errno = save_errno ? save_errno : ENOSPC;
3955 ereport(ERROR,
3956 (errcode_for_file_access(),
3957 errmsg("could not write to file \"%s\": %m", tmppath)));
3960 close(srcfd);
3964 * Append one line with the details of this timeline split.
3966 * If we did have a parent file, insert an extra newline just in case the
3967 * parent file failed to end with one.
3969 XLogFileName(xlogfname, endTLI, endLogId, endLogSeg);
3971 snprintf(buffer, sizeof(buffer),
3972 "%s%u\t%s\t%s transaction %u at %s\n",
3973 (srcfd < 0) ? "" : "\n",
3974 parentTLI,
3975 xlogfname,
3976 recoveryStopAfter ? "after" : "before",
3977 recoveryStopXid,
3978 timestamptz_to_str(recoveryStopTime));
3980 nbytes = strlen(buffer);
3981 errno = 0;
3982 if ((int) write(fd, buffer, nbytes) != nbytes)
3984 int save_errno = errno;
3987 * If we fail to make the file, delete it to release disk space
3989 unlink(tmppath);
3990 /* if write didn't set errno, assume problem is no disk space */
3991 errno = save_errno ? save_errno : ENOSPC;
3993 ereport(ERROR,
3994 (errcode_for_file_access(),
3995 errmsg("could not write to file \"%s\": %m", tmppath)));
3998 if (pg_fsync(fd) != 0)
3999 ereport(ERROR,
4000 (errcode_for_file_access(),
4001 errmsg("could not fsync file \"%s\": %m", tmppath)));
4003 if (close(fd))
4004 ereport(ERROR,
4005 (errcode_for_file_access(),
4006 errmsg("could not close file \"%s\": %m", tmppath)));
4010 * Now move the completed history file into place with its final name.
4012 TLHistoryFilePath(path, newTLI);
4015 * Prefer link() to rename() here just to be really sure that we don't
4016 * overwrite an existing logfile. However, there shouldn't be one, so
4017 * rename() is an acceptable substitute except for the truly paranoid.
4019 #if HAVE_WORKING_LINK
4020 if (link(tmppath, path) < 0)
4021 ereport(ERROR,
4022 (errcode_for_file_access(),
4023 errmsg("could not link file \"%s\" to \"%s\": %m",
4024 tmppath, path)));
4025 unlink(tmppath);
4026 #else
4027 if (rename(tmppath, path) < 0)
4028 ereport(ERROR,
4029 (errcode_for_file_access(),
4030 errmsg("could not rename file \"%s\" to \"%s\": %m",
4031 tmppath, path)));
4032 #endif
4034 /* The history file can be archived immediately. */
4035 TLHistoryFileName(histfname, newTLI);
4036 XLogArchiveNotify(histfname);
4040 * I/O routines for pg_control
4042 * *ControlFile is a buffer in shared memory that holds an image of the
4043 * contents of pg_control. WriteControlFile() initializes pg_control
4044 * given a preloaded buffer, ReadControlFile() loads the buffer from
4045 * the pg_control file (during postmaster or standalone-backend startup),
4046 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
4048 * For simplicity, WriteControlFile() initializes the fields of pg_control
4049 * that are related to checking backend/database compatibility, and
4050 * ReadControlFile() verifies they are correct. We could split out the
4051 * I/O and compatibility-check functions, but there seems no need currently.
4053 static void
4054 WriteControlFile(void)
4056 int fd;
4057 char buffer[PG_CONTROL_SIZE]; /* need not be aligned */
4060 * Initialize version and compatibility-check fields
4062 ControlFile->pg_control_version = PG_CONTROL_VERSION;
4063 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
4065 ControlFile->maxAlign = MAXIMUM_ALIGNOF;
4066 ControlFile->floatFormat = FLOATFORMAT_VALUE;
4068 ControlFile->blcksz = BLCKSZ;
4069 ControlFile->relseg_size = RELSEG_SIZE;
4070 ControlFile->xlog_blcksz = XLOG_BLCKSZ;
4071 ControlFile->xlog_seg_size = XLOG_SEG_SIZE;
4073 ControlFile->nameDataLen = NAMEDATALEN;
4074 ControlFile->indexMaxKeys = INDEX_MAX_KEYS;
4076 ControlFile->toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
4078 #ifdef HAVE_INT64_TIMESTAMP
4079 ControlFile->enableIntTimes = true;
4080 #else
4081 ControlFile->enableIntTimes = false;
4082 #endif
4083 ControlFile->float4ByVal = FLOAT4PASSBYVAL;
4084 ControlFile->float8ByVal = FLOAT8PASSBYVAL;
4086 /* Contents are protected with a CRC */
4087 INIT_CRC32(ControlFile->crc);
4088 COMP_CRC32(ControlFile->crc,
4089 (char *) ControlFile,
4090 offsetof(ControlFileData, crc));
4091 FIN_CRC32(ControlFile->crc);
4094 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
4095 * excess over sizeof(ControlFileData). This reduces the odds of
4096 * premature-EOF errors when reading pg_control. We'll still fail when we
4097 * check the contents of the file, but hopefully with a more specific
4098 * error than "couldn't read pg_control".
4100 if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
4101 elog(PANIC, "sizeof(ControlFileData) is larger than PG_CONTROL_SIZE; fix either one");
4103 memset(buffer, 0, PG_CONTROL_SIZE);
4104 memcpy(buffer, ControlFile, sizeof(ControlFileData));
4106 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4107 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
4108 S_IRUSR | S_IWUSR);
4109 if (fd < 0)
4110 ereport(PANIC,
4111 (errcode_for_file_access(),
4112 errmsg("could not create control file \"%s\": %m",
4113 XLOG_CONTROL_FILE)));
4115 errno = 0;
4116 if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
4118 /* if write didn't set errno, assume problem is no disk space */
4119 if (errno == 0)
4120 errno = ENOSPC;
4121 ereport(PANIC,
4122 (errcode_for_file_access(),
4123 errmsg("could not write to control file: %m")));
4126 if (pg_fsync(fd) != 0)
4127 ereport(PANIC,
4128 (errcode_for_file_access(),
4129 errmsg("could not fsync control file: %m")));
4131 if (close(fd))
4132 ereport(PANIC,
4133 (errcode_for_file_access(),
4134 errmsg("could not close control file: %m")));
4137 static void
4138 ReadControlFile(void)
4140 pg_crc32 crc;
4141 int fd;
4144 * Read data...
4146 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4147 O_RDWR | PG_BINARY,
4148 S_IRUSR | S_IWUSR);
4149 if (fd < 0)
4150 ereport(PANIC,
4151 (errcode_for_file_access(),
4152 errmsg("could not open control file \"%s\": %m",
4153 XLOG_CONTROL_FILE)));
4155 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4156 ereport(PANIC,
4157 (errcode_for_file_access(),
4158 errmsg("could not read from control file: %m")));
4160 close(fd);
4163 * Check for expected pg_control format version. If this is wrong, the
4164 * CRC check will likely fail because we'll be checking the wrong number
4165 * of bytes. Complaining about wrong version will probably be more
4166 * enlightening than complaining about wrong CRC.
4169 if (ControlFile->pg_control_version != PG_CONTROL_VERSION && ControlFile->pg_control_version % 65536 == 0 && ControlFile->pg_control_version / 65536 != 0)
4170 ereport(FATAL,
4171 (errmsg("database files are incompatible with server"),
4172 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4173 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4174 ControlFile->pg_control_version, ControlFile->pg_control_version,
4175 PG_CONTROL_VERSION, PG_CONTROL_VERSION),
4176 errhint("This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4178 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
4179 ereport(FATAL,
4180 (errmsg("database files are incompatible with server"),
4181 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
4182 " but the server was compiled with PG_CONTROL_VERSION %d.",
4183 ControlFile->pg_control_version, PG_CONTROL_VERSION),
4184 errhint("It looks like you need to initdb.")));
4186 /* Now check the CRC. */
4187 INIT_CRC32(crc);
4188 COMP_CRC32(crc,
4189 (char *) ControlFile,
4190 offsetof(ControlFileData, crc));
4191 FIN_CRC32(crc);
4193 if (!EQ_CRC32(crc, ControlFile->crc))
4194 ereport(FATAL,
4195 (errmsg("incorrect checksum in control file")));
4198 * Do compatibility checking immediately. If the database isn't
4199 * compatible with the backend executable, we want to abort before we
4200 * can possibly do any damage.
4202 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
4203 ereport(FATAL,
4204 (errmsg("database files are incompatible with server"),
4205 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
4206 " but the server was compiled with CATALOG_VERSION_NO %d.",
4207 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
4208 errhint("It looks like you need to initdb.")));
4209 if (ControlFile->maxAlign != MAXIMUM_ALIGNOF)
4210 ereport(FATAL,
4211 (errmsg("database files are incompatible with server"),
4212 errdetail("The database cluster was initialized with MAXALIGN %d,"
4213 " but the server was compiled with MAXALIGN %d.",
4214 ControlFile->maxAlign, MAXIMUM_ALIGNOF),
4215 errhint("It looks like you need to initdb.")));
4216 if (ControlFile->floatFormat != FLOATFORMAT_VALUE)
4217 ereport(FATAL,
4218 (errmsg("database files are incompatible with server"),
4219 errdetail("The database cluster appears to use a different floating-point number format than the server executable."),
4220 errhint("It looks like you need to initdb.")));
4221 if (ControlFile->blcksz != BLCKSZ)
4222 ereport(FATAL,
4223 (errmsg("database files are incompatible with server"),
4224 errdetail("The database cluster was initialized with BLCKSZ %d,"
4225 " but the server was compiled with BLCKSZ %d.",
4226 ControlFile->blcksz, BLCKSZ),
4227 errhint("It looks like you need to recompile or initdb.")));
4228 if (ControlFile->relseg_size != RELSEG_SIZE)
4229 ereport(FATAL,
4230 (errmsg("database files are incompatible with server"),
4231 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
4232 " but the server was compiled with RELSEG_SIZE %d.",
4233 ControlFile->relseg_size, RELSEG_SIZE),
4234 errhint("It looks like you need to recompile or initdb.")));
4235 if (ControlFile->xlog_blcksz != XLOG_BLCKSZ)
4236 ereport(FATAL,
4237 (errmsg("database files are incompatible with server"),
4238 errdetail("The database cluster was initialized with XLOG_BLCKSZ %d,"
4239 " but the server was compiled with XLOG_BLCKSZ %d.",
4240 ControlFile->xlog_blcksz, XLOG_BLCKSZ),
4241 errhint("It looks like you need to recompile or initdb.")));
4242 if (ControlFile->xlog_seg_size != XLOG_SEG_SIZE)
4243 ereport(FATAL,
4244 (errmsg("database files are incompatible with server"),
4245 errdetail("The database cluster was initialized with XLOG_SEG_SIZE %d,"
4246 " but the server was compiled with XLOG_SEG_SIZE %d.",
4247 ControlFile->xlog_seg_size, XLOG_SEG_SIZE),
4248 errhint("It looks like you need to recompile or initdb.")));
4249 if (ControlFile->nameDataLen != NAMEDATALEN)
4250 ereport(FATAL,
4251 (errmsg("database files are incompatible with server"),
4252 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
4253 " but the server was compiled with NAMEDATALEN %d.",
4254 ControlFile->nameDataLen, NAMEDATALEN),
4255 errhint("It looks like you need to recompile or initdb.")));
4256 if (ControlFile->indexMaxKeys != INDEX_MAX_KEYS)
4257 ereport(FATAL,
4258 (errmsg("database files are incompatible with server"),
4259 errdetail("The database cluster was initialized with INDEX_MAX_KEYS %d,"
4260 " but the server was compiled with INDEX_MAX_KEYS %d.",
4261 ControlFile->indexMaxKeys, INDEX_MAX_KEYS),
4262 errhint("It looks like you need to recompile or initdb.")));
4263 if (ControlFile->toast_max_chunk_size != TOAST_MAX_CHUNK_SIZE)
4264 ereport(FATAL,
4265 (errmsg("database files are incompatible with server"),
4266 errdetail("The database cluster was initialized with TOAST_MAX_CHUNK_SIZE %d,"
4267 " but the server was compiled with TOAST_MAX_CHUNK_SIZE %d.",
4268 ControlFile->toast_max_chunk_size, (int) TOAST_MAX_CHUNK_SIZE),
4269 errhint("It looks like you need to recompile or initdb.")));
4271 #ifdef HAVE_INT64_TIMESTAMP
4272 if (ControlFile->enableIntTimes != true)
4273 ereport(FATAL,
4274 (errmsg("database files are incompatible with server"),
4275 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
4276 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
4277 errhint("It looks like you need to recompile or initdb.")));
4278 #else
4279 if (ControlFile->enableIntTimes != false)
4280 ereport(FATAL,
4281 (errmsg("database files are incompatible with server"),
4282 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
4283 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
4284 errhint("It looks like you need to recompile or initdb.")));
4285 #endif
4287 #ifdef USE_FLOAT4_BYVAL
4288 if (ControlFile->float4ByVal != true)
4289 ereport(FATAL,
4290 (errmsg("database files are incompatible with server"),
4291 errdetail("The database cluster was initialized without USE_FLOAT4_BYVAL"
4292 " but the server was compiled with USE_FLOAT4_BYVAL."),
4293 errhint("It looks like you need to recompile or initdb.")));
4294 #else
4295 if (ControlFile->float4ByVal != false)
4296 ereport(FATAL,
4297 (errmsg("database files are incompatible with server"),
4298 errdetail("The database cluster was initialized with USE_FLOAT4_BYVAL"
4299 " but the server was compiled without USE_FLOAT4_BYVAL."),
4300 errhint("It looks like you need to recompile or initdb.")));
4301 #endif
4303 #ifdef USE_FLOAT8_BYVAL
4304 if (ControlFile->float8ByVal != true)
4305 ereport(FATAL,
4306 (errmsg("database files are incompatible with server"),
4307 errdetail("The database cluster was initialized without USE_FLOAT8_BYVAL"
4308 " but the server was compiled with USE_FLOAT8_BYVAL."),
4309 errhint("It looks like you need to recompile or initdb.")));
4310 #else
4311 if (ControlFile->float8ByVal != false)
4312 ereport(FATAL,
4313 (errmsg("database files are incompatible with server"),
4314 errdetail("The database cluster was initialized with USE_FLOAT8_BYVAL"
4315 " but the server was compiled without USE_FLOAT8_BYVAL."),
4316 errhint("It looks like you need to recompile or initdb.")));
4317 #endif
4320 void
4321 UpdateControlFile(void)
4323 int fd;
4325 INIT_CRC32(ControlFile->crc);
4326 COMP_CRC32(ControlFile->crc,
4327 (char *) ControlFile,
4328 offsetof(ControlFileData, crc));
4329 FIN_CRC32(ControlFile->crc);
4331 fd = BasicOpenFile(XLOG_CONTROL_FILE,
4332 O_RDWR | PG_BINARY,
4333 S_IRUSR | S_IWUSR);
4334 if (fd < 0)
4335 ereport(PANIC,
4336 (errcode_for_file_access(),
4337 errmsg("could not open control file \"%s\": %m",
4338 XLOG_CONTROL_FILE)));
4340 errno = 0;
4341 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
4343 /* if write didn't set errno, assume problem is no disk space */
4344 if (errno == 0)
4345 errno = ENOSPC;
4346 ereport(PANIC,
4347 (errcode_for_file_access(),
4348 errmsg("could not write to control file: %m")));
4351 if (pg_fsync(fd) != 0)
4352 ereport(PANIC,
4353 (errcode_for_file_access(),
4354 errmsg("could not fsync control file: %m")));
4356 if (close(fd))
4357 ereport(PANIC,
4358 (errcode_for_file_access(),
4359 errmsg("could not close control file: %m")));
4363 * Initialization of shared memory for XLOG
4365 Size
4366 XLOGShmemSize(void)
4368 Size size;
4370 /* XLogCtl */
4371 size = sizeof(XLogCtlData);
4372 /* xlblocks array */
4373 size = add_size(size, mul_size(sizeof(XLogRecPtr), XLOGbuffers));
4374 /* extra alignment padding for XLOG I/O buffers */
4375 size = add_size(size, ALIGNOF_XLOG_BUFFER);
4376 /* and the buffers themselves */
4377 size = add_size(size, mul_size(XLOG_BLCKSZ, XLOGbuffers));
4380 * Note: we don't count ControlFileData, it comes out of the "slop factor"
4381 * added by CreateSharedMemoryAndSemaphores. This lets us use this
4382 * routine again below to compute the actual allocation size.
4385 return size;
4388 void
4389 XLOGShmemInit(void)
4391 bool foundCFile,
4392 foundXLog;
4393 char *allocptr;
4395 ControlFile = (ControlFileData *)
4396 ShmemInitStruct("Control File", sizeof(ControlFileData), &foundCFile);
4397 XLogCtl = (XLogCtlData *)
4398 ShmemInitStruct("XLOG Ctl", XLOGShmemSize(), &foundXLog);
4400 if (foundCFile || foundXLog)
4402 /* both should be present or neither */
4403 Assert(foundCFile && foundXLog);
4404 return;
4407 memset(XLogCtl, 0, sizeof(XLogCtlData));
4410 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be a
4411 * multiple of the alignment for same, so no extra alignment padding is
4412 * needed here.
4414 allocptr = ((char *) XLogCtl) + sizeof(XLogCtlData);
4415 XLogCtl->xlblocks = (XLogRecPtr *) allocptr;
4416 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
4417 allocptr += sizeof(XLogRecPtr) * XLOGbuffers;
4420 * Align the start of the page buffers to an ALIGNOF_XLOG_BUFFER boundary.
4422 allocptr = (char *) TYPEALIGN(ALIGNOF_XLOG_BUFFER, allocptr);
4423 XLogCtl->pages = allocptr;
4424 memset(XLogCtl->pages, 0, (Size) XLOG_BLCKSZ * XLOGbuffers);
4427 * Do basic initialization of XLogCtl shared data. (StartupXLOG will fill
4428 * in additional info.)
4430 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
4431 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
4432 SpinLockInit(&XLogCtl->info_lck);
4435 * If we are not in bootstrap mode, pg_control should already exist. Read
4436 * and validate it immediately (see comments in ReadControlFile() for the
4437 * reasons why).
4439 if (!IsBootstrapProcessingMode())
4440 ReadControlFile();
4444 * This func must be called ONCE on system install. It creates pg_control
4445 * and the initial XLOG segment.
4447 void
4448 BootStrapXLOG(void)
4450 CheckPoint checkPoint;
4451 char *buffer;
4452 XLogPageHeader page;
4453 XLogLongPageHeader longpage;
4454 XLogRecord *record;
4455 bool use_existent;
4456 uint64 sysidentifier;
4457 struct timeval tv;
4458 pg_crc32 crc;
4461 * Select a hopefully-unique system identifier code for this installation.
4462 * We use the result of gettimeofday(), including the fractional seconds
4463 * field, as being about as unique as we can easily get. (Think not to
4464 * use random(), since it hasn't been seeded and there's no portable way
4465 * to seed it other than the system clock value...) The upper half of the
4466 * uint64 value is just the tv_sec part, while the lower half is the XOR
4467 * of tv_sec and tv_usec. This is to ensure that we don't lose uniqueness
4468 * unnecessarily if "uint64" is really only 32 bits wide. A person
4469 * knowing this encoding can determine the initialization time of the
4470 * installation, which could perhaps be useful sometimes.
4472 gettimeofday(&tv, NULL);
4473 sysidentifier = ((uint64) tv.tv_sec) << 32;
4474 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
4476 /* First timeline ID is always 1 */
4477 ThisTimeLineID = 1;
4479 /* page buffer must be aligned suitably for O_DIRECT */
4480 buffer = (char *) palloc(XLOG_BLCKSZ + ALIGNOF_XLOG_BUFFER);
4481 page = (XLogPageHeader) TYPEALIGN(ALIGNOF_XLOG_BUFFER, buffer);
4482 memset(page, 0, XLOG_BLCKSZ);
4484 /* Set up information for the initial checkpoint record */
4485 checkPoint.redo.xlogid = 0;
4486 checkPoint.redo.xrecoff = SizeOfXLogLongPHD;
4487 checkPoint.ThisTimeLineID = ThisTimeLineID;
4488 checkPoint.nextXidEpoch = 0;
4489 checkPoint.nextXid = FirstNormalTransactionId;
4490 checkPoint.nextOid = FirstBootstrapObjectId;
4491 checkPoint.nextMulti = FirstMultiXactId;
4492 checkPoint.nextMultiOffset = 0;
4493 checkPoint.time = (pg_time_t) time(NULL);
4495 ShmemVariableCache->nextXid = checkPoint.nextXid;
4496 ShmemVariableCache->nextOid = checkPoint.nextOid;
4497 ShmemVariableCache->oidCount = 0;
4498 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
4500 /* Set up the XLOG page header */
4501 page->xlp_magic = XLOG_PAGE_MAGIC;
4502 page->xlp_info = XLP_LONG_HEADER;
4503 page->xlp_tli = ThisTimeLineID;
4504 page->xlp_pageaddr.xlogid = 0;
4505 page->xlp_pageaddr.xrecoff = 0;
4506 longpage = (XLogLongPageHeader) page;
4507 longpage->xlp_sysid = sysidentifier;
4508 longpage->xlp_seg_size = XLogSegSize;
4509 longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
4511 /* Insert the initial checkpoint record */
4512 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
4513 record->xl_prev.xlogid = 0;
4514 record->xl_prev.xrecoff = 0;
4515 record->xl_xid = InvalidTransactionId;
4516 record->xl_tot_len = SizeOfXLogRecord + sizeof(checkPoint);
4517 record->xl_len = sizeof(checkPoint);
4518 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
4519 record->xl_rmid = RM_XLOG_ID;
4520 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
4522 INIT_CRC32(crc);
4523 COMP_CRC32(crc, &checkPoint, sizeof(checkPoint));
4524 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
4525 SizeOfXLogRecord - sizeof(pg_crc32));
4526 FIN_CRC32(crc);
4527 record->xl_crc = crc;
4529 /* Create first XLOG segment file */
4530 use_existent = false;
4531 openLogFile = XLogFileInit(0, 0, &use_existent, false);
4533 /* Write the first page with the initial record */
4534 errno = 0;
4535 if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
4537 /* if write didn't set errno, assume problem is no disk space */
4538 if (errno == 0)
4539 errno = ENOSPC;
4540 ereport(PANIC,
4541 (errcode_for_file_access(),
4542 errmsg("could not write bootstrap transaction log file: %m")));
4545 if (pg_fsync(openLogFile) != 0)
4546 ereport(PANIC,
4547 (errcode_for_file_access(),
4548 errmsg("could not fsync bootstrap transaction log file: %m")));
4550 if (close(openLogFile))
4551 ereport(PANIC,
4552 (errcode_for_file_access(),
4553 errmsg("could not close bootstrap transaction log file: %m")));
4555 openLogFile = -1;
4557 /* Now create pg_control */
4559 memset(ControlFile, 0, sizeof(ControlFileData));
4560 /* Initialize pg_control status fields */
4561 ControlFile->system_identifier = sysidentifier;
4562 ControlFile->state = DB_SHUTDOWNED;
4563 ControlFile->time = checkPoint.time;
4564 ControlFile->checkPoint = checkPoint.redo;
4565 ControlFile->checkPointCopy = checkPoint;
4566 /* some additional ControlFile fields are set in WriteControlFile() */
4568 WriteControlFile();
4570 /* Bootstrap the commit log, too */
4571 BootStrapCLOG();
4572 BootStrapSUBTRANS();
4573 BootStrapMultiXact();
4575 pfree(buffer);
4578 static char *
4579 str_time(pg_time_t tnow)
4581 static char buf[128];
4583 pg_strftime(buf, sizeof(buf),
4584 "%Y-%m-%d %H:%M:%S %Z",
4585 pg_localtime(&tnow, log_timezone));
4587 return buf;
4591 * See if there is a recovery command file (recovery.conf), and if so
4592 * read in parameters for archive recovery.
4594 * XXX longer term intention is to expand this to
4595 * cater for additional parameters and controls
4596 * possibly use a flex lexer similar to the GUC one
4598 static void
4599 readRecoveryCommandFile(void)
4601 FILE *fd;
4602 char cmdline[MAXPGPATH];
4603 TimeLineID rtli = 0;
4604 bool rtliGiven = false;
4605 bool syntaxError = false;
4607 fd = AllocateFile(RECOVERY_COMMAND_FILE, "r");
4608 if (fd == NULL)
4610 if (errno == ENOENT)
4611 return; /* not there, so no archive recovery */
4612 ereport(FATAL,
4613 (errcode_for_file_access(),
4614 errmsg("could not open recovery command file \"%s\": %m",
4615 RECOVERY_COMMAND_FILE)));
4618 ereport(LOG,
4619 (errmsg("starting archive recovery")));
4622 * Parse the file...
4624 while (fgets(cmdline, sizeof(cmdline), fd) != NULL)
4626 /* skip leading whitespace and check for # comment */
4627 char *ptr;
4628 char *tok1;
4629 char *tok2;
4631 for (ptr = cmdline; *ptr; ptr++)
4633 if (!isspace((unsigned char) *ptr))
4634 break;
4636 if (*ptr == '\0' || *ptr == '#')
4637 continue;
4639 /* identify the quoted parameter value */
4640 tok1 = strtok(ptr, "'");
4641 if (!tok1)
4643 syntaxError = true;
4644 break;
4646 tok2 = strtok(NULL, "'");
4647 if (!tok2)
4649 syntaxError = true;
4650 break;
4652 /* reparse to get just the parameter name */
4653 tok1 = strtok(ptr, " \t=");
4654 if (!tok1)
4656 syntaxError = true;
4657 break;
4660 if (strcmp(tok1, "restore_command") == 0)
4662 recoveryRestoreCommand = pstrdup(tok2);
4663 ereport(LOG,
4664 (errmsg("restore_command = '%s'",
4665 recoveryRestoreCommand)));
4667 else if (strcmp(tok1, "recovery_target_timeline") == 0)
4669 rtliGiven = true;
4670 if (strcmp(tok2, "latest") == 0)
4671 rtli = 0;
4672 else
4674 errno = 0;
4675 rtli = (TimeLineID) strtoul(tok2, NULL, 0);
4676 if (errno == EINVAL || errno == ERANGE)
4677 ereport(FATAL,
4678 (errmsg("recovery_target_timeline is not a valid number: \"%s\"",
4679 tok2)));
4681 if (rtli)
4682 ereport(LOG,
4683 (errmsg("recovery_target_timeline = %u", rtli)));
4684 else
4685 ereport(LOG,
4686 (errmsg("recovery_target_timeline = latest")));
4688 else if (strcmp(tok1, "recovery_target_xid") == 0)
4690 errno = 0;
4691 recoveryTargetXid = (TransactionId) strtoul(tok2, NULL, 0);
4692 if (errno == EINVAL || errno == ERANGE)
4693 ereport(FATAL,
4694 (errmsg("recovery_target_xid is not a valid number: \"%s\"",
4695 tok2)));
4696 ereport(LOG,
4697 (errmsg("recovery_target_xid = %u",
4698 recoveryTargetXid)));
4699 recoveryTarget = true;
4700 recoveryTargetExact = true;
4702 else if (strcmp(tok1, "recovery_target_time") == 0)
4705 * if recovery_target_xid specified, then this overrides
4706 * recovery_target_time
4708 if (recoveryTargetExact)
4709 continue;
4710 recoveryTarget = true;
4711 recoveryTargetExact = false;
4714 * Convert the time string given by the user to TimestampTz form.
4716 recoveryTargetTime =
4717 DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
4718 CStringGetDatum(tok2),
4719 ObjectIdGetDatum(InvalidOid),
4720 Int32GetDatum(-1)));
4721 ereport(LOG,
4722 (errmsg("recovery_target_time = '%s'",
4723 timestamptz_to_str(recoveryTargetTime))));
4725 else if (strcmp(tok1, "recovery_target_inclusive") == 0)
4728 * does nothing if a recovery_target is not also set
4730 if (!parse_bool(tok2, &recoveryTargetInclusive))
4731 ereport(ERROR,
4732 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4733 errmsg("parameter \"recovery_target_inclusive\" requires a Boolean value")));
4734 ereport(LOG,
4735 (errmsg("recovery_target_inclusive = %s", tok2)));
4737 else
4738 ereport(FATAL,
4739 (errmsg("unrecognized recovery parameter \"%s\"",
4740 tok1)));
4743 FreeFile(fd);
4745 if (syntaxError)
4746 ereport(FATAL,
4747 (errmsg("syntax error in recovery command file: %s",
4748 cmdline),
4749 errhint("Lines should have the format parameter = 'value'.")));
4751 /* Check that required parameters were supplied */
4752 if (recoveryRestoreCommand == NULL)
4753 ereport(FATAL,
4754 (errmsg("recovery command file \"%s\" did not specify restore_command",
4755 RECOVERY_COMMAND_FILE)));
4757 /* Enable fetching from archive recovery area */
4758 InArchiveRecovery = true;
4761 * If user specified recovery_target_timeline, validate it or compute the
4762 * "latest" value. We can't do this until after we've gotten the restore
4763 * command and set InArchiveRecovery, because we need to fetch timeline
4764 * history files from the archive.
4766 if (rtliGiven)
4768 if (rtli)
4770 /* Timeline 1 does not have a history file, all else should */
4771 if (rtli != 1 && !existsTimeLineHistory(rtli))
4772 ereport(FATAL,
4773 (errmsg("recovery target timeline %u does not exist",
4774 rtli)));
4775 recoveryTargetTLI = rtli;
4777 else
4779 /* We start the "latest" search from pg_control's timeline */
4780 recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
4786 * Exit archive-recovery state
4788 static void
4789 exitArchiveRecovery(TimeLineID endTLI, uint32 endLogId, uint32 endLogSeg)
4791 char recoveryPath[MAXPGPATH];
4792 char xlogpath[MAXPGPATH];
4795 * We are no longer in archive recovery state.
4797 InArchiveRecovery = false;
4800 * We should have the ending log segment currently open. Verify, and then
4801 * close it (to avoid problems on Windows with trying to rename or delete
4802 * an open file).
4804 Assert(readFile >= 0);
4805 Assert(readId == endLogId);
4806 Assert(readSeg == endLogSeg);
4808 close(readFile);
4809 readFile = -1;
4812 * If the segment was fetched from archival storage, we want to replace
4813 * the existing xlog segment (if any) with the archival version. This is
4814 * because whatever is in XLOGDIR is very possibly older than what we have
4815 * from the archives, since it could have come from restoring a PGDATA
4816 * backup. In any case, the archival version certainly is more
4817 * descriptive of what our current database state is, because that is what
4818 * we replayed from.
4820 * Note that if we are establishing a new timeline, ThisTimeLineID is
4821 * already set to the new value, and so we will create a new file instead
4822 * of overwriting any existing file. (This is, in fact, always the case
4823 * at present.)
4825 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
4826 XLogFilePath(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4828 if (restoredFromArchive)
4830 ereport(DEBUG3,
4831 (errmsg_internal("moving last restored xlog to \"%s\"",
4832 xlogpath)));
4833 unlink(xlogpath); /* might or might not exist */
4834 if (rename(recoveryPath, xlogpath) != 0)
4835 ereport(FATAL,
4836 (errcode_for_file_access(),
4837 errmsg("could not rename file \"%s\" to \"%s\": %m",
4838 recoveryPath, xlogpath)));
4839 /* XXX might we need to fix permissions on the file? */
4841 else
4844 * If the latest segment is not archival, but there's still a
4845 * RECOVERYXLOG laying about, get rid of it.
4847 unlink(recoveryPath); /* ignore any error */
4850 * If we are establishing a new timeline, we have to copy data from
4851 * the last WAL segment of the old timeline to create a starting WAL
4852 * segment for the new timeline.
4854 * Notify the archiver that the last WAL segment of the old timeline
4855 * is ready to copy to archival storage. Otherwise, it is not archived
4856 * for a while.
4858 if (endTLI != ThisTimeLineID)
4860 XLogFileCopy(endLogId, endLogSeg,
4861 endTLI, endLogId, endLogSeg);
4863 if (XLogArchivingActive())
4865 XLogFileName(xlogpath, endTLI, endLogId, endLogSeg);
4866 XLogArchiveNotify(xlogpath);
4872 * Let's just make real sure there are not .ready or .done flags posted
4873 * for the new segment.
4875 XLogFileName(xlogpath, ThisTimeLineID, endLogId, endLogSeg);
4876 XLogArchiveCleanup(xlogpath);
4878 /* Get rid of any remaining recovered timeline-history file, too */
4879 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
4880 unlink(recoveryPath); /* ignore any error */
4883 * Rename the config file out of the way, so that we don't accidentally
4884 * re-enter archive recovery mode in a subsequent crash.
4886 unlink(RECOVERY_COMMAND_DONE);
4887 if (rename(RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE) != 0)
4888 ereport(FATAL,
4889 (errcode_for_file_access(),
4890 errmsg("could not rename file \"%s\" to \"%s\": %m",
4891 RECOVERY_COMMAND_FILE, RECOVERY_COMMAND_DONE)));
4893 ereport(LOG,
4894 (errmsg("archive recovery complete")));
4898 * For point-in-time recovery, this function decides whether we want to
4899 * stop applying the XLOG at or after the current record.
4901 * Returns TRUE if we are stopping, FALSE otherwise. On TRUE return,
4902 * *includeThis is set TRUE if we should apply this record before stopping.
4904 * We also track the timestamp of the latest applied COMMIT/ABORT record
4905 * in recoveryLastXTime, for logging purposes.
4906 * Also, some information is saved in recoveryStopXid et al for use in
4907 * annotating the new timeline's history file.
4909 static bool
4910 recoveryStopsHere(XLogRecord *record, bool *includeThis)
4912 bool stopsHere;
4913 uint8 record_info;
4914 TimestampTz recordXtime;
4916 /* We only consider stopping at COMMIT or ABORT records */
4917 if (record->xl_rmid != RM_XACT_ID)
4918 return false;
4919 record_info = record->xl_info & ~XLR_INFO_MASK;
4920 if (record_info == XLOG_XACT_COMMIT)
4922 xl_xact_commit *recordXactCommitData;
4924 recordXactCommitData = (xl_xact_commit *) XLogRecGetData(record);
4925 recordXtime = recordXactCommitData->xact_time;
4927 else if (record_info == XLOG_XACT_ABORT)
4929 xl_xact_abort *recordXactAbortData;
4931 recordXactAbortData = (xl_xact_abort *) XLogRecGetData(record);
4932 recordXtime = recordXactAbortData->xact_time;
4934 else
4935 return false;
4937 /* Do we have a PITR target at all? */
4938 if (!recoveryTarget)
4940 recoveryLastXTime = recordXtime;
4941 return false;
4944 if (recoveryTargetExact)
4947 * there can be only one transaction end record with this exact
4948 * transactionid
4950 * when testing for an xid, we MUST test for equality only, since
4951 * transactions are numbered in the order they start, not the order
4952 * they complete. A higher numbered xid will complete before you about
4953 * 50% of the time...
4955 stopsHere = (record->xl_xid == recoveryTargetXid);
4956 if (stopsHere)
4957 *includeThis = recoveryTargetInclusive;
4959 else
4962 * there can be many transactions that share the same commit time, so
4963 * we stop after the last one, if we are inclusive, or stop at the
4964 * first one if we are exclusive
4966 if (recoveryTargetInclusive)
4967 stopsHere = (recordXtime > recoveryTargetTime);
4968 else
4969 stopsHere = (recordXtime >= recoveryTargetTime);
4970 if (stopsHere)
4971 *includeThis = false;
4974 if (stopsHere)
4976 recoveryStopXid = record->xl_xid;
4977 recoveryStopTime = recordXtime;
4978 recoveryStopAfter = *includeThis;
4980 if (record_info == XLOG_XACT_COMMIT)
4982 if (recoveryStopAfter)
4983 ereport(LOG,
4984 (errmsg("recovery stopping after commit of transaction %u, time %s",
4985 recoveryStopXid,
4986 timestamptz_to_str(recoveryStopTime))));
4987 else
4988 ereport(LOG,
4989 (errmsg("recovery stopping before commit of transaction %u, time %s",
4990 recoveryStopXid,
4991 timestamptz_to_str(recoveryStopTime))));
4993 else
4995 if (recoveryStopAfter)
4996 ereport(LOG,
4997 (errmsg("recovery stopping after abort of transaction %u, time %s",
4998 recoveryStopXid,
4999 timestamptz_to_str(recoveryStopTime))));
5000 else
5001 ereport(LOG,
5002 (errmsg("recovery stopping before abort of transaction %u, time %s",
5003 recoveryStopXid,
5004 timestamptz_to_str(recoveryStopTime))));
5007 if (recoveryStopAfter)
5008 recoveryLastXTime = recordXtime;
5010 else
5011 recoveryLastXTime = recordXtime;
5013 return stopsHere;
5017 * This must be called ONCE during postmaster or standalone-backend startup
5019 void
5020 StartupXLOG(void)
5022 XLogCtlInsert *Insert;
5023 CheckPoint checkPoint;
5024 bool wasShutdown;
5025 bool reachedStopPoint = false;
5026 bool haveBackupLabel = false;
5027 XLogRecPtr RecPtr,
5028 LastRec,
5029 checkPointLoc,
5030 backupStopLoc,
5031 EndOfLog;
5032 uint32 endLogId;
5033 uint32 endLogSeg;
5034 XLogRecord *record;
5035 uint32 freespace;
5036 TransactionId oldestActiveXID;
5038 XLogCtl->SharedRecoveryInProgress = true;
5041 * Read control file and check XLOG status looks valid.
5043 * Note: in most control paths, *ControlFile is already valid and we need
5044 * not do ReadControlFile() here, but might as well do it to be sure.
5046 ReadControlFile();
5048 if (ControlFile->state < DB_SHUTDOWNED ||
5049 ControlFile->state > DB_IN_PRODUCTION ||
5050 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
5051 ereport(FATAL,
5052 (errmsg("control file contains invalid data")));
5054 if (ControlFile->state == DB_SHUTDOWNED)
5055 ereport(LOG,
5056 (errmsg("database system was shut down at %s",
5057 str_time(ControlFile->time))));
5058 else if (ControlFile->state == DB_SHUTDOWNING)
5059 ereport(LOG,
5060 (errmsg("database system shutdown was interrupted; last known up at %s",
5061 str_time(ControlFile->time))));
5062 else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
5063 ereport(LOG,
5064 (errmsg("database system was interrupted while in recovery at %s",
5065 str_time(ControlFile->time)),
5066 errhint("This probably means that some data is corrupted and"
5067 " you will have to use the last backup for recovery.")));
5068 else if (ControlFile->state == DB_IN_ARCHIVE_RECOVERY)
5069 ereport(LOG,
5070 (errmsg("database system was interrupted while in recovery at log time %s",
5071 str_time(ControlFile->checkPointCopy.time)),
5072 errhint("If this has occurred more than once some data might be corrupted"
5073 " and you might need to choose an earlier recovery target.")));
5074 else if (ControlFile->state == DB_IN_PRODUCTION)
5075 ereport(LOG,
5076 (errmsg("database system was interrupted; last known up at %s",
5077 str_time(ControlFile->time))));
5079 /* This is just to allow attaching to startup process with a debugger */
5080 #ifdef XLOG_REPLAY_DELAY
5081 if (ControlFile->state != DB_SHUTDOWNED)
5082 pg_usleep(60000000L);
5083 #endif
5086 * Verify that pg_xlog and pg_xlog/archive_status exist. In cases where
5087 * someone has performed a copy for PITR, these directories may have
5088 * been excluded and need to be re-created.
5090 ValidateXLOGDirectoryStructure();
5093 * Initialize on the assumption we want to recover to the same timeline
5094 * that's active according to pg_control.
5096 recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
5099 * Check for recovery control file, and if so set up state for offline
5100 * recovery
5102 readRecoveryCommandFile();
5104 /* Now we can determine the list of expected TLIs */
5105 expectedTLIs = readTimeLineHistory(recoveryTargetTLI);
5108 * If pg_control's timeline is not in expectedTLIs, then we cannot
5109 * proceed: the backup is not part of the history of the requested
5110 * timeline.
5112 if (!list_member_int(expectedTLIs,
5113 (int) ControlFile->checkPointCopy.ThisTimeLineID))
5114 ereport(FATAL,
5115 (errmsg("requested timeline %u is not a child of database system timeline %u",
5116 recoveryTargetTLI,
5117 ControlFile->checkPointCopy.ThisTimeLineID)));
5119 if (read_backup_label(&checkPointLoc, &backupStopLoc))
5122 * When a backup_label file is present, we want to roll forward from
5123 * the checkpoint it identifies, rather than using pg_control.
5125 record = ReadCheckpointRecord(checkPointLoc, 0);
5126 if (record != NULL)
5128 ereport(DEBUG1,
5129 (errmsg("checkpoint record is at %X/%X",
5130 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
5131 InRecovery = true; /* force recovery even if SHUTDOWNED */
5133 else
5135 ereport(PANIC,
5136 (errmsg("could not locate required checkpoint record"),
5137 errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
5139 /* set flag to delete it later */
5140 haveBackupLabel = true;
5142 else
5145 * Get the last valid checkpoint record. If the latest one according
5146 * to pg_control is broken, try the next-to-last one.
5148 checkPointLoc = ControlFile->checkPoint;
5149 record = ReadCheckpointRecord(checkPointLoc, 1);
5150 if (record != NULL)
5152 ereport(DEBUG1,
5153 (errmsg("checkpoint record is at %X/%X",
5154 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
5156 else
5158 checkPointLoc = ControlFile->prevCheckPoint;
5159 record = ReadCheckpointRecord(checkPointLoc, 2);
5160 if (record != NULL)
5162 ereport(LOG,
5163 (errmsg("using previous checkpoint record at %X/%X",
5164 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
5165 InRecovery = true; /* force recovery even if SHUTDOWNED */
5167 else
5168 ereport(PANIC,
5169 (errmsg("could not locate a valid checkpoint record")));
5173 LastRec = RecPtr = checkPointLoc;
5174 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
5175 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
5177 ereport(DEBUG1,
5178 (errmsg("redo record is at %X/%X; shutdown %s",
5179 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
5180 wasShutdown ? "TRUE" : "FALSE")));
5181 ereport(DEBUG1,
5182 (errmsg("next transaction ID: %u/%u; next OID: %u",
5183 checkPoint.nextXidEpoch, checkPoint.nextXid,
5184 checkPoint.nextOid)));
5185 ereport(DEBUG1,
5186 (errmsg("next MultiXactId: %u; next MultiXactOffset: %u",
5187 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
5188 if (!TransactionIdIsNormal(checkPoint.nextXid))
5189 ereport(PANIC,
5190 (errmsg("invalid next transaction ID")));
5192 ShmemVariableCache->nextXid = checkPoint.nextXid;
5193 ShmemVariableCache->nextOid = checkPoint.nextOid;
5194 ShmemVariableCache->oidCount = 0;
5195 MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5198 * We must replay WAL entries using the same TimeLineID they were created
5199 * under, so temporarily adopt the TLI indicated by the checkpoint (see
5200 * also xlog_redo()).
5202 ThisTimeLineID = checkPoint.ThisTimeLineID;
5204 RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
5206 if (XLByteLT(RecPtr, checkPoint.redo))
5207 ereport(PANIC,
5208 (errmsg("invalid redo in checkpoint record")));
5211 * Check whether we need to force recovery from WAL. If it appears to
5212 * have been a clean shutdown and we did not have a recovery.conf file,
5213 * then assume no recovery needed.
5215 if (XLByteLT(checkPoint.redo, RecPtr))
5217 if (wasShutdown)
5218 ereport(PANIC,
5219 (errmsg("invalid redo record in shutdown checkpoint")));
5220 InRecovery = true;
5222 else if (ControlFile->state != DB_SHUTDOWNED)
5223 InRecovery = true;
5224 else if (InArchiveRecovery)
5226 /* force recovery due to presence of recovery.conf */
5227 InRecovery = true;
5230 /* REDO */
5231 if (InRecovery)
5233 int rmid;
5236 * Update pg_control to show that we are recovering and to show the
5237 * selected checkpoint as the place we are starting from. We also mark
5238 * pg_control with any minimum recovery stop point obtained from a
5239 * backup history file.
5241 if (InArchiveRecovery)
5243 ereport(LOG,
5244 (errmsg("automatic recovery in progress")));
5245 ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
5247 else
5249 ereport(LOG,
5250 (errmsg("database system was not properly shut down; "
5251 "automatic recovery in progress")));
5252 ControlFile->state = DB_IN_CRASH_RECOVERY;
5254 ControlFile->prevCheckPoint = ControlFile->checkPoint;
5255 ControlFile->checkPoint = checkPointLoc;
5256 ControlFile->checkPointCopy = checkPoint;
5257 if (backupStopLoc.xlogid != 0 || backupStopLoc.xrecoff != 0)
5259 if (XLByteLT(ControlFile->minRecoveryPoint, backupStopLoc))
5260 ControlFile->minRecoveryPoint = backupStopLoc;
5262 ControlFile->time = (pg_time_t) time(NULL);
5263 /* No need to hold ControlFileLock yet, we aren't up far enough */
5264 UpdateControlFile();
5266 /* update our local copy of minRecoveryPoint */
5267 minRecoveryPoint = ControlFile->minRecoveryPoint;
5270 * Reset pgstat data, because it may be invalid after recovery.
5272 pgstat_reset_all();
5275 * If there was a backup label file, it's done its job and the info
5276 * has now been propagated into pg_control. We must get rid of the
5277 * label file so that if we crash during recovery, we'll pick up at
5278 * the latest recovery restartpoint instead of going all the way back
5279 * to the backup start point. It seems prudent though to just rename
5280 * the file out of the way rather than delete it completely.
5282 if (haveBackupLabel)
5284 unlink(BACKUP_LABEL_OLD);
5285 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) != 0)
5286 ereport(FATAL,
5287 (errcode_for_file_access(),
5288 errmsg("could not rename file \"%s\" to \"%s\": %m",
5289 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
5292 /* Initialize resource managers */
5293 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5295 if (RmgrTable[rmid].rm_startup != NULL)
5296 RmgrTable[rmid].rm_startup();
5300 * Find the first record that logically follows the checkpoint --- it
5301 * might physically precede it, though.
5303 if (XLByteLT(checkPoint.redo, RecPtr))
5305 /* back up to find the record */
5306 record = ReadRecord(&(checkPoint.redo), PANIC);
5308 else
5310 /* just have to read next record after CheckPoint */
5311 record = ReadRecord(NULL, LOG);
5314 if (record != NULL)
5316 bool recoveryContinue = true;
5317 bool recoveryApply = true;
5318 bool reachedMinRecoveryPoint = false;
5319 ErrorContextCallback errcontext;
5320 /* use volatile pointer to prevent code rearrangement */
5321 volatile XLogCtlData *xlogctl = XLogCtl;
5323 /* Update shared replayEndRecPtr */
5324 SpinLockAcquire(&xlogctl->info_lck);
5325 xlogctl->replayEndRecPtr = ReadRecPtr;
5326 SpinLockRelease(&xlogctl->info_lck);
5328 InRedo = true;
5330 if (minRecoveryPoint.xlogid == 0 && minRecoveryPoint.xrecoff == 0)
5331 ereport(LOG,
5332 (errmsg("redo starts at %X/%X",
5333 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5334 else
5335 ereport(LOG,
5336 (errmsg("redo starts at %X/%X, consistency will be reached at %X/%X",
5337 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
5338 minRecoveryPoint.xlogid, minRecoveryPoint.xrecoff)));
5341 * Let postmaster know we've started redo now, so that it can
5342 * launch bgwriter to perform restartpoints. We don't bother
5343 * during crash recovery as restartpoints can only be performed
5344 * during archive recovery. And we'd like to keep crash recovery
5345 * simple, to avoid introducing bugs that could you from
5346 * recovering after crash.
5348 * After this point, we can no longer assume that we're the only
5349 * process in addition to postmaster!
5351 if (InArchiveRecovery && IsUnderPostmaster)
5352 SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED);
5355 * main redo apply loop
5359 #ifdef WAL_DEBUG
5360 if (XLOG_DEBUG)
5362 StringInfoData buf;
5364 initStringInfo(&buf);
5365 appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
5366 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
5367 EndRecPtr.xlogid, EndRecPtr.xrecoff);
5368 xlog_outrec(&buf, record);
5369 appendStringInfo(&buf, " - ");
5370 RmgrTable[record->xl_rmid].rm_desc(&buf,
5371 record->xl_info,
5372 XLogRecGetData(record));
5373 elog(LOG, "%s", buf.data);
5374 pfree(buf.data);
5376 #endif
5379 * Check if we were requested to re-read config file.
5381 if (got_SIGHUP)
5383 got_SIGHUP = false;
5384 ProcessConfigFile(PGC_SIGHUP);
5388 * Check if we were requested to exit without finishing
5389 * recovery.
5391 if (shutdown_requested)
5392 proc_exit(1);
5395 * Have we reached our safe starting point? If so, we can
5396 * tell postmaster that the database is consistent now.
5398 if (!reachedMinRecoveryPoint &&
5399 XLByteLE(minRecoveryPoint, EndRecPtr))
5401 reachedMinRecoveryPoint = true;
5402 if (InArchiveRecovery)
5404 ereport(LOG,
5405 (errmsg("consistent recovery state reached")));
5406 if (IsUnderPostmaster)
5407 SendPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT);
5412 * Have we reached our recovery target?
5414 if (recoveryStopsHere(record, &recoveryApply))
5416 reachedStopPoint = true; /* see below */
5417 recoveryContinue = false;
5418 if (!recoveryApply)
5419 break;
5422 /* Setup error traceback support for ereport() */
5423 errcontext.callback = rm_redo_error_callback;
5424 errcontext.arg = (void *) record;
5425 errcontext.previous = error_context_stack;
5426 error_context_stack = &errcontext;
5428 /* nextXid must be beyond record's xid */
5429 if (TransactionIdFollowsOrEquals(record->xl_xid,
5430 ShmemVariableCache->nextXid))
5432 ShmemVariableCache->nextXid = record->xl_xid;
5433 TransactionIdAdvance(ShmemVariableCache->nextXid);
5437 * Update shared replayEndRecPtr before replaying this
5438 * record, so that XLogFlush will update minRecoveryPoint
5439 * correctly.
5441 SpinLockAcquire(&xlogctl->info_lck);
5442 xlogctl->replayEndRecPtr = EndRecPtr;
5443 SpinLockRelease(&xlogctl->info_lck);
5445 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
5447 /* Pop the error context stack */
5448 error_context_stack = errcontext.previous;
5450 LastRec = ReadRecPtr;
5452 record = ReadRecord(NULL, LOG);
5453 } while (record != NULL && recoveryContinue);
5456 * end of main redo apply loop
5459 ereport(LOG,
5460 (errmsg("redo done at %X/%X",
5461 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
5462 if (recoveryLastXTime)
5463 ereport(LOG,
5464 (errmsg("last completed transaction was at log time %s",
5465 timestamptz_to_str(recoveryLastXTime))));
5466 InRedo = false;
5468 else
5470 /* there are no WAL records following the checkpoint */
5471 ereport(LOG,
5472 (errmsg("redo is not required")));
5477 * Re-fetch the last valid or last applied record, so we can identify the
5478 * exact endpoint of what we consider the valid portion of WAL.
5480 record = ReadRecord(&LastRec, PANIC);
5481 EndOfLog = EndRecPtr;
5482 XLByteToPrevSeg(EndOfLog, endLogId, endLogSeg);
5485 * Complain if we did not roll forward far enough to render the backup
5486 * dump consistent.
5488 if (InRecovery && XLByteLT(EndOfLog, minRecoveryPoint))
5490 if (reachedStopPoint) /* stopped because of stop request */
5491 ereport(FATAL,
5492 (errmsg("requested recovery stop point is before consistent recovery point")));
5493 else /* ran off end of WAL */
5494 ereport(FATAL,
5495 (errmsg("WAL ends before consistent recovery point")));
5499 * Consider whether we need to assign a new timeline ID.
5501 * If we are doing an archive recovery, we always assign a new ID. This
5502 * handles a couple of issues. If we stopped short of the end of WAL
5503 * during recovery, then we are clearly generating a new timeline and must
5504 * assign it a unique new ID. Even if we ran to the end, modifying the
5505 * current last segment is problematic because it may result in trying to
5506 * overwrite an already-archived copy of that segment, and we encourage
5507 * DBAs to make their archive_commands reject that. We can dodge the
5508 * problem by making the new active segment have a new timeline ID.
5510 * In a normal crash recovery, we can just extend the timeline we were in.
5512 if (InArchiveRecovery)
5514 ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
5515 ereport(LOG,
5516 (errmsg("selected new timeline ID: %u", ThisTimeLineID)));
5517 writeTimeLineHistory(ThisTimeLineID, recoveryTargetTLI,
5518 curFileTLI, endLogId, endLogSeg);
5521 /* Save the selected TimeLineID in shared memory, too */
5522 XLogCtl->ThisTimeLineID = ThisTimeLineID;
5525 * We are now done reading the old WAL. Turn off archive fetching if it
5526 * was active, and make a writable copy of the last WAL segment. (Note
5527 * that we also have a copy of the last block of the old WAL in readBuf;
5528 * we will use that below.)
5530 if (InArchiveRecovery)
5531 exitArchiveRecovery(curFileTLI, endLogId, endLogSeg);
5534 * Prepare to write WAL starting at EndOfLog position, and init xlog
5535 * buffer cache using the block containing the last record from the
5536 * previous incarnation.
5538 openLogId = endLogId;
5539 openLogSeg = endLogSeg;
5540 openLogFile = XLogFileOpen(openLogId, openLogSeg);
5541 openLogOff = 0;
5542 Insert = &XLogCtl->Insert;
5543 Insert->PrevRecord = LastRec;
5544 XLogCtl->xlblocks[0].xlogid = openLogId;
5545 XLogCtl->xlblocks[0].xrecoff =
5546 ((EndOfLog.xrecoff - 1) / XLOG_BLCKSZ + 1) * XLOG_BLCKSZ;
5549 * Tricky point here: readBuf contains the *last* block that the LastRec
5550 * record spans, not the one it starts in. The last block is indeed the
5551 * one we want to use.
5553 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - XLOG_BLCKSZ) % XLogSegSize);
5554 memcpy((char *) Insert->currpage, readBuf, XLOG_BLCKSZ);
5555 Insert->currpos = (char *) Insert->currpage +
5556 (EndOfLog.xrecoff + XLOG_BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
5558 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
5560 XLogCtl->Write.LogwrtResult = LogwrtResult;
5561 Insert->LogwrtResult = LogwrtResult;
5562 XLogCtl->LogwrtResult = LogwrtResult;
5564 XLogCtl->LogwrtRqst.Write = EndOfLog;
5565 XLogCtl->LogwrtRqst.Flush = EndOfLog;
5567 freespace = INSERT_FREESPACE(Insert);
5568 if (freespace > 0)
5570 /* Make sure rest of page is zero */
5571 MemSet(Insert->currpos, 0, freespace);
5572 XLogCtl->Write.curridx = 0;
5574 else
5577 * Whenever Write.LogwrtResult points to exactly the end of a page,
5578 * Write.curridx must point to the *next* page (see XLogWrite()).
5580 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
5581 * this is sufficient. The first actual attempt to insert a log
5582 * record will advance the insert state.
5584 XLogCtl->Write.curridx = NextBufIdx(0);
5587 /* Pre-scan prepared transactions to find out the range of XIDs present */
5588 oldestActiveXID = PrescanPreparedTransactions();
5591 * Allow writing WAL for us, so that we can create a checkpoint record.
5592 * But not yet for other backends!
5594 LocalRecoveryInProgress = false;
5596 if (InRecovery)
5598 int rmid;
5601 * Allow resource managers to do any required cleanup.
5603 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
5605 if (RmgrTable[rmid].rm_cleanup != NULL)
5606 RmgrTable[rmid].rm_cleanup();
5610 * Check to see if the XLOG sequence contained any unresolved
5611 * references to uninitialized pages.
5613 XLogCheckInvalidPages();
5616 * Perform a checkpoint to update all our recovery activity to disk.
5618 * Note that we write a shutdown checkpoint rather than an on-line
5619 * one. This is not particularly critical, but since we may be
5620 * assigning a new TLI, using a shutdown checkpoint allows us to have
5621 * the rule that TLI only changes in shutdown checkpoints, which
5622 * allows some extra error checking in xlog_redo.
5624 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5628 * Preallocate additional log files, if wanted.
5630 PreallocXlogFiles(EndOfLog);
5633 * Okay, we're officially UP.
5635 InRecovery = false;
5637 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5638 ControlFile->state = DB_IN_PRODUCTION;
5639 ControlFile->time = (pg_time_t) time(NULL);
5640 UpdateControlFile();
5641 LWLockRelease(ControlFileLock);
5643 /* start the archive_timeout timer running */
5644 XLogCtl->Write.lastSegSwitchTime = (pg_time_t) time(NULL);
5646 /* initialize shared-memory copy of latest checkpoint XID/epoch */
5647 XLogCtl->ckptXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
5648 XLogCtl->ckptXid = ControlFile->checkPointCopy.nextXid;
5650 /* also initialize latestCompletedXid, to nextXid - 1 */
5651 ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid;
5652 TransactionIdRetreat(ShmemVariableCache->latestCompletedXid);
5654 /* Start up the commit log and related stuff, too */
5655 StartupCLOG();
5656 StartupSUBTRANS(oldestActiveXID);
5657 StartupMultiXact();
5659 /* Reload shared-memory state for prepared transactions */
5660 RecoverPreparedTransactions();
5662 /* Shut down readFile facility, free space */
5663 if (readFile >= 0)
5665 close(readFile);
5666 readFile = -1;
5668 if (readBuf)
5670 free(readBuf);
5671 readBuf = NULL;
5673 if (readRecordBuf)
5675 free(readRecordBuf);
5676 readRecordBuf = NULL;
5677 readRecordBufSize = 0;
5681 * All done. Allow others to write WAL.
5683 XLogCtl->SharedRecoveryInProgress = false;
5687 * Is the system still in recovery?
5689 * As a side-effect, we initialize the local TimeLineID and RedoRecPtr
5690 * variables the first time we see that recovery is finished.
5692 bool
5693 RecoveryInProgress(void)
5696 * We check shared state each time only until we leave recovery mode.
5697 * We can't re-enter recovery, so we rely on the local state variable
5698 * after that.
5700 if (!LocalRecoveryInProgress)
5701 return false;
5702 else
5704 /* use volatile pointer to prevent code rearrangement */
5705 volatile XLogCtlData *xlogctl = XLogCtl;
5707 LocalRecoveryInProgress = xlogctl->SharedRecoveryInProgress;
5710 * Initialize TimeLineID and RedoRecPtr the first time we see that
5711 * recovery is finished.
5713 if (!LocalRecoveryInProgress)
5714 InitXLOGAccess();
5716 return LocalRecoveryInProgress;
5721 * Subroutine to try to fetch and validate a prior checkpoint record.
5723 * whichChkpt identifies the checkpoint (merely for reporting purposes).
5724 * 1 for "primary", 2 for "secondary", 0 for "other" (backup_label)
5726 static XLogRecord *
5727 ReadCheckpointRecord(XLogRecPtr RecPtr, int whichChkpt)
5729 XLogRecord *record;
5731 if (!XRecOffIsValid(RecPtr.xrecoff))
5733 switch (whichChkpt)
5735 case 1:
5736 ereport(LOG,
5737 (errmsg("invalid primary checkpoint link in control file")));
5738 break;
5739 case 2:
5740 ereport(LOG,
5741 (errmsg("invalid secondary checkpoint link in control file")));
5742 break;
5743 default:
5744 ereport(LOG,
5745 (errmsg("invalid checkpoint link in backup_label file")));
5746 break;
5748 return NULL;
5751 record = ReadRecord(&RecPtr, LOG);
5753 if (record == NULL)
5755 switch (whichChkpt)
5757 case 1:
5758 ereport(LOG,
5759 (errmsg("invalid primary checkpoint record")));
5760 break;
5761 case 2:
5762 ereport(LOG,
5763 (errmsg("invalid secondary checkpoint record")));
5764 break;
5765 default:
5766 ereport(LOG,
5767 (errmsg("invalid checkpoint record")));
5768 break;
5770 return NULL;
5772 if (record->xl_rmid != RM_XLOG_ID)
5774 switch (whichChkpt)
5776 case 1:
5777 ereport(LOG,
5778 (errmsg("invalid resource manager ID in primary checkpoint record")));
5779 break;
5780 case 2:
5781 ereport(LOG,
5782 (errmsg("invalid resource manager ID in secondary checkpoint record")));
5783 break;
5784 default:
5785 ereport(LOG,
5786 (errmsg("invalid resource manager ID in checkpoint record")));
5787 break;
5789 return NULL;
5791 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
5792 record->xl_info != XLOG_CHECKPOINT_ONLINE)
5794 switch (whichChkpt)
5796 case 1:
5797 ereport(LOG,
5798 (errmsg("invalid xl_info in primary checkpoint record")));
5799 break;
5800 case 2:
5801 ereport(LOG,
5802 (errmsg("invalid xl_info in secondary checkpoint record")));
5803 break;
5804 default:
5805 ereport(LOG,
5806 (errmsg("invalid xl_info in checkpoint record")));
5807 break;
5809 return NULL;
5811 if (record->xl_len != sizeof(CheckPoint) ||
5812 record->xl_tot_len != SizeOfXLogRecord + sizeof(CheckPoint))
5814 switch (whichChkpt)
5816 case 1:
5817 ereport(LOG,
5818 (errmsg("invalid length of primary checkpoint record")));
5819 break;
5820 case 2:
5821 ereport(LOG,
5822 (errmsg("invalid length of secondary checkpoint record")));
5823 break;
5824 default:
5825 ereport(LOG,
5826 (errmsg("invalid length of checkpoint record")));
5827 break;
5829 return NULL;
5831 return record;
5835 * This must be called during startup of a backend process, except that
5836 * it need not be called in a standalone backend (which does StartupXLOG
5837 * instead). We need to initialize the local copies of ThisTimeLineID and
5838 * RedoRecPtr.
5840 * Note: before Postgres 8.0, we went to some effort to keep the postmaster
5841 * process's copies of ThisTimeLineID and RedoRecPtr valid too. This was
5842 * unnecessary however, since the postmaster itself never touches XLOG anyway.
5844 void
5845 InitXLOGAccess(void)
5847 /* ThisTimeLineID doesn't change so we need no lock to copy it */
5848 ThisTimeLineID = XLogCtl->ThisTimeLineID;
5849 Assert(ThisTimeLineID != 0);
5851 /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
5852 (void) GetRedoRecPtr();
5856 * Once spawned, a backend may update its local RedoRecPtr from
5857 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
5858 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
5860 XLogRecPtr
5861 GetRedoRecPtr(void)
5863 /* use volatile pointer to prevent code rearrangement */
5864 volatile XLogCtlData *xlogctl = XLogCtl;
5866 SpinLockAcquire(&xlogctl->info_lck);
5867 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
5868 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
5869 SpinLockRelease(&xlogctl->info_lck);
5871 return RedoRecPtr;
5875 * GetInsertRecPtr -- Returns the current insert position.
5877 * NOTE: The value *actually* returned is the position of the last full
5878 * xlog page. It lags behind the real insert position by at most 1 page.
5879 * For that, we don't need to acquire WALInsertLock which can be quite
5880 * heavily contended, and an approximation is enough for the current
5881 * usage of this function.
5883 XLogRecPtr
5884 GetInsertRecPtr(void)
5886 /* use volatile pointer to prevent code rearrangement */
5887 volatile XLogCtlData *xlogctl = XLogCtl;
5888 XLogRecPtr recptr;
5890 SpinLockAcquire(&xlogctl->info_lck);
5891 recptr = xlogctl->LogwrtRqst.Write;
5892 SpinLockRelease(&xlogctl->info_lck);
5894 return recptr;
5898 * Get the time of the last xlog segment switch
5900 pg_time_t
5901 GetLastSegSwitchTime(void)
5903 pg_time_t result;
5905 /* Need WALWriteLock, but shared lock is sufficient */
5906 LWLockAcquire(WALWriteLock, LW_SHARED);
5907 result = XLogCtl->Write.lastSegSwitchTime;
5908 LWLockRelease(WALWriteLock);
5910 return result;
5914 * GetNextXidAndEpoch - get the current nextXid value and associated epoch
5916 * This is exported for use by code that would like to have 64-bit XIDs.
5917 * We don't really support such things, but all XIDs within the system
5918 * can be presumed "close to" the result, and thus the epoch associated
5919 * with them can be determined.
5921 void
5922 GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch)
5924 uint32 ckptXidEpoch;
5925 TransactionId ckptXid;
5926 TransactionId nextXid;
5928 /* Must read checkpoint info first, else have race condition */
5930 /* use volatile pointer to prevent code rearrangement */
5931 volatile XLogCtlData *xlogctl = XLogCtl;
5933 SpinLockAcquire(&xlogctl->info_lck);
5934 ckptXidEpoch = xlogctl->ckptXidEpoch;
5935 ckptXid = xlogctl->ckptXid;
5936 SpinLockRelease(&xlogctl->info_lck);
5939 /* Now fetch current nextXid */
5940 nextXid = ReadNewTransactionId();
5943 * nextXid is certainly logically later than ckptXid. So if it's
5944 * numerically less, it must have wrapped into the next epoch.
5946 if (nextXid < ckptXid)
5947 ckptXidEpoch++;
5949 *xid = nextXid;
5950 *epoch = ckptXidEpoch;
5954 * This must be called ONCE during postmaster or standalone-backend shutdown
5956 void
5957 ShutdownXLOG(int code, Datum arg)
5959 ereport(LOG,
5960 (errmsg("shutting down")));
5962 if (RecoveryInProgress())
5963 CreateRestartPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5964 else
5965 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
5966 ShutdownCLOG();
5967 ShutdownSUBTRANS();
5968 ShutdownMultiXact();
5970 ereport(LOG,
5971 (errmsg("database system is shut down")));
5975 * Log start of a checkpoint.
5977 static void
5978 LogCheckpointStart(int flags, bool restartpoint)
5980 char *msg;
5983 * XXX: This is hopelessly untranslatable. We could call gettext_noop
5984 * for the main message, but what about all the flags?
5986 if (restartpoint)
5987 msg = "restartpoint starting:%s%s%s%s%s%s";
5988 else
5989 msg = "checkpoint starting:%s%s%s%s%s%s";
5991 elog(LOG, msg,
5992 (flags & CHECKPOINT_IS_SHUTDOWN) ? " shutdown" : "",
5993 (flags & CHECKPOINT_IMMEDIATE) ? " immediate" : "",
5994 (flags & CHECKPOINT_FORCE) ? " force" : "",
5995 (flags & CHECKPOINT_WAIT) ? " wait" : "",
5996 (flags & CHECKPOINT_CAUSE_XLOG) ? " xlog" : "",
5997 (flags & CHECKPOINT_CAUSE_TIME) ? " time" : "");
6001 * Log end of a checkpoint.
6003 static void
6004 LogCheckpointEnd(bool restartpoint)
6006 long write_secs,
6007 sync_secs,
6008 total_secs;
6009 int write_usecs,
6010 sync_usecs,
6011 total_usecs;
6013 CheckpointStats.ckpt_end_t = GetCurrentTimestamp();
6015 TimestampDifference(CheckpointStats.ckpt_start_t,
6016 CheckpointStats.ckpt_end_t,
6017 &total_secs, &total_usecs);
6019 TimestampDifference(CheckpointStats.ckpt_write_t,
6020 CheckpointStats.ckpt_sync_t,
6021 &write_secs, &write_usecs);
6023 TimestampDifference(CheckpointStats.ckpt_sync_t,
6024 CheckpointStats.ckpt_sync_end_t,
6025 &sync_secs, &sync_usecs);
6027 if (restartpoint)
6028 elog(LOG, "restartpoint complete: wrote %d buffers (%.1f%%); "
6029 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
6030 CheckpointStats.ckpt_bufs_written,
6031 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
6032 write_secs, write_usecs / 1000,
6033 sync_secs, sync_usecs / 1000,
6034 total_secs, total_usecs / 1000);
6035 else
6036 elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
6037 "%d transaction log file(s) added, %d removed, %d recycled; "
6038 "write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
6039 CheckpointStats.ckpt_bufs_written,
6040 (double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
6041 CheckpointStats.ckpt_segs_added,
6042 CheckpointStats.ckpt_segs_removed,
6043 CheckpointStats.ckpt_segs_recycled,
6044 write_secs, write_usecs / 1000,
6045 sync_secs, sync_usecs / 1000,
6046 total_secs, total_usecs / 1000);
6050 * Perform a checkpoint --- either during shutdown, or on-the-fly
6052 * flags is a bitwise OR of the following:
6053 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
6054 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
6055 * ignoring checkpoint_completion_target parameter.
6056 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
6057 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
6059 * Note: flags contains other bits, of interest here only for logging purposes.
6060 * In particular note that this routine is synchronous and does not pay
6061 * attention to CHECKPOINT_WAIT.
6063 void
6064 CreateCheckPoint(int flags)
6066 bool shutdown = (flags & CHECKPOINT_IS_SHUTDOWN) != 0;
6067 CheckPoint checkPoint;
6068 XLogRecPtr recptr;
6069 XLogCtlInsert *Insert = &XLogCtl->Insert;
6070 XLogRecData rdata;
6071 uint32 freespace;
6072 uint32 _logId;
6073 uint32 _logSeg;
6074 TransactionId *inCommitXids;
6075 int nInCommit;
6077 /* shouldn't happen */
6078 if (RecoveryInProgress())
6079 elog(ERROR, "can't create a checkpoint during recovery");
6082 * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
6083 * During normal operation, bgwriter is the only process that creates
6084 * checkpoints, but at the end of archive recovery, the bgwriter can be
6085 * busy creating a restartpoint while the startup process tries to perform
6086 * the startup checkpoint.
6088 if (!LWLockConditionalAcquire(CheckpointLock, LW_EXCLUSIVE))
6090 Assert(InRecovery);
6093 * A restartpoint is in progress. Wait until it finishes. This can
6094 * cause an extra restartpoint to be performed, but that's OK because
6095 * we're just about to perform a checkpoint anyway. Flushing the
6096 * buffers in this restartpoint can take some time, but that time is
6097 * saved from the upcoming checkpoint so the net effect is zero.
6099 ereport(DEBUG2, (errmsg("hurrying in-progress restartpoint")));
6100 RequestCheckpoint(CHECKPOINT_IMMEDIATE | CHECKPOINT_WAIT);
6102 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
6106 * Prepare to accumulate statistics.
6108 * Note: because it is possible for log_checkpoints to change while a
6109 * checkpoint proceeds, we always accumulate stats, even if
6110 * log_checkpoints is currently off.
6112 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
6113 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
6116 * Use a critical section to force system panic if we have trouble.
6118 START_CRIT_SECTION();
6120 if (shutdown)
6122 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6123 ControlFile->state = DB_SHUTDOWNING;
6124 ControlFile->time = (pg_time_t) time(NULL);
6125 UpdateControlFile();
6126 LWLockRelease(ControlFileLock);
6130 * Let smgr prepare for checkpoint; this has to happen before we determine
6131 * the REDO pointer. Note that smgr must not do anything that'd have to
6132 * be undone if we decide no checkpoint is needed.
6134 smgrpreckpt();
6136 /* Begin filling in the checkpoint WAL record */
6137 MemSet(&checkPoint, 0, sizeof(checkPoint));
6138 checkPoint.ThisTimeLineID = ThisTimeLineID;
6139 checkPoint.time = (pg_time_t) time(NULL);
6142 * We must hold WALInsertLock while examining insert state to determine
6143 * the checkpoint REDO pointer.
6145 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6148 * If this isn't a shutdown or forced checkpoint, and we have not inserted
6149 * any XLOG records since the start of the last checkpoint, skip the
6150 * checkpoint. The idea here is to avoid inserting duplicate checkpoints
6151 * when the system is idle. That wastes log space, and more importantly it
6152 * exposes us to possible loss of both current and previous checkpoint
6153 * records if the machine crashes just as we're writing the update.
6154 * (Perhaps it'd make even more sense to checkpoint only when the previous
6155 * checkpoint record is in a different xlog page?)
6157 * We have to make two tests to determine that nothing has happened since
6158 * the start of the last checkpoint: current insertion point must match
6159 * the end of the last checkpoint record, and its redo pointer must point
6160 * to itself.
6162 if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_FORCE)) == 0)
6164 XLogRecPtr curInsert;
6166 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
6167 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
6168 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
6169 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
6170 ControlFile->checkPoint.xlogid ==
6171 ControlFile->checkPointCopy.redo.xlogid &&
6172 ControlFile->checkPoint.xrecoff ==
6173 ControlFile->checkPointCopy.redo.xrecoff)
6175 LWLockRelease(WALInsertLock);
6176 LWLockRelease(CheckpointLock);
6177 END_CRIT_SECTION();
6178 return;
6183 * Compute new REDO record ptr = location of next XLOG record.
6185 * NB: this is NOT necessarily where the checkpoint record itself will be,
6186 * since other backends may insert more XLOG records while we're off doing
6187 * the buffer flush work. Those XLOG records are logically after the
6188 * checkpoint, even though physically before it. Got that?
6190 freespace = INSERT_FREESPACE(Insert);
6191 if (freespace < SizeOfXLogRecord)
6193 (void) AdvanceXLInsertBuffer(false);
6194 /* OK to ignore update return flag, since we will do flush anyway */
6195 freespace = INSERT_FREESPACE(Insert);
6197 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
6200 * Here we update the shared RedoRecPtr for future XLogInsert calls; this
6201 * must be done while holding the insert lock AND the info_lck.
6203 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
6204 * pointing past where it really needs to point. This is okay; the only
6205 * consequence is that XLogInsert might back up whole buffers that it
6206 * didn't really need to. We can't postpone advancing RedoRecPtr because
6207 * XLogInserts that happen while we are dumping buffers must assume that
6208 * their buffer changes are not included in the checkpoint.
6211 /* use volatile pointer to prevent code rearrangement */
6212 volatile XLogCtlData *xlogctl = XLogCtl;
6214 SpinLockAcquire(&xlogctl->info_lck);
6215 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
6216 SpinLockRelease(&xlogctl->info_lck);
6220 * Now we can release WAL insert lock, allowing other xacts to proceed
6221 * while we are flushing disk buffers.
6223 LWLockRelease(WALInsertLock);
6226 * If enabled, log checkpoint start. We postpone this until now so as not
6227 * to log anything if we decided to skip the checkpoint.
6229 if (log_checkpoints)
6230 LogCheckpointStart(flags, false);
6232 TRACE_POSTGRESQL_CHECKPOINT_START(flags);
6235 * Before flushing data, we must wait for any transactions that are
6236 * currently in their commit critical sections. If an xact inserted its
6237 * commit record into XLOG just before the REDO point, then a crash
6238 * restart from the REDO point would not replay that record, which means
6239 * that our flushing had better include the xact's update of pg_clog. So
6240 * we wait till he's out of his commit critical section before proceeding.
6241 * See notes in RecordTransactionCommit().
6243 * Because we've already released WALInsertLock, this test is a bit fuzzy:
6244 * it is possible that we will wait for xacts we didn't really need to
6245 * wait for. But the delay should be short and it seems better to make
6246 * checkpoint take a bit longer than to hold locks longer than necessary.
6247 * (In fact, the whole reason we have this issue is that xact.c does
6248 * commit record XLOG insertion and clog update as two separate steps
6249 * protected by different locks, but again that seems best on grounds of
6250 * minimizing lock contention.)
6252 * A transaction that has not yet set inCommit when we look cannot be at
6253 * risk, since he's not inserted his commit record yet; and one that's
6254 * already cleared it is not at risk either, since he's done fixing clog
6255 * and we will correctly flush the update below. So we cannot miss any
6256 * xacts we need to wait for.
6258 nInCommit = GetTransactionsInCommit(&inCommitXids);
6259 if (nInCommit > 0)
6263 pg_usleep(10000L); /* wait for 10 msec */
6264 } while (HaveTransactionsInCommit(inCommitXids, nInCommit));
6266 pfree(inCommitXids);
6269 * Get the other info we need for the checkpoint record.
6271 LWLockAcquire(XidGenLock, LW_SHARED);
6272 checkPoint.nextXid = ShmemVariableCache->nextXid;
6273 LWLockRelease(XidGenLock);
6275 /* Increase XID epoch if we've wrapped around since last checkpoint */
6276 checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
6277 if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
6278 checkPoint.nextXidEpoch++;
6280 LWLockAcquire(OidGenLock, LW_SHARED);
6281 checkPoint.nextOid = ShmemVariableCache->nextOid;
6282 if (!shutdown)
6283 checkPoint.nextOid += ShmemVariableCache->oidCount;
6284 LWLockRelease(OidGenLock);
6286 MultiXactGetCheckptMulti(shutdown,
6287 &checkPoint.nextMulti,
6288 &checkPoint.nextMultiOffset);
6291 * Having constructed the checkpoint record, ensure all shmem disk buffers
6292 * and commit-log buffers are flushed to disk.
6294 * This I/O could fail for various reasons. If so, we will fail to
6295 * complete the checkpoint, but there is no reason to force a system
6296 * panic. Accordingly, exit critical section while doing it.
6298 END_CRIT_SECTION();
6300 CheckPointGuts(checkPoint.redo, flags);
6302 START_CRIT_SECTION();
6305 * Now insert the checkpoint record into XLOG.
6307 rdata.data = (char *) (&checkPoint);
6308 rdata.len = sizeof(checkPoint);
6309 rdata.buffer = InvalidBuffer;
6310 rdata.next = NULL;
6312 recptr = XLogInsert(RM_XLOG_ID,
6313 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
6314 XLOG_CHECKPOINT_ONLINE,
6315 &rdata);
6317 XLogFlush(recptr);
6320 * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
6321 * = end of actual checkpoint record.
6323 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
6324 ereport(PANIC,
6325 (errmsg("concurrent transaction log activity while database system is shutting down")));
6328 * Select point at which we can truncate the log, which we base on the
6329 * prior checkpoint's earliest info.
6331 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
6334 * Update the control file.
6336 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6337 if (shutdown)
6338 ControlFile->state = DB_SHUTDOWNED;
6339 ControlFile->prevCheckPoint = ControlFile->checkPoint;
6340 ControlFile->checkPoint = ProcLastRecPtr;
6341 ControlFile->checkPointCopy = checkPoint;
6342 ControlFile->time = (pg_time_t) time(NULL);
6343 UpdateControlFile();
6344 LWLockRelease(ControlFileLock);
6346 /* Update shared-memory copy of checkpoint XID/epoch */
6348 /* use volatile pointer to prevent code rearrangement */
6349 volatile XLogCtlData *xlogctl = XLogCtl;
6351 SpinLockAcquire(&xlogctl->info_lck);
6352 xlogctl->ckptXidEpoch = checkPoint.nextXidEpoch;
6353 xlogctl->ckptXid = checkPoint.nextXid;
6354 SpinLockRelease(&xlogctl->info_lck);
6358 * We are now done with critical updates; no need for system panic if we
6359 * have trouble while fooling with old log segments.
6361 END_CRIT_SECTION();
6364 * Let smgr do post-checkpoint cleanup (eg, deleting old files).
6366 smgrpostckpt();
6369 * Delete old log files (those no longer needed even for previous
6370 * checkpoint).
6372 if (_logId || _logSeg)
6374 PrevLogSeg(_logId, _logSeg);
6375 RemoveOldXlogFiles(_logId, _logSeg, recptr);
6379 * Make more log segments if needed. (Do this after recycling old log
6380 * segments, since that may supply some of the needed files.)
6382 if (!shutdown)
6383 PreallocXlogFiles(recptr);
6386 * Truncate pg_subtrans if possible. We can throw away all data before
6387 * the oldest XMIN of any running transaction. No future transaction will
6388 * attempt to reference any pg_subtrans entry older than that (see Asserts
6389 * in subtrans.c). During recovery, though, we mustn't do this because
6390 * StartupSUBTRANS hasn't been called yet.
6392 if (!InRecovery)
6393 TruncateSUBTRANS(GetOldestXmin(true, false));
6395 /* All real work is done, but log before releasing lock. */
6396 if (log_checkpoints)
6397 LogCheckpointEnd(false);
6399 TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
6400 NBuffers,
6401 CheckpointStats.ckpt_segs_added,
6402 CheckpointStats.ckpt_segs_removed,
6403 CheckpointStats.ckpt_segs_recycled);
6405 LWLockRelease(CheckpointLock);
6409 * Flush all data in shared memory to disk, and fsync
6411 * This is the common code shared between regular checkpoints and
6412 * recovery restartpoints.
6414 static void
6415 CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
6417 CheckPointCLOG();
6418 CheckPointSUBTRANS();
6419 CheckPointMultiXact();
6420 CheckPointBuffers(flags); /* performs all required fsyncs */
6421 /* We deliberately delay 2PC checkpointing as long as possible */
6422 CheckPointTwoPhase(checkPointRedo);
6426 * This is used during WAL recovery to establish a point from which recovery
6427 * can roll forward without replaying the entire recovery log. This function
6428 * is called each time a checkpoint record is read from XLOG. It is stored
6429 * in shared memory, so that it can be used as a restartpoint later on.
6431 static void
6432 RecoveryRestartPoint(const CheckPoint *checkPoint)
6434 int rmid;
6435 /* use volatile pointer to prevent code rearrangement */
6436 volatile XLogCtlData *xlogctl = XLogCtl;
6439 * Is it safe to checkpoint? We must ask each of the resource managers
6440 * whether they have any partial state information that might prevent a
6441 * correct restart from this point. If so, we skip this opportunity, but
6442 * return at the next checkpoint record for another try.
6444 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
6446 if (RmgrTable[rmid].rm_safe_restartpoint != NULL)
6447 if (!(RmgrTable[rmid].rm_safe_restartpoint()))
6449 elog(DEBUG2, "RM %d not safe to record restart point at %X/%X",
6450 rmid,
6451 checkPoint->redo.xlogid,
6452 checkPoint->redo.xrecoff);
6453 return;
6458 * Copy the checkpoint record to shared memory, so that bgwriter can
6459 * use it the next time it wants to perform a restartpoint.
6461 SpinLockAcquire(&xlogctl->info_lck);
6462 XLogCtl->lastCheckPointRecPtr = ReadRecPtr;
6463 memcpy(&XLogCtl->lastCheckPoint, checkPoint, sizeof(CheckPoint));
6464 SpinLockRelease(&xlogctl->info_lck);
6468 * This is similar to CreateCheckPoint, but is used during WAL recovery
6469 * to establish a point from which recovery can roll forward without
6470 * replaying the entire recovery log.
6472 * Returns true if a new restartpoint was established. We can only establish
6473 * a restartpoint if we have replayed a checkpoint record since last
6474 * restartpoint.
6476 bool
6477 CreateRestartPoint(int flags)
6479 XLogRecPtr lastCheckPointRecPtr;
6480 CheckPoint lastCheckPoint;
6481 /* use volatile pointer to prevent code rearrangement */
6482 volatile XLogCtlData *xlogctl = XLogCtl;
6485 * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
6486 * happens at a time.
6488 LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
6490 /* Get the a local copy of the last checkpoint record. */
6491 SpinLockAcquire(&xlogctl->info_lck);
6492 lastCheckPointRecPtr = xlogctl->lastCheckPointRecPtr;
6493 memcpy(&lastCheckPoint, &XLogCtl->lastCheckPoint, sizeof(CheckPoint));
6494 SpinLockRelease(&xlogctl->info_lck);
6497 * Check that we're still in recovery mode. It's ok if we exit recovery
6498 * mode after this check, the restart point is valid anyway.
6500 if (!RecoveryInProgress())
6502 ereport(DEBUG2,
6503 (errmsg("skipping restartpoint, recovery has already ended")));
6504 LWLockRelease(CheckpointLock);
6505 return false;
6509 * If the last checkpoint record we've replayed is already our last
6510 * restartpoint, we can't perform a new restart point. We still update
6511 * minRecoveryPoint in that case, so that if this is a shutdown restart
6512 * point, we won't start up earlier than before. That's not strictly
6513 * necessary, but when we get hot standby capability, it would be rather
6514 * weird if the database opened up for read-only connections at a
6515 * point-in-time before the last shutdown. Such time travel is still
6516 * possible in case of immediate shutdown, though.
6518 * We don't explicitly advance minRecoveryPoint when we do create a
6519 * restartpoint. It's assumed that flushing the buffers will do that
6520 * as a side-effect.
6522 if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
6523 XLByteLE(lastCheckPoint.redo, ControlFile->checkPointCopy.redo))
6525 XLogRecPtr InvalidXLogRecPtr = {0, 0};
6526 ereport(DEBUG2,
6527 (errmsg("skipping restartpoint, already performed at %X/%X",
6528 lastCheckPoint.redo.xlogid, lastCheckPoint.redo.xrecoff)));
6530 UpdateMinRecoveryPoint(InvalidXLogRecPtr, true);
6531 LWLockRelease(CheckpointLock);
6532 return false;
6535 if (log_checkpoints)
6538 * Prepare to accumulate statistics.
6540 MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
6541 CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
6543 LogCheckpointStart(flags, true);
6546 CheckPointGuts(lastCheckPoint.redo, flags);
6549 * Update pg_control, using current time
6551 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
6552 ControlFile->prevCheckPoint = ControlFile->checkPoint;
6553 ControlFile->checkPoint = lastCheckPointRecPtr;
6554 ControlFile->checkPointCopy = lastCheckPoint;
6555 ControlFile->time = (pg_time_t) time(NULL);
6556 UpdateControlFile();
6557 LWLockRelease(ControlFileLock);
6560 * Currently, there is no need to truncate pg_subtrans during recovery.
6561 * If we did do that, we will need to have called StartupSUBTRANS()
6562 * already and then TruncateSUBTRANS() would go here.
6565 /* All real work is done, but log before releasing lock. */
6566 if (log_checkpoints)
6567 LogCheckpointEnd(true);
6569 ereport((log_checkpoints ? LOG : DEBUG2),
6570 (errmsg("recovery restart point at %X/%X",
6571 lastCheckPoint.redo.xlogid, lastCheckPoint.redo.xrecoff)));
6573 if (recoveryLastXTime)
6574 ereport((log_checkpoints ? LOG : DEBUG2),
6575 (errmsg("last completed transaction was at log time %s",
6576 timestamptz_to_str(recoveryLastXTime))));
6578 LWLockRelease(CheckpointLock);
6579 return true;
6583 * Write a NEXTOID log record
6585 void
6586 XLogPutNextOid(Oid nextOid)
6588 XLogRecData rdata;
6590 rdata.data = (char *) (&nextOid);
6591 rdata.len = sizeof(Oid);
6592 rdata.buffer = InvalidBuffer;
6593 rdata.next = NULL;
6594 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
6597 * We need not flush the NEXTOID record immediately, because any of the
6598 * just-allocated OIDs could only reach disk as part of a tuple insert or
6599 * update that would have its own XLOG record that must follow the NEXTOID
6600 * record. Therefore, the standard buffer LSN interlock applied to those
6601 * records will ensure no such OID reaches disk before the NEXTOID record
6602 * does.
6604 * Note, however, that the above statement only covers state "within" the
6605 * database. When we use a generated OID as a file or directory name, we
6606 * are in a sense violating the basic WAL rule, because that filesystem
6607 * change may reach disk before the NEXTOID WAL record does. The impact
6608 * of this is that if a database crash occurs immediately afterward, we
6609 * might after restart re-generate the same OID and find that it conflicts
6610 * with the leftover file or directory. But since for safety's sake we
6611 * always loop until finding a nonconflicting filename, this poses no real
6612 * problem in practice. See pgsql-hackers discussion 27-Sep-2006.
6617 * Write an XLOG SWITCH record.
6619 * Here we just blindly issue an XLogInsert request for the record.
6620 * All the magic happens inside XLogInsert.
6622 * The return value is either the end+1 address of the switch record,
6623 * or the end+1 address of the prior segment if we did not need to
6624 * write a switch record because we are already at segment start.
6626 XLogRecPtr
6627 RequestXLogSwitch(void)
6629 XLogRecPtr RecPtr;
6630 XLogRecData rdata;
6632 /* XLOG SWITCH, alone among xlog record types, has no data */
6633 rdata.buffer = InvalidBuffer;
6634 rdata.data = NULL;
6635 rdata.len = 0;
6636 rdata.next = NULL;
6638 RecPtr = XLogInsert(RM_XLOG_ID, XLOG_SWITCH, &rdata);
6640 return RecPtr;
6644 * XLOG resource manager's routines
6646 * Definitions of info values are in include/catalog/pg_control.h, though
6647 * not all records types are related to control file processing.
6649 void
6650 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
6652 uint8 info = record->xl_info & ~XLR_INFO_MASK;
6654 /* Backup blocks are not used in xlog records */
6655 Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
6657 if (info == XLOG_NEXTOID)
6659 Oid nextOid;
6661 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
6662 if (ShmemVariableCache->nextOid < nextOid)
6664 ShmemVariableCache->nextOid = nextOid;
6665 ShmemVariableCache->oidCount = 0;
6668 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
6670 CheckPoint checkPoint;
6672 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6673 /* In a SHUTDOWN checkpoint, believe the counters exactly */
6674 ShmemVariableCache->nextXid = checkPoint.nextXid;
6675 ShmemVariableCache->nextOid = checkPoint.nextOid;
6676 ShmemVariableCache->oidCount = 0;
6677 MultiXactSetNextMXact(checkPoint.nextMulti,
6678 checkPoint.nextMultiOffset);
6680 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6681 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6682 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6685 * TLI may change in a shutdown checkpoint, but it shouldn't decrease
6687 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6689 if (checkPoint.ThisTimeLineID < ThisTimeLineID ||
6690 !list_member_int(expectedTLIs,
6691 (int) checkPoint.ThisTimeLineID))
6692 ereport(PANIC,
6693 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
6694 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6695 /* Following WAL records should be run with new TLI */
6696 ThisTimeLineID = checkPoint.ThisTimeLineID;
6699 RecoveryRestartPoint(&checkPoint);
6701 else if (info == XLOG_CHECKPOINT_ONLINE)
6703 CheckPoint checkPoint;
6705 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
6706 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
6707 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
6708 checkPoint.nextXid))
6709 ShmemVariableCache->nextXid = checkPoint.nextXid;
6710 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
6712 ShmemVariableCache->nextOid = checkPoint.nextOid;
6713 ShmemVariableCache->oidCount = 0;
6715 MultiXactAdvanceNextMXact(checkPoint.nextMulti,
6716 checkPoint.nextMultiOffset);
6718 /* ControlFile->checkPointCopy always tracks the latest ckpt XID */
6719 ControlFile->checkPointCopy.nextXidEpoch = checkPoint.nextXidEpoch;
6720 ControlFile->checkPointCopy.nextXid = checkPoint.nextXid;
6722 /* TLI should not change in an on-line checkpoint */
6723 if (checkPoint.ThisTimeLineID != ThisTimeLineID)
6724 ereport(PANIC,
6725 (errmsg("unexpected timeline ID %u (should be %u) in checkpoint record",
6726 checkPoint.ThisTimeLineID, ThisTimeLineID)));
6728 RecoveryRestartPoint(&checkPoint);
6730 else if (info == XLOG_NOOP)
6732 /* nothing to do here */
6734 else if (info == XLOG_SWITCH)
6736 /* nothing to do here */
6740 void
6741 xlog_desc(StringInfo buf, uint8 xl_info, char *rec)
6743 uint8 info = xl_info & ~XLR_INFO_MASK;
6745 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
6746 info == XLOG_CHECKPOINT_ONLINE)
6748 CheckPoint *checkpoint = (CheckPoint *) rec;
6750 appendStringInfo(buf, "checkpoint: redo %X/%X; "
6751 "tli %u; xid %u/%u; oid %u; multi %u; offset %u; %s",
6752 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
6753 checkpoint->ThisTimeLineID,
6754 checkpoint->nextXidEpoch, checkpoint->nextXid,
6755 checkpoint->nextOid,
6756 checkpoint->nextMulti,
6757 checkpoint->nextMultiOffset,
6758 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
6760 else if (info == XLOG_NOOP)
6762 appendStringInfo(buf, "xlog no-op");
6764 else if (info == XLOG_NEXTOID)
6766 Oid nextOid;
6768 memcpy(&nextOid, rec, sizeof(Oid));
6769 appendStringInfo(buf, "nextOid: %u", nextOid);
6771 else if (info == XLOG_SWITCH)
6773 appendStringInfo(buf, "xlog switch");
6775 else
6776 appendStringInfo(buf, "UNKNOWN");
6779 #ifdef WAL_DEBUG
6781 static void
6782 xlog_outrec(StringInfo buf, XLogRecord *record)
6784 int i;
6786 appendStringInfo(buf, "prev %X/%X; xid %u",
6787 record->xl_prev.xlogid, record->xl_prev.xrecoff,
6788 record->xl_xid);
6790 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
6792 if (record->xl_info & XLR_SET_BKP_BLOCK(i))
6793 appendStringInfo(buf, "; bkpb%d", i + 1);
6796 appendStringInfo(buf, ": %s", RmgrTable[record->xl_rmid].rm_name);
6798 #endif /* WAL_DEBUG */
6802 * Return the (possible) sync flag used for opening a file, depending on the
6803 * value of the GUC wal_sync_method.
6805 static int
6806 get_sync_bit(int method)
6808 /* If fsync is disabled, never open in sync mode */
6809 if (!enableFsync)
6810 return 0;
6812 switch (method)
6815 * enum values for all sync options are defined even if they are not
6816 * supported on the current platform. But if not, they are not
6817 * included in the enum option array, and therefore will never be seen
6818 * here.
6820 case SYNC_METHOD_FSYNC:
6821 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6822 case SYNC_METHOD_FDATASYNC:
6823 return 0;
6824 #ifdef OPEN_SYNC_FLAG
6825 case SYNC_METHOD_OPEN:
6826 return OPEN_SYNC_FLAG;
6827 #endif
6828 #ifdef OPEN_DATASYNC_FLAG
6829 case SYNC_METHOD_OPEN_DSYNC:
6830 return OPEN_DATASYNC_FLAG;
6831 #endif
6832 default:
6833 /* can't happen (unless we are out of sync with option array) */
6834 elog(ERROR, "unrecognized wal_sync_method: %d", method);
6835 return 0; /* silence warning */
6840 * GUC support
6842 bool
6843 assign_xlog_sync_method(int new_sync_method, bool doit, GucSource source)
6845 if (!doit)
6846 return true;
6848 if (sync_method != new_sync_method)
6851 * To ensure that no blocks escape unsynced, force an fsync on the
6852 * currently open log segment (if any). Also, if the open flag is
6853 * changing, close the log file so it will be reopened (with new flag
6854 * bit) at next use.
6856 if (openLogFile >= 0)
6858 if (pg_fsync(openLogFile) != 0)
6859 ereport(PANIC,
6860 (errcode_for_file_access(),
6861 errmsg("could not fsync log file %u, segment %u: %m",
6862 openLogId, openLogSeg)));
6863 if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
6864 XLogFileClose();
6868 return true;
6873 * Issue appropriate kind of fsync (if any) on the current XLOG output file
6875 static void
6876 issue_xlog_fsync(void)
6878 switch (sync_method)
6880 case SYNC_METHOD_FSYNC:
6881 if (pg_fsync_no_writethrough(openLogFile) != 0)
6882 ereport(PANIC,
6883 (errcode_for_file_access(),
6884 errmsg("could not fsync log file %u, segment %u: %m",
6885 openLogId, openLogSeg)));
6886 break;
6887 #ifdef HAVE_FSYNC_WRITETHROUGH
6888 case SYNC_METHOD_FSYNC_WRITETHROUGH:
6889 if (pg_fsync_writethrough(openLogFile) != 0)
6890 ereport(PANIC,
6891 (errcode_for_file_access(),
6892 errmsg("could not fsync write-through log file %u, segment %u: %m",
6893 openLogId, openLogSeg)));
6894 break;
6895 #endif
6896 #ifdef HAVE_FDATASYNC
6897 case SYNC_METHOD_FDATASYNC:
6898 if (pg_fdatasync(openLogFile) != 0)
6899 ereport(PANIC,
6900 (errcode_for_file_access(),
6901 errmsg("could not fdatasync log file %u, segment %u: %m",
6902 openLogId, openLogSeg)));
6903 break;
6904 #endif
6905 case SYNC_METHOD_OPEN:
6906 case SYNC_METHOD_OPEN_DSYNC:
6907 /* write synced it already */
6908 break;
6909 default:
6910 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
6911 break;
6917 * pg_start_backup: set up for taking an on-line backup dump
6919 * Essentially what this does is to create a backup label file in $PGDATA,
6920 * where it will be archived as part of the backup dump. The label file
6921 * contains the user-supplied label string (typically this would be used
6922 * to tell where the backup dump will be stored) and the starting time and
6923 * starting WAL location for the dump.
6925 Datum
6926 pg_start_backup(PG_FUNCTION_ARGS)
6928 text *backupid = PG_GETARG_TEXT_P(0);
6929 bool fast = PG_GETARG_BOOL(1);
6930 char *backupidstr;
6931 XLogRecPtr checkpointloc;
6932 XLogRecPtr startpoint;
6933 pg_time_t stamp_time;
6934 char strfbuf[128];
6935 char xlogfilename[MAXFNAMELEN];
6936 uint32 _logId;
6937 uint32 _logSeg;
6938 struct stat stat_buf;
6939 FILE *fp;
6941 if (!superuser())
6942 ereport(ERROR,
6943 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6944 errmsg("must be superuser to run a backup")));
6946 if (!XLogArchivingActive())
6947 ereport(ERROR,
6948 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6949 errmsg("WAL archiving is not active"),
6950 errhint("archive_mode must be enabled at server start.")));
6952 if (!XLogArchiveCommandSet())
6953 ereport(ERROR,
6954 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6955 errmsg("WAL archiving is not active"),
6956 errhint("archive_command must be defined before "
6957 "online backups can be made safely.")));
6959 backupidstr = text_to_cstring(backupid);
6962 * Mark backup active in shared memory. We must do full-page WAL writes
6963 * during an on-line backup even if not doing so at other times, because
6964 * it's quite possible for the backup dump to obtain a "torn" (partially
6965 * written) copy of a database page if it reads the page concurrently with
6966 * our write to the same page. This can be fixed as long as the first
6967 * write to the page in the WAL sequence is a full-page write. Hence, we
6968 * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
6969 * are no dirty pages in shared memory that might get dumped while the
6970 * backup is in progress without having a corresponding WAL record. (Once
6971 * the backup is complete, we need not force full-page writes anymore,
6972 * since we expect that any pages not modified during the backup interval
6973 * must have been correctly captured by the backup.)
6975 * We must hold WALInsertLock to change the value of forcePageWrites, to
6976 * ensure adequate interlocking against XLogInsert().
6978 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
6979 if (XLogCtl->Insert.forcePageWrites)
6981 LWLockRelease(WALInsertLock);
6982 ereport(ERROR,
6983 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6984 errmsg("a backup is already in progress"),
6985 errhint("Run pg_stop_backup() and try again.")));
6987 XLogCtl->Insert.forcePageWrites = true;
6988 LWLockRelease(WALInsertLock);
6990 /* Ensure we release forcePageWrites if fail below */
6991 PG_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
6994 * Force a CHECKPOINT. Aside from being necessary to prevent torn
6995 * page problems, this guarantees that two successive backup runs will
6996 * have different checkpoint positions and hence different history
6997 * file names, even if nothing happened in between.
6999 * We use CHECKPOINT_IMMEDIATE only if requested by user (via
7000 * passing fast = true). Otherwise this can take awhile.
7002 RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT |
7003 (fast ? CHECKPOINT_IMMEDIATE : 0));
7006 * Now we need to fetch the checkpoint record location, and also its
7007 * REDO pointer. The oldest point in WAL that would be needed to
7008 * restore starting from the checkpoint is precisely the REDO pointer.
7010 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7011 checkpointloc = ControlFile->checkPoint;
7012 startpoint = ControlFile->checkPointCopy.redo;
7013 LWLockRelease(ControlFileLock);
7015 XLByteToSeg(startpoint, _logId, _logSeg);
7016 XLogFileName(xlogfilename, ThisTimeLineID, _logId, _logSeg);
7018 /* Use the log timezone here, not the session timezone */
7019 stamp_time = (pg_time_t) time(NULL);
7020 pg_strftime(strfbuf, sizeof(strfbuf),
7021 "%Y-%m-%d %H:%M:%S %Z",
7022 pg_localtime(&stamp_time, log_timezone));
7025 * Check for existing backup label --- implies a backup is already
7026 * running. (XXX given that we checked forcePageWrites above, maybe
7027 * it would be OK to just unlink any such label file?)
7029 if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
7031 if (errno != ENOENT)
7032 ereport(ERROR,
7033 (errcode_for_file_access(),
7034 errmsg("could not stat file \"%s\": %m",
7035 BACKUP_LABEL_FILE)));
7037 else
7038 ereport(ERROR,
7039 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7040 errmsg("a backup is already in progress"),
7041 errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
7042 BACKUP_LABEL_FILE)));
7045 * Okay, write the file
7047 fp = AllocateFile(BACKUP_LABEL_FILE, "w");
7048 if (!fp)
7049 ereport(ERROR,
7050 (errcode_for_file_access(),
7051 errmsg("could not create file \"%s\": %m",
7052 BACKUP_LABEL_FILE)));
7053 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
7054 startpoint.xlogid, startpoint.xrecoff, xlogfilename);
7055 fprintf(fp, "CHECKPOINT LOCATION: %X/%X\n",
7056 checkpointloc.xlogid, checkpointloc.xrecoff);
7057 fprintf(fp, "START TIME: %s\n", strfbuf);
7058 fprintf(fp, "LABEL: %s\n", backupidstr);
7059 if (fflush(fp) || ferror(fp) || FreeFile(fp))
7060 ereport(ERROR,
7061 (errcode_for_file_access(),
7062 errmsg("could not write file \"%s\": %m",
7063 BACKUP_LABEL_FILE)));
7065 PG_END_ENSURE_ERROR_CLEANUP(pg_start_backup_callback, (Datum) 0);
7068 * We're done. As a convenience, return the starting WAL location.
7070 snprintf(xlogfilename, sizeof(xlogfilename), "%X/%X",
7071 startpoint.xlogid, startpoint.xrecoff);
7072 PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
7075 /* Error cleanup callback for pg_start_backup */
7076 static void
7077 pg_start_backup_callback(int code, Datum arg)
7079 /* Turn off forcePageWrites on failure */
7080 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
7081 XLogCtl->Insert.forcePageWrites = false;
7082 LWLockRelease(WALInsertLock);
7086 * pg_stop_backup: finish taking an on-line backup dump
7088 * We remove the backup label file created by pg_start_backup, and instead
7089 * create a backup history file in pg_xlog (whence it will immediately be
7090 * archived). The backup history file contains the same info found in
7091 * the label file, plus the backup-end time and WAL location.
7092 * Note: different from CancelBackup which just cancels online backup mode.
7094 Datum
7095 pg_stop_backup(PG_FUNCTION_ARGS)
7097 XLogRecPtr startpoint;
7098 XLogRecPtr stoppoint;
7099 pg_time_t stamp_time;
7100 char strfbuf[128];
7101 char histfilepath[MAXPGPATH];
7102 char startxlogfilename[MAXFNAMELEN];
7103 char stopxlogfilename[MAXFNAMELEN];
7104 char lastxlogfilename[MAXFNAMELEN];
7105 char histfilename[MAXFNAMELEN];
7106 uint32 _logId;
7107 uint32 _logSeg;
7108 FILE *lfp;
7109 FILE *fp;
7110 char ch;
7111 int ich;
7112 int seconds_before_warning;
7113 int waits = 0;
7115 if (!superuser())
7116 ereport(ERROR,
7117 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7118 (errmsg("must be superuser to run a backup"))));
7120 if (!XLogArchivingActive())
7121 ereport(ERROR,
7122 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7123 errmsg("WAL archiving is not active"),
7124 errhint("archive_mode must be enabled at server start.")));
7127 * OK to clear forcePageWrites
7129 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
7130 XLogCtl->Insert.forcePageWrites = false;
7131 LWLockRelease(WALInsertLock);
7134 * Force a switch to a new xlog segment file, so that the backup is valid
7135 * as soon as archiver moves out the current segment file. We'll report
7136 * the end address of the XLOG SWITCH record as the backup stopping point.
7138 stoppoint = RequestXLogSwitch();
7140 XLByteToSeg(stoppoint, _logId, _logSeg);
7141 XLogFileName(stopxlogfilename, ThisTimeLineID, _logId, _logSeg);
7143 /* Use the log timezone here, not the session timezone */
7144 stamp_time = (pg_time_t) time(NULL);
7145 pg_strftime(strfbuf, sizeof(strfbuf),
7146 "%Y-%m-%d %H:%M:%S %Z",
7147 pg_localtime(&stamp_time, log_timezone));
7150 * Open the existing label file
7152 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
7153 if (!lfp)
7155 if (errno != ENOENT)
7156 ereport(ERROR,
7157 (errcode_for_file_access(),
7158 errmsg("could not read file \"%s\": %m",
7159 BACKUP_LABEL_FILE)));
7160 ereport(ERROR,
7161 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7162 errmsg("a backup is not in progress")));
7166 * Read and parse the START WAL LOCATION line (this code is pretty crude,
7167 * but we are not expecting any variability in the file format).
7169 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %24s)%c",
7170 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
7171 &ch) != 4 || ch != '\n')
7172 ereport(ERROR,
7173 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7174 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7177 * Write the backup history file
7179 XLByteToSeg(startpoint, _logId, _logSeg);
7180 BackupHistoryFilePath(histfilepath, ThisTimeLineID, _logId, _logSeg,
7181 startpoint.xrecoff % XLogSegSize);
7182 fp = AllocateFile(histfilepath, "w");
7183 if (!fp)
7184 ereport(ERROR,
7185 (errcode_for_file_access(),
7186 errmsg("could not create file \"%s\": %m",
7187 histfilepath)));
7188 fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
7189 startpoint.xlogid, startpoint.xrecoff, startxlogfilename);
7190 fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
7191 stoppoint.xlogid, stoppoint.xrecoff, stopxlogfilename);
7192 /* transfer remaining lines from label to history file */
7193 while ((ich = fgetc(lfp)) != EOF)
7194 fputc(ich, fp);
7195 fprintf(fp, "STOP TIME: %s\n", strfbuf);
7196 if (fflush(fp) || ferror(fp) || FreeFile(fp))
7197 ereport(ERROR,
7198 (errcode_for_file_access(),
7199 errmsg("could not write file \"%s\": %m",
7200 histfilepath)));
7203 * Close and remove the backup label file
7205 if (ferror(lfp) || FreeFile(lfp))
7206 ereport(ERROR,
7207 (errcode_for_file_access(),
7208 errmsg("could not read file \"%s\": %m",
7209 BACKUP_LABEL_FILE)));
7210 if (unlink(BACKUP_LABEL_FILE) != 0)
7211 ereport(ERROR,
7212 (errcode_for_file_access(),
7213 errmsg("could not remove file \"%s\": %m",
7214 BACKUP_LABEL_FILE)));
7217 * Clean out any no-longer-needed history files. As a side effect, this
7218 * will post a .ready file for the newly created history file, notifying
7219 * the archiver that history file may be archived immediately.
7221 CleanupBackupHistory();
7224 * Wait until both the last WAL file filled during backup and the history
7225 * file have been archived. We assume that the alphabetic sorting
7226 * property of the WAL files ensures any earlier WAL files are safely
7227 * archived as well.
7229 * We wait forever, since archive_command is supposed to work and
7230 * we assume the admin wanted his backup to work completely. If you
7231 * don't wish to wait, you can set statement_timeout.
7233 XLByteToPrevSeg(stoppoint, _logId, _logSeg);
7234 XLogFileName(lastxlogfilename, ThisTimeLineID, _logId, _logSeg);
7236 XLByteToSeg(startpoint, _logId, _logSeg);
7237 BackupHistoryFileName(histfilename, ThisTimeLineID, _logId, _logSeg,
7238 startpoint.xrecoff % XLogSegSize);
7240 seconds_before_warning = 60;
7241 waits = 0;
7243 while (XLogArchiveIsBusy(lastxlogfilename) ||
7244 XLogArchiveIsBusy(histfilename))
7246 CHECK_FOR_INTERRUPTS();
7248 pg_usleep(1000000L);
7250 if (++waits >= seconds_before_warning)
7252 seconds_before_warning *= 2; /* This wraps in >10 years... */
7253 ereport(WARNING,
7254 (errmsg("pg_stop_backup still waiting for archive to complete (%d seconds elapsed)",
7255 waits)));
7260 * We're done. As a convenience, return the ending WAL location.
7262 snprintf(stopxlogfilename, sizeof(stopxlogfilename), "%X/%X",
7263 stoppoint.xlogid, stoppoint.xrecoff);
7264 PG_RETURN_TEXT_P(cstring_to_text(stopxlogfilename));
7268 * pg_switch_xlog: switch to next xlog file
7270 Datum
7271 pg_switch_xlog(PG_FUNCTION_ARGS)
7273 XLogRecPtr switchpoint;
7274 char location[MAXFNAMELEN];
7276 if (!superuser())
7277 ereport(ERROR,
7278 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7279 (errmsg("must be superuser to switch transaction log files"))));
7281 switchpoint = RequestXLogSwitch();
7284 * As a convenience, return the WAL location of the switch record
7286 snprintf(location, sizeof(location), "%X/%X",
7287 switchpoint.xlogid, switchpoint.xrecoff);
7288 PG_RETURN_TEXT_P(cstring_to_text(location));
7292 * Report the current WAL write location (same format as pg_start_backup etc)
7294 * This is useful for determining how much of WAL is visible to an external
7295 * archiving process. Note that the data before this point is written out
7296 * to the kernel, but is not necessarily synced to disk.
7298 Datum
7299 pg_current_xlog_location(PG_FUNCTION_ARGS)
7301 char location[MAXFNAMELEN];
7303 /* Make sure we have an up-to-date local LogwrtResult */
7305 /* use volatile pointer to prevent code rearrangement */
7306 volatile XLogCtlData *xlogctl = XLogCtl;
7308 SpinLockAcquire(&xlogctl->info_lck);
7309 LogwrtResult = xlogctl->LogwrtResult;
7310 SpinLockRelease(&xlogctl->info_lck);
7313 snprintf(location, sizeof(location), "%X/%X",
7314 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff);
7315 PG_RETURN_TEXT_P(cstring_to_text(location));
7319 * Report the current WAL insert location (same format as pg_start_backup etc)
7321 * This function is mostly for debugging purposes.
7323 Datum
7324 pg_current_xlog_insert_location(PG_FUNCTION_ARGS)
7326 XLogCtlInsert *Insert = &XLogCtl->Insert;
7327 XLogRecPtr current_recptr;
7328 char location[MAXFNAMELEN];
7331 * Get the current end-of-WAL position ... shared lock is sufficient
7333 LWLockAcquire(WALInsertLock, LW_SHARED);
7334 INSERT_RECPTR(current_recptr, Insert, Insert->curridx);
7335 LWLockRelease(WALInsertLock);
7337 snprintf(location, sizeof(location), "%X/%X",
7338 current_recptr.xlogid, current_recptr.xrecoff);
7339 PG_RETURN_TEXT_P(cstring_to_text(location));
7343 * Compute an xlog file name and decimal byte offset given a WAL location,
7344 * such as is returned by pg_stop_backup() or pg_xlog_switch().
7346 * Note that a location exactly at a segment boundary is taken to be in
7347 * the previous segment. This is usually the right thing, since the
7348 * expected usage is to determine which xlog file(s) are ready to archive.
7350 Datum
7351 pg_xlogfile_name_offset(PG_FUNCTION_ARGS)
7353 text *location = PG_GETARG_TEXT_P(0);
7354 char *locationstr;
7355 unsigned int uxlogid;
7356 unsigned int uxrecoff;
7357 uint32 xlogid;
7358 uint32 xlogseg;
7359 uint32 xrecoff;
7360 XLogRecPtr locationpoint;
7361 char xlogfilename[MAXFNAMELEN];
7362 Datum values[2];
7363 bool isnull[2];
7364 TupleDesc resultTupleDesc;
7365 HeapTuple resultHeapTuple;
7366 Datum result;
7369 * Read input and parse
7371 locationstr = text_to_cstring(location);
7373 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
7374 ereport(ERROR,
7375 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7376 errmsg("could not parse transaction log location \"%s\"",
7377 locationstr)));
7379 locationpoint.xlogid = uxlogid;
7380 locationpoint.xrecoff = uxrecoff;
7383 * Construct a tuple descriptor for the result row. This must match this
7384 * function's pg_proc entry!
7386 resultTupleDesc = CreateTemplateTupleDesc(2, false);
7387 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
7388 TEXTOID, -1, 0);
7389 TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
7390 INT4OID, -1, 0);
7392 resultTupleDesc = BlessTupleDesc(resultTupleDesc);
7395 * xlogfilename
7397 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
7398 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
7400 values[0] = CStringGetTextDatum(xlogfilename);
7401 isnull[0] = false;
7404 * offset
7406 xrecoff = locationpoint.xrecoff - xlogseg * XLogSegSize;
7408 values[1] = UInt32GetDatum(xrecoff);
7409 isnull[1] = false;
7412 * Tuple jam: Having first prepared your Datums, then squash together
7414 resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
7416 result = HeapTupleGetDatum(resultHeapTuple);
7418 PG_RETURN_DATUM(result);
7422 * Compute an xlog file name given a WAL location,
7423 * such as is returned by pg_stop_backup() or pg_xlog_switch().
7425 Datum
7426 pg_xlogfile_name(PG_FUNCTION_ARGS)
7428 text *location = PG_GETARG_TEXT_P(0);
7429 char *locationstr;
7430 unsigned int uxlogid;
7431 unsigned int uxrecoff;
7432 uint32 xlogid;
7433 uint32 xlogseg;
7434 XLogRecPtr locationpoint;
7435 char xlogfilename[MAXFNAMELEN];
7437 locationstr = text_to_cstring(location);
7439 if (sscanf(locationstr, "%X/%X", &uxlogid, &uxrecoff) != 2)
7440 ereport(ERROR,
7441 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7442 errmsg("could not parse transaction log location \"%s\"",
7443 locationstr)));
7445 locationpoint.xlogid = uxlogid;
7446 locationpoint.xrecoff = uxrecoff;
7448 XLByteToPrevSeg(locationpoint, xlogid, xlogseg);
7449 XLogFileName(xlogfilename, ThisTimeLineID, xlogid, xlogseg);
7451 PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
7455 * read_backup_label: check to see if a backup_label file is present
7457 * If we see a backup_label during recovery, we assume that we are recovering
7458 * from a backup dump file, and we therefore roll forward from the checkpoint
7459 * identified by the label file, NOT what pg_control says. This avoids the
7460 * problem that pg_control might have been archived one or more checkpoints
7461 * later than the start of the dump, and so if we rely on it as the start
7462 * point, we will fail to restore a consistent database state.
7464 * We also attempt to retrieve the corresponding backup history file.
7465 * If successful, set *minRecoveryLoc to constrain valid PITR stopping
7466 * points.
7468 * Returns TRUE if a backup_label was found (and fills the checkpoint
7469 * location into *checkPointLoc); returns FALSE if not.
7471 static bool
7472 read_backup_label(XLogRecPtr *checkPointLoc, XLogRecPtr *minRecoveryLoc)
7474 XLogRecPtr startpoint;
7475 XLogRecPtr stoppoint;
7476 char histfilename[MAXFNAMELEN];
7477 char histfilepath[MAXPGPATH];
7478 char startxlogfilename[MAXFNAMELEN];
7479 char stopxlogfilename[MAXFNAMELEN];
7480 TimeLineID tli;
7481 uint32 _logId;
7482 uint32 _logSeg;
7483 FILE *lfp;
7484 FILE *fp;
7485 char ch;
7487 /* Default is to not constrain recovery stop point */
7488 minRecoveryLoc->xlogid = 0;
7489 minRecoveryLoc->xrecoff = 0;
7492 * See if label file is present
7494 lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
7495 if (!lfp)
7497 if (errno != ENOENT)
7498 ereport(FATAL,
7499 (errcode_for_file_access(),
7500 errmsg("could not read file \"%s\": %m",
7501 BACKUP_LABEL_FILE)));
7502 return false; /* it's not there, all is fine */
7506 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
7507 * is pretty crude, but we are not expecting any variability in the file
7508 * format).
7510 if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
7511 &startpoint.xlogid, &startpoint.xrecoff, &tli,
7512 startxlogfilename, &ch) != 5 || ch != '\n')
7513 ereport(FATAL,
7514 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7515 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7516 if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
7517 &checkPointLoc->xlogid, &checkPointLoc->xrecoff,
7518 &ch) != 3 || ch != '\n')
7519 ereport(FATAL,
7520 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7521 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
7522 if (ferror(lfp) || FreeFile(lfp))
7523 ereport(FATAL,
7524 (errcode_for_file_access(),
7525 errmsg("could not read file \"%s\": %m",
7526 BACKUP_LABEL_FILE)));
7529 * Try to retrieve the backup history file (no error if we can't)
7531 XLByteToSeg(startpoint, _logId, _logSeg);
7532 BackupHistoryFileName(histfilename, tli, _logId, _logSeg,
7533 startpoint.xrecoff % XLogSegSize);
7535 if (InArchiveRecovery)
7536 RestoreArchivedFile(histfilepath, histfilename, "RECOVERYHISTORY", 0);
7537 else
7538 BackupHistoryFilePath(histfilepath, tli, _logId, _logSeg,
7539 startpoint.xrecoff % XLogSegSize);
7541 fp = AllocateFile(histfilepath, "r");
7542 if (fp)
7545 * Parse history file to identify stop point.
7547 if (fscanf(fp, "START WAL LOCATION: %X/%X (file %24s)%c",
7548 &startpoint.xlogid, &startpoint.xrecoff, startxlogfilename,
7549 &ch) != 4 || ch != '\n')
7550 ereport(FATAL,
7551 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7552 errmsg("invalid data in file \"%s\"", histfilename)));
7553 if (fscanf(fp, "STOP WAL LOCATION: %X/%X (file %24s)%c",
7554 &stoppoint.xlogid, &stoppoint.xrecoff, stopxlogfilename,
7555 &ch) != 4 || ch != '\n')
7556 ereport(FATAL,
7557 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7558 errmsg("invalid data in file \"%s\"", histfilename)));
7559 *minRecoveryLoc = stoppoint;
7560 if (ferror(fp) || FreeFile(fp))
7561 ereport(FATAL,
7562 (errcode_for_file_access(),
7563 errmsg("could not read file \"%s\": %m",
7564 histfilepath)));
7567 return true;
7571 * Error context callback for errors occurring during rm_redo().
7573 static void
7574 rm_redo_error_callback(void *arg)
7576 XLogRecord *record = (XLogRecord *) arg;
7577 StringInfoData buf;
7579 initStringInfo(&buf);
7580 RmgrTable[record->xl_rmid].rm_desc(&buf,
7581 record->xl_info,
7582 XLogRecGetData(record));
7584 /* don't bother emitting empty description */
7585 if (buf.len > 0)
7586 errcontext("xlog redo %s", buf.data);
7588 pfree(buf.data);
7592 * BackupInProgress: check if online backup mode is active
7594 * This is done by checking for existence of the "backup_label" file.
7596 bool
7597 BackupInProgress(void)
7599 struct stat stat_buf;
7601 return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
7605 * CancelBackup: rename the "backup_label" file to cancel backup mode
7607 * If the "backup_label" file exists, it will be renamed to "backup_label.old".
7608 * Note that this will render an online backup in progress useless.
7609 * To correctly finish an online backup, pg_stop_backup must be called.
7611 void
7612 CancelBackup(void)
7614 struct stat stat_buf;
7616 /* if the file is not there, return */
7617 if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
7618 return;
7620 /* remove leftover file from previously cancelled backup if it exists */
7621 unlink(BACKUP_LABEL_OLD);
7623 if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) == 0)
7625 ereport(LOG,
7626 (errmsg("online backup mode cancelled"),
7627 errdetail("\"%s\" was renamed to \"%s\".",
7628 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
7630 else
7632 ereport(WARNING,
7633 (errcode_for_file_access(),
7634 errmsg("online backup mode was not cancelled"),
7635 errdetail("Could not rename \"%s\" to \"%s\": %m.",
7636 BACKUP_LABEL_FILE, BACKUP_LABEL_OLD)));
7640 /* ------------------------------------------------------
7641 * Startup Process main entry point and signal handlers
7642 * ------------------------------------------------------
7646 * startupproc_quickdie() occurs when signalled SIGQUIT by the postmaster.
7648 * Some backend has bought the farm,
7649 * so we need to stop what we're doing and exit.
7651 static void
7652 startupproc_quickdie(SIGNAL_ARGS)
7654 PG_SETMASK(&BlockSig);
7657 * DO NOT proc_exit() -- we're here because shared memory may be
7658 * corrupted, so we don't want to try to clean up our transaction. Just
7659 * nail the windows shut and get out of town.
7661 * Note we do exit(2) not exit(0). This is to force the postmaster into a
7662 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
7663 * backend. This is necessary precisely because we don't clean up our
7664 * shared memory state.
7666 exit(2);
7670 /* SIGHUP: set flag to re-read config file at next convenient time */
7671 static void
7672 StartupProcSigHupHandler(SIGNAL_ARGS)
7674 got_SIGHUP = true;
7677 /* SIGTERM: set flag to abort redo and exit */
7678 static void
7679 StartupProcShutdownHandler(SIGNAL_ARGS)
7681 if (in_restore_command)
7682 proc_exit(1);
7683 else
7684 shutdown_requested = true;
7687 /* Main entry point for startup process */
7688 void
7689 StartupProcessMain(void)
7692 * If possible, make this process a group leader, so that the postmaster
7693 * can signal any child processes too.
7695 #ifdef HAVE_SETSID
7696 if (setsid() < 0)
7697 elog(FATAL, "setsid() failed: %m");
7698 #endif
7701 * Properly accept or ignore signals the postmaster might send us
7703 pqsignal(SIGHUP, StartupProcSigHupHandler); /* reload config file */
7704 pqsignal(SIGINT, SIG_IGN); /* ignore query cancel */
7705 pqsignal(SIGTERM, StartupProcShutdownHandler); /* request shutdown */
7706 pqsignal(SIGQUIT, startupproc_quickdie); /* hard crash time */
7707 pqsignal(SIGALRM, SIG_IGN);
7708 pqsignal(SIGPIPE, SIG_IGN);
7709 pqsignal(SIGUSR1, SIG_IGN);
7710 pqsignal(SIGUSR2, SIG_IGN);
7713 * Reset some signals that are accepted by postmaster but not here
7715 pqsignal(SIGCHLD, SIG_DFL);
7716 pqsignal(SIGTTIN, SIG_DFL);
7717 pqsignal(SIGTTOU, SIG_DFL);
7718 pqsignal(SIGCONT, SIG_DFL);
7719 pqsignal(SIGWINCH, SIG_DFL);
7722 * Unblock signals (they were blocked when the postmaster forked us)
7724 PG_SETMASK(&UnBlockSig);
7726 StartupXLOG();
7728 BuildFlatFiles(false);
7731 * Exit normally. Exit code 0 tells postmaster that we completed
7732 * recovery successfully.
7734 proc_exit(0);