]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/xlogutils.c
Update copyright for 2014
[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-2014, 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 "common/relpath.h"
24 #include "storage/smgr.h"
25 #include "utils/guc.h"
26 #include "utils/hsearch.h"
27 #include "utils/rel.h"
28
29
30 /*
31  * During XLOG replay, we may see XLOG records for incremental updates of
32  * pages that no longer exist, because their relation was later dropped or
33  * truncated.  (Note: this is only possible when full_page_writes = OFF,
34  * since when it's ON, the first reference we see to a page should always
35  * be a full-page rewrite not an incremental update.)  Rather than simply
36  * ignoring such records, we make a note of the referenced page, and then
37  * complain if we don't actually see a drop or truncate covering the page
38  * later in replay.
39  */
40 typedef struct xl_invalid_page_key
41 {
42         RelFileNode node;                       /* the relation */
43         ForkNumber      forkno;                 /* the fork number */
44         BlockNumber blkno;                      /* the page */
45 } xl_invalid_page_key;
46
47 typedef struct xl_invalid_page
48 {
49         xl_invalid_page_key key;        /* hash key ... must be first */
50         bool            present;                /* page existed but contained zeroes */
51 } xl_invalid_page;
52
53 static HTAB *invalid_page_tab = NULL;
54
55
56 /* Report a reference to an invalid page */
57 static void
58 report_invalid_page(int elevel, RelFileNode node, ForkNumber forkno,
59                                         BlockNumber blkno, bool present)
60 {
61         char       *path = relpathperm(node, forkno);
62
63         if (present)
64                 elog(elevel, "page %u of relation %s is uninitialized",
65                          blkno, path);
66         else
67                 elog(elevel, "page %u of relation %s does not exist",
68                          blkno, path);
69         pfree(path);
70 }
71
72 /* Log a reference to an invalid page */
73 static void
74 log_invalid_page(RelFileNode node, ForkNumber forkno, BlockNumber blkno,
75                                  bool present)
76 {
77         xl_invalid_page_key key;
78         xl_invalid_page *hentry;
79         bool            found;
80
81         /*
82          * Once recovery has reached a consistent state, the invalid-page table
83          * should be empty and remain so. If a reference to an invalid page is
84          * found after consistency is reached, PANIC immediately. This might seem
85          * aggressive, but it's better than letting the invalid reference linger
86          * in the hash table until the end of recovery and PANIC there, which
87          * might come only much later if this is a standby server.
88          */
89         if (reachedConsistency)
90         {
91                 report_invalid_page(WARNING, node, forkno, blkno, present);
92                 elog(PANIC, "WAL contains references to invalid pages");
93         }
94
95         /*
96          * Log references to invalid pages at DEBUG1 level.  This allows some
97          * tracing of the cause (note the elog context mechanism will tell us
98          * something about the XLOG record that generated the reference).
99          */
100         if (log_min_messages <= DEBUG1 || client_min_messages <= DEBUG1)
101                 report_invalid_page(DEBUG1, node, forkno, blkno, present);
102
103         if (invalid_page_tab == NULL)
104         {
105                 /* create hash table when first needed */
106                 HASHCTL         ctl;
107
108                 memset(&ctl, 0, sizeof(ctl));
109                 ctl.keysize = sizeof(xl_invalid_page_key);
110                 ctl.entrysize = sizeof(xl_invalid_page);
111                 ctl.hash = tag_hash;
112
113                 invalid_page_tab = hash_create("XLOG invalid-page table",
114                                                                            100,
115                                                                            &ctl,
116                                                                            HASH_ELEM | HASH_FUNCTION);
117         }
118
119         /* we currently assume xl_invalid_page_key contains no padding */
120         key.node = node;
121         key.forkno = forkno;
122         key.blkno = blkno;
123         hentry = (xl_invalid_page *)
124                 hash_search(invalid_page_tab, (void *) &key, HASH_ENTER, &found);
125
126         if (!found)
127         {
128                 /* hash_search already filled in the key */
129                 hentry->present = present;
130         }
131         else
132         {
133                 /* repeat reference ... leave "present" as it was */
134         }
135 }
136
137 /* Forget any invalid pages >= minblkno, because they've been dropped */
138 static void
139 forget_invalid_pages(RelFileNode node, ForkNumber forkno, BlockNumber minblkno)
140 {
141         HASH_SEQ_STATUS status;
142         xl_invalid_page *hentry;
143
144         if (invalid_page_tab == NULL)
145                 return;                                 /* nothing to do */
146
147         hash_seq_init(&status, invalid_page_tab);
148
149         while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
150         {
151                 if (RelFileNodeEquals(hentry->key.node, node) &&
152                         hentry->key.forkno == forkno &&
153                         hentry->key.blkno >= minblkno)
154                 {
155                         if (log_min_messages <= DEBUG2 || client_min_messages <= DEBUG2)
156                         {
157                                 char       *path = relpathperm(hentry->key.node, forkno);
158
159                                 elog(DEBUG2, "page %u of relation %s has been dropped",
160                                          hentry->key.blkno, path);
161                                 pfree(path);
162                         }
163
164                         if (hash_search(invalid_page_tab,
165                                                         (void *) &hentry->key,
166                                                         HASH_REMOVE, NULL) == NULL)
167                                 elog(ERROR, "hash table corrupted");
168                 }
169         }
170 }
171
172 /* Forget any invalid pages in a whole database */
173 static void
174 forget_invalid_pages_db(Oid dbid)
175 {
176         HASH_SEQ_STATUS status;
177         xl_invalid_page *hentry;
178
179         if (invalid_page_tab == NULL)
180                 return;                                 /* nothing to do */
181
182         hash_seq_init(&status, invalid_page_tab);
183
184         while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
185         {
186                 if (hentry->key.node.dbNode == dbid)
187                 {
188                         if (log_min_messages <= DEBUG2 || client_min_messages <= DEBUG2)
189                         {
190                                 char       *path = relpathperm(hentry->key.node, hentry->key.forkno);
191
192                                 elog(DEBUG2, "page %u of relation %s has been dropped",
193                                          hentry->key.blkno, path);
194                                 pfree(path);
195                         }
196
197                         if (hash_search(invalid_page_tab,
198                                                         (void *) &hentry->key,
199                                                         HASH_REMOVE, NULL) == NULL)
200                                 elog(ERROR, "hash table corrupted");
201                 }
202         }
203 }
204
205 /* Are there any unresolved references to invalid pages? */
206 bool
207 XLogHaveInvalidPages(void)
208 {
209         if (invalid_page_tab != NULL &&
210                 hash_get_num_entries(invalid_page_tab) > 0)
211                 return true;
212         return false;
213 }
214
215 /* Complain about any remaining invalid-page entries */
216 void
217 XLogCheckInvalidPages(void)
218 {
219         HASH_SEQ_STATUS status;
220         xl_invalid_page *hentry;
221         bool            foundone = false;
222
223         if (invalid_page_tab == NULL)
224                 return;                                 /* nothing to do */
225
226         hash_seq_init(&status, invalid_page_tab);
227
228         /*
229          * Our strategy is to emit WARNING messages for all remaining entries and
230          * only PANIC after we've dumped all the available info.
231          */
232         while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
233         {
234                 report_invalid_page(WARNING, hentry->key.node, hentry->key.forkno,
235                                                         hentry->key.blkno, hentry->present);
236                 foundone = true;
237         }
238
239         if (foundone)
240                 elog(PANIC, "WAL contains references to invalid pages");
241
242         hash_destroy(invalid_page_tab);
243         invalid_page_tab = NULL;
244 }
245
246 /*
247  * XLogReadBuffer
248  *              Read a page during XLOG replay.
249  *
250  * This is a shorthand of XLogReadBufferExtended() followed by
251  * LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE), for reading from the main
252  * fork.
253  *
254  * (Getting the buffer lock is not really necessary during single-process
255  * crash recovery, but some subroutines such as MarkBufferDirty will complain
256  * if we don't have the lock.  In hot standby mode it's definitely necessary.)
257  *
258  * The returned buffer is exclusively-locked.
259  *
260  * For historical reasons, instead of a ReadBufferMode argument, this only
261  * supports RBM_ZERO (init == true) and RBM_NORMAL (init == false) modes.
262  */
263 Buffer
264 XLogReadBuffer(RelFileNode rnode, BlockNumber blkno, bool init)
265 {
266         Buffer          buf;
267
268         buf = XLogReadBufferExtended(rnode, MAIN_FORKNUM, blkno,
269                                                                  init ? RBM_ZERO : RBM_NORMAL);
270         if (BufferIsValid(buf))
271                 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
272
273         return buf;
274 }
275
276 /*
277  * XLogReadBufferExtended
278  *              Read a page during XLOG replay
279  *
280  * This is functionally comparable to ReadBufferExtended. There's some
281  * differences in the behavior wrt. the "mode" argument:
282  *
283  * In RBM_NORMAL mode, if the page doesn't exist, or contains all-zeroes, we
284  * return InvalidBuffer. In this case the caller should silently skip the
285  * update on this page. (In this situation, we expect that the page was later
286  * dropped or truncated. If we don't see evidence of that later in the WAL
287  * sequence, we'll complain at the end of WAL replay.)
288  *
289  * In RBM_ZERO and RBM_ZERO_ON_ERROR modes, if the page doesn't exist, the
290  * relation is extended with all-zeroes pages up to the given block number.
291  */
292 Buffer
293 XLogReadBufferExtended(RelFileNode rnode, ForkNumber forknum,
294                                            BlockNumber blkno, ReadBufferMode mode)
295 {
296         BlockNumber lastblock;
297         Buffer          buffer;
298         SMgrRelation smgr;
299
300         Assert(blkno != P_NEW);
301
302         /* Open the relation at smgr level */
303         smgr = smgropen(rnode, InvalidBackendId);
304
305         /*
306          * Create the target file if it doesn't already exist.  This lets us cope
307          * if the replay sequence contains writes to a relation that is later
308          * deleted.  (The original coding of this routine would instead suppress
309          * the writes, but that seems like it risks losing valuable data if the
310          * filesystem loses an inode during a crash.  Better to write the data
311          * until we are actually told to delete the file.)
312          */
313         smgrcreate(smgr, forknum, true);
314
315         lastblock = smgrnblocks(smgr, forknum);
316
317         if (blkno < lastblock)
318         {
319                 /* page exists in file */
320                 buffer = ReadBufferWithoutRelcache(rnode, forknum, blkno,
321                                                                                    mode, NULL);
322         }
323         else
324         {
325                 /* hm, page doesn't exist in file */
326                 if (mode == RBM_NORMAL)
327                 {
328                         log_invalid_page(rnode, forknum, blkno, false);
329                         return InvalidBuffer;
330                 }
331                 /* OK to extend the file */
332                 /* we do this in recovery only - no rel-extension lock needed */
333                 Assert(InRecovery);
334                 buffer = InvalidBuffer;
335                 while (blkno >= lastblock)
336                 {
337                         if (buffer != InvalidBuffer)
338                                 ReleaseBuffer(buffer);
339                         buffer = ReadBufferWithoutRelcache(rnode, forknum,
340                                                                                            P_NEW, mode, NULL);
341                         lastblock++;
342                 }
343                 Assert(BufferGetBlockNumber(buffer) == blkno);
344         }
345
346         if (mode == RBM_NORMAL)
347         {
348                 /* check that page has been initialized */
349                 Page            page = (Page) BufferGetPage(buffer);
350
351                 /*
352                  * We assume that PageIsNew is safe without a lock. During recovery,
353                  * there should be no other backends that could modify the buffer at
354                  * the same time.
355                  */
356                 if (PageIsNew(page))
357                 {
358                         ReleaseBuffer(buffer);
359                         log_invalid_page(rnode, forknum, blkno, true);
360                         return InvalidBuffer;
361                 }
362         }
363
364         return buffer;
365 }
366
367
368 /*
369  * Struct actually returned by XLogFakeRelcacheEntry, though the declared
370  * return type is Relation.
371  */
372 typedef struct
373 {
374         RelationData reldata;           /* Note: this must be first */
375         FormData_pg_class pgc;
376 } FakeRelCacheEntryData;
377
378 typedef FakeRelCacheEntryData *FakeRelCacheEntry;
379
380 /*
381  * Create a fake relation cache entry for a physical relation
382  *
383  * It's often convenient to use the same functions in XLOG replay as in the
384  * main codepath, but those functions typically work with a relcache entry.
385  * We don't have a working relation cache during XLOG replay, but this
386  * function can be used to create a fake relcache entry instead. Only the
387  * fields related to physical storage, like rd_rel, are initialized, so the
388  * fake entry is only usable in low-level operations like ReadBuffer().
389  *
390  * Caller must free the returned entry with FreeFakeRelcacheEntry().
391  */
392 Relation
393 CreateFakeRelcacheEntry(RelFileNode rnode)
394 {
395         FakeRelCacheEntry fakeentry;
396         Relation        rel;
397
398         Assert(InRecovery);
399
400         /* Allocate the Relation struct and all related space in one block. */
401         fakeentry = palloc0(sizeof(FakeRelCacheEntryData));
402         rel = (Relation) fakeentry;
403
404         rel->rd_rel = &fakeentry->pgc;
405         rel->rd_node = rnode;
406         /* We will never be working with temp rels during recovery */
407         rel->rd_backend = InvalidBackendId;
408
409         /* It must be a permanent table if we're in recovery. */
410         rel->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
411
412         /* We don't know the name of the relation; use relfilenode instead */
413         sprintf(RelationGetRelationName(rel), "%u", rnode.relNode);
414
415         /*
416          * We set up the lockRelId in case anything tries to lock the dummy
417          * relation.  Note that this is fairly bogus since relNode may be
418          * different from the relation's OID.  It shouldn't really matter though,
419          * since we are presumably running by ourselves and can't have any lock
420          * conflicts ...
421          */
422         rel->rd_lockInfo.lockRelId.dbId = rnode.dbNode;
423         rel->rd_lockInfo.lockRelId.relId = rnode.relNode;
424
425         rel->rd_smgr = NULL;
426
427         return rel;
428 }
429
430 /*
431  * Free a fake relation cache entry.
432  */
433 void
434 FreeFakeRelcacheEntry(Relation fakerel)
435 {
436         pfree(fakerel);
437 }
438
439 /*
440  * Drop a relation during XLOG replay
441  *
442  * This is called when the relation is about to be deleted; we need to remove
443  * any open "invalid-page" records for the relation.
444  */
445 void
446 XLogDropRelation(RelFileNode rnode, ForkNumber forknum)
447 {
448         forget_invalid_pages(rnode, forknum, 0);
449 }
450
451 /*
452  * Drop a whole database during XLOG replay
453  *
454  * As above, but for DROP DATABASE instead of dropping a single rel
455  */
456 void
457 XLogDropDatabase(Oid dbid)
458 {
459         /*
460          * This is unnecessarily heavy-handed, as it will close SMgrRelation
461          * objects for other databases as well. DROP DATABASE occurs seldom enough
462          * that it's not worth introducing a variant of smgrclose for just this
463          * purpose. XXX: Or should we rather leave the smgr entries dangling?
464          */
465         smgrcloseall();
466
467         forget_invalid_pages_db(dbid);
468 }
469
470 /*
471  * Truncate a relation during XLOG replay
472  *
473  * We need to clean up any open "invalid-page" records for the dropped pages.
474  */
475 void
476 XLogTruncateRelation(RelFileNode rnode, ForkNumber forkNum,
477                                          BlockNumber nblocks)
478 {
479         forget_invalid_pages(rnode, forkNum, nblocks);
480 }