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