1 /*-------------------------------------------------------------------------
5 * PostgreSQL transaction log manager utility routines
7 * This file contains support routines that are used by XLOG replay functions.
8 * None of this code is used during normal system operation.
11 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
12 * Portions Copyright (c) 1994, Regents of the University of California
14 * src/backend/access/transam/xlogutils.c
16 *-------------------------------------------------------------------------
20 #include "access/xlog.h"
21 #include "access/xlogutils.h"
22 #include "catalog/catalog.h"
23 #include "storage/smgr.h"
24 #include "utils/guc.h"
25 #include "utils/hsearch.h"
26 #include "utils/rel.h"
30 * During XLOG replay, we may see XLOG records for incremental updates of
31 * pages that no longer exist, because their relation was later dropped or
32 * truncated. (Note: this is only possible when full_page_writes = OFF,
33 * since when it's ON, the first reference we see to a page should always
34 * be a full-page rewrite not an incremental update.) Rather than simply
35 * ignoring such records, we make a note of the referenced page, and then
36 * complain if we don't actually see a drop or truncate covering the page
39 typedef struct xl_invalid_page_key
41 RelFileNode node; /* the relation */
42 ForkNumber forkno; /* the fork number */
43 BlockNumber blkno; /* the page */
44 } xl_invalid_page_key;
46 typedef struct xl_invalid_page
48 xl_invalid_page_key key; /* hash key ... must be first */
49 bool present; /* page existed but contained zeroes */
52 static HTAB *invalid_page_tab = NULL;
55 /* Report a reference to an invalid page */
57 report_invalid_page(int elevel, RelFileNode node, ForkNumber forkno,
58 BlockNumber blkno, bool present)
60 char *path = relpathperm(node, forkno);
63 elog(elevel, "page %u of relation %s is uninitialized",
66 elog(elevel, "page %u of relation %s does not exist",
71 /* Log a reference to an invalid page */
73 log_invalid_page(RelFileNode node, ForkNumber forkno, BlockNumber blkno,
76 xl_invalid_page_key key;
77 xl_invalid_page *hentry;
81 * Once recovery has reached a consistent state, the invalid-page table
82 * should be empty and remain so. If a reference to an invalid page is
83 * found after consistency is reached, PANIC immediately. This might seem
84 * aggressive, but it's better than letting the invalid reference linger
85 * in the hash table until the end of recovery and PANIC there, which
86 * might come only much later if this is a standby server.
88 if (reachedConsistency)
90 report_invalid_page(WARNING, node, forkno, blkno, present);
91 elog(PANIC, "WAL contains references to invalid pages");
95 * Log references to invalid pages at DEBUG1 level. This allows some
96 * tracing of the cause (note the elog context mechanism will tell us
97 * something about the XLOG record that generated the reference).
99 if (log_min_messages <= DEBUG1 || client_min_messages <= DEBUG1)
100 report_invalid_page(DEBUG1, node, forkno, blkno, present);
102 if (invalid_page_tab == NULL)
104 /* create hash table when first needed */
107 memset(&ctl, 0, sizeof(ctl));
108 ctl.keysize = sizeof(xl_invalid_page_key);
109 ctl.entrysize = sizeof(xl_invalid_page);
111 invalid_page_tab = hash_create("XLOG invalid-page table",
114 HASH_ELEM | HASH_BLOBS);
117 /* we currently assume xl_invalid_page_key contains no padding */
121 hentry = (xl_invalid_page *)
122 hash_search(invalid_page_tab, (void *) &key, HASH_ENTER, &found);
126 /* hash_search already filled in the key */
127 hentry->present = present;
131 /* repeat reference ... leave "present" as it was */
135 /* Forget any invalid pages >= minblkno, because they've been dropped */
137 forget_invalid_pages(RelFileNode node, ForkNumber forkno, BlockNumber minblkno)
139 HASH_SEQ_STATUS status;
140 xl_invalid_page *hentry;
142 if (invalid_page_tab == NULL)
143 return; /* nothing to do */
145 hash_seq_init(&status, invalid_page_tab);
147 while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
149 if (RelFileNodeEquals(hentry->key.node, node) &&
150 hentry->key.forkno == forkno &&
151 hentry->key.blkno >= minblkno)
153 if (log_min_messages <= DEBUG2 || client_min_messages <= DEBUG2)
155 char *path = relpathperm(hentry->key.node, forkno);
157 elog(DEBUG2, "page %u of relation %s has been dropped",
158 hentry->key.blkno, path);
162 if (hash_search(invalid_page_tab,
163 (void *) &hentry->key,
164 HASH_REMOVE, NULL) == NULL)
165 elog(ERROR, "hash table corrupted");
170 /* Forget any invalid pages in a whole database */
172 forget_invalid_pages_db(Oid dbid)
174 HASH_SEQ_STATUS status;
175 xl_invalid_page *hentry;
177 if (invalid_page_tab == NULL)
178 return; /* nothing to do */
180 hash_seq_init(&status, invalid_page_tab);
182 while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
184 if (hentry->key.node.dbNode == dbid)
186 if (log_min_messages <= DEBUG2 || client_min_messages <= DEBUG2)
188 char *path = relpathperm(hentry->key.node, hentry->key.forkno);
190 elog(DEBUG2, "page %u of relation %s has been dropped",
191 hentry->key.blkno, path);
195 if (hash_search(invalid_page_tab,
196 (void *) &hentry->key,
197 HASH_REMOVE, NULL) == NULL)
198 elog(ERROR, "hash table corrupted");
203 /* Are there any unresolved references to invalid pages? */
205 XLogHaveInvalidPages(void)
207 if (invalid_page_tab != NULL &&
208 hash_get_num_entries(invalid_page_tab) > 0)
213 /* Complain about any remaining invalid-page entries */
215 XLogCheckInvalidPages(void)
217 HASH_SEQ_STATUS status;
218 xl_invalid_page *hentry;
219 bool foundone = false;
221 if (invalid_page_tab == NULL)
222 return; /* nothing to do */
224 hash_seq_init(&status, invalid_page_tab);
227 * Our strategy is to emit WARNING messages for all remaining entries and
228 * only PANIC after we've dumped all the available info.
230 while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
232 report_invalid_page(WARNING, hentry->key.node, hentry->key.forkno,
233 hentry->key.blkno, hentry->present);
238 elog(PANIC, "WAL contains references to invalid pages");
240 hash_destroy(invalid_page_tab);
241 invalid_page_tab = NULL;
246 * XLogReadBufferForRedo
247 * Read a page during XLOG replay
249 * Reads a block referenced by a WAL record into shared buffer cache, and
250 * determines what needs to be done to redo the changes to it. If the WAL
251 * record includes a full-page image of the page, it is restored.
253 * 'lsn' is the LSN of the record being replayed. It is compared with the
254 * page's LSN to determine if the record has already been replayed.
255 * 'block_id' is the ID number the block was registered with, when the WAL
256 * record was created.
258 * Returns one of the following:
260 * BLK_NEEDS_REDO - changes from the WAL record need to be applied
261 * BLK_DONE - block doesn't need replaying
262 * BLK_RESTORED - block was restored from a full-page image included in
264 * BLK_NOTFOUND - block was not found (because it was truncated away by
265 * an operation later in the WAL stream)
267 * On return, the buffer is locked in exclusive-mode, and returned in *buf.
268 * Note that the buffer is locked and returned even if it doesn't need
269 * replaying. (Getting the buffer lock is not really necessary during
270 * single-process crash recovery, but some subroutines such as MarkBufferDirty
271 * will complain if we don't have the lock. In hot standby mode it's
272 * definitely necessary.)
274 * Note: when a backup block is available in XLOG, we restore it
275 * unconditionally, even if the page in the database appears newer. This is
276 * to protect ourselves against database pages that were partially or
277 * incorrectly written during a crash. We assume that the XLOG data must be
278 * good because it has passed a CRC check, while the database page might not
279 * be. This will force us to replay all subsequent modifications of the page
280 * that appear in XLOG, rather than possibly ignoring them as already
281 * applied, but that's not a huge drawback.
284 XLogReadBufferForRedo(XLogReaderState *record, uint8 block_id,
287 return XLogReadBufferForRedoExtended(record, block_id, RBM_NORMAL,
292 * Pin and lock a buffer referenced by a WAL record, for the purpose of
293 * re-initializing it.
296 XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id)
300 XLogReadBufferForRedoExtended(record, block_id, RBM_ZERO_AND_LOCK, false,
306 * XLogReadBufferForRedoExtended
307 * Like XLogReadBufferForRedo, but with extra options.
309 * In RBM_ZERO_* modes, if the page doesn't exist, the relation is extended
310 * with all-zeroes pages up to the referenced block number. In
311 * RBM_ZERO_AND_LOCK and RBM_ZERO_AND_CLEANUP_LOCK modes, the return value
312 * is always BLK_NEEDS_REDO.
314 * (The RBM_ZERO_AND_CLEANUP_LOCK mode is redundant with the get_cleanup_lock
315 * parameter. Do not use an inconsistent combination!)
317 * If 'get_cleanup_lock' is true, a "cleanup lock" is acquired on the buffer
318 * using LockBufferForCleanup(), instead of a regular exclusive lock.
321 XLogReadBufferForRedoExtended(XLogReaderState *record,
323 ReadBufferMode mode, bool get_cleanup_lock,
326 XLogRecPtr lsn = record->EndRecPtr;
334 if (!XLogRecGetBlockTag(record, block_id, &rnode, &forknum, &blkno))
336 /* Caller specified a bogus block_id */
337 elog(PANIC, "failed to locate backup block with ID %d", block_id);
341 * Make sure that if the block is marked with WILL_INIT, the caller is
342 * going to initialize it. And vice versa.
344 zeromode = (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
345 willinit = (record->blocks[block_id].flags & BKPBLOCK_WILL_INIT) != 0;
346 if (willinit && !zeromode)
347 elog(PANIC, "block with WILL_INIT flag in WAL record must be zeroed by redo routine");
348 if (!willinit && zeromode)
349 elog(PANIC, "block to be initialized in redo routine must be marked with WILL_INIT flag in the WAL record");
351 /* If it's a full-page image, restore it. */
352 if (XLogRecHasBlockImage(record, block_id))
354 *buf = XLogReadBufferExtended(rnode, forknum, blkno,
355 get_cleanup_lock ? RBM_ZERO_AND_CLEANUP_LOCK : RBM_ZERO_AND_LOCK);
356 page = BufferGetPage(*buf);
357 if (!RestoreBlockImage(record, block_id, page))
358 elog(ERROR, "failed to restore block image");
361 * The page may be uninitialized. If so, we can't set the LSN because
362 * that would corrupt the page.
364 if (!PageIsNew(page))
366 PageSetLSN(page, lsn);
369 MarkBufferDirty(*buf);
372 * At the end of crash recovery the init forks of unlogged relations
373 * are copied, without going through shared buffers. So we need to
374 * force the on-disk state of init forks to always be in sync with the
375 * state in shared buffers.
377 if (forknum == INIT_FORKNUM)
378 FlushOneBuffer(*buf);
384 *buf = XLogReadBufferExtended(rnode, forknum, blkno, mode);
385 if (BufferIsValid(*buf))
387 if (mode != RBM_ZERO_AND_LOCK && mode != RBM_ZERO_AND_CLEANUP_LOCK)
389 if (get_cleanup_lock)
390 LockBufferForCleanup(*buf);
392 LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);
394 if (lsn <= PageGetLSN(BufferGetPage(*buf)))
397 return BLK_NEEDS_REDO;
405 * XLogReadBufferExtended
406 * Read a page during XLOG replay
408 * This is functionally comparable to ReadBufferExtended. There's some
409 * differences in the behavior wrt. the "mode" argument:
411 * In RBM_NORMAL mode, if the page doesn't exist, or contains all-zeroes, we
412 * return InvalidBuffer. In this case the caller should silently skip the
413 * update on this page. (In this situation, we expect that the page was later
414 * dropped or truncated. If we don't see evidence of that later in the WAL
415 * sequence, we'll complain at the end of WAL replay.)
417 * In RBM_ZERO_* modes, if the page doesn't exist, the relation is extended
418 * with all-zeroes pages up to the given block number.
420 * In RBM_NORMAL_NO_LOG mode, we return InvalidBuffer if the page doesn't
421 * exist, and we don't check for all-zeroes. Thus, no log entry is made
422 * to imply that the page should be dropped or truncated later.
424 * NB: A redo function should normally not call this directly. To get a page
425 * to modify, use XLogReplayBuffer instead. It is important that all pages
426 * modified by a WAL record are registered in the WAL records, or they will be
427 * invisible to tools that that need to know which pages are modified.
430 XLogReadBufferExtended(RelFileNode rnode, ForkNumber forknum,
431 BlockNumber blkno, ReadBufferMode mode)
433 BlockNumber lastblock;
437 Assert(blkno != P_NEW);
439 /* Open the relation at smgr level */
440 smgr = smgropen(rnode, InvalidBackendId);
443 * Create the target file if it doesn't already exist. This lets us cope
444 * if the replay sequence contains writes to a relation that is later
445 * deleted. (The original coding of this routine would instead suppress
446 * the writes, but that seems like it risks losing valuable data if the
447 * filesystem loses an inode during a crash. Better to write the data
448 * until we are actually told to delete the file.)
450 smgrcreate(smgr, forknum, true);
452 lastblock = smgrnblocks(smgr, forknum);
454 if (blkno < lastblock)
456 /* page exists in file */
457 buffer = ReadBufferWithoutRelcache(rnode, forknum, blkno,
462 /* hm, page doesn't exist in file */
463 if (mode == RBM_NORMAL)
465 log_invalid_page(rnode, forknum, blkno, false);
466 return InvalidBuffer;
468 if (mode == RBM_NORMAL_NO_LOG)
469 return InvalidBuffer;
470 /* OK to extend the file */
471 /* we do this in recovery only - no rel-extension lock needed */
473 buffer = InvalidBuffer;
476 if (buffer != InvalidBuffer)
478 if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
479 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
480 ReleaseBuffer(buffer);
482 buffer = ReadBufferWithoutRelcache(rnode, forknum,
485 while (BufferGetBlockNumber(buffer) < blkno);
486 /* Handle the corner case that P_NEW returns non-consecutive pages */
487 if (BufferGetBlockNumber(buffer) != blkno)
489 if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
490 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
491 ReleaseBuffer(buffer);
492 buffer = ReadBufferWithoutRelcache(rnode, forknum, blkno,
497 if (mode == RBM_NORMAL)
499 /* check that page has been initialized */
500 Page page = (Page) BufferGetPage(buffer);
503 * We assume that PageIsNew is safe without a lock. During recovery,
504 * there should be no other backends that could modify the buffer at
509 ReleaseBuffer(buffer);
510 log_invalid_page(rnode, forknum, blkno, true);
511 return InvalidBuffer;
519 * Struct actually returned by XLogFakeRelcacheEntry, though the declared
520 * return type is Relation.
524 RelationData reldata; /* Note: this must be first */
525 FormData_pg_class pgc;
526 } FakeRelCacheEntryData;
528 typedef FakeRelCacheEntryData *FakeRelCacheEntry;
531 * Create a fake relation cache entry for a physical relation
533 * It's often convenient to use the same functions in XLOG replay as in the
534 * main codepath, but those functions typically work with a relcache entry.
535 * We don't have a working relation cache during XLOG replay, but this
536 * function can be used to create a fake relcache entry instead. Only the
537 * fields related to physical storage, like rd_rel, are initialized, so the
538 * fake entry is only usable in low-level operations like ReadBuffer().
540 * Caller must free the returned entry with FreeFakeRelcacheEntry().
543 CreateFakeRelcacheEntry(RelFileNode rnode)
545 FakeRelCacheEntry fakeentry;
550 /* Allocate the Relation struct and all related space in one block. */
551 fakeentry = palloc0(sizeof(FakeRelCacheEntryData));
552 rel = (Relation) fakeentry;
554 rel->rd_rel = &fakeentry->pgc;
555 rel->rd_node = rnode;
556 /* We will never be working with temp rels during recovery */
557 rel->rd_backend = InvalidBackendId;
559 /* It must be a permanent table if we're in recovery. */
560 rel->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
562 /* We don't know the name of the relation; use relfilenode instead */
563 sprintf(RelationGetRelationName(rel), "%u", rnode.relNode);
566 * We set up the lockRelId in case anything tries to lock the dummy
567 * relation. Note that this is fairly bogus since relNode may be
568 * different from the relation's OID. It shouldn't really matter though,
569 * since we are presumably running by ourselves and can't have any lock
572 rel->rd_lockInfo.lockRelId.dbId = rnode.dbNode;
573 rel->rd_lockInfo.lockRelId.relId = rnode.relNode;
581 * Free a fake relation cache entry.
584 FreeFakeRelcacheEntry(Relation fakerel)
586 /* make sure the fakerel is not referenced by the SmgrRelation anymore */
587 if (fakerel->rd_smgr != NULL)
588 smgrclearowner(&fakerel->rd_smgr, fakerel->rd_smgr);
593 * Drop a relation during XLOG replay
595 * This is called when the relation is about to be deleted; we need to remove
596 * any open "invalid-page" records for the relation.
599 XLogDropRelation(RelFileNode rnode, ForkNumber forknum)
601 forget_invalid_pages(rnode, forknum, 0);
605 * Drop a whole database during XLOG replay
607 * As above, but for DROP DATABASE instead of dropping a single rel
610 XLogDropDatabase(Oid dbid)
613 * This is unnecessarily heavy-handed, as it will close SMgrRelation
614 * objects for other databases as well. DROP DATABASE occurs seldom enough
615 * that it's not worth introducing a variant of smgrclose for just this
616 * purpose. XXX: Or should we rather leave the smgr entries dangling?
620 forget_invalid_pages_db(dbid);
624 * Truncate a relation during XLOG replay
626 * We need to clean up any open "invalid-page" records for the dropped pages.
629 XLogTruncateRelation(RelFileNode rnode, ForkNumber forkNum,
632 forget_invalid_pages(rnode, forkNum, nblocks);