1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction log manager
7 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/access/transam/xlog.c,v 1.122 2003/08/04 02:39:57 momjian Exp $
12 *-------------------------------------------------------------------------
25 #include "access/clog.h"
26 #include "access/transam.h"
27 #include "access/xact.h"
28 #include "access/xlog.h"
29 #include "access/xlogutils.h"
30 #include "catalog/catversion.h"
31 #include "catalog/pg_control.h"
32 #include "storage/bufpage.h"
33 #include "storage/lwlock.h"
34 #include "storage/pmsignal.h"
35 #include "storage/proc.h"
36 #include "storage/sinval.h"
37 #include "storage/spin.h"
38 #include "utils/builtins.h"
39 #include "utils/guc.h"
40 #include "utils/relcache.h"
41 #include "miscadmin.h"
45 * This chunk of hackery attempts to determine which file sync methods
46 * are available on the current platform, and to choose an appropriate
47 * default method. We assume that fsync() is always available, and that
48 * configure determined whether fdatasync() is.
50 #define SYNC_METHOD_FSYNC 0
51 #define SYNC_METHOD_FDATASYNC 1
52 #define SYNC_METHOD_OPEN 2 /* used for both O_SYNC and
56 #define OPEN_SYNC_FLAG O_SYNC
59 #define OPEN_SYNC_FLAG O_FSYNC
63 #if defined(OPEN_SYNC_FLAG)
64 #if defined(O_DSYNC) && (O_DSYNC != OPEN_SYNC_FLAG)
65 #define OPEN_DATASYNC_FLAG O_DSYNC
69 #if defined(OPEN_DATASYNC_FLAG)
70 #define DEFAULT_SYNC_METHOD_STR "open_datasync"
71 #define DEFAULT_SYNC_METHOD SYNC_METHOD_OPEN
72 #define DEFAULT_SYNC_FLAGBIT OPEN_DATASYNC_FLAG
74 #if defined(HAVE_FDATASYNC)
75 #define DEFAULT_SYNC_METHOD_STR "fdatasync"
76 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FDATASYNC
77 #define DEFAULT_SYNC_FLAGBIT 0
79 #define DEFAULT_SYNC_METHOD_STR "fsync"
80 #define DEFAULT_SYNC_METHOD SYNC_METHOD_FSYNC
81 #define DEFAULT_SYNC_FLAGBIT 0
86 /* User-settable parameters */
87 int CheckPointSegments = 3;
90 char *XLOG_sync_method = NULL;
91 const char XLOG_sync_method_default[] = DEFAULT_SYNC_METHOD_STR;
92 char XLOG_archive_dir[MAXPGPATH]; /* null string means
96 * XLOGfileslop is used in the code as the allowed "fuzz" in the number of
97 * preallocated XLOG segments --- we try to have at least XLOGfiles advance
98 * segments but no more than XLOGfileslop segments. This could
99 * be made a separate GUC variable, but at present I think it's sufficient
100 * to hardwire it as 2*CheckPointSegments+1. Under normal conditions, a
101 * checkpoint will free no more than 2*CheckPointSegments log segments, and
102 * we want to recycle all of them; the +1 allows boundary cases to happen
103 * without wasting a delete/create-segment cycle.
106 #define XLOGfileslop (2*CheckPointSegments + 1)
109 /* these are derived from XLOG_sync_method by assign_xlog_sync_method */
110 static int sync_method = DEFAULT_SYNC_METHOD;
111 static int open_sync_bit = DEFAULT_SYNC_FLAGBIT;
113 #define XLOG_SYNC_BIT (enableFsync ? open_sync_bit : 0)
115 #define MinXLOGbuffers 4
119 * ThisStartUpID will be same in all backends --- it identifies current
120 * instance of the database system.
122 StartUpID ThisStartUpID = 0;
124 /* Are we doing recovery by reading XLOG? */
125 bool InRecovery = false;
128 * MyLastRecPtr points to the start of the last XLOG record inserted by the
129 * current transaction. If MyLastRecPtr.xrecoff == 0, then the current
130 * xact hasn't yet inserted any transaction-controlled XLOG records.
132 * Note that XLOG records inserted outside transaction control are not
133 * reflected into MyLastRecPtr. They do, however, cause MyXactMadeXLogEntry
134 * to be set true. The latter can be used to test whether the current xact
135 * made any loggable changes (including out-of-xact changes, such as
138 * When we insert/update/delete a tuple in a temporary relation, we do not
139 * make any XLOG record, since we don't care about recovering the state of
140 * the temp rel after a crash. However, we will still need to remember
141 * whether our transaction committed or aborted in that case. So, we must
142 * set MyXactMadeTempRelUpdate true to indicate that the XID will be of
145 XLogRecPtr MyLastRecPtr = {0, 0};
147 bool MyXactMadeXLogEntry = false;
149 bool MyXactMadeTempRelUpdate = false;
152 * ProcLastRecPtr points to the start of the last XLOG record inserted by the
153 * current backend. It is updated for all inserts, transaction-controlled
154 * or not. ProcLastRecEnd is similar but points to end+1 of last record.
156 static XLogRecPtr ProcLastRecPtr = {0, 0};
158 XLogRecPtr ProcLastRecEnd = {0, 0};
161 * RedoRecPtr is this backend's local copy of the REDO record pointer
162 * (which is almost but not quite the same as a pointer to the most recent
163 * CHECKPOINT record). We update this from the shared-memory copy,
164 * XLogCtl->Insert.RedoRecPtr, whenever we can safely do so (ie, when we
165 * hold the Insert lock). See XLogInsert for details. We are also allowed
166 * to update from XLogCtl->Insert.RedoRecPtr if we hold the info_lck;
169 static XLogRecPtr RedoRecPtr;
172 * Shared-memory data structures for XLOG control
174 * LogwrtRqst indicates a byte position that we need to write and/or fsync
175 * the log up to (all records before that point must be written or fsynced).
176 * LogwrtResult indicates the byte positions we have already written/fsynced.
177 * These structs are identical but are declared separately to indicate their
178 * slightly different functions.
180 * We do a lot of pushups to minimize the amount of access to lockable
181 * shared memory values. There are actually three shared-memory copies of
182 * LogwrtResult, plus one unshared copy in each backend. Here's how it works:
183 * XLogCtl->LogwrtResult is protected by info_lck
184 * XLogCtl->Write.LogwrtResult is protected by WALWriteLock
185 * XLogCtl->Insert.LogwrtResult is protected by WALInsertLock
186 * One must hold the associated lock to read or write any of these, but
187 * of course no lock is needed to read/write the unshared LogwrtResult.
189 * XLogCtl->LogwrtResult and XLogCtl->Write.LogwrtResult are both "always
190 * right", since both are updated by a write or flush operation before
191 * it releases WALWriteLock. The point of keeping XLogCtl->Write.LogwrtResult
192 * is that it can be examined/modified by code that already holds WALWriteLock
193 * without needing to grab info_lck as well.
195 * XLogCtl->Insert.LogwrtResult may lag behind the reality of the other two,
196 * but is updated when convenient. Again, it exists for the convenience of
197 * code that is already holding WALInsertLock but not the other locks.
199 * The unshared LogwrtResult may lag behind any or all of these, and again
200 * is updated when convenient.
202 * The request bookkeeping is simpler: there is a shared XLogCtl->LogwrtRqst
203 * (protected by info_lck), but we don't need to cache any copies of it.
205 * Note that this all works because the request and result positions can only
206 * advance forward, never back up, and so we can easily determine which of two
207 * values is "more up to date".
209 * info_lck is only held long enough to read/update the protected variables,
210 * so it's a plain spinlock. The other locks are held longer (potentially
211 * over I/O operations), so we use LWLocks for them. These locks are:
213 * WALInsertLock: must be held to insert a record into the WAL buffers.
215 * WALWriteLock: must be held to write WAL buffers to disk (XLogWrite or
218 * ControlFileLock: must be held to read/update control file or create
221 * CheckpointLock: must be held to do a checkpoint (ensures only one
222 * checkpointer at a time; even though the postmaster won't launch
223 * parallel checkpoint processes, we need this because manual checkpoints
224 * could be launched simultaneously).
228 typedef struct XLogwrtRqst
230 XLogRecPtr Write; /* last byte + 1 to write out */
231 XLogRecPtr Flush; /* last byte + 1 to flush */
234 typedef struct XLogwrtResult
236 XLogRecPtr Write; /* last byte + 1 written out */
237 XLogRecPtr Flush; /* last byte + 1 flushed */
241 * Shared state data for XLogInsert.
243 typedef struct XLogCtlInsert
245 XLogwrtResult LogwrtResult; /* a recent value of LogwrtResult */
246 XLogRecPtr PrevRecord; /* start of previously-inserted record */
247 uint16 curridx; /* current block index in cache */
248 XLogPageHeader currpage; /* points to header of block in cache */
249 char *currpos; /* current insertion point in cache */
250 XLogRecPtr RedoRecPtr; /* current redo point for insertions */
254 * Shared state data for XLogWrite/XLogFlush.
256 typedef struct XLogCtlWrite
258 XLogwrtResult LogwrtResult; /* current value of LogwrtResult */
259 uint16 curridx; /* cache index of next block to write */
263 * Total shared-memory state for XLOG.
265 typedef struct XLogCtlData
267 /* Protected by WALInsertLock: */
268 XLogCtlInsert Insert;
269 /* Protected by info_lck: */
270 XLogwrtRqst LogwrtRqst;
271 XLogwrtResult LogwrtResult;
272 /* Protected by WALWriteLock: */
276 * These values do not change after startup, although the pointed-to
277 * pages and xlblocks values certainly do. Permission to read/write
278 * the pages and xlblocks values depends on WALInsertLock and
281 char *pages; /* buffers for unwritten XLOG pages */
282 XLogRecPtr *xlblocks; /* 1st byte ptr-s + BLCKSZ */
283 uint32 XLogCacheByte; /* # bytes in xlog buffers */
284 uint32 XLogCacheBlck; /* highest allocated xlog buffer index */
285 StartUpID ThisStartUpID;
287 /* This value is not protected by *any* lock... */
288 /* see SetSavedRedoRecPtr/GetSavedRedoRecPtr */
289 XLogRecPtr SavedRedoRecPtr;
291 slock_t info_lck; /* locks shared LogwrtRqst/LogwrtResult */
294 static XLogCtlData *XLogCtl = NULL;
297 * We maintain an image of pg_control in shared memory.
299 static ControlFileData *ControlFile = NULL;
302 * Macros for managing XLogInsert state. In most cases, the calling routine
303 * has local copies of XLogCtl->Insert and/or XLogCtl->Insert->curridx,
304 * so these are passed as parameters instead of being fetched via XLogCtl.
307 /* Free space remaining in the current xlog page buffer */
308 #define INSERT_FREESPACE(Insert) \
309 (BLCKSZ - ((Insert)->currpos - (char *) (Insert)->currpage))
311 /* Construct XLogRecPtr value for current insertion point */
312 #define INSERT_RECPTR(recptr,Insert,curridx) \
314 (recptr).xlogid = XLogCtl->xlblocks[curridx].xlogid, \
316 XLogCtl->xlblocks[curridx].xrecoff - INSERT_FREESPACE(Insert) \
320 /* Increment an xlogid/segment pair */
321 #define NextLogSeg(logId, logSeg) \
323 if ((logSeg) >= XLogSegsPerFile-1) \
332 /* Decrement an xlogid/segment pair (assume it's not 0,0) */
333 #define PrevLogSeg(logId, logSeg) \
340 (logSeg) = XLogSegsPerFile-1; \
345 * Compute ID and segment from an XLogRecPtr.
347 * For XLByteToSeg, do the computation at face value. For XLByteToPrevSeg,
348 * a boundary byte is taken to be in the previous segment. This is suitable
349 * for deciding which segment to write given a pointer to a record end,
350 * for example. (We can assume xrecoff is not zero, since no valid recptr
353 #define XLByteToSeg(xlrp, logId, logSeg) \
354 ( logId = (xlrp).xlogid, \
355 logSeg = (xlrp).xrecoff / XLogSegSize \
357 #define XLByteToPrevSeg(xlrp, logId, logSeg) \
358 ( logId = (xlrp).xlogid, \
359 logSeg = ((xlrp).xrecoff - 1) / XLogSegSize \
363 * Is an XLogRecPtr within a particular XLOG segment?
365 * For XLByteInSeg, do the computation at face value. For XLByteInPrevSeg,
366 * a boundary byte is taken to be in the previous segment.
368 #define XLByteInSeg(xlrp, logId, logSeg) \
369 ((xlrp).xlogid == (logId) && \
370 (xlrp).xrecoff / XLogSegSize == (logSeg))
372 #define XLByteInPrevSeg(xlrp, logId, logSeg) \
373 ((xlrp).xlogid == (logId) && \
374 ((xlrp).xrecoff - 1) / XLogSegSize == (logSeg))
377 #define XLogFileName(path, log, seg) \
378 snprintf(path, MAXPGPATH, "%s/%08X%08X", \
381 #define PrevBufIdx(idx) \
382 (((idx) == 0) ? XLogCtl->XLogCacheBlck : ((idx) - 1))
384 #define NextBufIdx(idx) \
385 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
387 #define XRecOffIsValid(xrecoff) \
388 ((xrecoff) % BLCKSZ >= SizeOfXLogPHD && \
389 (BLCKSZ - (xrecoff) % BLCKSZ) >= SizeOfXLogRecord)
392 * _INTL_MAXLOGRECSZ: max space needed for a record including header and
393 * any backup-block data.
395 #define _INTL_MAXLOGRECSZ (SizeOfXLogRecord + MAXLOGRECSZ + \
396 XLR_MAX_BKP_BLOCKS * (sizeof(BkpBlock) + BLCKSZ))
399 /* File path names */
400 static char XLogDir[MAXPGPATH];
401 static char ControlFilePath[MAXPGPATH];
404 * Private, possibly out-of-date copy of shared LogwrtResult.
405 * See discussion above.
407 static XLogwrtResult LogwrtResult = {{0, 0}, {0, 0}};
410 * openLogFile is -1 or a kernel FD for an open log file segment.
411 * When it's open, openLogOff is the current seek offset in the file.
412 * openLogId/openLogSeg identify the segment. These variables are only
413 * used to write the XLOG, and so will normally refer to the active segment.
415 static int openLogFile = -1;
416 static uint32 openLogId = 0;
417 static uint32 openLogSeg = 0;
418 static uint32 openLogOff = 0;
421 * These variables are used similarly to the ones above, but for reading
422 * the XLOG. Note, however, that readOff generally represents the offset
423 * of the page just read, not the seek position of the FD itself, which
424 * will be just past that page.
426 static int readFile = -1;
427 static uint32 readId = 0;
428 static uint32 readSeg = 0;
429 static uint32 readOff = 0;
431 /* Buffer for currently read page (BLCKSZ bytes) */
432 static char *readBuf = NULL;
434 /* State information for XLOG reading */
435 static XLogRecPtr ReadRecPtr;
436 static XLogRecPtr EndRecPtr;
437 static XLogRecord *nextRecord = NULL;
438 static StartUpID lastReadSUI;
440 static bool InRedo = false;
443 static bool AdvanceXLInsertBuffer(void);
444 static void XLogWrite(XLogwrtRqst WriteRqst);
445 static int XLogFileInit(uint32 log, uint32 seg,
446 bool *use_existent, bool use_lock);
447 static bool InstallXLogFileSegment(uint32 log, uint32 seg, char *tmppath,
448 bool find_free, int max_advance,
450 static int XLogFileOpen(uint32 log, uint32 seg, bool econt);
451 static void PreallocXlogFiles(XLogRecPtr endptr);
452 static void MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr);
453 static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, int emode, char *buffer);
454 static bool ValidXLOGHeader(XLogPageHeader hdr, int emode, bool checkSUI);
455 static XLogRecord *ReadCheckpointRecord(XLogRecPtr RecPtr,
458 static void WriteControlFile(void);
459 static void ReadControlFile(void);
460 static char *str_time(time_t tnow);
461 static void xlog_outrec(char *buf, XLogRecord *record);
462 static void issue_xlog_fsync(void);
466 * Insert an XLOG record having the specified RMID and info bytes,
467 * with the body of the record being the data chunk(s) described by
468 * the rdata list (see xlog.h for notes about rdata).
470 * Returns XLOG pointer to end of record (beginning of next record).
471 * This can be used as LSN for data pages affected by the logged action.
472 * (LSN is the XLOG point up to which the XLOG must be flushed to disk
473 * before the data page can be written out. This implements the basic
474 * WAL rule "write the log before the data".)
476 * NB: this routine feels free to scribble on the XLogRecData structs,
477 * though not on the data they reference. This is OK since the XLogRecData
478 * structs are always just temporaries in the calling code.
481 XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
483 XLogCtlInsert *Insert = &XLogCtl->Insert;
485 XLogContRecord *contrecord;
487 XLogRecPtr WriteRqst;
491 Buffer dtbuf[XLR_MAX_BKP_BLOCKS];
492 bool dtbuf_bkp[XLR_MAX_BKP_BLOCKS];
493 BkpBlock dtbuf_xlg[XLR_MAX_BKP_BLOCKS];
494 XLogRecPtr dtbuf_lsn[XLR_MAX_BKP_BLOCKS];
495 XLogRecData dtbuf_rdt[2 * XLR_MAX_BKP_BLOCKS];
500 XLogwrtRqst LogwrtRqst;
502 bool no_tran = (rmid == RM_XLOG_ID) ? true : false;
504 if (info & XLR_INFO_MASK)
506 if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
507 elog(PANIC, "invalid xlog info mask %02X", (info & XLR_INFO_MASK));
509 info &= ~XLR_INFO_MASK;
513 * In bootstrap mode, we don't actually log anything but XLOG
514 * resources; return a phony record pointer.
516 if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
519 RecPtr.xrecoff = SizeOfXLogPHD; /* start of 1st checkpoint record */
524 * Here we scan the rdata list, determine which buffers must be backed
525 * up, and compute the CRC values for the data. Note that the record
526 * header isn't added into the CRC yet since we don't know the final
527 * length or info bits quite yet.
529 * We may have to loop back to here if a race condition is detected
530 * below. We could prevent the race by doing all this work while
531 * holding the insert lock, but it seems better to avoid doing CRC
532 * calculations while holding the lock. This means we have to be
533 * careful about modifying the rdata list until we know we aren't
534 * going to loop back again. The only change we allow ourselves to
535 * make earlier is to set rdt->data = NULL in list items we have
536 * decided we will have to back up the whole buffer for. This is OK
537 * because we will certainly decide the same thing again for those
538 * items if we do it over; doing it here saves an extra pass over the
542 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
544 dtbuf[i] = InvalidBuffer;
545 dtbuf_bkp[i] = false;
548 INIT_CRC64(rdata_crc);
552 if (rdt->buffer == InvalidBuffer)
554 /* Simple data, just include it */
556 COMP_CRC64(rdata_crc, rdt->data, rdt->len);
560 /* Find info for buffer */
561 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
563 if (rdt->buffer == dtbuf[i])
565 /* Buffer already referenced by earlier list item */
571 COMP_CRC64(rdata_crc, rdt->data, rdt->len);
575 if (dtbuf[i] == InvalidBuffer)
577 /* OK, put it in this slot */
578 dtbuf[i] = rdt->buffer;
581 * XXX We assume page LSN is first data on page
583 dtbuf_lsn[i] = *((XLogRecPtr *) BufferGetBlock(rdt->buffer));
584 if (XLByteLE(dtbuf_lsn[i], RedoRecPtr))
592 BufferGetBlock(dtbuf[i]),
594 dtbuf_xlg[i].node = BufferGetFileNode(dtbuf[i]);
595 dtbuf_xlg[i].block = BufferGetBlockNumber(dtbuf[i]);
597 (char *) &(dtbuf_xlg[i]) + sizeof(crc64),
598 sizeof(BkpBlock) - sizeof(crc64));
600 dtbuf_xlg[i].crc = dtcrc;
605 COMP_CRC64(rdata_crc, rdt->data, rdt->len);
610 if (i >= XLR_MAX_BKP_BLOCKS)
611 elog(PANIC, "can backup at most %d blocks per xlog record",
614 /* Break out of loop when rdt points to last list item */
615 if (rdt->next == NULL)
621 * NOTE: the test for len == 0 here is somewhat fishy, since in theory
622 * all of the rmgr data might have been suppressed in favor of backup
623 * blocks. Currently, all callers of XLogInsert provide at least some
624 * not-in-a-buffer data and so len == 0 should never happen, but that
625 * may not be true forever. If you need to remove the len == 0 check,
626 * also remove the check for xl_len == 0 in ReadRecord, below.
628 if (len == 0 || len > MAXLOGRECSZ)
629 elog(PANIC, "invalid xlog record length %u", len);
631 START_CRIT_SECTION();
633 /* update LogwrtResult before doing cache fill check */
635 /* use volatile pointer to prevent code rearrangement */
636 volatile XLogCtlData *xlogctl = XLogCtl;
638 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
639 LogwrtRqst = xlogctl->LogwrtRqst;
640 LogwrtResult = xlogctl->LogwrtResult;
641 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
645 * If cache is half filled then try to acquire write lock and do
646 * XLogWrite. Ignore any fractional blocks in performing this check.
648 LogwrtRqst.Write.xrecoff -= LogwrtRqst.Write.xrecoff % BLCKSZ;
649 if (LogwrtRqst.Write.xlogid != LogwrtResult.Write.xlogid ||
650 (LogwrtRqst.Write.xrecoff >= LogwrtResult.Write.xrecoff +
651 XLogCtl->XLogCacheByte / 2))
653 if (LWLockConditionalAcquire(WALWriteLock, LW_EXCLUSIVE))
655 LogwrtResult = XLogCtl->Write.LogwrtResult;
656 if (XLByteLT(LogwrtResult.Write, LogwrtRqst.Write))
657 XLogWrite(LogwrtRqst);
658 LWLockRelease(WALWriteLock);
662 /* Now wait to get insert lock */
663 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
666 * Check to see if my RedoRecPtr is out of date. If so, may have to
667 * go back and recompute everything. This can only happen just after
668 * a checkpoint, so it's better to be slow in this case and fast
671 if (!XLByteEQ(RedoRecPtr, Insert->RedoRecPtr))
673 Assert(XLByteLT(RedoRecPtr, Insert->RedoRecPtr));
674 RedoRecPtr = Insert->RedoRecPtr;
676 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
678 if (dtbuf[i] == InvalidBuffer)
680 if (dtbuf_bkp[i] == false &&
681 XLByteLE(dtbuf_lsn[i], RedoRecPtr))
684 * Oops, this buffer now needs to be backed up, but we
685 * didn't think so above. Start over.
687 LWLockRelease(WALInsertLock);
695 * Make additional rdata list entries for the backup blocks, so that
696 * we don't need to special-case them in the write loop. Note that we
697 * have now irrevocably changed the input rdata list. At the exit of
698 * this loop, write_len includes the backup block data.
700 * Also set the appropriate info bits to show which buffers were backed
701 * up. The i'th XLR_SET_BKP_BLOCK bit corresponds to the i'th
702 * distinct buffer value (ignoring InvalidBuffer) appearing in the
706 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
708 if (dtbuf[i] == InvalidBuffer || !(dtbuf_bkp[i]))
711 info |= XLR_SET_BKP_BLOCK(i);
713 rdt->next = &(dtbuf_rdt[2 * i]);
715 dtbuf_rdt[2 * i].data = (char *) &(dtbuf_xlg[i]);
716 dtbuf_rdt[2 * i].len = sizeof(BkpBlock);
717 write_len += sizeof(BkpBlock);
719 rdt = dtbuf_rdt[2 * i].next = &(dtbuf_rdt[2 * i + 1]);
721 dtbuf_rdt[2 * i + 1].data = (char *) BufferGetBlock(dtbuf[i]);
722 dtbuf_rdt[2 * i + 1].len = BLCKSZ;
724 dtbuf_rdt[2 * i + 1].next = NULL;
727 /* Insert record header */
730 freespace = INSERT_FREESPACE(Insert);
731 if (freespace < SizeOfXLogRecord)
733 updrqst = AdvanceXLInsertBuffer();
734 freespace = BLCKSZ - SizeOfXLogPHD;
737 curridx = Insert->curridx;
738 record = (XLogRecord *) Insert->currpos;
740 record->xl_prev = Insert->PrevRecord;
743 record->xl_xact_prev.xlogid = 0;
744 record->xl_xact_prev.xrecoff = 0;
747 record->xl_xact_prev = MyLastRecPtr;
749 record->xl_xid = GetCurrentTransactionId();
750 record->xl_len = len; /* doesn't include backup blocks */
751 record->xl_info = info;
752 record->xl_rmid = rmid;
754 /* Now we can finish computing the main CRC */
755 COMP_CRC64(rdata_crc, (char *) record + sizeof(crc64),
756 SizeOfXLogRecord - sizeof(crc64));
757 FIN_CRC64(rdata_crc);
758 record->xl_crc = rdata_crc;
760 /* Compute record's XLOG location */
761 INSERT_RECPTR(RecPtr, Insert, curridx);
763 /* If first XLOG record of transaction, save it in PGPROC array */
764 if (MyLastRecPtr.xrecoff == 0 && !no_tran)
767 * We do not acquire SInvalLock here because of possible deadlock.
768 * Anyone who wants to inspect other procs' logRec must acquire
769 * WALInsertLock, instead. A better solution would be a per-PROC
770 * spinlock, but no time for that before 7.2 --- tgl 12/19/01.
772 MyProc->logRec = RecPtr;
779 sprintf(buf, "INSERT @ %X/%X: ", RecPtr.xlogid, RecPtr.xrecoff);
780 xlog_outrec(buf, record);
781 if (rdata->data != NULL)
784 RmgrTable[record->xl_rmid].rm_desc(buf, record->xl_info, rdata->data);
786 elog(LOG, "%s", buf);
789 /* Record begin of record in appropriate places */
791 MyLastRecPtr = RecPtr;
792 ProcLastRecPtr = RecPtr;
793 Insert->PrevRecord = RecPtr;
794 MyXactMadeXLogEntry = true;
796 Insert->currpos += SizeOfXLogRecord;
797 freespace -= SizeOfXLogRecord;
800 * Append the data, including backup blocks if any
804 while (rdata->data == NULL)
809 if (rdata->len > freespace)
811 memcpy(Insert->currpos, rdata->data, freespace);
812 rdata->data += freespace;
813 rdata->len -= freespace;
814 write_len -= freespace;
818 memcpy(Insert->currpos, rdata->data, rdata->len);
819 freespace -= rdata->len;
820 write_len -= rdata->len;
821 Insert->currpos += rdata->len;
827 /* Use next buffer */
828 updrqst = AdvanceXLInsertBuffer();
829 curridx = Insert->curridx;
830 /* Insert cont-record header */
831 Insert->currpage->xlp_info |= XLP_FIRST_IS_CONTRECORD;
832 contrecord = (XLogContRecord *) Insert->currpos;
833 contrecord->xl_rem_len = write_len;
834 Insert->currpos += SizeOfXLogContRecord;
835 freespace = BLCKSZ - SizeOfXLogPHD - SizeOfXLogContRecord;
838 /* Ensure next record will be properly aligned */
839 Insert->currpos = (char *) Insert->currpage +
840 MAXALIGN(Insert->currpos - (char *) Insert->currpage);
841 freespace = INSERT_FREESPACE(Insert);
844 * The recptr I return is the beginning of the *next* record. This
845 * will be stored as LSN for changed data pages...
847 INSERT_RECPTR(RecPtr, Insert, curridx);
849 /* Need to update shared LogwrtRqst if some block was filled up */
850 if (freespace < SizeOfXLogRecord)
851 updrqst = true; /* curridx is filled and available for
854 curridx = PrevBufIdx(curridx);
855 WriteRqst = XLogCtl->xlblocks[curridx];
857 LWLockRelease(WALInsertLock);
861 /* use volatile pointer to prevent code rearrangement */
862 volatile XLogCtlData *xlogctl = XLogCtl;
864 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
865 /* advance global request to include new block(s) */
866 if (XLByteLT(xlogctl->LogwrtRqst.Write, WriteRqst))
867 xlogctl->LogwrtRqst.Write = WriteRqst;
868 /* update local result copy while I have the chance */
869 LogwrtResult = xlogctl->LogwrtResult;
870 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
873 ProcLastRecEnd = RecPtr;
881 * Advance the Insert state to the next buffer page, writing out the next
882 * buffer if it still contains unwritten data.
884 * The global LogwrtRqst.Write pointer needs to be advanced to include the
885 * just-filled page. If we can do this for free (without an extra lock),
886 * we do so here. Otherwise the caller must do it. We return TRUE if the
887 * request update still needs to be done, FALSE if we did it internally.
889 * Must be called with WALInsertLock held.
892 AdvanceXLInsertBuffer(void)
894 XLogCtlInsert *Insert = &XLogCtl->Insert;
895 XLogCtlWrite *Write = &XLogCtl->Write;
896 uint16 nextidx = NextBufIdx(Insert->curridx);
897 bool update_needed = true;
898 XLogRecPtr OldPageRqstPtr;
899 XLogwrtRqst WriteRqst;
900 XLogRecPtr NewPageEndPtr;
901 XLogPageHeader NewPage;
903 /* Use Insert->LogwrtResult copy if it's more fresh */
904 if (XLByteLT(LogwrtResult.Write, Insert->LogwrtResult.Write))
905 LogwrtResult = Insert->LogwrtResult;
908 * Get ending-offset of the buffer page we need to replace (this may
909 * be zero if the buffer hasn't been used yet). Fall through if it's
910 * already written out.
912 OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
913 if (!XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
915 /* nope, got work to do... */
916 XLogRecPtr FinishedPageRqstPtr;
918 FinishedPageRqstPtr = XLogCtl->xlblocks[Insert->curridx];
920 /* Before waiting, get info_lck and update LogwrtResult */
922 /* use volatile pointer to prevent code rearrangement */
923 volatile XLogCtlData *xlogctl = XLogCtl;
925 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
926 if (XLByteLT(xlogctl->LogwrtRqst.Write, FinishedPageRqstPtr))
927 xlogctl->LogwrtRqst.Write = FinishedPageRqstPtr;
928 LogwrtResult = xlogctl->LogwrtResult;
929 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
932 update_needed = false; /* Did the shared-request update */
934 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
936 /* OK, someone wrote it already */
937 Insert->LogwrtResult = LogwrtResult;
941 /* Must acquire write lock */
942 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
943 LogwrtResult = Write->LogwrtResult;
944 if (XLByteLE(OldPageRqstPtr, LogwrtResult.Write))
946 /* OK, someone wrote it already */
947 LWLockRelease(WALWriteLock);
948 Insert->LogwrtResult = LogwrtResult;
953 * Have to write buffers while holding insert lock. This
954 * is not good, so only write as much as we absolutely
957 WriteRqst.Write = OldPageRqstPtr;
958 WriteRqst.Flush.xlogid = 0;
959 WriteRqst.Flush.xrecoff = 0;
960 XLogWrite(WriteRqst);
961 LWLockRelease(WALWriteLock);
962 Insert->LogwrtResult = LogwrtResult;
968 * Now the next buffer slot is free and we can set it up to be the
971 NewPageEndPtr = XLogCtl->xlblocks[Insert->curridx];
972 if (NewPageEndPtr.xrecoff >= XLogFileSize)
974 /* crossing a logid boundary */
975 NewPageEndPtr.xlogid += 1;
976 NewPageEndPtr.xrecoff = BLCKSZ;
979 NewPageEndPtr.xrecoff += BLCKSZ;
980 XLogCtl->xlblocks[nextidx] = NewPageEndPtr;
981 NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * BLCKSZ);
982 Insert->curridx = nextidx;
983 Insert->currpage = NewPage;
984 Insert->currpos = ((char *) NewPage) + SizeOfXLogPHD;
987 * Be sure to re-zero the buffer so that bytes beyond what we've
988 * written will look like zeroes and not valid XLOG records...
990 MemSet((char *) NewPage, 0, BLCKSZ);
992 /* And fill the new page's header */
993 NewPage->xlp_magic = XLOG_PAGE_MAGIC;
994 /* NewPage->xlp_info = 0; */ /* done by memset */
995 NewPage->xlp_sui = ThisStartUpID;
996 NewPage->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid;
997 NewPage->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - BLCKSZ;
999 return update_needed;
1003 * Write and/or fsync the log at least as far as WriteRqst indicates.
1005 * Must be called with WALWriteLock held.
1008 XLogWrite(XLogwrtRqst WriteRqst)
1010 XLogCtlWrite *Write = &XLogCtl->Write;
1016 * Update local LogwrtResult (caller probably did this already,
1019 LogwrtResult = Write->LogwrtResult;
1021 while (XLByteLT(LogwrtResult.Write, WriteRqst.Write))
1024 * Make sure we're not ahead of the insert process. This could
1025 * happen if we're passed a bogus WriteRqst.Write that is past the
1026 * end of the last page that's been initialized by
1027 * AdvanceXLInsertBuffer.
1029 if (!XLByteLT(LogwrtResult.Write, XLogCtl->xlblocks[Write->curridx]))
1030 elog(PANIC, "xlog write request %X/%X is past end of log %X/%X",
1031 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1032 XLogCtl->xlblocks[Write->curridx].xlogid,
1033 XLogCtl->xlblocks[Write->curridx].xrecoff);
1035 /* Advance LogwrtResult.Write to end of current buffer page */
1036 LogwrtResult.Write = XLogCtl->xlblocks[Write->curridx];
1037 ispartialpage = XLByteLT(WriteRqst.Write, LogwrtResult.Write);
1039 if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1042 * Switch to new logfile segment.
1044 if (openLogFile >= 0)
1046 if (close(openLogFile) != 0)
1048 (errcode_for_file_access(),
1049 errmsg("close of log file %u, segment %u failed: %m",
1050 openLogId, openLogSeg)));
1053 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1055 /* create/use new log file */
1056 use_existent = true;
1057 openLogFile = XLogFileInit(openLogId, openLogSeg,
1058 &use_existent, true);
1061 /* update pg_control, unless someone else already did */
1062 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1063 if (ControlFile->logId < openLogId ||
1064 (ControlFile->logId == openLogId &&
1065 ControlFile->logSeg < openLogSeg + 1))
1067 ControlFile->logId = openLogId;
1068 ControlFile->logSeg = openLogSeg + 1;
1069 ControlFile->time = time(NULL);
1070 UpdateControlFile();
1073 * Signal postmaster to start a checkpoint if it's been
1074 * too long since the last one. (We look at local copy of
1075 * RedoRecPtr which might be a little out of date, but
1076 * should be close enough for this purpose.)
1078 if (IsUnderPostmaster &&
1079 (openLogId != RedoRecPtr.xlogid ||
1080 openLogSeg >= (RedoRecPtr.xrecoff / XLogSegSize) +
1081 (uint32) CheckPointSegments))
1084 elog(LOG, "time for a checkpoint, signaling postmaster");
1085 SendPostmasterSignal(PMSIGNAL_DO_CHECKPOINT);
1088 LWLockRelease(ControlFileLock);
1091 if (openLogFile < 0)
1093 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1094 openLogFile = XLogFileOpen(openLogId, openLogSeg, false);
1098 /* Need to seek in the file? */
1099 if (openLogOff != (LogwrtResult.Write.xrecoff - BLCKSZ) % XLogSegSize)
1101 openLogOff = (LogwrtResult.Write.xrecoff - BLCKSZ) % XLogSegSize;
1102 if (lseek(openLogFile, (off_t) openLogOff, SEEK_SET) < 0)
1104 (errcode_for_file_access(),
1105 errmsg("lseek of log file %u, segment %u, offset %u failed: %m",
1106 openLogId, openLogSeg, openLogOff)));
1109 /* OK to write the page */
1110 from = XLogCtl->pages + Write->curridx * BLCKSZ;
1112 if (write(openLogFile, from, BLCKSZ) != BLCKSZ)
1114 /* if write didn't set errno, assume problem is no disk space */
1118 (errcode_for_file_access(),
1119 errmsg("write of log file %u, segment %u, offset %u failed: %m",
1120 openLogId, openLogSeg, openLogOff)));
1122 openLogOff += BLCKSZ;
1125 * If we just wrote the whole last page of a logfile segment,
1126 * fsync the segment immediately. This avoids having to go back
1127 * and re-open prior segments when an fsync request comes along
1128 * later. Doing it here ensures that one and only one backend will
1129 * perform this fsync.
1131 if (openLogOff >= XLogSegSize && !ispartialpage)
1134 LogwrtResult.Flush = LogwrtResult.Write; /* end of current page */
1139 /* Only asked to write a partial page */
1140 LogwrtResult.Write = WriteRqst.Write;
1143 Write->curridx = NextBufIdx(Write->curridx);
1147 * If asked to flush, do so
1149 if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) &&
1150 XLByteLT(LogwrtResult.Flush, LogwrtResult.Write))
1153 * Could get here without iterating above loop, in which case we
1154 * might have no open file or the wrong one. However, we do not
1155 * need to fsync more than one file.
1157 if (sync_method != SYNC_METHOD_OPEN)
1159 if (openLogFile >= 0 &&
1160 !XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg))
1162 if (close(openLogFile) != 0)
1164 (errcode_for_file_access(),
1165 errmsg("close of log file %u, segment %u failed: %m",
1166 openLogId, openLogSeg)));
1169 if (openLogFile < 0)
1171 XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg);
1172 openLogFile = XLogFileOpen(openLogId, openLogSeg, false);
1177 LogwrtResult.Flush = LogwrtResult.Write;
1181 * Update shared-memory status
1183 * We make sure that the shared 'request' values do not fall behind the
1184 * 'result' values. This is not absolutely essential, but it saves
1185 * some code in a couple of places.
1188 /* use volatile pointer to prevent code rearrangement */
1189 volatile XLogCtlData *xlogctl = XLogCtl;
1191 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
1192 xlogctl->LogwrtResult = LogwrtResult;
1193 if (XLByteLT(xlogctl->LogwrtRqst.Write, LogwrtResult.Write))
1194 xlogctl->LogwrtRqst.Write = LogwrtResult.Write;
1195 if (XLByteLT(xlogctl->LogwrtRqst.Flush, LogwrtResult.Flush))
1196 xlogctl->LogwrtRqst.Flush = LogwrtResult.Flush;
1197 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
1200 Write->LogwrtResult = LogwrtResult;
1204 * Ensure that all XLOG data through the given position is flushed to disk.
1206 * NOTE: this differs from XLogWrite mainly in that the WALWriteLock is not
1207 * already held, and we try to avoid acquiring it if possible.
1210 XLogFlush(XLogRecPtr record)
1212 XLogRecPtr WriteRqstPtr;
1213 XLogwrtRqst WriteRqst;
1215 /* Disabled during REDO */
1219 /* Quick exit if already known flushed */
1220 if (XLByteLE(record, LogwrtResult.Flush))
1224 elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X",
1225 record.xlogid, record.xrecoff,
1226 LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff,
1227 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1229 START_CRIT_SECTION();
1232 * Since fsync is usually a horribly expensive operation, we try to
1233 * piggyback as much data as we can on each fsync: if we see any more
1234 * data entered into the xlog buffer, we'll write and fsync that too,
1235 * so that the final value of LogwrtResult.Flush is as large as
1236 * possible. This gives us some chance of avoiding another fsync
1237 * immediately after.
1240 /* initialize to given target; may increase below */
1241 WriteRqstPtr = record;
1243 /* read LogwrtResult and update local state */
1245 /* use volatile pointer to prevent code rearrangement */
1246 volatile XLogCtlData *xlogctl = XLogCtl;
1248 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
1249 if (XLByteLT(WriteRqstPtr, xlogctl->LogwrtRqst.Write))
1250 WriteRqstPtr = xlogctl->LogwrtRqst.Write;
1251 LogwrtResult = xlogctl->LogwrtResult;
1252 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
1256 if (!XLByteLE(record, LogwrtResult.Flush))
1258 /* now wait for the write lock */
1259 LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
1260 LogwrtResult = XLogCtl->Write.LogwrtResult;
1261 if (!XLByteLE(record, LogwrtResult.Flush))
1263 /* try to write/flush later additions to XLOG as well */
1264 if (LWLockConditionalAcquire(WALInsertLock, LW_EXCLUSIVE))
1266 XLogCtlInsert *Insert = &XLogCtl->Insert;
1267 uint32 freespace = INSERT_FREESPACE(Insert);
1269 if (freespace < SizeOfXLogRecord) /* buffer is full */
1270 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1273 WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx];
1274 WriteRqstPtr.xrecoff -= freespace;
1276 LWLockRelease(WALInsertLock);
1277 WriteRqst.Write = WriteRqstPtr;
1278 WriteRqst.Flush = WriteRqstPtr;
1282 WriteRqst.Write = WriteRqstPtr;
1283 WriteRqst.Flush = record;
1285 XLogWrite(WriteRqst);
1287 LWLockRelease(WALWriteLock);
1293 * If we still haven't flushed to the request point then we have a
1294 * problem; most likely, the requested flush point is past end of
1295 * XLOG. This has been seen to occur when a disk page has a corrupted
1298 * Formerly we treated this as a PANIC condition, but that hurts the
1299 * system's robustness rather than helping it: we do not want to take
1300 * down the whole system due to corruption on one data page. In
1301 * particular, if the bad page is encountered again during recovery
1302 * then we would be unable to restart the database at all! (This
1303 * scenario has actually happened in the field several times with 7.1
1304 * releases. Note that we cannot get here while InRedo is true, but if
1305 * the bad page is brought in and marked dirty during recovery then
1306 * CreateCheckpoint will try to flush it at the end of recovery.)
1308 * The current approach is to ERROR under normal conditions, but only
1309 * WARNING during recovery, so that the system can be brought up even
1310 * if there's a corrupt LSN. Note that for calls from xact.c, the
1311 * ERROR will be promoted to PANIC since xact.c calls this routine
1312 * inside a critical section. However, calls from bufmgr.c are not
1313 * within critical sections and so we will not force a restart for a
1314 * bad LSN on a data page.
1316 if (XLByteLT(LogwrtResult.Flush, record))
1317 elog(InRecovery ? WARNING : ERROR,
1318 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
1319 record.xlogid, record.xrecoff,
1320 LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff);
1324 * Create a new XLOG file segment, or open a pre-existing one.
1326 * log, seg: identify segment to be created/opened.
1328 * *use_existent: if TRUE, OK to use a pre-existing file (else, any
1329 * pre-existing file will be deleted). On return, TRUE if a pre-existing
1332 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1333 * place. This should be TRUE except during bootstrap log creation. The
1334 * caller must *not* hold the lock at call.
1336 * Returns FD of opened file.
1339 XLogFileInit(uint32 log, uint32 seg,
1340 bool *use_existent, bool use_lock)
1342 char path[MAXPGPATH];
1343 char tmppath[MAXPGPATH];
1344 char zbuffer[BLCKSZ];
1348 XLogFileName(path, log, seg);
1351 * Try to use existent file (checkpoint maker may have created it
1356 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1360 if (errno != ENOENT)
1362 (errcode_for_file_access(),
1363 errmsg("open of \"%s\" (log file %u, segment %u) failed: %m",
1371 * Initialize an empty (all zeroes) segment. NOTE: it is possible
1372 * that another process is doing the same thing. If so, we will end
1373 * up pre-creating an extra log segment. That seems OK, and better
1374 * than holding the lock throughout this lengthy process.
1376 snprintf(tmppath, MAXPGPATH, "%s/xlogtemp.%d",
1377 XLogDir, (int) getpid());
1381 /* do not use XLOG_SYNC_BIT here --- want to fsync only at end of fill */
1382 fd = BasicOpenFile(tmppath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
1386 (errcode_for_file_access(),
1387 errmsg("creation of file \"%s\" failed: %m", tmppath)));
1390 * Zero-fill the file. We have to do this the hard way to ensure that
1391 * all the file space has really been allocated --- on platforms that
1392 * allow "holes" in files, just seeking to the end doesn't allocate
1393 * intermediate space. This way, we know that we have all the space
1394 * and (after the fsync below) that all the indirect blocks are down
1395 * on disk. Therefore, fdatasync(2) or O_DSYNC will be sufficient to
1396 * sync future writes to the log file.
1398 MemSet(zbuffer, 0, sizeof(zbuffer));
1399 for (nbytes = 0; nbytes < XLogSegSize; nbytes += sizeof(zbuffer))
1402 if ((int) write(fd, zbuffer, sizeof(zbuffer)) != (int) sizeof(zbuffer))
1404 int save_errno = errno;
1407 * If we fail to make the file, delete it to release disk
1411 /* if write didn't set errno, assume problem is no disk space */
1412 errno = save_errno ? save_errno : ENOSPC;
1415 (errcode_for_file_access(),
1416 errmsg("failed to write \"%s\": %m", tmppath)));
1420 if (pg_fsync(fd) != 0)
1422 (errcode_for_file_access(),
1423 errmsg("fsync of file \"%s\" failed: %m", tmppath)));
1428 * Now move the segment into place with its final name.
1430 * If caller didn't want to use a pre-existing file, get rid of any
1431 * pre-existing file. Otherwise, cope with possibility that someone
1432 * else has created the file while we were filling ours: if so, use
1433 * ours to pre-create a future log segment.
1435 if (!InstallXLogFileSegment(log, seg, tmppath,
1436 *use_existent, XLOGfileslop,
1439 /* No need for any more future segments... */
1443 /* Set flag to tell caller there was no existent file */
1444 *use_existent = false;
1446 /* Now open original target segment (might not be file I just made) */
1447 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1451 (errcode_for_file_access(),
1452 errmsg("open of \"%s\" (log file %u, segment %u) failed: %m",
1459 * Install a new XLOG segment file as a current or future log segment.
1461 * This is used both to install a newly-created segment (which has a temp
1462 * filename while it's being created) and to recycle an old segment.
1464 * log, seg: identify segment to install as (or first possible target).
1466 * tmppath: initial name of file to install. It will be renamed into place.
1468 * find_free: if TRUE, install the new segment at the first empty log/seg
1469 * number at or after the passed numbers. If FALSE, install the new segment
1470 * exactly where specified, deleting any existing segment file there.
1472 * max_advance: maximum number of log/seg slots to advance past the starting
1473 * point. Fail if no free slot is found in this range. (Irrelevant if
1474 * find_free is FALSE.)
1476 * use_lock: if TRUE, acquire ControlFileLock while moving file into
1477 * place. This should be TRUE except during bootstrap log creation. The
1478 * caller must *not* hold the lock at call.
1480 * Returns TRUE if file installed, FALSE if not installed because of
1481 * exceeding max_advance limit. (Any other kind of failure causes ereport().)
1484 InstallXLogFileSegment(uint32 log, uint32 seg, char *tmppath,
1485 bool find_free, int max_advance,
1488 char path[MAXPGPATH];
1489 struct stat stat_buf;
1491 XLogFileName(path, log, seg);
1494 * We want to be sure that only one process does this at a time.
1497 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
1501 /* Force installation: get rid of any pre-existing segment file */
1506 /* Find a free slot to put it in */
1507 while (stat(path, &stat_buf) == 0)
1509 if (--max_advance < 0)
1511 /* Failed to find a free slot within specified range */
1513 LWLockRelease(ControlFileLock);
1516 NextLogSeg(log, seg);
1517 XLogFileName(path, log, seg);
1522 * Prefer link() to rename() here just to be really sure that we don't
1523 * overwrite an existing logfile. However, there shouldn't be one, so
1524 * rename() is an acceptable substitute except for the truly paranoid.
1526 #if HAVE_WORKING_LINK
1527 if (link(tmppath, path) < 0)
1529 (errcode_for_file_access(),
1530 errmsg("link from \"%s\" to \"%s\" (initialization of log file %u, segment %u) failed: %m",
1531 tmppath, path, log, seg)));
1534 if (rename(tmppath, path) < 0)
1536 (errcode_for_file_access(),
1537 errmsg("rename from \"%s\" to \"%s\" (initialization of log file %u, segment %u) failed: %m",
1538 tmppath, path, log, seg)));
1542 LWLockRelease(ControlFileLock);
1548 * Open a pre-existing logfile segment.
1551 XLogFileOpen(uint32 log, uint32 seg, bool econt)
1553 char path[MAXPGPATH];
1556 XLogFileName(path, log, seg);
1558 fd = BasicOpenFile(path, O_RDWR | PG_BINARY | XLOG_SYNC_BIT,
1562 if (econt && errno == ENOENT)
1565 (errcode_for_file_access(),
1566 errmsg("open of \"%s\" (log file %u, segment %u) failed: %m",
1571 (errcode_for_file_access(),
1572 errmsg("open of \"%s\" (log file %u, segment %u) failed: %m",
1580 * Preallocate log files beyond the specified log endpoint, according to
1581 * the XLOGfile user parameter.
1584 PreallocXlogFiles(XLogRecPtr endptr)
1591 XLByteToPrevSeg(endptr, _logId, _logSeg);
1592 if ((endptr.xrecoff - 1) % XLogSegSize >=
1593 (uint32) (0.75 * XLogSegSize))
1595 NextLogSeg(_logId, _logSeg);
1596 use_existent = true;
1597 lf = XLogFileInit(_logId, _logSeg, &use_existent, true);
1603 * Remove or move offline all log files older or equal to passed log/seg#
1605 * endptr is current (or recent) end of xlog; this is used to determine
1606 * whether we want to recycle rather than delete no-longer-wanted log files.
1609 MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr)
1614 struct dirent *xlde;
1616 char path[MAXPGPATH];
1618 XLByteToPrevSeg(endptr, endlogId, endlogSeg);
1620 xldir = opendir(XLogDir);
1623 (errcode_for_file_access(),
1624 errmsg("could not open transaction log directory \"%s\": %m",
1627 sprintf(lastoff, "%08X%08X", log, seg);
1630 while ((xlde = readdir(xldir)) != NULL)
1632 if (strlen(xlde->d_name) == 16 &&
1633 strspn(xlde->d_name, "0123456789ABCDEF") == 16 &&
1634 strcmp(xlde->d_name, lastoff) <= 0)
1636 snprintf(path, MAXPGPATH, "%s/%s", XLogDir, xlde->d_name);
1637 if (XLOG_archive_dir[0])
1640 (errmsg("archiving transaction log file \"%s\"",
1642 elog(WARNING, "archiving log files is not implemented");
1647 * Before deleting the file, see if it can be recycled as
1648 * a future log segment. We allow recycling segments up
1649 * to XLOGfileslop segments beyond the current XLOG
1652 if (InstallXLogFileSegment(endlogId, endlogSeg, path,
1657 (errmsg("recycled transaction log file \"%s\"",
1662 /* No need for any more future segments... */
1664 (errmsg("removing transaction log file \"%s\"",
1674 (errcode_for_file_access(),
1675 errmsg("could not read transaction log directory \"%s\": %m",
1681 * Restore the backup blocks present in an XLOG record, if any.
1683 * We assume all of the record has been read into memory at *record.
1686 RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
1695 blk = (char *) XLogRecGetData(record) + record->xl_len;
1696 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
1698 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
1701 memcpy((char *) &bkpb, blk, sizeof(BkpBlock));
1702 blk += sizeof(BkpBlock);
1704 reln = XLogOpenRelation(true, record->xl_rmid, bkpb.node);
1708 buffer = XLogReadBuffer(true, reln, bkpb.block);
1709 if (BufferIsValid(buffer))
1711 page = (Page) BufferGetPage(buffer);
1712 memcpy((char *) page, blk, BLCKSZ);
1713 PageSetLSN(page, lsn);
1714 PageSetSUI(page, ThisStartUpID);
1715 UnlockAndWriteBuffer(buffer);
1724 * CRC-check an XLOG record. We do not believe the contents of an XLOG
1725 * record (other than to the minimal extent of computing the amount of
1726 * data to read in) until we've checked the CRCs.
1728 * We assume all of the record has been read into memory at *record.
1731 RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
1736 uint32 len = record->xl_len;
1739 /* Check CRC of rmgr data and record header */
1741 COMP_CRC64(crc, XLogRecGetData(record), len);
1742 COMP_CRC64(crc, (char *) record + sizeof(crc64),
1743 SizeOfXLogRecord - sizeof(crc64));
1746 if (!EQ_CRC64(record->xl_crc, crc))
1749 (errmsg("bad resource manager data checksum in record at %X/%X",
1750 recptr.xlogid, recptr.xrecoff)));
1754 /* Check CRCs of backup blocks, if any */
1755 blk = (char *) XLogRecGetData(record) + len;
1756 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
1758 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
1762 COMP_CRC64(crc, blk + sizeof(BkpBlock), BLCKSZ);
1763 COMP_CRC64(crc, blk + sizeof(crc64),
1764 sizeof(BkpBlock) - sizeof(crc64));
1766 memcpy((char *) &cbuf, blk, sizeof(crc64)); /* don't assume
1769 if (!EQ_CRC64(cbuf, crc))
1772 (errmsg("bad checksum of backup block %d in record at %X/%X",
1773 i + 1, recptr.xlogid, recptr.xrecoff)));
1776 blk += sizeof(BkpBlock) + BLCKSZ;
1783 * Attempt to read an XLOG record.
1785 * If RecPtr is not NULL, try to read a record at that position. Otherwise
1786 * try to read a record just after the last one previously read.
1788 * If no valid record is available, returns NULL, or fails if emode is PANIC.
1789 * (emode must be either PANIC or LOG.)
1791 * buffer is a workspace at least _INTL_MAXLOGRECSZ bytes long. It is needed
1792 * to reassemble a record that crosses block boundaries. Note that on
1793 * successful return, the returned record pointer always points at buffer.
1796 ReadRecord(XLogRecPtr *RecPtr, int emode, char *buffer)
1799 XLogRecPtr tmpRecPtr = EndRecPtr;
1802 uint32 targetPageOff;
1804 bool nextmode = false;
1806 if (readBuf == NULL)
1809 * First time through, permanently allocate readBuf. We do it
1810 * this way, rather than just making a static array, for two
1811 * reasons: (1) no need to waste the storage in most
1812 * instantiations of the backend; (2) a static char array isn't
1813 * guaranteed to have any particular alignment, whereas malloc()
1814 * will provide MAXALIGN'd storage.
1816 readBuf = (char *) malloc(BLCKSZ);
1817 Assert(readBuf != NULL);
1822 RecPtr = &tmpRecPtr;
1824 /* fast case if next record is on same page */
1825 if (nextRecord != NULL)
1827 record = nextRecord;
1830 /* align old recptr to next page */
1831 if (tmpRecPtr.xrecoff % BLCKSZ != 0)
1832 tmpRecPtr.xrecoff += (BLCKSZ - tmpRecPtr.xrecoff % BLCKSZ);
1833 if (tmpRecPtr.xrecoff >= XLogFileSize)
1835 (tmpRecPtr.xlogid)++;
1836 tmpRecPtr.xrecoff = 0;
1838 tmpRecPtr.xrecoff += SizeOfXLogPHD;
1840 else if (!XRecOffIsValid(RecPtr->xrecoff))
1842 (errmsg("invalid record offset at %X/%X",
1843 RecPtr->xlogid, RecPtr->xrecoff)));
1845 if (readFile >= 0 && !XLByteInSeg(*RecPtr, readId, readSeg))
1850 XLByteToSeg(*RecPtr, readId, readSeg);
1853 readFile = XLogFileOpen(readId, readSeg, (emode == LOG));
1855 goto next_record_is_invalid;
1856 readOff = (uint32) (-1); /* force read to occur below */
1859 targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / BLCKSZ) * BLCKSZ;
1860 if (readOff != targetPageOff)
1862 readOff = targetPageOff;
1863 if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
1866 (errcode_for_file_access(),
1867 errmsg("lseek of log file %u, segment %u, offset %u failed: %m",
1868 readId, readSeg, readOff)));
1869 goto next_record_is_invalid;
1871 if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
1874 (errcode_for_file_access(),
1875 errmsg("read of log file %u, segment %u, offset %u failed: %m",
1876 readId, readSeg, readOff)));
1877 goto next_record_is_invalid;
1879 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode, nextmode))
1880 goto next_record_is_invalid;
1882 if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
1883 RecPtr->xrecoff % BLCKSZ == SizeOfXLogPHD)
1886 (errmsg("contrecord is requested by %X/%X",
1887 RecPtr->xlogid, RecPtr->xrecoff)));
1888 goto next_record_is_invalid;
1890 record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % BLCKSZ);
1895 * Currently, xl_len == 0 must be bad data, but that might not be true
1896 * forever. See note in XLogInsert.
1898 if (record->xl_len == 0)
1901 (errmsg("record with zero length at %X/%X",
1902 RecPtr->xlogid, RecPtr->xrecoff)));
1903 goto next_record_is_invalid;
1907 * Compute total length of record including any appended backup
1910 total_len = SizeOfXLogRecord + record->xl_len;
1911 for (i = 0; i < XLR_MAX_BKP_BLOCKS; i++)
1913 if (!(record->xl_info & XLR_SET_BKP_BLOCK(i)))
1915 total_len += sizeof(BkpBlock) + BLCKSZ;
1919 * Make sure it will fit in buffer (currently, it is mechanically
1920 * impossible for this test to fail, but it seems like a good idea
1923 if (total_len > _INTL_MAXLOGRECSZ)
1926 (errmsg("record length %u at %X/%X too long",
1927 total_len, RecPtr->xlogid, RecPtr->xrecoff)));
1928 goto next_record_is_invalid;
1930 if (record->xl_rmid > RM_MAX_ID)
1933 (errmsg("invalid resource manager id %u at %X/%X",
1934 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff)));
1935 goto next_record_is_invalid;
1938 len = BLCKSZ - RecPtr->xrecoff % BLCKSZ;
1939 if (total_len > len)
1941 /* Need to reassemble record */
1942 XLogContRecord *contrecord;
1943 uint32 gotlen = len;
1945 memcpy(buffer, record, len);
1946 record = (XLogRecord *) buffer;
1951 if (readOff >= XLogSegSize)
1955 NextLogSeg(readId, readSeg);
1956 readFile = XLogFileOpen(readId, readSeg, (emode == LOG));
1958 goto next_record_is_invalid;
1961 if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
1964 (errcode_for_file_access(),
1965 errmsg("read of log file %u, segment %u, offset %u failed: %m",
1966 readId, readSeg, readOff)));
1967 goto next_record_is_invalid;
1969 if (!ValidXLOGHeader((XLogPageHeader) readBuf, emode, true))
1970 goto next_record_is_invalid;
1971 if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD))
1974 (errmsg("there is no contrecord flag in log file %u, segment %u, offset %u",
1975 readId, readSeg, readOff)));
1976 goto next_record_is_invalid;
1978 contrecord = (XLogContRecord *) ((char *) readBuf + SizeOfXLogPHD);
1979 if (contrecord->xl_rem_len == 0 ||
1980 total_len != (contrecord->xl_rem_len + gotlen))
1983 (errmsg("invalid contrecord length %u in log file %u, segment %u, offset %u",
1984 contrecord->xl_rem_len,
1985 readId, readSeg, readOff)));
1986 goto next_record_is_invalid;
1988 len = BLCKSZ - SizeOfXLogPHD - SizeOfXLogContRecord;
1989 if (contrecord->xl_rem_len > len)
1991 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord, len);
1996 memcpy(buffer, (char *) contrecord + SizeOfXLogContRecord,
1997 contrecord->xl_rem_len);
2000 if (!RecordIsValid(record, *RecPtr, emode))
2001 goto next_record_is_invalid;
2002 if (BLCKSZ - SizeOfXLogRecord >= SizeOfXLogPHD +
2003 SizeOfXLogContRecord + MAXALIGN(contrecord->xl_rem_len))
2005 nextRecord = (XLogRecord *) ((char *) contrecord +
2006 SizeOfXLogContRecord + MAXALIGN(contrecord->xl_rem_len));
2008 EndRecPtr.xlogid = readId;
2009 EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff +
2010 SizeOfXLogPHD + SizeOfXLogContRecord +
2011 MAXALIGN(contrecord->xl_rem_len);
2012 ReadRecPtr = *RecPtr;
2016 /* Record does not cross a page boundary */
2017 if (!RecordIsValid(record, *RecPtr, emode))
2018 goto next_record_is_invalid;
2019 if (BLCKSZ - SizeOfXLogRecord >= RecPtr->xrecoff % BLCKSZ +
2020 MAXALIGN(total_len))
2021 nextRecord = (XLogRecord *) ((char *) record + MAXALIGN(total_len));
2022 EndRecPtr.xlogid = RecPtr->xlogid;
2023 EndRecPtr.xrecoff = RecPtr->xrecoff + MAXALIGN(total_len);
2024 ReadRecPtr = *RecPtr;
2025 memcpy(buffer, record, total_len);
2026 return (XLogRecord *) buffer;
2028 next_record_is_invalid:;
2036 * Check whether the xlog header of a page just read in looks valid.
2038 * This is just a convenience subroutine to avoid duplicated code in
2039 * ReadRecord. It's not intended for use from anywhere else.
2042 ValidXLOGHeader(XLogPageHeader hdr, int emode, bool checkSUI)
2046 if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
2049 (errmsg("invalid magic number %04X in log file %u, segment %u, offset %u",
2050 hdr->xlp_magic, readId, readSeg, readOff)));
2053 if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
2056 (errmsg("invalid info bits %04X in log file %u, segment %u, offset %u",
2057 hdr->xlp_info, readId, readSeg, readOff)));
2060 recaddr.xlogid = readId;
2061 recaddr.xrecoff = readSeg * XLogSegSize + readOff;
2062 if (!XLByteEQ(hdr->xlp_pageaddr, recaddr))
2065 (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u",
2066 hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff,
2067 readId, readSeg, readOff)));
2072 * We disbelieve a SUI less than the previous page's SUI, or more than
2073 * a few counts greater. In theory as many as 512 shutdown checkpoint
2074 * records could appear on a 32K-sized xlog page, so that's the most
2075 * differential there could legitimately be.
2077 * Note this check can only be applied when we are reading the next page
2078 * in sequence, so ReadRecord passes a flag indicating whether to
2083 if (hdr->xlp_sui < lastReadSUI ||
2084 hdr->xlp_sui > lastReadSUI + 512)
2087 /* translator: SUI = startup id */
2088 (errmsg("out-of-sequence SUI %u (after %u) in log file %u, segment %u, offset %u",
2089 hdr->xlp_sui, lastReadSUI,
2090 readId, readSeg, readOff)));
2094 lastReadSUI = hdr->xlp_sui;
2099 * I/O routines for pg_control
2101 * *ControlFile is a buffer in shared memory that holds an image of the
2102 * contents of pg_control. WriteControlFile() initializes pg_control
2103 * given a preloaded buffer, ReadControlFile() loads the buffer from
2104 * the pg_control file (during postmaster or standalone-backend startup),
2105 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
2107 * For simplicity, WriteControlFile() initializes the fields of pg_control
2108 * that are related to checking backend/database compatibility, and
2109 * ReadControlFile() verifies they are correct. We could split out the
2110 * I/O and compatibility-check functions, but there seems no need currently.
2116 /* Init XLOG file paths */
2117 snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
2118 snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
2122 WriteControlFile(void)
2125 char buffer[BLCKSZ]; /* need not be aligned */
2129 * Initialize version and compatibility-check fields
2131 ControlFile->pg_control_version = PG_CONTROL_VERSION;
2132 ControlFile->catalog_version_no = CATALOG_VERSION_NO;
2133 ControlFile->blcksz = BLCKSZ;
2134 ControlFile->relseg_size = RELSEG_SIZE;
2136 ControlFile->nameDataLen = NAMEDATALEN;
2137 ControlFile->funcMaxArgs = FUNC_MAX_ARGS;
2139 #ifdef HAVE_INT64_TIMESTAMP
2140 ControlFile->enableIntTimes = TRUE;
2142 ControlFile->enableIntTimes = FALSE;
2145 ControlFile->localeBuflen = LOCALE_NAME_BUFLEN;
2146 localeptr = setlocale(LC_COLLATE, NULL);
2149 (errmsg("invalid LC_COLLATE setting")));
2150 StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
2151 localeptr = setlocale(LC_CTYPE, NULL);
2154 (errmsg("invalid LC_CTYPE setting")));
2155 StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
2157 /* Contents are protected with a CRC */
2158 INIT_CRC64(ControlFile->crc);
2159 COMP_CRC64(ControlFile->crc,
2160 (char *) ControlFile + sizeof(crc64),
2161 sizeof(ControlFileData) - sizeof(crc64));
2162 FIN_CRC64(ControlFile->crc);
2165 * We write out BLCKSZ bytes into pg_control, zero-padding the excess
2166 * over sizeof(ControlFileData). This reduces the odds of
2167 * premature-EOF errors when reading pg_control. We'll still fail
2168 * when we check the contents of the file, but hopefully with a more
2169 * specific error than "couldn't read pg_control".
2171 if (sizeof(ControlFileData) > BLCKSZ)
2173 (errmsg("sizeof(ControlFileData) is larger than BLCKSZ; fix either one")));
2175 memset(buffer, 0, BLCKSZ);
2176 memcpy(buffer, ControlFile, sizeof(ControlFileData));
2178 fd = BasicOpenFile(ControlFilePath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
2182 (errcode_for_file_access(),
2183 errmsg("could not create control file \"%s\": %m",
2187 if (write(fd, buffer, BLCKSZ) != BLCKSZ)
2189 /* if write didn't set errno, assume problem is no disk space */
2193 (errcode_for_file_access(),
2194 errmsg("write to control file failed: %m")));
2197 if (pg_fsync(fd) != 0)
2199 (errcode_for_file_access(),
2200 errmsg("fsync of control file failed: %m")));
2206 ReadControlFile(void)
2214 fd = BasicOpenFile(ControlFilePath, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
2217 (errcode_for_file_access(),
2218 errmsg("could not open control file \"%s\": %m",
2221 if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
2223 (errcode_for_file_access(),
2224 errmsg("read from control file failed: %m")));
2229 * Check for expected pg_control format version. If this is wrong,
2230 * the CRC check will likely fail because we'll be checking the wrong
2231 * number of bytes. Complaining about wrong version will probably be
2232 * more enlightening than complaining about wrong CRC.
2234 if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
2236 (errmsg("database files are incompatible with server"),
2237 errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d,"
2238 " but the server was compiled with PG_CONTROL_VERSION %d.",
2239 ControlFile->pg_control_version, PG_CONTROL_VERSION),
2240 errhint("It looks like you need to initdb.")));
2241 /* Now check the CRC. */
2244 (char *) ControlFile + sizeof(crc64),
2245 sizeof(ControlFileData) - sizeof(crc64));
2248 if (!EQ_CRC64(crc, ControlFile->crc))
2250 (errmsg("invalid checksum in control file")));
2253 * Do compatibility checking immediately. We do this here for 2
2256 * (1) if the database isn't compatible with the backend executable, we
2257 * want to abort before we can possibly do any damage;
2259 * (2) this code is executed in the postmaster, so the setlocale() will
2260 * propagate to forked backends, which aren't going to read this file
2261 * for themselves. (These locale settings are considered critical
2262 * compatibility items because they can affect sort order of indexes.)
2264 if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
2266 (errmsg("database files are incompatible with server"),
2267 errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d,"
2268 " but the server was compiled with CATALOG_VERSION_NO %d.",
2269 ControlFile->catalog_version_no, CATALOG_VERSION_NO),
2270 errhint("It looks like you need to initdb.")));
2271 if (ControlFile->blcksz != BLCKSZ)
2273 (errmsg("database files are incompatible with server"),
2274 errdetail("The database cluster was initialized with BLCKSZ %d,"
2275 " but the server was compiled with BLCKSZ %d.",
2276 ControlFile->blcksz, BLCKSZ),
2277 errhint("It looks like you need to recompile or initdb.")));
2278 if (ControlFile->relseg_size != RELSEG_SIZE)
2280 (errmsg("database files are incompatible with server"),
2281 errdetail("The database cluster was initialized with RELSEG_SIZE %d,"
2282 " but the server was compiled with RELSEG_SIZE %d.",
2283 ControlFile->relseg_size, RELSEG_SIZE),
2284 errhint("It looks like you need to recompile or initdb.")));
2285 if (ControlFile->nameDataLen != NAMEDATALEN)
2287 (errmsg("database files are incompatible with server"),
2288 errdetail("The database cluster was initialized with NAMEDATALEN %d,"
2289 " but the server was compiled with NAMEDATALEN %d.",
2290 ControlFile->nameDataLen, NAMEDATALEN),
2291 errhint("It looks like you need to recompile or initdb.")));
2292 if (ControlFile->funcMaxArgs != FUNC_MAX_ARGS)
2294 (errmsg("database files are incompatible with server"),
2295 errdetail("The database cluster was initialized with FUNC_MAX_ARGS %d,"
2296 " but the server was compiled with FUNC_MAX_ARGS %d.",
2297 ControlFile->funcMaxArgs, FUNC_MAX_ARGS),
2298 errhint("It looks like you need to recompile or initdb.")));
2300 #ifdef HAVE_INT64_TIMESTAMP
2301 if (ControlFile->enableIntTimes != TRUE)
2303 (errmsg("database files are incompatible with server"),
2304 errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP"
2305 " but the server was compiled with HAVE_INT64_TIMESTAMP."),
2306 errhint("It looks like you need to recompile or initdb.")));
2308 if (ControlFile->enableIntTimes != FALSE)
2310 (errmsg("database files are incompatible with server"),
2311 errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP"
2312 " but the server was compiled without HAVE_INT64_TIMESTAMP."),
2313 errhint("It looks like you need to recompile or initdb.")));
2316 if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN)
2318 (errmsg("database files are incompatible with server"),
2319 errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d,"
2320 " but the server was compiled with LOCALE_NAME_BUFLEN %d.",
2321 ControlFile->localeBuflen, LOCALE_NAME_BUFLEN),
2322 errhint("It looks like you need to recompile or initdb.")));
2323 if (setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
2325 (errmsg("database files are incompatible with operating system"),
2326 errdetail("The database cluster was initialized with LC_COLLATE \"%s\","
2327 " which is not recognized by setlocale().",
2328 ControlFile->lc_collate),
2329 errhint("It looks like you need to initdb or install locale support.")));
2330 if (setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
2332 (errmsg("database files are incompatible with operating system"),
2333 errdetail("The database cluster was initialized with LC_CTYPE \"%s\","
2334 " which is not recognized by setlocale().",
2335 ControlFile->lc_ctype),
2336 errhint("It looks like you need to initdb or install locale support.")));
2338 /* Make the fixed locale settings visible as GUC variables, too */
2339 SetConfigOption("lc_collate", ControlFile->lc_collate,
2340 PGC_INTERNAL, PGC_S_OVERRIDE);
2341 SetConfigOption("lc_ctype", ControlFile->lc_ctype,
2342 PGC_INTERNAL, PGC_S_OVERRIDE);
2346 UpdateControlFile(void)
2350 INIT_CRC64(ControlFile->crc);
2351 COMP_CRC64(ControlFile->crc,
2352 (char *) ControlFile + sizeof(crc64),
2353 sizeof(ControlFileData) - sizeof(crc64));
2354 FIN_CRC64(ControlFile->crc);
2356 fd = BasicOpenFile(ControlFilePath, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
2359 (errcode_for_file_access(),
2360 errmsg("could not open control file \"%s\": %m",
2364 if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
2366 /* if write didn't set errno, assume problem is no disk space */
2370 (errcode_for_file_access(),
2371 errmsg("write to control file failed: %m")));
2374 if (pg_fsync(fd) != 0)
2376 (errcode_for_file_access(),
2377 errmsg("fsync of control file failed: %m")));
2383 * Initialization of shared memory for XLOG
2389 if (XLOGbuffers < MinXLOGbuffers)
2390 XLOGbuffers = MinXLOGbuffers;
2392 return MAXALIGN(sizeof(XLogCtlData) + sizeof(XLogRecPtr) * XLOGbuffers)
2393 + BLCKSZ * XLOGbuffers +
2394 MAXALIGN(sizeof(ControlFileData));
2402 /* this must agree with space requested by XLOGShmemSize() */
2403 if (XLOGbuffers < MinXLOGbuffers)
2404 XLOGbuffers = MinXLOGbuffers;
2406 XLogCtl = (XLogCtlData *)
2407 ShmemInitStruct("XLOG Ctl",
2408 MAXALIGN(sizeof(XLogCtlData) +
2409 sizeof(XLogRecPtr) * XLOGbuffers)
2410 + BLCKSZ * XLOGbuffers,
2413 ControlFile = (ControlFileData *)
2414 ShmemInitStruct("Control File", sizeof(ControlFileData), &found);
2417 memset(XLogCtl, 0, sizeof(XLogCtlData));
2420 * Since XLogCtlData contains XLogRecPtr fields, its sizeof should be
2421 * a multiple of the alignment for same, so no extra alignment padding
2424 XLogCtl->xlblocks = (XLogRecPtr *)
2425 (((char *) XLogCtl) + sizeof(XLogCtlData));
2426 memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
2429 * Here, on the other hand, we must MAXALIGN to ensure the page
2430 * buffers have worst-case alignment.
2433 ((char *) XLogCtl) + MAXALIGN(sizeof(XLogCtlData) +
2434 sizeof(XLogRecPtr) * XLOGbuffers);
2435 memset(XLogCtl->pages, 0, BLCKSZ * XLOGbuffers);
2438 * Do basic initialization of XLogCtl shared data. (StartupXLOG will
2439 * fill in additional info.)
2441 XLogCtl->XLogCacheByte = BLCKSZ * XLOGbuffers;
2442 XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
2443 XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
2444 SpinLockInit(&XLogCtl->info_lck);
2447 * If we are not in bootstrap mode, pg_control should already exist.
2448 * Read and validate it immediately (see comments in ReadControlFile()
2449 * for the reasons why).
2451 if (!IsBootstrapProcessingMode())
2456 * This func must be called ONCE on system install. It creates pg_control
2457 * and the initial XLOG segment.
2462 CheckPoint checkPoint;
2464 XLogPageHeader page;
2469 /* Use malloc() to ensure buffer is MAXALIGNED */
2470 buffer = (char *) malloc(BLCKSZ);
2471 page = (XLogPageHeader) buffer;
2473 checkPoint.redo.xlogid = 0;
2474 checkPoint.redo.xrecoff = SizeOfXLogPHD;
2475 checkPoint.undo = checkPoint.redo;
2476 checkPoint.ThisStartUpID = 0;
2477 checkPoint.nextXid = FirstNormalTransactionId;
2478 checkPoint.nextOid = BootstrapObjectIdData;
2479 checkPoint.time = time(NULL);
2481 ShmemVariableCache->nextXid = checkPoint.nextXid;
2482 ShmemVariableCache->nextOid = checkPoint.nextOid;
2483 ShmemVariableCache->oidCount = 0;
2485 memset(buffer, 0, BLCKSZ);
2486 page->xlp_magic = XLOG_PAGE_MAGIC;
2488 page->xlp_sui = checkPoint.ThisStartUpID;
2489 page->xlp_pageaddr.xlogid = 0;
2490 page->xlp_pageaddr.xrecoff = 0;
2491 record = (XLogRecord *) ((char *) page + SizeOfXLogPHD);
2492 record->xl_prev.xlogid = 0;
2493 record->xl_prev.xrecoff = 0;
2494 record->xl_xact_prev = record->xl_prev;
2495 record->xl_xid = InvalidTransactionId;
2496 record->xl_len = sizeof(checkPoint);
2497 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
2498 record->xl_rmid = RM_XLOG_ID;
2499 memcpy(XLogRecGetData(record), &checkPoint, sizeof(checkPoint));
2502 COMP_CRC64(crc, &checkPoint, sizeof(checkPoint));
2503 COMP_CRC64(crc, (char *) record + sizeof(crc64),
2504 SizeOfXLogRecord - sizeof(crc64));
2506 record->xl_crc = crc;
2508 use_existent = false;
2509 openLogFile = XLogFileInit(0, 0, &use_existent, false);
2512 if (write(openLogFile, buffer, BLCKSZ) != BLCKSZ)
2514 /* if write didn't set errno, assume problem is no disk space */
2518 (errcode_for_file_access(),
2519 errmsg("failed to write bootstrap xlog file: %m")));
2522 if (pg_fsync(openLogFile) != 0)
2524 (errcode_for_file_access(),
2525 errmsg("failed to fsync bootstrap xlog file: %m")));
2530 memset(ControlFile, 0, sizeof(ControlFileData));
2531 /* Initialize pg_control status fields */
2532 ControlFile->state = DB_SHUTDOWNED;
2533 ControlFile->time = checkPoint.time;
2534 ControlFile->logId = 0;
2535 ControlFile->logSeg = 1;
2536 ControlFile->checkPoint = checkPoint.redo;
2537 ControlFile->checkPointCopy = checkPoint;
2538 /* some additional ControlFile fields are set in WriteControlFile() */
2542 /* Bootstrap the commit log, too */
2547 str_time(time_t tnow)
2549 static char buf[32];
2551 strftime(buf, sizeof(buf),
2552 "%Y-%m-%d %H:%M:%S %Z",
2559 * This must be called ONCE during postmaster or standalone-backend startup
2564 XLogCtlInsert *Insert;
2565 CheckPoint checkPoint;
2575 /* Use malloc() to ensure record buffer is MAXALIGNED */
2576 buffer = (char *) malloc(_INTL_MAXLOGRECSZ);
2581 * Read control file and check XLOG status looks valid.
2583 * Note: in most control paths, *ControlFile is already valid and we need
2584 * not do ReadControlFile() here, but might as well do it to be sure.
2588 if (ControlFile->logSeg == 0 ||
2589 ControlFile->state < DB_SHUTDOWNED ||
2590 ControlFile->state > DB_IN_PRODUCTION ||
2591 !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
2593 (errmsg("control file contains invalid data")));
2595 if (ControlFile->state == DB_SHUTDOWNED)
2597 (errmsg("database system was shut down at %s",
2598 str_time(ControlFile->time))));
2599 else if (ControlFile->state == DB_SHUTDOWNING)
2601 (errmsg("database system shutdown was interrupted at %s",
2602 str_time(ControlFile->time))));
2603 else if (ControlFile->state == DB_IN_RECOVERY)
2605 (errmsg("database system was interrupted while in recovery at %s",
2606 str_time(ControlFile->time)),
2607 errhint("This probably means that some data is corrupted and"
2608 " you will have to use the last backup for recovery.")));
2609 else if (ControlFile->state == DB_IN_PRODUCTION)
2611 (errmsg("database system was interrupted at %s",
2612 str_time(ControlFile->time))));
2614 /* This is just to allow attaching to startup process with a debugger */
2615 #ifdef XLOG_REPLAY_DELAY
2616 if (XLOG_DEBUG && ControlFile->state != DB_SHUTDOWNED)
2621 * Get the last valid checkpoint record. If the latest one according
2622 * to pg_control is broken, try the next-to-last one.
2624 record = ReadCheckpointRecord(ControlFile->checkPoint, 1, buffer);
2627 checkPointLoc = ControlFile->checkPoint;
2629 (errmsg("checkpoint record is at %X/%X",
2630 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
2634 record = ReadCheckpointRecord(ControlFile->prevCheckPoint, 2, buffer);
2637 checkPointLoc = ControlFile->prevCheckPoint;
2639 (errmsg("using previous checkpoint record at %X/%X",
2640 checkPointLoc.xlogid, checkPointLoc.xrecoff)));
2641 InRecovery = true; /* force recovery even if SHUTDOWNED */
2645 (errmsg("could not locate a valid checkpoint record")));
2647 LastRec = RecPtr = checkPointLoc;
2648 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
2649 wasShutdown = (record->xl_info == XLOG_CHECKPOINT_SHUTDOWN);
2652 (errmsg("redo record is at %X/%X; undo record is at %X/%X; shutdown %s",
2653 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
2654 checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
2655 wasShutdown ? "TRUE" : "FALSE")));
2657 (errmsg("next transaction id: %u; next oid: %u",
2658 checkPoint.nextXid, checkPoint.nextOid)));
2659 if (!TransactionIdIsNormal(checkPoint.nextXid))
2661 (errmsg("invalid next transaction id")));
2663 ShmemVariableCache->nextXid = checkPoint.nextXid;
2664 ShmemVariableCache->nextOid = checkPoint.nextOid;
2665 ShmemVariableCache->oidCount = 0;
2668 * If it was a shutdown checkpoint, then any following WAL entries
2669 * were created under the next StartUpID; if it was a regular
2670 * checkpoint then any following WAL entries were created under the
2671 * same StartUpID. We must replay WAL entries using the same StartUpID
2672 * they were created under, so temporarily adopt that SUI (see also
2676 ThisStartUpID = checkPoint.ThisStartUpID + 1;
2678 ThisStartUpID = checkPoint.ThisStartUpID;
2680 RedoRecPtr = XLogCtl->Insert.RedoRecPtr =
2681 XLogCtl->SavedRedoRecPtr = checkPoint.redo;
2683 if (XLByteLT(RecPtr, checkPoint.redo))
2685 (errmsg("invalid redo in checkpoint record")));
2686 if (checkPoint.undo.xrecoff == 0)
2687 checkPoint.undo = RecPtr;
2689 if (XLByteLT(checkPoint.undo, RecPtr) ||
2690 XLByteLT(checkPoint.redo, RecPtr))
2694 (errmsg("invalid redo/undo record in shutdown checkpoint")));
2697 else if (ControlFile->state != DB_SHUTDOWNED)
2706 (errmsg("database system was not properly shut down; "
2707 "automatic recovery in progress")));
2708 ControlFile->state = DB_IN_RECOVERY;
2709 ControlFile->time = time(NULL);
2710 UpdateControlFile();
2712 /* Start up the recovery environment */
2713 XLogInitRelationCache();
2715 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
2717 if (RmgrTable[rmid].rm_startup != NULL)
2718 RmgrTable[rmid].rm_startup();
2721 /* Is REDO required ? */
2722 if (XLByteLT(checkPoint.redo, RecPtr))
2723 record = ReadRecord(&(checkPoint.redo), PANIC, buffer);
2726 /* read past CheckPoint record */
2727 record = ReadRecord(NULL, LOG, buffer);
2734 (errmsg("redo starts at %X/%X",
2735 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
2738 /* nextXid must be beyond record's xid */
2739 if (TransactionIdFollowsOrEquals(record->xl_xid,
2740 ShmemVariableCache->nextXid))
2742 ShmemVariableCache->nextXid = record->xl_xid;
2743 TransactionIdAdvance(ShmemVariableCache->nextXid);
2749 sprintf(buf, "REDO @ %X/%X; LSN %X/%X: ",
2750 ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
2751 EndRecPtr.xlogid, EndRecPtr.xrecoff);
2752 xlog_outrec(buf, record);
2754 RmgrTable[record->xl_rmid].rm_desc(buf,
2755 record->xl_info, XLogRecGetData(record));
2756 elog(LOG, "%s", buf);
2759 if (record->xl_info & XLR_BKP_BLOCK_MASK)
2760 RestoreBkpBlocks(record, EndRecPtr);
2762 RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
2763 record = ReadRecord(NULL, LOG, buffer);
2764 } while (record != NULL);
2766 (errmsg("redo done at %X/%X",
2767 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
2768 LastRec = ReadRecPtr;
2773 (errmsg("redo is not required")));
2777 * Init xlog buffer cache using the block containing the last valid
2778 * record from the previous incarnation.
2780 record = ReadRecord(&LastRec, PANIC, buffer);
2781 EndOfLog = EndRecPtr;
2782 XLByteToPrevSeg(EndOfLog, openLogId, openLogSeg);
2783 openLogFile = XLogFileOpen(openLogId, openLogSeg, false);
2785 ControlFile->logId = openLogId;
2786 ControlFile->logSeg = openLogSeg + 1;
2787 Insert = &XLogCtl->Insert;
2788 Insert->PrevRecord = LastRec;
2789 XLogCtl->xlblocks[0].xlogid = openLogId;
2790 XLogCtl->xlblocks[0].xrecoff =
2791 ((EndOfLog.xrecoff - 1) / BLCKSZ + 1) * BLCKSZ;
2794 * Tricky point here: readBuf contains the *last* block that the
2795 * LastRec record spans, not the one it starts in. The last block is
2796 * indeed the one we want to use.
2798 Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - BLCKSZ) % XLogSegSize);
2799 memcpy((char *) Insert->currpage, readBuf, BLCKSZ);
2800 Insert->currpos = (char *) Insert->currpage +
2801 (EndOfLog.xrecoff + BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
2803 LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;
2805 XLogCtl->Write.LogwrtResult = LogwrtResult;
2806 Insert->LogwrtResult = LogwrtResult;
2807 XLogCtl->LogwrtResult = LogwrtResult;
2809 XLogCtl->LogwrtRqst.Write = EndOfLog;
2810 XLogCtl->LogwrtRqst.Flush = EndOfLog;
2812 freespace = INSERT_FREESPACE(Insert);
2815 /* Make sure rest of page is zero */
2816 MemSet(Insert->currpos, 0, freespace);
2817 XLogCtl->Write.curridx = 0;
2822 * Whenever Write.LogwrtResult points to exactly the end of a
2823 * page, Write.curridx must point to the *next* page (see
2826 * Note: it might seem we should do AdvanceXLInsertBuffer() here, but
2827 * we can't since we haven't yet determined the correct StartUpID
2828 * to put into the new page's header. The first actual attempt to
2829 * insert a log record will advance the insert state.
2831 XLogCtl->Write.curridx = NextBufIdx(0);
2838 RecPtr = ReadRecPtr;
2839 if (XLByteLT(checkPoint.undo, RecPtr))
2842 (errmsg("undo starts at %X/%X",
2843 RecPtr.xlogid, RecPtr.xrecoff)));
2846 record = ReadRecord(&RecPtr, PANIC, buffer);
2847 if (TransactionIdIsValid(record->xl_xid) &&
2848 !TransactionIdDidCommit(record->xl_xid))
2849 RmgrTable[record->xl_rmid].rm_undo(EndRecPtr, record);
2850 RecPtr = record->xl_prev;
2851 } while (XLByteLE(checkPoint.undo, RecPtr));
2853 (errmsg("undo done at %X/%X",
2854 ReadRecPtr.xlogid, ReadRecPtr.xrecoff)));
2858 (errmsg("undo is not required")));
2867 * Allow resource managers to do any required cleanup.
2869 for (rmid = 0; rmid <= RM_MAX_ID; rmid++)
2871 if (RmgrTable[rmid].rm_cleanup != NULL)
2872 RmgrTable[rmid].rm_cleanup();
2875 /* suppress in-transaction check in CreateCheckPoint */
2876 MyLastRecPtr.xrecoff = 0;
2877 MyXactMadeXLogEntry = false;
2878 MyXactMadeTempRelUpdate = false;
2881 * At this point, ThisStartUpID is the largest SUI that we could
2882 * find evidence for in the WAL entries. But check it against
2883 * pg_control's latest checkpoint, to make sure that we can't
2884 * accidentally re-use an already-used SUI.
2886 if (ThisStartUpID < ControlFile->checkPointCopy.ThisStartUpID)
2887 ThisStartUpID = ControlFile->checkPointCopy.ThisStartUpID;
2890 * Perform a new checkpoint to update our recovery activity to
2893 * Note that we write a shutdown checkpoint. This is correct since
2894 * the records following it will use SUI one more than what is
2895 * shown in the checkpoint's ThisStartUpID.
2897 * In case we had to use the secondary checkpoint, make sure that it
2898 * will still be shown as the secondary checkpoint after this
2899 * CreateCheckPoint operation; we don't want the broken primary
2900 * checkpoint to become prevCheckPoint...
2902 ControlFile->checkPoint = checkPointLoc;
2903 CreateCheckPoint(true, true);
2906 * Close down recovery environment
2908 XLogCloseRelationCache();
2913 * If we are not doing recovery, then we saw a checkpoint with
2914 * nothing after it, and we can safely use StartUpID equal to one
2915 * more than the checkpoint's SUI. But just for paranoia's sake,
2916 * check against pg_control too.
2918 ThisStartUpID = checkPoint.ThisStartUpID;
2919 if (ThisStartUpID < ControlFile->checkPointCopy.ThisStartUpID)
2920 ThisStartUpID = ControlFile->checkPointCopy.ThisStartUpID;
2924 * Preallocate additional log files, if wanted.
2926 PreallocXlogFiles(EndOfLog);
2929 * Advance StartUpID to one more than the highest value used
2933 XLogCtl->ThisStartUpID = ThisStartUpID;
2936 * Okay, we're officially UP.
2940 ControlFile->state = DB_IN_PRODUCTION;
2941 ControlFile->time = time(NULL);
2942 UpdateControlFile();
2944 /* Start up the commit log, too */
2948 (errmsg("database system is ready")));
2951 /* Shut down readFile facility, free space */
2967 * Subroutine to try to fetch and validate a prior checkpoint record.
2968 * whichChkpt = 1 for "primary", 2 for "secondary", merely informative
2971 ReadCheckpointRecord(XLogRecPtr RecPtr,
2977 if (!XRecOffIsValid(RecPtr.xrecoff))
2980 /* translator: %s is "primary" or "secondary" */
2981 (errmsg("invalid %s checkpoint link in control file",
2982 (whichChkpt == 1) ? gettext("primary") : gettext("secondary"))));
2986 record = ReadRecord(&RecPtr, LOG, buffer);
2991 /* translator: %s is "primary" or "secondary" */
2992 (errmsg("invalid %s checkpoint record",
2993 (whichChkpt == 1) ? gettext("primary") : gettext("secondary"))));
2996 if (record->xl_rmid != RM_XLOG_ID)
2999 /* translator: %s is "primary" or "secondary" */
3000 (errmsg("invalid resource manager id in %s checkpoint record",
3001 (whichChkpt == 1) ? gettext("primary") : gettext("secondary"))));
3004 if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN &&
3005 record->xl_info != XLOG_CHECKPOINT_ONLINE)
3008 /* translator: %s is "primary" or "secondary" */
3009 (errmsg("invalid xl_info in %s checkpoint record",
3010 (whichChkpt == 1) ? gettext("primary") : gettext("secondary"))));
3013 if (record->xl_len != sizeof(CheckPoint))
3016 /* translator: %s is "primary" or "secondary" */
3017 (errmsg("invalid length of %s checkpoint record",
3018 (whichChkpt == 1) ? gettext("primary") : gettext("secondary"))));
3025 * Postmaster uses this to initialize ThisStartUpID & RedoRecPtr from
3026 * XLogCtlData located in shmem after successful startup.
3029 SetThisStartUpID(void)
3031 ThisStartUpID = XLogCtl->ThisStartUpID;
3032 RedoRecPtr = XLogCtl->SavedRedoRecPtr;
3036 * CheckPoint process called by postmaster saves copy of new RedoRecPtr
3037 * in shmem (using SetSavedRedoRecPtr). When checkpointer completes,
3038 * postmaster calls GetSavedRedoRecPtr to update its own copy of RedoRecPtr,
3039 * so that subsequently-spawned backends will start out with a reasonably
3040 * up-to-date local RedoRecPtr. Since these operations are not protected by
3041 * any lock and copying an XLogRecPtr isn't atomic, it's unsafe to use either
3042 * of these routines at other times!
3045 SetSavedRedoRecPtr(void)
3047 XLogCtl->SavedRedoRecPtr = RedoRecPtr;
3051 GetSavedRedoRecPtr(void)
3053 RedoRecPtr = XLogCtl->SavedRedoRecPtr;
3057 * Once spawned, a backend may update its local RedoRecPtr from
3058 * XLogCtl->Insert.RedoRecPtr; it must hold the insert lock or info_lck
3059 * to do so. This is done in XLogInsert() or GetRedoRecPtr().
3064 /* use volatile pointer to prevent code rearrangement */
3065 volatile XLogCtlData *xlogctl = XLogCtl;
3067 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
3068 Assert(XLByteLE(RedoRecPtr, xlogctl->Insert.RedoRecPtr));
3069 RedoRecPtr = xlogctl->Insert.RedoRecPtr;
3070 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
3076 * This must be called ONCE during postmaster or standalone-backend shutdown
3082 (errmsg("shutting down")));
3084 /* suppress in-transaction check in CreateCheckPoint */
3085 MyLastRecPtr.xrecoff = 0;
3086 MyXactMadeXLogEntry = false;
3087 MyXactMadeTempRelUpdate = false;
3090 CreateDummyCaches();
3091 CreateCheckPoint(true, true);
3096 (errmsg("database system is shut down")));
3100 * Perform a checkpoint --- either during shutdown, or on-the-fly
3102 * If force is true, we force a checkpoint regardless of whether any XLOG
3103 * activity has occurred since the last one.
3106 CreateCheckPoint(bool shutdown, bool force)
3108 CheckPoint checkPoint;
3110 XLogCtlInsert *Insert = &XLogCtl->Insert;
3116 if (MyXactMadeXLogEntry)
3118 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3119 errmsg("checkpoint cannot be made inside transaction block")));
3122 * Acquire CheckpointLock to ensure only one checkpoint happens at a
3125 * The CheckpointLock can be held for quite a while, which is not good
3126 * because we won't respond to a cancel/die request while waiting for
3127 * an LWLock. (But the alternative of using a regular lock won't work
3128 * for background checkpoint processes, which are not regular
3129 * backends.) So, rather than use a plain LWLockAcquire, use this
3130 * kluge to allow an interrupt to be accepted while we are waiting:
3132 while (!LWLockConditionalAcquire(CheckpointLock, LW_EXCLUSIVE))
3134 CHECK_FOR_INTERRUPTS();
3139 * Use a critical section to force system panic if we have trouble.
3141 START_CRIT_SECTION();
3145 ControlFile->state = DB_SHUTDOWNING;
3146 ControlFile->time = time(NULL);
3147 UpdateControlFile();
3150 MemSet(&checkPoint, 0, sizeof(checkPoint));
3151 checkPoint.ThisStartUpID = ThisStartUpID;
3152 checkPoint.time = time(NULL);
3154 LWLockAcquire(WALInsertLock, LW_EXCLUSIVE);
3157 * If this isn't a shutdown or forced checkpoint, and we have not
3158 * inserted any XLOG records since the start of the last checkpoint,
3159 * skip the checkpoint. The idea here is to avoid inserting duplicate
3160 * checkpoints when the system is idle. That wastes log space, and
3161 * more importantly it exposes us to possible loss of both current and
3162 * previous checkpoint records if the machine crashes just as we're
3163 * writing the update. (Perhaps it'd make even more sense to
3164 * checkpoint only when the previous checkpoint record is in a
3165 * different xlog page?)
3167 * We have to make two tests to determine that nothing has happened since
3168 * the start of the last checkpoint: current insertion point must
3169 * match the end of the last checkpoint record, and its redo pointer
3170 * must point to itself.
3172 if (!shutdown && !force)
3174 XLogRecPtr curInsert;
3176 INSERT_RECPTR(curInsert, Insert, Insert->curridx);
3177 if (curInsert.xlogid == ControlFile->checkPoint.xlogid &&
3178 curInsert.xrecoff == ControlFile->checkPoint.xrecoff +
3179 MAXALIGN(SizeOfXLogRecord + sizeof(CheckPoint)) &&
3180 ControlFile->checkPoint.xlogid ==
3181 ControlFile->checkPointCopy.redo.xlogid &&
3182 ControlFile->checkPoint.xrecoff ==
3183 ControlFile->checkPointCopy.redo.xrecoff)
3185 LWLockRelease(WALInsertLock);
3186 LWLockRelease(CheckpointLock);
3193 * Compute new REDO record ptr = location of next XLOG record.
3195 * NB: this is NOT necessarily where the checkpoint record itself will
3196 * be, since other backends may insert more XLOG records while we're
3197 * off doing the buffer flush work. Those XLOG records are logically
3198 * after the checkpoint, even though physically before it. Got that?
3200 freespace = INSERT_FREESPACE(Insert);
3201 if (freespace < SizeOfXLogRecord)
3203 (void) AdvanceXLInsertBuffer();
3204 /* OK to ignore update return flag, since we will do flush anyway */
3205 freespace = BLCKSZ - SizeOfXLogPHD;
3207 INSERT_RECPTR(checkPoint.redo, Insert, Insert->curridx);
3210 * Here we update the shared RedoRecPtr for future XLogInsert calls;
3211 * this must be done while holding the insert lock AND the info_lck.
3213 * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
3214 * pointing past where it really needs to point. This is okay; the
3215 * only consequence is that XLogInsert might back up whole buffers
3216 * that it didn't really need to. We can't postpone advancing
3217 * RedoRecPtr because XLogInserts that happen while we are dumping
3218 * buffers must assume that their buffer changes are not included in
3222 /* use volatile pointer to prevent code rearrangement */
3223 volatile XLogCtlData *xlogctl = XLogCtl;
3225 SpinLockAcquire_NoHoldoff(&xlogctl->info_lck);
3226 RedoRecPtr = xlogctl->Insert.RedoRecPtr = checkPoint.redo;
3227 SpinLockRelease_NoHoldoff(&xlogctl->info_lck);
3231 * Get UNDO record ptr - this is oldest of PGPROC->logRec values. We
3232 * do this while holding insert lock to ensure that we won't miss any
3233 * about-to-commit transactions (UNDO must include all xacts that have
3234 * commits after REDO point).
3236 * XXX temporarily ifdef'd out to avoid three-way deadlock condition:
3237 * GetUndoRecPtr needs to grab SInvalLock to ensure that it is looking
3238 * at a stable set of proc records, but grabbing SInvalLock while
3239 * holding WALInsertLock is no good. GetNewTransactionId may cause a
3240 * WAL record to be written while holding XidGenLock, and
3241 * GetSnapshotData needs to get XidGenLock while holding SInvalLock,
3242 * so there's a risk of deadlock. Need to find a better solution. See
3243 * pgsql-hackers discussion of 17-Dec-01.
3246 checkPoint.undo = GetUndoRecPtr();
3248 if (shutdown && checkPoint.undo.xrecoff != 0)
3249 elog(PANIC, "active transaction while database system is shutting down");
3253 * Now we can release insert lock, allowing other xacts to proceed
3254 * even while we are flushing disk buffers.
3256 LWLockRelease(WALInsertLock);
3259 * Get the other info we need for the checkpoint record.
3261 LWLockAcquire(XidGenLock, LW_SHARED);
3262 checkPoint.nextXid = ShmemVariableCache->nextXid;
3263 LWLockRelease(XidGenLock);
3265 LWLockAcquire(OidGenLock, LW_SHARED);
3266 checkPoint.nextOid = ShmemVariableCache->nextOid;
3268 checkPoint.nextOid += ShmemVariableCache->oidCount;
3269 LWLockRelease(OidGenLock);
3272 * Having constructed the checkpoint record, ensure all shmem disk
3273 * buffers and commit-log buffers are flushed to disk.
3275 * This I/O could fail for various reasons. If so, we will fail to
3276 * complete the checkpoint, but there is no reason to force a system
3277 * panic. Accordingly, exit critical section while doing it.
3284 START_CRIT_SECTION();
3287 * Now insert the checkpoint record into XLOG.
3289 rdata.buffer = InvalidBuffer;
3290 rdata.data = (char *) (&checkPoint);
3291 rdata.len = sizeof(checkPoint);
3294 recptr = XLogInsert(RM_XLOG_ID,
3295 shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
3296 XLOG_CHECKPOINT_ONLINE,
3302 * We now have ProcLastRecPtr = start of actual checkpoint record,
3303 * recptr = end of actual checkpoint record.
3305 if (shutdown && !XLByteEQ(checkPoint.redo, ProcLastRecPtr))
3307 (errmsg("concurrent transaction log activity while database system is shutting down")));
3310 * Select point at which we can truncate the log, which we base on the
3311 * prior checkpoint's earliest info.
3313 * With UNDO support: oldest item is redo or undo, whichever is older;
3314 * but watch out for case that undo = 0.
3316 * Without UNDO support: just use the redo pointer. This allows xlog
3317 * space to be freed much faster when there are long-running
3321 if (ControlFile->checkPointCopy.undo.xrecoff != 0 &&
3322 XLByteLT(ControlFile->checkPointCopy.undo,
3323 ControlFile->checkPointCopy.redo))
3324 XLByteToSeg(ControlFile->checkPointCopy.undo, _logId, _logSeg);
3327 XLByteToSeg(ControlFile->checkPointCopy.redo, _logId, _logSeg);
3330 * Update the control file.
3332 LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
3334 ControlFile->state = DB_SHUTDOWNED;
3335 ControlFile->prevCheckPoint = ControlFile->checkPoint;
3336 ControlFile->checkPoint = ProcLastRecPtr;
3337 ControlFile->checkPointCopy = checkPoint;
3338 ControlFile->time = time(NULL);
3339 UpdateControlFile();
3340 LWLockRelease(ControlFileLock);
3343 * We are now done with critical updates; no need for system panic if
3344 * we have trouble while fooling with offline log segments.
3349 * Delete offline log files (those no longer needed even for previous
3352 if (_logId || _logSeg)
3354 PrevLogSeg(_logId, _logSeg);
3355 MoveOfflineLogs(_logId, _logSeg, recptr);
3359 * Make more log segments if needed. (Do this after deleting offline
3360 * log segments, to avoid having peak disk space usage higher than
3364 PreallocXlogFiles(recptr);
3366 LWLockRelease(CheckpointLock);
3370 * Write a NEXTOID log record
3373 XLogPutNextOid(Oid nextOid)
3377 rdata.buffer = InvalidBuffer;
3378 rdata.data = (char *) (&nextOid);
3379 rdata.len = sizeof(Oid);
3381 (void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
3385 * XLOG resource manager's routines
3388 xlog_redo(XLogRecPtr lsn, XLogRecord *record)
3390 uint8 info = record->xl_info & ~XLR_INFO_MASK;
3392 if (info == XLOG_NEXTOID)
3396 memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
3397 if (ShmemVariableCache->nextOid < nextOid)
3399 ShmemVariableCache->nextOid = nextOid;
3400 ShmemVariableCache->oidCount = 0;
3403 else if (info == XLOG_CHECKPOINT_SHUTDOWN)
3405 CheckPoint checkPoint;
3407 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
3408 /* In a SHUTDOWN checkpoint, believe the counters exactly */
3409 ShmemVariableCache->nextXid = checkPoint.nextXid;
3410 ShmemVariableCache->nextOid = checkPoint.nextOid;
3411 ShmemVariableCache->oidCount = 0;
3412 /* Any later WAL records should be run with shutdown SUI plus 1 */
3413 ThisStartUpID = checkPoint.ThisStartUpID + 1;
3415 else if (info == XLOG_CHECKPOINT_ONLINE)
3417 CheckPoint checkPoint;
3419 memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint));
3420 /* In an ONLINE checkpoint, treat the counters like NEXTOID */
3421 if (TransactionIdPrecedes(ShmemVariableCache->nextXid,
3422 checkPoint.nextXid))
3423 ShmemVariableCache->nextXid = checkPoint.nextXid;
3424 if (ShmemVariableCache->nextOid < checkPoint.nextOid)
3426 ShmemVariableCache->nextOid = checkPoint.nextOid;
3427 ShmemVariableCache->oidCount = 0;
3429 /* Any later WAL records should be run with the then-active SUI */
3430 ThisStartUpID = checkPoint.ThisStartUpID;
3435 xlog_undo(XLogRecPtr lsn, XLogRecord *record)
3440 xlog_desc(char *buf, uint8 xl_info, char *rec)
3442 uint8 info = xl_info & ~XLR_INFO_MASK;
3444 if (info == XLOG_CHECKPOINT_SHUTDOWN ||
3445 info == XLOG_CHECKPOINT_ONLINE)
3447 CheckPoint *checkpoint = (CheckPoint *) rec;
3449 sprintf(buf + strlen(buf), "checkpoint: redo %X/%X; undo %X/%X; "
3450 "sui %u; xid %u; oid %u; %s",
3451 checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
3452 checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
3453 checkpoint->ThisStartUpID, checkpoint->nextXid,
3454 checkpoint->nextOid,
3455 (info == XLOG_CHECKPOINT_SHUTDOWN) ? "shutdown" : "online");
3457 else if (info == XLOG_NEXTOID)
3461 memcpy(&nextOid, rec, sizeof(Oid));
3462 sprintf(buf + strlen(buf), "nextOid: %u", nextOid);
3465 strcat(buf, "UNKNOWN");
3469 xlog_outrec(char *buf, XLogRecord *record)
3474 sprintf(buf + strlen(buf), "prev %X/%X; xprev %X/%X; xid %u",
3475 record->xl_prev.xlogid, record->xl_prev.xrecoff,
3476 record->xl_xact_prev.xlogid, record->xl_xact_prev.xrecoff,
3479 for (i = 0, bkpb = 0; i < XLR_MAX_BKP_BLOCKS; i++)
3481 if (!(record->xl_info & (XLR_SET_BKP_BLOCK(i))))
3487 sprintf(buf + strlen(buf), "; bkpb %d", bkpb);
3489 sprintf(buf + strlen(buf), ": %s",
3490 RmgrTable[record->xl_rmid].rm_name);
3498 assign_xlog_sync_method(const char *method, bool doit, bool interactive)
3500 int new_sync_method;
3503 if (strcasecmp(method, "fsync") == 0)
3505 new_sync_method = SYNC_METHOD_FSYNC;
3508 #ifdef HAVE_FDATASYNC
3509 else if (strcasecmp(method, "fdatasync") == 0)
3511 new_sync_method = SYNC_METHOD_FDATASYNC;
3515 #ifdef OPEN_SYNC_FLAG
3516 else if (strcasecmp(method, "open_sync") == 0)
3518 new_sync_method = SYNC_METHOD_OPEN;
3519 new_sync_bit = OPEN_SYNC_FLAG;
3522 #ifdef OPEN_DATASYNC_FLAG
3523 else if (strcasecmp(method, "open_datasync") == 0)
3525 new_sync_method = SYNC_METHOD_OPEN;
3526 new_sync_bit = OPEN_DATASYNC_FLAG;
3535 if (sync_method != new_sync_method || open_sync_bit != new_sync_bit)
3538 * To ensure that no blocks escape unsynced, force an fsync on the
3539 * currently open log segment (if any). Also, if the open flag is
3540 * changing, close the log file so it will be reopened (with new
3541 * flag bit) at next use.
3543 if (openLogFile >= 0)
3545 if (pg_fsync(openLogFile) != 0)
3547 (errcode_for_file_access(),
3548 errmsg("fsync of log file %u, segment %u failed: %m",
3549 openLogId, openLogSeg)));
3550 if (open_sync_bit != new_sync_bit)
3552 if (close(openLogFile) != 0)
3554 (errcode_for_file_access(),
3555 errmsg("close of log file %u, segment %u failed: %m",
3556 openLogId, openLogSeg)));
3560 sync_method = new_sync_method;
3561 open_sync_bit = new_sync_bit;
3569 * Issue appropriate kind of fsync (if any) on the current XLOG output file
3572 issue_xlog_fsync(void)
3574 switch (sync_method)
3576 case SYNC_METHOD_FSYNC:
3577 if (pg_fsync(openLogFile) != 0)
3579 (errcode_for_file_access(),
3580 errmsg("fsync of log file %u, segment %u failed: %m",
3581 openLogId, openLogSeg)));
3583 #ifdef HAVE_FDATASYNC
3584 case SYNC_METHOD_FDATASYNC:
3585 if (pg_fdatasync(openLogFile) != 0)
3587 (errcode_for_file_access(),
3588 errmsg("fdatasync of log file %u, segment %u failed: %m",
3589 openLogId, openLogSeg)));
3592 case SYNC_METHOD_OPEN:
3593 /* write synced it already */
3596 elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);