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