PostgreSQL Source Code  git master
xlogutils.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * xlogutils.c
4  *
5  * PostgreSQL write-ahead 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-2020, 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 <unistd.h>
21 
22 #include "access/timeline.h"
23 #include "access/xlog.h"
24 #include "access/xlog_internal.h"
25 #include "access/xlogutils.h"
26 #include "miscadmin.h"
27 #include "pgstat.h"
28 #include "storage/smgr.h"
29 #include "utils/guc.h"
30 #include "utils/hsearch.h"
31 #include "utils/rel.h"
32 
33 
34 /* GUC variable */
35 bool ignore_invalid_pages = false;
36 
37 /*
38  * During XLOG replay, we may see XLOG records for incremental updates of
39  * pages that no longer exist, because their relation was later dropped or
40  * truncated. (Note: this is only possible when full_page_writes = OFF,
41  * since when it's ON, the first reference we see to a page should always
42  * be a full-page rewrite not an incremental update.) Rather than simply
43  * ignoring such records, we make a note of the referenced page, and then
44  * complain if we don't actually see a drop or truncate covering the page
45  * later in replay.
46  */
47 typedef struct xl_invalid_page_key
48 {
49  RelFileNode node; /* the relation */
50  ForkNumber forkno; /* the fork number */
51  BlockNumber blkno; /* the page */
53 
54 typedef struct xl_invalid_page
55 {
56  xl_invalid_page_key key; /* hash key ... must be first */
57  bool present; /* page existed but contained zeroes */
59 
60 static HTAB *invalid_page_tab = NULL;
61 
62 
63 /* Report a reference to an invalid page */
64 static void
66  BlockNumber blkno, bool present)
67 {
68  char *path = relpathperm(node, forkno);
69 
70  if (present)
71  elog(elevel, "page %u of relation %s is uninitialized",
72  blkno, path);
73  else
74  elog(elevel, "page %u of relation %s does not exist",
75  blkno, path);
76  pfree(path);
77 }
78 
79 /* Log a reference to an invalid page */
80 static void
82  bool present)
83 {
85  xl_invalid_page *hentry;
86  bool found;
87 
88  /*
89  * Once recovery has reached a consistent state, the invalid-page table
90  * should be empty and remain so. If a reference to an invalid page is
91  * found after consistency is reached, PANIC immediately. This might seem
92  * aggressive, but it's better than letting the invalid reference linger
93  * in the hash table until the end of recovery and PANIC there, which
94  * might come only much later if this is a standby server.
95  */
97  {
98  report_invalid_page(WARNING, node, forkno, blkno, present);
100  "WAL contains references to invalid pages");
101  }
102 
103  /*
104  * Log references to invalid pages at DEBUG1 level. This allows some
105  * tracing of the cause (note the elog context mechanism will tell us
106  * something about the XLOG record that generated the reference).
107  */
109  report_invalid_page(DEBUG1, node, forkno, blkno, present);
110 
111  if (invalid_page_tab == NULL)
112  {
113  /* create hash table when first needed */
114  HASHCTL ctl;
115 
116  memset(&ctl, 0, sizeof(ctl));
117  ctl.keysize = sizeof(xl_invalid_page_key);
118  ctl.entrysize = sizeof(xl_invalid_page);
119 
120  invalid_page_tab = hash_create("XLOG invalid-page table",
121  100,
122  &ctl,
124  }
125 
126  /* we currently assume xl_invalid_page_key contains no padding */
127  key.node = node;
128  key.forkno = forkno;
129  key.blkno = blkno;
130  hentry = (xl_invalid_page *)
131  hash_search(invalid_page_tab, (void *) &key, HASH_ENTER, &found);
132 
133  if (!found)
134  {
135  /* hash_search already filled in the key */
136  hentry->present = present;
137  }
138  else
139  {
140  /* repeat reference ... leave "present" as it was */
141  }
142 }
143 
144 /* Forget any invalid pages >= minblkno, because they've been dropped */
145 static void
147 {
149  xl_invalid_page *hentry;
150 
151  if (invalid_page_tab == NULL)
152  return; /* nothing to do */
153 
154  hash_seq_init(&status, invalid_page_tab);
155 
156  while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
157  {
158  if (RelFileNodeEquals(hentry->key.node, node) &&
159  hentry->key.forkno == forkno &&
160  hentry->key.blkno >= minblkno)
161  {
163  {
164  char *path = relpathperm(hentry->key.node, forkno);
165 
166  elog(DEBUG2, "page %u of relation %s has been dropped",
167  hentry->key.blkno, path);
168  pfree(path);
169  }
170 
171  if (hash_search(invalid_page_tab,
172  (void *) &hentry->key,
173  HASH_REMOVE, NULL) == NULL)
174  elog(ERROR, "hash table corrupted");
175  }
176  }
177 }
178 
179 /* Forget any invalid pages in a whole database */
180 static void
182 {
184  xl_invalid_page *hentry;
185 
186  if (invalid_page_tab == NULL)
187  return; /* nothing to do */
188 
189  hash_seq_init(&status, invalid_page_tab);
190 
191  while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
192  {
193  if (hentry->key.node.dbNode == dbid)
194  {
196  {
197  char *path = relpathperm(hentry->key.node, hentry->key.forkno);
198 
199  elog(DEBUG2, "page %u of relation %s has been dropped",
200  hentry->key.blkno, path);
201  pfree(path);
202  }
203 
204  if (hash_search(invalid_page_tab,
205  (void *) &hentry->key,
206  HASH_REMOVE, NULL) == NULL)
207  elog(ERROR, "hash table corrupted");
208  }
209  }
210 }
211 
212 /* Are there any unresolved references to invalid pages? */
213 bool
215 {
216  if (invalid_page_tab != NULL &&
217  hash_get_num_entries(invalid_page_tab) > 0)
218  return true;
219  return false;
220 }
221 
222 /* Complain about any remaining invalid-page entries */
223 void
225 {
227  xl_invalid_page *hentry;
228  bool foundone = false;
229 
230  if (invalid_page_tab == NULL)
231  return; /* nothing to do */
232 
233  hash_seq_init(&status, invalid_page_tab);
234 
235  /*
236  * Our strategy is to emit WARNING messages for all remaining entries and
237  * only PANIC after we've dumped all the available info.
238  */
239  while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
240  {
241  report_invalid_page(WARNING, hentry->key.node, hentry->key.forkno,
242  hentry->key.blkno, hentry->present);
243  foundone = true;
244  }
245 
246  if (foundone)
248  "WAL contains references to invalid pages");
249 
250  hash_destroy(invalid_page_tab);
251  invalid_page_tab = NULL;
252 }
253 
254 
255 /*
256  * XLogReadBufferForRedo
257  * Read a page during XLOG replay
258  *
259  * Reads a block referenced by a WAL record into shared buffer cache, and
260  * determines what needs to be done to redo the changes to it. If the WAL
261  * record includes a full-page image of the page, it is restored.
262  *
263  * 'record.EndRecPtr' is compared to the page's LSN to determine if the record
264  * has already been replayed. 'block_id' is the ID number the block was
265  * registered with, when the WAL record was created.
266  *
267  * Returns one of the following:
268  *
269  * BLK_NEEDS_REDO - changes from the WAL record need to be applied
270  * BLK_DONE - block doesn't need replaying
271  * BLK_RESTORED - block was restored from a full-page image included in
272  * the record
273  * BLK_NOTFOUND - block was not found (because it was truncated away by
274  * an operation later in the WAL stream)
275  *
276  * On return, the buffer is locked in exclusive-mode, and returned in *buf.
277  * Note that the buffer is locked and returned even if it doesn't need
278  * replaying. (Getting the buffer lock is not really necessary during
279  * single-process crash recovery, but some subroutines such as MarkBufferDirty
280  * will complain if we don't have the lock. In hot standby mode it's
281  * definitely necessary.)
282  *
283  * Note: when a backup block is available in XLOG with the BKPIMAGE_APPLY flag
284  * set, we restore it, even if the page in the database appears newer. This
285  * is to protect ourselves against database pages that were partially or
286  * incorrectly written during a crash. We assume that the XLOG data must be
287  * good because it has passed a CRC check, while the database page might not
288  * be. This will force us to replay all subsequent modifications of the page
289  * that appear in XLOG, rather than possibly ignoring them as already
290  * applied, but that's not a huge drawback.
291  */
294  Buffer *buf)
295 {
296  return XLogReadBufferForRedoExtended(record, block_id, RBM_NORMAL,
297  false, buf);
298 }
299 
300 /*
301  * Pin and lock a buffer referenced by a WAL record, for the purpose of
302  * re-initializing it.
303  */
304 Buffer
306 {
307  Buffer buf;
308 
309  XLogReadBufferForRedoExtended(record, block_id, RBM_ZERO_AND_LOCK, false,
310  &buf);
311  return buf;
312 }
313 
314 /*
315  * XLogReadBufferForRedoExtended
316  * Like XLogReadBufferForRedo, but with extra options.
317  *
318  * In RBM_ZERO_* modes, if the page doesn't exist, the relation is extended
319  * with all-zeroes pages up to the referenced block number. In
320  * RBM_ZERO_AND_LOCK and RBM_ZERO_AND_CLEANUP_LOCK modes, the return value
321  * is always BLK_NEEDS_REDO.
322  *
323  * (The RBM_ZERO_AND_CLEANUP_LOCK mode is redundant with the get_cleanup_lock
324  * parameter. Do not use an inconsistent combination!)
325  *
326  * If 'get_cleanup_lock' is true, a "cleanup lock" is acquired on the buffer
327  * using LockBufferForCleanup(), instead of a regular exclusive lock.
328  */
331  uint8 block_id,
332  ReadBufferMode mode, bool get_cleanup_lock,
333  Buffer *buf)
334 {
335  XLogRecPtr lsn = record->EndRecPtr;
336  RelFileNode rnode;
337  ForkNumber forknum;
339  Page page;
340  bool zeromode;
341  bool willinit;
342 
343  if (!XLogRecGetBlockTag(record, block_id, &rnode, &forknum, &blkno))
344  {
345  /* Caller specified a bogus block_id */
346  elog(PANIC, "failed to locate backup block with ID %d", block_id);
347  }
348 
349  /*
350  * Make sure that if the block is marked with WILL_INIT, the caller is
351  * going to initialize it. And vice versa.
352  */
353  zeromode = (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
354  willinit = (record->blocks[block_id].flags & BKPBLOCK_WILL_INIT) != 0;
355  if (willinit && !zeromode)
356  elog(PANIC, "block with WILL_INIT flag in WAL record must be zeroed by redo routine");
357  if (!willinit && zeromode)
358  elog(PANIC, "block to be initialized in redo routine must be marked with WILL_INIT flag in the WAL record");
359 
360  /* If it has a full-page image and it should be restored, do it. */
361  if (XLogRecBlockImageApply(record, block_id))
362  {
363  Assert(XLogRecHasBlockImage(record, block_id));
364  *buf = XLogReadBufferExtended(rnode, forknum, blkno,
365  get_cleanup_lock ? RBM_ZERO_AND_CLEANUP_LOCK : RBM_ZERO_AND_LOCK);
366  page = BufferGetPage(*buf);
367  if (!RestoreBlockImage(record, block_id, page))
368  elog(ERROR, "failed to restore block image");
369 
370  /*
371  * The page may be uninitialized. If so, we can't set the LSN because
372  * that would corrupt the page.
373  */
374  if (!PageIsNew(page))
375  {
376  PageSetLSN(page, lsn);
377  }
378 
379  MarkBufferDirty(*buf);
380 
381  /*
382  * At the end of crash recovery the init forks of unlogged relations
383  * are copied, without going through shared buffers. So we need to
384  * force the on-disk state of init forks to always be in sync with the
385  * state in shared buffers.
386  */
387  if (forknum == INIT_FORKNUM)
388  FlushOneBuffer(*buf);
389 
390  return BLK_RESTORED;
391  }
392  else
393  {
394  *buf = XLogReadBufferExtended(rnode, forknum, blkno, mode);
395  if (BufferIsValid(*buf))
396  {
397  if (mode != RBM_ZERO_AND_LOCK && mode != RBM_ZERO_AND_CLEANUP_LOCK)
398  {
399  if (get_cleanup_lock)
400  LockBufferForCleanup(*buf);
401  else
403  }
404  if (lsn <= PageGetLSN(BufferGetPage(*buf)))
405  return BLK_DONE;
406  else
407  return BLK_NEEDS_REDO;
408  }
409  else
410  return BLK_NOTFOUND;
411  }
412 }
413 
414 /*
415  * XLogReadBufferExtended
416  * Read a page during XLOG replay
417  *
418  * This is functionally comparable to ReadBufferExtended. There's some
419  * differences in the behavior wrt. the "mode" argument:
420  *
421  * In RBM_NORMAL mode, if the page doesn't exist, or contains all-zeroes, we
422  * return InvalidBuffer. In this case the caller should silently skip the
423  * update on this page. (In this situation, we expect that the page was later
424  * dropped or truncated. If we don't see evidence of that later in the WAL
425  * sequence, we'll complain at the end of WAL replay.)
426  *
427  * In RBM_ZERO_* modes, if the page doesn't exist, the relation is extended
428  * with all-zeroes pages up to the given block number.
429  *
430  * In RBM_NORMAL_NO_LOG mode, we return InvalidBuffer if the page doesn't
431  * exist, and we don't check for all-zeroes. Thus, no log entry is made
432  * to imply that the page should be dropped or truncated later.
433  *
434  * NB: A redo function should normally not call this directly. To get a page
435  * to modify, use XLogReadBufferForRedoExtended instead. It is important that
436  * all pages modified by a WAL record are registered in the WAL records, or
437  * they will be invisible to tools that that need to know which pages are
438  * modified.
439  */
440 Buffer
443 {
444  BlockNumber lastblock;
445  Buffer buffer;
446  SMgrRelation smgr;
447 
448  Assert(blkno != P_NEW);
449 
450  /* Open the relation at smgr level */
451  smgr = smgropen(rnode, InvalidBackendId);
452 
453  /*
454  * Create the target file if it doesn't already exist. This lets us cope
455  * if the replay sequence contains writes to a relation that is later
456  * deleted. (The original coding of this routine would instead suppress
457  * the writes, but that seems like it risks losing valuable data if the
458  * filesystem loses an inode during a crash. Better to write the data
459  * until we are actually told to delete the file.)
460  */
461  smgrcreate(smgr, forknum, true);
462 
463  lastblock = smgrnblocks(smgr, forknum);
464 
465  if (blkno < lastblock)
466  {
467  /* page exists in file */
468  buffer = ReadBufferWithoutRelcache(rnode, forknum, blkno,
469  mode, NULL);
470  }
471  else
472  {
473  /* hm, page doesn't exist in file */
474  if (mode == RBM_NORMAL)
475  {
476  log_invalid_page(rnode, forknum, blkno, false);
477  return InvalidBuffer;
478  }
479  if (mode == RBM_NORMAL_NO_LOG)
480  return InvalidBuffer;
481  /* OK to extend the file */
482  /* we do this in recovery only - no rel-extension lock needed */
484  buffer = InvalidBuffer;
485  do
486  {
487  if (buffer != InvalidBuffer)
488  {
489  if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
491  ReleaseBuffer(buffer);
492  }
493  buffer = ReadBufferWithoutRelcache(rnode, forknum,
494  P_NEW, mode, NULL);
495  }
496  while (BufferGetBlockNumber(buffer) < blkno);
497  /* Handle the corner case that P_NEW returns non-consecutive pages */
498  if (BufferGetBlockNumber(buffer) != blkno)
499  {
500  if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
502  ReleaseBuffer(buffer);
503  buffer = ReadBufferWithoutRelcache(rnode, forknum, blkno,
504  mode, NULL);
505  }
506  }
507 
508  if (mode == RBM_NORMAL)
509  {
510  /* check that page has been initialized */
511  Page page = (Page) BufferGetPage(buffer);
512 
513  /*
514  * We assume that PageIsNew is safe without a lock. During recovery,
515  * there should be no other backends that could modify the buffer at
516  * the same time.
517  */
518  if (PageIsNew(page))
519  {
520  ReleaseBuffer(buffer);
521  log_invalid_page(rnode, forknum, blkno, true);
522  return InvalidBuffer;
523  }
524  }
525 
526  return buffer;
527 }
528 
529 /*
530  * Struct actually returned by CreateFakeRelcacheEntry, though the declared
531  * return type is Relation.
532  */
533 typedef struct
534 {
535  RelationData reldata; /* Note: this must be first */
538 
540 
541 /*
542  * Create a fake relation cache entry for a physical relation
543  *
544  * It's often convenient to use the same functions in XLOG replay as in the
545  * main codepath, but those functions typically work with a relcache entry.
546  * We don't have a working relation cache during XLOG replay, but this
547  * function can be used to create a fake relcache entry instead. Only the
548  * fields related to physical storage, like rd_rel, are initialized, so the
549  * fake entry is only usable in low-level operations like ReadBuffer().
550  *
551  * This is also used for syncing WAL-skipped files.
552  *
553  * Caller must free the returned entry with FreeFakeRelcacheEntry().
554  */
555 Relation
557 {
558  FakeRelCacheEntry fakeentry;
559  Relation rel;
560 
561  /* Allocate the Relation struct and all related space in one block. */
562  fakeentry = palloc0(sizeof(FakeRelCacheEntryData));
563  rel = (Relation) fakeentry;
564 
565  rel->rd_rel = &fakeentry->pgc;
566  rel->rd_node = rnode;
567 
568  /*
569  * We will never be working with temp rels during recovery or while
570  * syncing WAL-skipped files.
571  */
573 
574  /* It must be a permanent table here */
575  rel->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
576 
577  /* We don't know the name of the relation; use relfilenode instead */
578  sprintf(RelationGetRelationName(rel), "%u", rnode.relNode);
579 
580  /*
581  * We set up the lockRelId in case anything tries to lock the dummy
582  * relation. Note that this is fairly bogus since relNode may be
583  * different from the relation's OID. It shouldn't really matter though.
584  * In recovery, we are running by ourselves and can't have any lock
585  * conflicts. While syncing, we already hold AccessExclusiveLock.
586  */
587  rel->rd_lockInfo.lockRelId.dbId = rnode.dbNode;
588  rel->rd_lockInfo.lockRelId.relId = rnode.relNode;
589 
590  rel->rd_smgr = NULL;
591 
592  return rel;
593 }
594 
595 /*
596  * Free a fake relation cache entry.
597  */
598 void
600 {
601  /* make sure the fakerel is not referenced by the SmgrRelation anymore */
602  if (fakerel->rd_smgr != NULL)
603  smgrclearowner(&fakerel->rd_smgr, fakerel->rd_smgr);
604  pfree(fakerel);
605 }
606 
607 /*
608  * Drop a relation during XLOG replay
609  *
610  * This is called when the relation is about to be deleted; we need to remove
611  * any open "invalid-page" records for the relation.
612  */
613 void
615 {
616  forget_invalid_pages(rnode, forknum, 0);
617 }
618 
619 /*
620  * Drop a whole database during XLOG replay
621  *
622  * As above, but for DROP DATABASE instead of dropping a single rel
623  */
624 void
626 {
627  /*
628  * This is unnecessarily heavy-handed, as it will close SMgrRelation
629  * objects for other databases as well. DROP DATABASE occurs seldom enough
630  * that it's not worth introducing a variant of smgrclose for just this
631  * purpose. XXX: Or should we rather leave the smgr entries dangling?
632  */
633  smgrcloseall();
634 
636 }
637 
638 /*
639  * Truncate a relation during XLOG replay
640  *
641  * We need to clean up any open "invalid-page" records for the dropped pages.
642  */
643 void
645  BlockNumber nblocks)
646 {
647  forget_invalid_pages(rnode, forkNum, nblocks);
648 }
649 
650 /*
651  * Determine which timeline to read an xlog page from and set the
652  * XLogReaderState's currTLI to that timeline ID.
653  *
654  * We care about timelines in xlogreader when we might be reading xlog
655  * generated prior to a promotion, either if we're currently a standby in
656  * recovery or if we're a promoted primary reading xlogs generated by the old
657  * primary before our promotion.
658  *
659  * wantPage must be set to the start address of the page to read and
660  * wantLength to the amount of the page that will be read, up to
661  * XLOG_BLCKSZ. If the amount to be read isn't known, pass XLOG_BLCKSZ.
662  *
663  * We switch to an xlog segment from the new timeline eagerly when on a
664  * historical timeline, as soon as we reach the start of the xlog segment
665  * containing the timeline switch. The server copied the segment to the new
666  * timeline so all the data up to the switch point is the same, but there's no
667  * guarantee the old segment will still exist. It may have been deleted or
668  * renamed with a .partial suffix so we can't necessarily keep reading from
669  * the old TLI even though tliSwitchPoint says it's OK.
670  *
671  * We can't just check the timeline when we read a page on a different segment
672  * to the last page. We could've received a timeline switch from a cascading
673  * upstream, so the current segment ends abruptly (possibly getting renamed to
674  * .partial) and we have to switch to a new one. Even in the middle of reading
675  * a page we could have to dump the cached page and switch to a new TLI.
676  *
677  * Because of this, callers MAY NOT assume that currTLI is the timeline that
678  * will be in a page's xlp_tli; the page may begin on an older timeline or we
679  * might be reading from historical timeline data on a segment that's been
680  * copied to a new timeline.
681  *
682  * The caller must also make sure it doesn't read past the current replay
683  * position (using GetXLogReplayRecPtr) if executing in recovery, so it
684  * doesn't fail to notice that the current timeline became historical. The
685  * caller must also update ThisTimeLineID with the result of
686  * GetXLogReplayRecPtr and must check RecoveryInProgress().
687  */
688 void
690 {
691  const XLogRecPtr lastReadPage = (state->seg.ws_segno *
692  state->segcxt.ws_segsize + state->segoff);
693 
694  Assert(wantPage != InvalidXLogRecPtr && wantPage % XLOG_BLCKSZ == 0);
695  Assert(wantLength <= XLOG_BLCKSZ);
696  Assert(state->readLen == 0 || state->readLen <= XLOG_BLCKSZ);
697 
698  /*
699  * If the desired page is currently read in and valid, we have nothing to
700  * do.
701  *
702  * The caller should've ensured that it didn't previously advance readOff
703  * past the valid limit of this timeline, so it doesn't matter if the
704  * current TLI has since become historical.
705  */
706  if (lastReadPage == wantPage &&
707  state->readLen != 0 &&
708  lastReadPage + state->readLen >= wantPage + Min(wantLength, XLOG_BLCKSZ - 1))
709  return;
710 
711  /*
712  * If we're reading from the current timeline, it hasn't become historical
713  * and the page we're reading is after the last page read, we can again
714  * just carry on. (Seeking backwards requires a check to make sure the
715  * older page isn't on a prior timeline).
716  *
717  * ThisTimeLineID might've become historical since we last looked, but the
718  * caller is required not to read past the flush limit it saw at the time
719  * it looked up the timeline. There's nothing we can do about it if
720  * StartupXLOG() renames it to .partial concurrently.
721  */
722  if (state->currTLI == ThisTimeLineID && wantPage >= lastReadPage)
723  {
725  return;
726  }
727 
728  /*
729  * If we're just reading pages from a previously validated historical
730  * timeline and the timeline we're reading from is valid until the end of
731  * the current segment we can just keep reading.
732  */
733  if (state->currTLIValidUntil != InvalidXLogRecPtr &&
734  state->currTLI != ThisTimeLineID &&
735  state->currTLI != 0 &&
736  ((wantPage + wantLength) / state->segcxt.ws_segsize) <
737  (state->currTLIValidUntil / state->segcxt.ws_segsize))
738  return;
739 
740  /*
741  * If we reach this point we're either looking up a page for random
742  * access, the current timeline just became historical, or we're reading
743  * from a new segment containing a timeline switch. In all cases we need
744  * to determine the newest timeline on the segment.
745  *
746  * If it's the current timeline we can just keep reading from here unless
747  * we detect a timeline switch that makes the current timeline historical.
748  * If it's a historical timeline we can read all the segment on the newest
749  * timeline because it contains all the old timelines' data too. So only
750  * one switch check is required.
751  */
752  {
753  /*
754  * We need to re-read the timeline history in case it's been changed
755  * by a promotion or replay from a cascaded replica.
756  */
757  List *timelineHistory = readTimeLineHistory(ThisTimeLineID);
758  XLogRecPtr endOfSegment;
759 
760  endOfSegment = ((wantPage / state->segcxt.ws_segsize) + 1) *
761  state->segcxt.ws_segsize - 1;
762  Assert(wantPage / state->segcxt.ws_segsize ==
763  endOfSegment / state->segcxt.ws_segsize);
764 
765  /*
766  * Find the timeline of the last LSN on the segment containing
767  * wantPage.
768  */
769  state->currTLI = tliOfPointInHistory(endOfSegment, timelineHistory);
770  state->currTLIValidUntil = tliSwitchPoint(state->currTLI, timelineHistory,
771  &state->nextTLI);
772 
774  wantPage + wantLength < state->currTLIValidUntil);
775 
776  list_free_deep(timelineHistory);
777 
778  elog(DEBUG3, "switched to timeline %u valid until %X/%X",
779  state->currTLI,
780  (uint32) (state->currTLIValidUntil >> 32),
781  (uint32) (state->currTLIValidUntil));
782  }
783 }
784 
785 /* XLogReaderRoutine->segment_open callback for local pg_wal files */
786 void
788  TimeLineID *tli_p)
789 {
790  TimeLineID tli = *tli_p;
791  char path[MAXPGPATH];
792 
793  XLogFilePath(path, tli, nextSegNo, state->segcxt.ws_segsize);
794  state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY);
795  if (state->seg.ws_file >= 0)
796  return;
797 
798  if (errno == ENOENT)
799  ereport(ERROR,
801  errmsg("requested WAL segment %s has already been removed",
802  path)));
803  else
804  ereport(ERROR,
806  errmsg("could not open file \"%s\": %m",
807  path)));
808 }
809 
810 /* stock XLogReaderRoutine->segment_close callback */
811 void
813 {
814  close(state->seg.ws_file);
815  /* need to check errno? */
816  state->seg.ws_file = -1;
817 }
818 
819 /*
820  * XLogReaderRoutine->page_read callback for reading local xlog files
821  *
822  * Public because it would likely be very helpful for someone writing another
823  * output method outside walsender, e.g. in a bgworker.
824  *
825  * TODO: The walsender has its own version of this, but it relies on the
826  * walsender's latch being set whenever WAL is flushed. No such infrastructure
827  * exists for normal backends, so we have to do a check/sleep/repeat style of
828  * loop for now.
829  */
830 int
832  int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
833 {
834  XLogRecPtr read_upto,
835  loc;
836  TimeLineID tli;
837  int count;
838  WALReadError errinfo;
839 
840  loc = targetPagePtr + reqLen;
841 
842  /* Loop waiting for xlog to be available if necessary */
843  while (1)
844  {
845  /*
846  * Determine the limit of xlog we can currently read to, and what the
847  * most recent timeline is.
848  *
849  * RecoveryInProgress() will update ThisTimeLineID when it first
850  * notices recovery finishes, so we only have to maintain it for the
851  * local process until recovery ends.
852  */
853  if (!RecoveryInProgress())
854  read_upto = GetFlushRecPtr();
855  else
856  read_upto = GetXLogReplayRecPtr(&ThisTimeLineID);
857  tli = ThisTimeLineID;
858 
859  /*
860  * Check which timeline to get the record from.
861  *
862  * We have to do it each time through the loop because if we're in
863  * recovery as a cascading standby, the current timeline might've
864  * become historical. We can't rely on RecoveryInProgress() because in
865  * a standby configuration like
866  *
867  * A => B => C
868  *
869  * if we're a logical decoding session on C, and B gets promoted, our
870  * timeline will change while we remain in recovery.
871  *
872  * We can't just keep reading from the old timeline as the last WAL
873  * archive in the timeline will get renamed to .partial by
874  * StartupXLOG().
875  *
876  * If that happens after our caller updated ThisTimeLineID but before
877  * we actually read the xlog page, we might still try to read from the
878  * old (now renamed) segment and fail. There's not much we can do
879  * about this, but it can only happen when we're a leaf of a cascading
880  * standby whose primary gets promoted while we're decoding, so a
881  * one-off ERROR isn't too bad.
882  */
883  XLogReadDetermineTimeline(state, targetPagePtr, reqLen);
884 
885  if (state->currTLI == ThisTimeLineID)
886  {
887 
888  if (loc <= read_upto)
889  break;
890 
892  pg_usleep(1000L);
893  }
894  else
895  {
896  /*
897  * We're on a historical timeline, so limit reading to the switch
898  * point where we moved to the next timeline.
899  *
900  * We don't need to GetFlushRecPtr or GetXLogReplayRecPtr. We know
901  * about the new timeline, so we must've received past the end of
902  * it.
903  */
904  read_upto = state->currTLIValidUntil;
905 
906  /*
907  * Setting tli to our wanted record's TLI is slightly wrong; the
908  * page might begin on an older timeline if it contains a timeline
909  * switch, since its xlog segment will have been copied from the
910  * prior timeline. This is pretty harmless though, as nothing
911  * cares so long as the timeline doesn't go backwards. We should
912  * read the page header instead; FIXME someday.
913  */
914  tli = state->currTLI;
915 
916  /* No need to wait on a historical timeline */
917  break;
918  }
919  }
920 
921  if (targetPagePtr + XLOG_BLCKSZ <= read_upto)
922  {
923  /*
924  * more than one block available; read only that block, have caller
925  * come back if they need more.
926  */
927  count = XLOG_BLCKSZ;
928  }
929  else if (targetPagePtr + reqLen > read_upto)
930  {
931  /* not enough data there */
932  return -1;
933  }
934  else
935  {
936  /* enough bytes available to satisfy the request */
937  count = read_upto - targetPagePtr;
938  }
939 
940  /*
941  * Even though we just determined how much of the page can be validly read
942  * as 'count', read the whole page anyway. It's guaranteed to be
943  * zero-padded up to the page boundary if it's incomplete.
944  */
945  if (!WALRead(state, cur_page, targetPagePtr, XLOG_BLCKSZ, tli,
946  &errinfo))
947  WALReadRaiseError(&errinfo);
948 
949  /* number of valid bytes in the buffer */
950  return count;
951 }
952 
953 /*
954  * Backend-specific convenience code to handle read errors encountered by
955  * WALRead().
956  */
957 void
959 {
960  WALOpenSegment *seg = &errinfo->wre_seg;
961  char fname[MAXFNAMELEN];
962 
963  XLogFileName(fname, seg->ws_tli, seg->ws_segno, wal_segment_size);
964 
965  if (errinfo->wre_read < 0)
966  {
967  errno = errinfo->wre_errno;
968  ereport(ERROR,
970  errmsg("could not read from log segment %s, offset %u: %m",
971  fname, errinfo->wre_off)));
972  }
973  else if (errinfo->wre_read == 0)
974  {
975  ereport(ERROR,
977  errmsg("could not read from log segment %s, offset %u: read %d of %zu",
978  fname, errinfo->wre_off, errinfo->wre_read,
979  (Size) errinfo->wre_req)));
980  }
981 }
WALOpenSegment wre_seg
Definition: xlogreader.h:291
bool XLogHaveInvalidPages(void)
Definition: xlogutils.c:214
void XLogTruncateRelation(RelFileNode rnode, ForkNumber forkNum, BlockNumber nblocks)
Definition: xlogutils.c:644
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:827
void LockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:3809
LockRelId lockRelId
Definition: rel.h:44
#define relpathperm(rnode, forknum)
Definition: relpath.h:83
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
TimeLineID tliOfPointInHistory(XLogRecPtr ptr, List *history)
Definition: timeline.c:552
#define DEBUG1
Definition: elog.h:25
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:334
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:812
uint32 TimeLineID
Definition: xlogdefs.h:52
void smgrclearowner(SMgrRelation *owner, SMgrRelation reln)
Definition: smgr.c:228
RelationData reldata
Definition: xlogutils.c:535
struct xl_invalid_page xl_invalid_page
#define HASH_ELEM
Definition: hsearch.h:85
int wal_segment_size
Definition: xlog.c:117
#define DEBUG3
Definition: elog.h:23
#define XLogRecHasBlockImage(decoder, block_id)
Definition: xlogreader.h:315
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1471
static void forget_invalid_pages_db(Oid dbid)
Definition: xlogutils.c:181
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
void XLogCheckInvalidPages(void)
Definition: xlogutils.c:224
bool InRecovery
Definition: xlog.c:205
#define Min(x, y)
Definition: c.h:982
Oid dbId
Definition: rel.h:39
void WALReadRaiseError(WALReadError *errinfo)
Definition: xlogutils.c:958
List * readTimeLineHistory(TimeLineID targetTLI)
Definition: timeline.c:76
Buffer XLogReadBufferExtended(RelFileNode rnode, ForkNumber forknum, BlockNumber blkno, ReadBufferMode mode)
Definition: xlogutils.c:441
unsigned char uint8
Definition: c.h:427
#define InvalidBuffer
Definition: buf.h:25
Size entrysize
Definition: hsearch.h:72
Buffer ReadBufferWithoutRelcache(RelFileNode rnode, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:696
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:787
int errcode(int sqlerrcode)
Definition: elog.c:691
struct xl_invalid_page_key xl_invalid_page_key
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1347
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8422
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3513
ForkNumber forkno
Definition: xlogutils.c:50
#define P_NEW
Definition: bufmgr.h:91
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:98
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:8070
#define PANIC
Definition: elog.h:53
void list_free_deep(List *list)
Definition: list.c:1390
#define PG_BINARY
Definition: c.h:1267
void XLogReadDetermineTimeline(XLogReaderState *state, XLogRecPtr wantPage, uint32 wantLength)
Definition: xlogutils.c:689
XLogRecPtr EndRecPtr
Definition: xlogreader.h:176
void smgrcloseall(void)
Definition: smgr.c:287
#define sprintf
Definition: port.h:217
WALOpenSegment seg
Definition: xlogreader.h:215
RelFileNode node
Definition: xlogutils.c:49
void pg_usleep(long microsec)
Definition: signal.c:53
Definition: dynahash.c:218
struct RelationData * Relation
Definition: relcache.h:27
void pfree(void *pointer)
Definition: mcxt.c:1057
static void report_invalid_page(int elevel, RelFileNode node, ForkNumber forkno, BlockNumber blkno, bool present)
Definition: xlogutils.c:65
#define ERROR
Definition: elog.h:43
Buffer XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id)
Definition: xlogutils.c:305
static void log_invalid_page(RelFileNode node, ForkNumber forkno, BlockNumber blkno, bool present)
Definition: xlogutils.c:81
#define MAXPGPATH
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11480
#define DEBUG2
Definition: elog.h:24
bool message_level_is_interesting(int elevel)
Definition: elog.c:264
Relation CreateFakeRelcacheEntry(RelFileNode rnode)
Definition: xlogutils.c:556
static void forget_invalid_pages(RelFileNode node, ForkNumber forkno, BlockNumber minblkno)
Definition: xlogutils.c:146
LockInfoData rd_lockInfo
Definition: rel.h:113
static char * buf
Definition: pg_test_fsync.c:68
uint64 XLogSegNo
Definition: xlogdefs.h:41
BlockNumber blkno
Definition: xlogutils.c:51
xl_invalid_page_key key
Definition: xlogutils.c:56
XLogSegNo ws_segno
Definition: xlogreader.h:47
int errcode_for_file_access(void)
Definition: elog.c:714
XLogRecPtr currTLIValidUntil
Definition: xlogreader.h:238
#define RelationGetRelationName(relation)
Definition: rel.h:491
unsigned int uint32
Definition: c.h:429
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
#define BKPBLOCK_WILL_INIT
Definition: xlogrecord.h:182
bool ignore_invalid_pages
Definition: xlogutils.c:35
SMgrRelation smgropen(RelFileNode rnode, BackendId backend)
Definition: smgr.c:146
ForkNumber
Definition: relpath.h:40
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:45
#define WARNING
Definition: elog.h:40
ReadBufferMode
Definition: bufmgr.h:37
void FreeFakeRelcacheEntry(Relation fakerel)
Definition: xlogutils.c:599
#define MAXFNAMELEN
static int elevel
Definition: vacuumlazy.c:333
TimeLineID nextTLI
Definition: xlogreader.h:244
bool XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
Definition: xlogreader.c:1498
#define HASH_BLOBS
Definition: hsearch.h:86
#define InvalidBackendId
Definition: backendid.h:23
void * palloc0(Size size)
Definition: mcxt.c:981
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:326
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3752
Size keysize
Definition: hsearch.h:71
XLogRecPtr tliSwitchPoint(TimeLineID tli, List *history, TimeLineID *nextTLI)
Definition: timeline.c:580
TimeLineID ThisTimeLineID
Definition: xlog.c:192
#define ereport(elevel,...)
Definition: elog.h:155
TimeLineID currTLI
Definition: xlogreader.h:228
XLogRedoAction XLogReadBufferForRedo(XLogReaderState *record, uint8 block_id, Buffer *buf)
Definition: xlogutils.c:293
RelFileNode rd_node
Definition: rel.h:55
bool reachedConsistency
Definition: xlog.c:870
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:549
FakeRelCacheEntryData * FakeRelCacheEntry
Definition: xlogutils.c:539
uint64 XLogRecPtr
Definition: xlogdefs.h:21
BackendId rd_backend
Definition: rel.h:59
#define Assert(condition)
Definition: c.h:800
Definition: regguts.h:298
XLogRedoAction
Definition: xlogutils.h:27
size_t Size
Definition: c.h:528
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1401
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1391
TimeLineID ws_tli
Definition: xlogreader.h:48
void FlushOneBuffer(Buffer buffer)
Definition: bufmgr.c:3493
bool RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
Definition: xlogreader.c:1551
#define PageGetLSN(page)
Definition: bufpage.h:366
int BasicOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:986
FormData_pg_class
Definition: pg_class.h:142
#define XLogFilePath(path, tli, logSegNo, wal_segsz_bytes)
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2663
void XLogDropRelation(RelFileNode rnode, ForkNumber forknum)
Definition: xlogutils.c:614
#define PageIsNew(page)
Definition: bufpage.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:902
XLogRedoAction XLogReadBufferForRedoExtended(XLogReaderState *record, uint8 block_id, ReadBufferMode mode, bool get_cleanup_lock, Buffer *buf)
Definition: xlogutils.c:330
void XLogDropDatabase(Oid dbid)
Definition: xlogutils.c:625
#define elog(elevel,...)
Definition: elog.h:228
static HTAB * invalid_page_tab
Definition: xlogutils.c:60
FormData_pg_class pgc
Definition: xlogutils.c:536
bool WALRead(XLogReaderState *state, char *buf, XLogRecPtr startptr, Size count, TimeLineID tli, WALReadError *errinfo)
Definition: xlogreader.c:1063
WALSegmentContext segcxt
Definition: xlogreader.h:214
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define XLogRecBlockImageApply(decoder, block_id)
Definition: xlogreader.h:317
#define close(a)
Definition: win32.h:12
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:831
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
Definition: pg_list.h:50
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:78
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88
DecodedBkpBlock blocks[XLR_MAX_BLOCK_ID+1]
Definition: xlogreader.h:197
Oid relId
Definition: rel.h:38