]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/xlogutils.c
Update copyright for 2016
[postgresql] / src / backend / access / transam / xlogutils.c
1 /*-------------------------------------------------------------------------
2  *
3  * xlogutils.c
4  *
5  * PostgreSQL transaction log manager utility routines
6  *
7  * This file contains support routines that are used by XLOG replay functions.
8  * None of this code is used during normal system operation.
9  *
10  *
11  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
12  * Portions Copyright (c) 1994, Regents of the University of California
13  *
14  * src/backend/access/transam/xlogutils.c
15  *
16  *-------------------------------------------------------------------------
17  */
18 #include "postgres.h"
19
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"
27
28
29 /*
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
37  * later in replay.
38  */
39 typedef struct xl_invalid_page_key
40 {
41         RelFileNode node;                       /* the relation */
42         ForkNumber      forkno;                 /* the fork number */
43         BlockNumber blkno;                      /* the page */
44 } xl_invalid_page_key;
45
46 typedef struct xl_invalid_page
47 {
48         xl_invalid_page_key key;        /* hash key ... must be first */
49         bool            present;                /* page existed but contained zeroes */
50 } xl_invalid_page;
51
52 static HTAB *invalid_page_tab = NULL;
53
54
55 /* Report a reference to an invalid page */
56 static void
57 report_invalid_page(int elevel, RelFileNode node, ForkNumber forkno,
58                                         BlockNumber blkno, bool present)
59 {
60         char       *path = relpathperm(node, forkno);
61
62         if (present)
63                 elog(elevel, "page %u of relation %s is uninitialized",
64                          blkno, path);
65         else
66                 elog(elevel, "page %u of relation %s does not exist",
67                          blkno, path);
68         pfree(path);
69 }
70
71 /* Log a reference to an invalid page */
72 static void
73 log_invalid_page(RelFileNode node, ForkNumber forkno, BlockNumber blkno,
74                                  bool present)
75 {
76         xl_invalid_page_key key;
77         xl_invalid_page *hentry;
78         bool            found;
79
80         /*
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.
87          */
88         if (reachedConsistency)
89         {
90                 report_invalid_page(WARNING, node, forkno, blkno, present);
91                 elog(PANIC, "WAL contains references to invalid pages");
92         }
93
94         /*
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).
98          */
99         if (log_min_messages <= DEBUG1 || client_min_messages <= DEBUG1)
100                 report_invalid_page(DEBUG1, node, forkno, blkno, present);
101
102         if (invalid_page_tab == NULL)
103         {
104                 /* create hash table when first needed */
105                 HASHCTL         ctl;
106
107                 memset(&ctl, 0, sizeof(ctl));
108                 ctl.keysize = sizeof(xl_invalid_page_key);
109                 ctl.entrysize = sizeof(xl_invalid_page);
110
111                 invalid_page_tab = hash_create("XLOG invalid-page table",
112                                                                            100,
113                                                                            &ctl,
114                                                                            HASH_ELEM | HASH_BLOBS);
115         }
116
117         /* we currently assume xl_invalid_page_key contains no padding */
118         key.node = node;
119         key.forkno = forkno;
120         key.blkno = blkno;
121         hentry = (xl_invalid_page *)
122                 hash_search(invalid_page_tab, (void *) &key, HASH_ENTER, &found);
123
124         if (!found)
125         {
126                 /* hash_search already filled in the key */
127                 hentry->present = present;
128         }
129         else
130         {
131                 /* repeat reference ... leave "present" as it was */
132         }
133 }
134
135 /* Forget any invalid pages >= minblkno, because they've been dropped */
136 static void
137 forget_invalid_pages(RelFileNode node, ForkNumber forkno, BlockNumber minblkno)
138 {
139         HASH_SEQ_STATUS status;
140         xl_invalid_page *hentry;
141
142         if (invalid_page_tab == NULL)
143                 return;                                 /* nothing to do */
144
145         hash_seq_init(&status, invalid_page_tab);
146
147         while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
148         {
149                 if (RelFileNodeEquals(hentry->key.node, node) &&
150                         hentry->key.forkno == forkno &&
151                         hentry->key.blkno >= minblkno)
152                 {
153                         if (log_min_messages <= DEBUG2 || client_min_messages <= DEBUG2)
154                         {
155                                 char       *path = relpathperm(hentry->key.node, forkno);
156
157                                 elog(DEBUG2, "page %u of relation %s has been dropped",
158                                          hentry->key.blkno, path);
159                                 pfree(path);
160                         }
161
162                         if (hash_search(invalid_page_tab,
163                                                         (void *) &hentry->key,
164                                                         HASH_REMOVE, NULL) == NULL)
165                                 elog(ERROR, "hash table corrupted");
166                 }
167         }
168 }
169
170 /* Forget any invalid pages in a whole database */
171 static void
172 forget_invalid_pages_db(Oid dbid)
173 {
174         HASH_SEQ_STATUS status;
175         xl_invalid_page *hentry;
176
177         if (invalid_page_tab == NULL)
178                 return;                                 /* nothing to do */
179
180         hash_seq_init(&status, invalid_page_tab);
181
182         while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
183         {
184                 if (hentry->key.node.dbNode == dbid)
185                 {
186                         if (log_min_messages <= DEBUG2 || client_min_messages <= DEBUG2)
187                         {
188                                 char       *path = relpathperm(hentry->key.node, hentry->key.forkno);
189
190                                 elog(DEBUG2, "page %u of relation %s has been dropped",
191                                          hentry->key.blkno, path);
192                                 pfree(path);
193                         }
194
195                         if (hash_search(invalid_page_tab,
196                                                         (void *) &hentry->key,
197                                                         HASH_REMOVE, NULL) == NULL)
198                                 elog(ERROR, "hash table corrupted");
199                 }
200         }
201 }
202
203 /* Are there any unresolved references to invalid pages? */
204 bool
205 XLogHaveInvalidPages(void)
206 {
207         if (invalid_page_tab != NULL &&
208                 hash_get_num_entries(invalid_page_tab) > 0)
209                 return true;
210         return false;
211 }
212
213 /* Complain about any remaining invalid-page entries */
214 void
215 XLogCheckInvalidPages(void)
216 {
217         HASH_SEQ_STATUS status;
218         xl_invalid_page *hentry;
219         bool            foundone = false;
220
221         if (invalid_page_tab == NULL)
222                 return;                                 /* nothing to do */
223
224         hash_seq_init(&status, invalid_page_tab);
225
226         /*
227          * Our strategy is to emit WARNING messages for all remaining entries and
228          * only PANIC after we've dumped all the available info.
229          */
230         while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
231         {
232                 report_invalid_page(WARNING, hentry->key.node, hentry->key.forkno,
233                                                         hentry->key.blkno, hentry->present);
234                 foundone = true;
235         }
236
237         if (foundone)
238                 elog(PANIC, "WAL contains references to invalid pages");
239
240         hash_destroy(invalid_page_tab);
241         invalid_page_tab = NULL;
242 }
243
244
245 /*
246  * XLogReadBufferForRedo
247  *              Read a page during XLOG replay
248  *
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.
252  *
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.
257  *
258  * Returns one of the following:
259  *
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
263  *                                        the record
264  *      BLK_NOTFOUND    - block was not found (because it was truncated away by
265  *                                        an operation later in the WAL stream)
266  *
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.)
273  *
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.
282  */
283 XLogRedoAction
284 XLogReadBufferForRedo(XLogReaderState *record, uint8 block_id,
285                                           Buffer *buf)
286 {
287         return XLogReadBufferForRedoExtended(record, block_id, RBM_NORMAL,
288                                                                                  false, buf);
289 }
290
291 /*
292  * Pin and lock a buffer referenced by a WAL record, for the purpose of
293  * re-initializing it.
294  */
295 Buffer
296 XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id)
297 {
298         Buffer          buf;
299
300         XLogReadBufferForRedoExtended(record, block_id, RBM_ZERO_AND_LOCK, false,
301                                                                   &buf);
302         return buf;
303 }
304
305 /*
306  * XLogReadBufferForRedoExtended
307  *              Like XLogReadBufferForRedo, but with extra options.
308  *
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.
313  *
314  * (The RBM_ZERO_AND_CLEANUP_LOCK mode is redundant with the get_cleanup_lock
315  * parameter. Do not use an inconsistent combination!)
316  *
317  * If 'get_cleanup_lock' is true, a "cleanup lock" is acquired on the buffer
318  * using LockBufferForCleanup(), instead of a regular exclusive lock.
319  */
320 XLogRedoAction
321 XLogReadBufferForRedoExtended(XLogReaderState *record,
322                                                           uint8 block_id,
323                                                           ReadBufferMode mode, bool get_cleanup_lock,
324                                                           Buffer *buf)
325 {
326         XLogRecPtr      lsn = record->EndRecPtr;
327         RelFileNode rnode;
328         ForkNumber      forknum;
329         BlockNumber blkno;
330         Page            page;
331         bool            zeromode;
332         bool            willinit;
333
334         if (!XLogRecGetBlockTag(record, block_id, &rnode, &forknum, &blkno))
335         {
336                 /* Caller specified a bogus block_id */
337                 elog(PANIC, "failed to locate backup block with ID %d", block_id);
338         }
339
340         /*
341          * Make sure that if the block is marked with WILL_INIT, the caller is
342          * going to initialize it. And vice versa.
343          */
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");
350
351         /* If it's a full-page image, restore it. */
352         if (XLogRecHasBlockImage(record, block_id))
353         {
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");
359
360                 /*
361                  * The page may be uninitialized. If so, we can't set the LSN because
362                  * that would corrupt the page.
363                  */
364                 if (!PageIsNew(page))
365                 {
366                         PageSetLSN(page, lsn);
367                 }
368
369                 MarkBufferDirty(*buf);
370
371                 /*
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.
376                  */
377                 if (forknum == INIT_FORKNUM)
378                         FlushOneBuffer(*buf);
379
380                 return BLK_RESTORED;
381         }
382         else
383         {
384                 *buf = XLogReadBufferExtended(rnode, forknum, blkno, mode);
385                 if (BufferIsValid(*buf))
386                 {
387                         if (mode != RBM_ZERO_AND_LOCK && mode != RBM_ZERO_AND_CLEANUP_LOCK)
388                         {
389                                 if (get_cleanup_lock)
390                                         LockBufferForCleanup(*buf);
391                                 else
392                                         LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);
393                         }
394                         if (lsn <= PageGetLSN(BufferGetPage(*buf)))
395                                 return BLK_DONE;
396                         else
397                                 return BLK_NEEDS_REDO;
398                 }
399                 else
400                         return BLK_NOTFOUND;
401         }
402 }
403
404 /*
405  * XLogReadBufferExtended
406  *              Read a page during XLOG replay
407  *
408  * This is functionally comparable to ReadBufferExtended. There's some
409  * differences in the behavior wrt. the "mode" argument:
410  *
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.)
416  *
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.
419  *
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.
423  *
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.
428  */
429 Buffer
430 XLogReadBufferExtended(RelFileNode rnode, ForkNumber forknum,
431                                            BlockNumber blkno, ReadBufferMode mode)
432 {
433         BlockNumber lastblock;
434         Buffer          buffer;
435         SMgrRelation smgr;
436
437         Assert(blkno != P_NEW);
438
439         /* Open the relation at smgr level */
440         smgr = smgropen(rnode, InvalidBackendId);
441
442         /*
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.)
449          */
450         smgrcreate(smgr, forknum, true);
451
452         lastblock = smgrnblocks(smgr, forknum);
453
454         if (blkno < lastblock)
455         {
456                 /* page exists in file */
457                 buffer = ReadBufferWithoutRelcache(rnode, forknum, blkno,
458                                                                                    mode, NULL);
459         }
460         else
461         {
462                 /* hm, page doesn't exist in file */
463                 if (mode == RBM_NORMAL)
464                 {
465                         log_invalid_page(rnode, forknum, blkno, false);
466                         return InvalidBuffer;
467                 }
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 */
472                 Assert(InRecovery);
473                 buffer = InvalidBuffer;
474                 do
475                 {
476                         if (buffer != InvalidBuffer)
477                         {
478                                 if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
479                                         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
480                                 ReleaseBuffer(buffer);
481                         }
482                         buffer = ReadBufferWithoutRelcache(rnode, forknum,
483                                                                                            P_NEW, mode, NULL);
484                 }
485                 while (BufferGetBlockNumber(buffer) < blkno);
486                 /* Handle the corner case that P_NEW returns non-consecutive pages */
487                 if (BufferGetBlockNumber(buffer) != blkno)
488                 {
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,
493                                                                                            mode, NULL);
494                 }
495         }
496
497         if (mode == RBM_NORMAL)
498         {
499                 /* check that page has been initialized */
500                 Page            page = (Page) BufferGetPage(buffer);
501
502                 /*
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
505                  * the same time.
506                  */
507                 if (PageIsNew(page))
508                 {
509                         ReleaseBuffer(buffer);
510                         log_invalid_page(rnode, forknum, blkno, true);
511                         return InvalidBuffer;
512                 }
513         }
514
515         return buffer;
516 }
517
518 /*
519  * Struct actually returned by XLogFakeRelcacheEntry, though the declared
520  * return type is Relation.
521  */
522 typedef struct
523 {
524         RelationData reldata;           /* Note: this must be first */
525         FormData_pg_class pgc;
526 } FakeRelCacheEntryData;
527
528 typedef FakeRelCacheEntryData *FakeRelCacheEntry;
529
530 /*
531  * Create a fake relation cache entry for a physical relation
532  *
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().
539  *
540  * Caller must free the returned entry with FreeFakeRelcacheEntry().
541  */
542 Relation
543 CreateFakeRelcacheEntry(RelFileNode rnode)
544 {
545         FakeRelCacheEntry fakeentry;
546         Relation        rel;
547
548         Assert(InRecovery);
549
550         /* Allocate the Relation struct and all related space in one block. */
551         fakeentry = palloc0(sizeof(FakeRelCacheEntryData));
552         rel = (Relation) fakeentry;
553
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;
558
559         /* It must be a permanent table if we're in recovery. */
560         rel->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
561
562         /* We don't know the name of the relation; use relfilenode instead */
563         sprintf(RelationGetRelationName(rel), "%u", rnode.relNode);
564
565         /*
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
570          * conflicts ...
571          */
572         rel->rd_lockInfo.lockRelId.dbId = rnode.dbNode;
573         rel->rd_lockInfo.lockRelId.relId = rnode.relNode;
574
575         rel->rd_smgr = NULL;
576
577         return rel;
578 }
579
580 /*
581  * Free a fake relation cache entry.
582  */
583 void
584 FreeFakeRelcacheEntry(Relation fakerel)
585 {
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);
589         pfree(fakerel);
590 }
591
592 /*
593  * Drop a relation during XLOG replay
594  *
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.
597  */
598 void
599 XLogDropRelation(RelFileNode rnode, ForkNumber forknum)
600 {
601         forget_invalid_pages(rnode, forknum, 0);
602 }
603
604 /*
605  * Drop a whole database during XLOG replay
606  *
607  * As above, but for DROP DATABASE instead of dropping a single rel
608  */
609 void
610 XLogDropDatabase(Oid dbid)
611 {
612         /*
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?
617          */
618         smgrcloseall();
619
620         forget_invalid_pages_db(dbid);
621 }
622
623 /*
624  * Truncate a relation during XLOG replay
625  *
626  * We need to clean up any open "invalid-page" records for the dropped pages.
627  */
628 void
629 XLogTruncateRelation(RelFileNode rnode, ForkNumber forkNum,
630                                          BlockNumber nblocks)
631 {
632         forget_invalid_pages(rnode, forkNum, nblocks);
633 }