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