PostgreSQL Source Code  git master
xlogutils.c File Reference
#include "postgres.h"
#include <unistd.h>
#include "access/timeline.h"
#include "access/xlogrecovery.h"
#include "access/xlog_internal.h"
#include "access/xlogprefetcher.h"
#include "access/xlogutils.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "storage/fd.h"
#include "storage/smgr.h"
#include "utils/guc.h"
#include "utils/hsearch.h"
#include "utils/rel.h"
Include dependency graph for xlogutils.c:

Go to the source code of this file.

Data Structures

struct  xl_invalid_page_key
 
struct  xl_invalid_page
 
struct  FakeRelCacheEntryData
 

Typedefs

typedef struct xl_invalid_page_key xl_invalid_page_key
 
typedef struct xl_invalid_page xl_invalid_page
 
typedef FakeRelCacheEntryDataFakeRelCacheEntry
 

Functions

static int read_local_xlog_page_guts (XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page, bool wait_for_wal)
 
static void report_invalid_page (int elevel, RelFileLocator locator, ForkNumber forkno, BlockNumber blkno, bool present)
 
static void log_invalid_page (RelFileLocator locator, ForkNumber forkno, BlockNumber blkno, bool present)
 
static void forget_invalid_pages (RelFileLocator locator, ForkNumber forkno, BlockNumber minblkno)
 
static void forget_invalid_pages_db (Oid dbid)
 
bool XLogHaveInvalidPages (void)
 
void XLogCheckInvalidPages (void)
 
XLogRedoAction XLogReadBufferForRedo (XLogReaderState *record, uint8 block_id, Buffer *buf)
 
Buffer XLogInitBufferForRedo (XLogReaderState *record, uint8 block_id)
 
XLogRedoAction XLogReadBufferForRedoExtended (XLogReaderState *record, uint8 block_id, ReadBufferMode mode, bool get_cleanup_lock, Buffer *buf)
 
Buffer XLogReadBufferExtended (RelFileLocator rlocator, ForkNumber forknum, BlockNumber blkno, ReadBufferMode mode, Buffer recent_buffer)
 
Relation CreateFakeRelcacheEntry (RelFileLocator rlocator)
 
void FreeFakeRelcacheEntry (Relation fakerel)
 
void XLogDropRelation (RelFileLocator rlocator, ForkNumber forknum)
 
void XLogDropDatabase (Oid dbid)
 
void XLogTruncateRelation (RelFileLocator rlocator, ForkNumber forkNum, BlockNumber nblocks)
 
void XLogReadDetermineTimeline (XLogReaderState *state, XLogRecPtr wantPage, uint32 wantLength, TimeLineID currTLI)
 
void wal_segment_open (XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
 
void wal_segment_close (XLogReaderState *state)
 
int read_local_xlog_page (XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
 
int read_local_xlog_page_no_wait (XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
 
void WALReadRaiseError (WALReadError *errinfo)
 

Variables

bool ignore_invalid_pages = false
 
bool InRecovery = false
 
HotStandbyState standbyState = STANDBY_DISABLED
 
static HTABinvalid_page_tab = NULL
 

Typedef Documentation

◆ FakeRelCacheEntry

Definition at line 583 of file xlogutils.c.

◆ xl_invalid_page

◆ xl_invalid_page_key

Function Documentation

◆ CreateFakeRelcacheEntry()

Relation CreateFakeRelcacheEntry ( RelFileLocator  rlocator)

Definition at line 600 of file xlogutils.c.

601 {
602  FakeRelCacheEntry fakeentry;
603  Relation rel;
604 
605  /* Allocate the Relation struct and all related space in one block. */
606  fakeentry = palloc0(sizeof(FakeRelCacheEntryData));
607  rel = (Relation) fakeentry;
608 
609  rel->rd_rel = &fakeentry->pgc;
610  rel->rd_locator = rlocator;
611 
612  /*
613  * We will never be working with temp rels during recovery or while
614  * syncing WAL-skipped files.
615  */
617 
618  /* It must be a permanent table here */
619  rel->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
620 
621  /* We don't know the name of the relation; use relfilenumber instead */
622  sprintf(RelationGetRelationName(rel), "%u", rlocator.relNumber);
623 
624  /*
625  * We set up the lockRelId in case anything tries to lock the dummy
626  * relation. Note that this is fairly bogus since relNumber may be
627  * different from the relation's OID. It shouldn't really matter though.
628  * In recovery, we are running by ourselves and can't have any lock
629  * conflicts. While syncing, we already hold AccessExclusiveLock.
630  */
631  rel->rd_lockInfo.lockRelId.dbId = rlocator.dbOid;
632  rel->rd_lockInfo.lockRelId.relId = rlocator.relNumber;
633 
634  rel->rd_smgr = NULL;
635 
636  return rel;
637 }
#define InvalidBackendId
Definition: backendid.h:23
void * palloc0(Size size)
Definition: mcxt.c:1230
#define sprintf
Definition: port.h:240
#define RelationGetRelationName(relation)
Definition: rel.h:535
struct RelationData * Relation
Definition: relcache.h:27
FormData_pg_class pgc
Definition: xlogutils.c:580
LockRelId lockRelId
Definition: rel.h:45
Oid relId
Definition: rel.h:39
Oid dbId
Definition: rel.h:40
RelFileNumber relNumber
LockInfoData rd_lockInfo
Definition: rel.h:113
BackendId rd_backend
Definition: rel.h:59
SMgrRelation rd_smgr
Definition: rel.h:57
RelFileLocator rd_locator
Definition: rel.h:56
Form_pg_class rd_rel
Definition: rel.h:110

References LockRelId::dbId, RelFileLocator::dbOid, InvalidBackendId, LockInfoData::lockRelId, palloc0(), FakeRelCacheEntryData::pgc, RelationData::rd_backend, RelationData::rd_locator, RelationData::rd_lockInfo, RelationData::rd_rel, RelationData::rd_smgr, RelationGetRelationName, LockRelId::relId, RelFileLocator::relNumber, and sprintf.

Referenced by heap_xlog_delete(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heap_xlog_visible(), smgr_redo(), and smgrDoPendingSyncs().

◆ forget_invalid_pages()

static void forget_invalid_pages ( RelFileLocator  locator,
ForkNumber  forkno,
BlockNumber  minblkno 
)
static

Definition at line 169 of file xlogutils.c.

171 {
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  (void *) &hentry->key,
197  HASH_REMOVE, NULL) == NULL)
198  elog(ERROR, "hash table corrupted");
199  }
200  }
201 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
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
bool message_level_is_interesting(int elevel)
Definition: elog.c:269
#define DEBUG2
Definition: elog.h:25
#define ERROR
Definition: elog.h:35
@ HASH_REMOVE
Definition: hsearch.h:115
void pfree(void *pointer)
Definition: mcxt.c:1306
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
#define RelFileLocatorEquals(locator1, locator2)
#define relpathperm(rlocator, forknum)
Definition: relpath.h:90
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
static HTAB * invalid_page_tab
Definition: xlogutils.c:81

References xl_invalid_page_key::blkno, DEBUG2, elog(), ERROR, xl_invalid_page_key::forkno, HASH_REMOVE, hash_search(), hash_seq_init(), hash_seq_search(), invalid_page_tab, xl_invalid_page::key, xl_invalid_page_key::locator, message_level_is_interesting(), pfree(), RelFileLocatorEquals, relpathperm, and status().

Referenced by XLogDropRelation(), and XLogTruncateRelation().

◆ forget_invalid_pages_db()

static void forget_invalid_pages_db ( Oid  dbid)
static

Definition at line 205 of file xlogutils.c.

206 {
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  (void *) &hentry->key,
230  HASH_REMOVE, NULL) == NULL)
231  elog(ERROR, "hash table corrupted");
232  }
233  }
234 }

References xl_invalid_page_key::blkno, RelFileLocator::dbOid, DEBUG2, elog(), ERROR, xl_invalid_page_key::forkno, HASH_REMOVE, hash_search(), hash_seq_init(), hash_seq_search(), invalid_page_tab, xl_invalid_page::key, xl_invalid_page_key::locator, message_level_is_interesting(), pfree(), relpathperm, and status().

Referenced by XLogDropDatabase().

◆ FreeFakeRelcacheEntry()

void FreeFakeRelcacheEntry ( Relation  fakerel)

Definition at line 643 of file xlogutils.c.

644 {
645  /* make sure the fakerel is not referenced by the SmgrRelation anymore */
646  if (fakerel->rd_smgr != NULL)
647  smgrclearowner(&fakerel->rd_smgr, fakerel->rd_smgr);
648  pfree(fakerel);
649 }
void smgrclearowner(SMgrRelation *owner, SMgrRelation reln)
Definition: smgr.c:227

References pfree(), RelationData::rd_smgr, and smgrclearowner().

Referenced by heap_xlog_delete(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heap_xlog_visible(), smgr_redo(), and smgrDoPendingSyncs().

◆ log_invalid_page()

static void log_invalid_page ( RelFileLocator  locator,
ForkNumber  forkno,
BlockNumber  blkno,
bool  present 
)
static

Definition at line 105 of file xlogutils.c.

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 *)
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 }
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
#define WARNING
Definition: elog.h:32
#define PANIC
Definition: elog.h:38
#define DEBUG1
Definition: elog.h:26
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
bool reachedConsistency
Definition: xlogrecovery.c:294
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
struct xl_invalid_page xl_invalid_page
struct xl_invalid_page_key xl_invalid_page_key

References DEBUG1, elog(), HASHCTL::entrysize, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), ignore_invalid_pages, invalid_page_tab, sort-test::key, HASHCTL::keysize, message_level_is_interesting(), PANIC, xl_invalid_page::present, reachedConsistency, report_invalid_page(), and WARNING.

Referenced by XLogReadBufferExtended().

◆ read_local_xlog_page()

int read_local_xlog_page ( XLogReaderState state,
XLogRecPtr  targetPagePtr,
int  reqLen,
XLogRecPtr  targetRecPtr,
char *  cur_page 
)

Definition at line 878 of file xlogutils.c.

880 {
881  return read_local_xlog_page_guts(state, targetPagePtr, reqLen,
882  targetRecPtr, cur_page, true);
883 }
Definition: regguts.h:318
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:902

References read_local_xlog_page_guts().

Referenced by create_logical_replication_slot(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), and XlogReadTwoPhaseData().

◆ read_local_xlog_page_guts()

static int read_local_xlog_page_guts ( XLogReaderState state,
XLogRecPtr  targetPagePtr,
int  reqLen,
XLogRecPtr  targetRecPtr,
char *  cur_page,
bool  wait_for_wal 
)
static

Definition at line 902 of file xlogutils.c.

905 {
906  XLogRecPtr read_upto,
907  loc;
908  TimeLineID tli;
909  int count;
910  WALReadError errinfo;
911  TimeLineID currTLI;
912 
913  loc = targetPagePtr + reqLen;
914 
915  /* Loop waiting for xlog to be available if necessary */
916  while (1)
917  {
918  /*
919  * Determine the limit of xlog we can currently read to, and what the
920  * most recent timeline is.
921  */
922  if (!RecoveryInProgress())
923  read_upto = GetFlushRecPtr(&currTLI);
924  else
925  read_upto = GetXLogReplayRecPtr(&currTLI);
926  tli = currTLI;
927 
928  /*
929  * Check which timeline to get the record from.
930  *
931  * We have to do it each time through the loop because if we're in
932  * recovery as a cascading standby, the current timeline might've
933  * become historical. We can't rely on RecoveryInProgress() because in
934  * a standby configuration like
935  *
936  * A => B => C
937  *
938  * if we're a logical decoding session on C, and B gets promoted, our
939  * timeline will change while we remain in recovery.
940  *
941  * We can't just keep reading from the old timeline as the last WAL
942  * archive in the timeline will get renamed to .partial by
943  * StartupXLOG().
944  *
945  * If that happens after our caller determined the TLI but before we
946  * actually read the xlog page, we might still try to read from the
947  * old (now renamed) segment and fail. There's not much we can do
948  * about this, but it can only happen when we're a leaf of a cascading
949  * standby whose primary gets promoted while we're decoding, so a
950  * one-off ERROR isn't too bad.
951  */
952  XLogReadDetermineTimeline(state, targetPagePtr, reqLen, tli);
953 
954  if (state->currTLI == currTLI)
955  {
956 
957  if (loc <= read_upto)
958  break;
959 
960  /* If asked, let's not wait for future WAL. */
961  if (!wait_for_wal)
962  {
963  ReadLocalXLogPageNoWaitPrivate *private_data;
964 
965  /*
966  * Inform the caller of read_local_xlog_page_no_wait that the
967  * end of WAL has been reached.
968  */
969  private_data = (ReadLocalXLogPageNoWaitPrivate *)
970  state->private_data;
971  private_data->end_of_wal = true;
972  break;
973  }
974 
976  pg_usleep(1000L);
977  }
978  else
979  {
980  /*
981  * We're on a historical timeline, so limit reading to the switch
982  * point where we moved to the next timeline.
983  *
984  * We don't need to GetFlushRecPtr or GetXLogReplayRecPtr. We know
985  * about the new timeline, so we must've received past the end of
986  * it.
987  */
988  read_upto = state->currTLIValidUntil;
989 
990  /*
991  * Setting tli to our wanted record's TLI is slightly wrong; the
992  * page might begin on an older timeline if it contains a timeline
993  * switch, since its xlog segment will have been copied from the
994  * prior timeline. This is pretty harmless though, as nothing
995  * cares so long as the timeline doesn't go backwards. We should
996  * read the page header instead; FIXME someday.
997  */
998  tli = state->currTLI;
999 
1000  /* No need to wait on a historical timeline */
1001  break;
1002  }
1003  }
1004 
1005  if (targetPagePtr + XLOG_BLCKSZ <= read_upto)
1006  {
1007  /*
1008  * more than one block available; read only that block, have caller
1009  * come back if they need more.
1010  */
1011  count = XLOG_BLCKSZ;
1012  }
1013  else if (targetPagePtr + reqLen > read_upto)
1014  {
1015  /* not enough data there */
1016  return -1;
1017  }
1018  else
1019  {
1020  /* enough bytes available to satisfy the request */
1021  count = read_upto - targetPagePtr;
1022  }
1023 
1024  /*
1025  * Even though we just determined how much of the page can be validly read
1026  * as 'count', read the whole page anyway. It's guaranteed to be
1027  * zero-padded up to the page boundary if it's incomplete.
1028  */
1029  if (!WALRead(state, cur_page, targetPagePtr, XLOG_BLCKSZ, tli,
1030  &errinfo))
1031  WALReadRaiseError(&errinfo);
1032 
1033  /* number of valid bytes in the buffer */
1034  return count;
1035 }
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
void pg_usleep(long microsec)
Definition: signal.c:53
bool RecoveryInProgress(void)
Definition: xlog.c:5912
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
Definition: xlog.c:6077
uint64 XLogRecPtr
Definition: xlogdefs.h:21
uint32 TimeLineID
Definition: xlogdefs.h:59
bool WALRead(XLogReaderState *state, char *buf, XLogRecPtr startptr, Size count, TimeLineID tli, WALReadError *errinfo)
Definition: xlogreader.c:1492
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
void XLogReadDetermineTimeline(XLogReaderState *state, XLogRecPtr wantPage, uint32 wantLength, TimeLineID currTLI)
Definition: xlogutils.c:735
void WALReadRaiseError(WALReadError *errinfo)
Definition: xlogutils.c:1042

References CHECK_FOR_INTERRUPTS, ReadLocalXLogPageNoWaitPrivate::end_of_wal, GetFlushRecPtr(), GetXLogReplayRecPtr(), pg_usleep(), RecoveryInProgress(), WALRead(), WALReadRaiseError(), and XLogReadDetermineTimeline().

Referenced by read_local_xlog_page(), and read_local_xlog_page_no_wait().

◆ read_local_xlog_page_no_wait()

int read_local_xlog_page_no_wait ( XLogReaderState state,
XLogRecPtr  targetPagePtr,
int  reqLen,
XLogRecPtr  targetRecPtr,
char *  cur_page 
)

Definition at line 890 of file xlogutils.c.

893 {
894  return read_local_xlog_page_guts(state, targetPagePtr, reqLen,
895  targetRecPtr, cur_page, false);
896 }

References read_local_xlog_page_guts().

Referenced by InitXLogReaderState().

◆ report_invalid_page()

static void report_invalid_page ( int  elevel,
RelFileLocator  locator,
ForkNumber  forkno,
BlockNumber  blkno,
bool  present 
)
static

Definition at line 89 of file xlogutils.c.

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 }

References elog(), pfree(), and relpathperm.

Referenced by log_invalid_page(), and XLogCheckInvalidPages().

◆ wal_segment_close()

void wal_segment_close ( XLogReaderState state)

◆ wal_segment_open()

void wal_segment_open ( XLogReaderState state,
XLogSegNo  nextSegNo,
TimeLineID tli_p 
)

Definition at line 834 of file xlogutils.c.

836 {
837  TimeLineID tli = *tli_p;
838  char path[MAXPGPATH];
839 
840  XLogFilePath(path, tli, nextSegNo, state->segcxt.ws_segsize);
841  state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY);
842  if (state->seg.ws_file >= 0)
843  return;
844 
845  if (errno == ENOENT)
846  ereport(ERROR,
848  errmsg("requested WAL segment %s has already been removed",
849  path)));
850  else
851  ereport(ERROR,
853  errmsg("could not open file \"%s\": %m",
854  path)));
855 }
#define PG_BINARY
Definition: c.h:1209
int errcode_for_file_access(void)
Definition: elog.c:718
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ereport(elevel,...)
Definition: elog.h:145
int BasicOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:993
#define MAXPGPATH
static void XLogFilePath(char *path, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)

References BasicOpenFile(), ereport, errcode_for_file_access(), errmsg(), ERROR, MAXPGPATH, PG_BINARY, and XLogFilePath().

Referenced by create_logical_replication_slot(), InitXLogReaderState(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), and XlogReadTwoPhaseData().

◆ WALReadRaiseError()

void WALReadRaiseError ( WALReadError errinfo)

Definition at line 1042 of file xlogutils.c.

1043 {
1044  WALOpenSegment *seg = &errinfo->wre_seg;
1045  char fname[MAXFNAMELEN];
1046 
1047  XLogFileName(fname, seg->ws_tli, seg->ws_segno, wal_segment_size);
1048 
1049  if (errinfo->wre_read < 0)
1050  {
1051  errno = errinfo->wre_errno;
1052  ereport(ERROR,
1054  errmsg("could not read from WAL segment %s, offset %d: %m",
1055  fname, errinfo->wre_off)));
1056  }
1057  else if (errinfo->wre_read == 0)
1058  {
1059  ereport(ERROR,
1061  errmsg("could not read from WAL segment %s, offset %d: read %d of %d",
1062  fname, errinfo->wre_off, errinfo->wre_read,
1063  errinfo->wre_req)));
1064  }
1065 }
int errcode(int sqlerrcode)
Definition: elog.c:695
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
XLogSegNo ws_segno
Definition: xlogreader.h:48
TimeLineID ws_tli
Definition: xlogreader.h:49
WALOpenSegment wre_seg
Definition: xlogreader.h:389
int wal_segment_size
Definition: xlog.c:146
#define MAXFNAMELEN
static void XLogFileName(char *fname, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)

References ereport, errcode(), ERRCODE_DATA_CORRUPTED, errcode_for_file_access(), errmsg(), ERROR, MAXFNAMELEN, wal_segment_size, WALReadError::wre_errno, WALReadError::wre_off, WALReadError::wre_read, WALReadError::wre_req, WALReadError::wre_seg, WALOpenSegment::ws_segno, WALOpenSegment::ws_tli, and XLogFileName().

Referenced by logical_read_xlog_page(), read_local_xlog_page_guts(), and XLogSendPhysical().

◆ XLogCheckInvalidPages()

void XLogCheckInvalidPages ( void  )

Definition at line 248 of file xlogutils.c.

249 {
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 }
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:863

References xl_invalid_page_key::blkno, elog(), xl_invalid_page_key::forkno, hash_destroy(), hash_seq_init(), hash_seq_search(), ignore_invalid_pages, invalid_page_tab, xl_invalid_page::key, xl_invalid_page_key::locator, PANIC, xl_invalid_page::present, report_invalid_page(), status(), and WARNING.

Referenced by CheckRecoveryConsistency().

◆ XLogDropDatabase()

void XLogDropDatabase ( Oid  dbid)

Definition at line 669 of file xlogutils.c.

670 {
671  /*
672  * This is unnecessarily heavy-handed, as it will close SMgrRelation
673  * objects for other databases as well. DROP DATABASE occurs seldom enough
674  * that it's not worth introducing a variant of smgrclose for just this
675  * purpose. XXX: Or should we rather leave the smgr entries dangling?
676  */
677  smgrcloseall();
678 
680 }
void smgrcloseall(void)
Definition: smgr.c:322
static void forget_invalid_pages_db(Oid dbid)
Definition: xlogutils.c:205

References forget_invalid_pages_db(), and smgrcloseall().

Referenced by dbase_redo().

◆ XLogDropRelation()

void XLogDropRelation ( RelFileLocator  rlocator,
ForkNumber  forknum 
)

Definition at line 658 of file xlogutils.c.

659 {
660  forget_invalid_pages(rlocator, forknum, 0);
661 }
static void forget_invalid_pages(RelFileLocator locator, ForkNumber forkno, BlockNumber minblkno)
Definition: xlogutils.c:169

References forget_invalid_pages().

Referenced by DropRelationFiles().

◆ XLogHaveInvalidPages()

bool XLogHaveInvalidPages ( void  )

Definition at line 238 of file xlogutils.c.

239 {
240  if (invalid_page_tab != NULL &&
242  return true;
243  return false;
244 }
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1377

References hash_get_num_entries(), and invalid_page_tab.

Referenced by RecoveryRestartPoint().

◆ XLogInitBufferForRedo()

◆ XLogReadBufferExtended()

Buffer XLogReadBufferExtended ( RelFileLocator  rlocator,
ForkNumber  forknum,
BlockNumber  blkno,
ReadBufferMode  mode,
Buffer  recent_buffer 
)

Definition at line 474 of file xlogutils.c.

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 = InvalidBuffer;
528  do
529  {
530  if (buffer != InvalidBuffer)
531  {
534  ReleaseBuffer(buffer);
535  }
536  buffer = ReadBufferWithoutRelcache(rlocator, forknum,
537  P_NEW, mode, NULL, true);
538  }
539  while (BufferGetBlockNumber(buffer) < blkno);
540  /* Handle the corner case that P_NEW returns non-consecutive pages */
541  if (BufferGetBlockNumber(buffer) != blkno)
542  {
545  ReleaseBuffer(buffer);
546  buffer = ReadBufferWithoutRelcache(rlocator, forknum, blkno,
547  mode, NULL, true);
548  }
549  }
550 
551 recent_buffer_fast_path:
552  if (mode == RBM_NORMAL)
553  {
554  /* check that page has been initialized */
555  Page page = (Page) BufferGetPage(buffer);
556 
557  /*
558  * We assume that PageIsNew is safe without a lock. During recovery,
559  * there should be no other backends that could modify the buffer at
560  * the same time.
561  */
562  if (PageIsNew(page))
563  {
564  ReleaseBuffer(buffer);
565  log_invalid_page(rlocator, forknum, blkno, true);
566  return InvalidBuffer;
567  }
568  }
569 
570  return buffer;
571 }
uint32 BlockNumber
Definition: block.h:31
#define InvalidBuffer
Definition: buf.h:25
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2763
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3931
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4172
Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
Definition: bufmgr.c:799
bool ReadRecentBuffer(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, Buffer recent_buffer)
Definition: bufmgr.c:623
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:105
#define P_NEW
Definition: bufmgr.h:100
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:280
@ RBM_ZERO_AND_CLEANUP_LOCK
Definition: bufmgr.h:42
@ RBM_NORMAL
Definition: bufmgr.h:39
@ RBM_NORMAL_NO_LOG
Definition: bufmgr.h:45
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:228
Pointer Page
Definition: bufpage.h:78
static bool PageIsNew(Page page)
Definition: bufpage.h:230
Assert(fmt[strlen(fmt) - 1] !='\n')
static PgChecksumMode mode
Definition: pg_checksums.c:65
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:579
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:369
SMgrRelation smgropen(RelFileLocator rlocator, BackendId backend)
Definition: smgr.c:146
bool InRecovery
Definition: xlogutils.c:53
static void log_invalid_page(RelFileLocator locator, ForkNumber forkno, BlockNumber blkno, bool present)
Definition: xlogutils.c:105

References Assert(), BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferGetPage(), BufferIsValid(), InRecovery, InvalidBackendId, InvalidBuffer, LockBuffer(), log_invalid_page(), mode, P_NEW, PageIsNew(), RBM_NORMAL, RBM_NORMAL_NO_LOG, RBM_ZERO_AND_CLEANUP_LOCK, RBM_ZERO_AND_LOCK, ReadBufferWithoutRelcache(), ReadRecentBuffer(), ReleaseBuffer(), smgrcreate(), smgrnblocks(), and smgropen().

Referenced by verifyBackupPageConsistency(), XLogReadBufferForRedoExtended(), and XLogRecordPageWithFreeSpace().

◆ XLogReadBufferForRedo()

XLogRedoAction XLogReadBufferForRedo ( XLogReaderState record,
uint8  block_id,
Buffer buf 
)

Definition at line 317 of file xlogutils.c.

319 {
320  return XLogReadBufferForRedoExtended(record, block_id, RBM_NORMAL,
321  false, buf);
322 }

References buf, RBM_NORMAL, and XLogReadBufferForRedoExtended().

Referenced by _bt_clear_incomplete_split(), brin_xlog_desummarize_page(), brin_xlog_insert_update(), brin_xlog_revmap_extend(), brin_xlog_samepage_update(), brin_xlog_update(), btree_xlog_dedup(), btree_xlog_delete(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_split(), btree_xlog_unlink_page(), generic_redo(), ginRedoClearIncompleteSplit(), ginRedoDeletePage(), ginRedoInsert(), ginRedoSplit(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginRedoVacuumPage(), gistRedoClearFollowRight(), gistRedoDeleteRecord(), gistRedoPageDelete(), gistRedoPageUpdateRecord(), hash_xlog_add_ovfl_page(), hash_xlog_delete(), hash_xlog_init_bitmap_page(), hash_xlog_insert(), hash_xlog_move_page_contents(), hash_xlog_split_allocate_page(), hash_xlog_split_cleanup(), hash_xlog_split_complete(), hash_xlog_split_page(), hash_xlog_squeeze_page(), hash_xlog_update_meta_page(), hash_xlog_vacuum_one_page(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_freeze_page(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heap_xlog_visible(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), and xlog_redo().

◆ XLogReadBufferForRedoExtended()

XLogRedoAction XLogReadBufferForRedoExtended ( XLogReaderState record,
uint8  block_id,
ReadBufferMode  mode,
bool  get_cleanup_lock,
Buffer buf 
)

Definition at line 354 of file xlogutils.c.

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 }
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1583
void LockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:4229
void FlushOneBuffer(Buffer buffer)
Definition: bufmgr.c:3911
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:107
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:388
static XLogRecPtr PageGetLSN(Page page)
Definition: bufpage.h:383
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
ForkNumber
Definition: relpath.h:48
@ INIT_FORKNUM
Definition: relpath.h:53
char * errormsg_buf
Definition: xlogreader.h:311
XLogRecPtr EndRecPtr
Definition: xlogreader.h:207
bool XLogRecGetBlockTagExtended(XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum, Buffer *prefetch_buffer)
Definition: xlogreader.c:1986
bool RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
Definition: xlogreader.c:2045
#define XLogRecBlockImageApply(decoder, block_id)
Definition: xlogreader.h:426
#define XLogRecGetBlock(decoder, i)
Definition: xlogreader.h:420
#define XLogRecHasBlockImage(decoder, block_id)
Definition: xlogreader.h:424
#define BKPBLOCK_WILL_INIT
Definition: xlogrecord.h:188
Buffer XLogReadBufferExtended(RelFileLocator rlocator, ForkNumber forknum, BlockNumber blkno, ReadBufferMode mode, Buffer recent_buffer)
Definition: xlogutils.c:474
@ 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

References Assert(), BKPBLOCK_WILL_INIT, BLK_DONE, BLK_NEEDS_REDO, BLK_NOTFOUND, BLK_RESTORED, buf, BUFFER_LOCK_EXCLUSIVE, BufferGetPage(), BufferIsValid(), elog(), XLogReaderState::EndRecPtr, ereport, errcode(), errmsg_internal(), ERROR, XLogReaderState::errormsg_buf, FlushOneBuffer(), INIT_FORKNUM, LockBuffer(), LockBufferForCleanup(), MarkBufferDirty(), mode, PageGetLSN(), PageIsNew(), PageSetLSN(), PANIC, RBM_ZERO_AND_CLEANUP_LOCK, RBM_ZERO_AND_LOCK, RestoreBlockImage(), XLogReadBufferExtended(), XLogRecBlockImageApply, XLogRecGetBlock, XLogRecGetBlockTagExtended(), and XLogRecHasBlockImage.

Referenced by btree_xlog_vacuum(), hash_xlog_delete(), hash_xlog_move_page_contents(), hash_xlog_split_allocate_page(), hash_xlog_squeeze_page(), hash_xlog_vacuum_one_page(), heap_xlog_prune(), heap_xlog_vacuum(), heap_xlog_visible(), XLogInitBufferForRedo(), and XLogReadBufferForRedo().

◆ XLogReadDetermineTimeline()

void XLogReadDetermineTimeline ( XLogReaderState state,
XLogRecPtr  wantPage,
uint32  wantLength,
TimeLineID  currTLI 
)

Definition at line 735 of file xlogutils.c.

737 {
738  const XLogRecPtr lastReadPage = (state->seg.ws_segno *
739  state->segcxt.ws_segsize + state->segoff);
740 
741  Assert(wantPage != InvalidXLogRecPtr && wantPage % XLOG_BLCKSZ == 0);
742  Assert(wantLength <= XLOG_BLCKSZ);
743  Assert(state->readLen == 0 || state->readLen <= XLOG_BLCKSZ);
744  Assert(currTLI != 0);
745 
746  /*
747  * If the desired page is currently read in and valid, we have nothing to
748  * do.
749  *
750  * The caller should've ensured that it didn't previously advance readOff
751  * past the valid limit of this timeline, so it doesn't matter if the
752  * current TLI has since become historical.
753  */
754  if (lastReadPage == wantPage &&
755  state->readLen != 0 &&
756  lastReadPage + state->readLen >= wantPage + Min(wantLength, XLOG_BLCKSZ - 1))
757  return;
758 
759  /*
760  * If we're reading from the current timeline, it hasn't become historical
761  * and the page we're reading is after the last page read, we can again
762  * just carry on. (Seeking backwards requires a check to make sure the
763  * older page isn't on a prior timeline).
764  *
765  * currTLI might've become historical since the caller obtained the value,
766  * but the caller is required not to read past the flush limit it saw at
767  * the time it looked up the timeline. There's nothing we can do about it
768  * if StartupXLOG() renames it to .partial concurrently.
769  */
770  if (state->currTLI == currTLI && wantPage >= lastReadPage)
771  {
772  Assert(state->currTLIValidUntil == InvalidXLogRecPtr);
773  return;
774  }
775 
776  /*
777  * If we're just reading pages from a previously validated historical
778  * timeline and the timeline we're reading from is valid until the end of
779  * the current segment we can just keep reading.
780  */
781  if (state->currTLIValidUntil != InvalidXLogRecPtr &&
782  state->currTLI != currTLI &&
783  state->currTLI != 0 &&
784  ((wantPage + wantLength) / state->segcxt.ws_segsize) <
785  (state->currTLIValidUntil / state->segcxt.ws_segsize))
786  return;
787 
788  /*
789  * If we reach this point we're either looking up a page for random
790  * access, the current timeline just became historical, or we're reading
791  * from a new segment containing a timeline switch. In all cases we need
792  * to determine the newest timeline on the segment.
793  *
794  * If it's the current timeline we can just keep reading from here unless
795  * we detect a timeline switch that makes the current timeline historical.
796  * If it's a historical timeline we can read all the segment on the newest
797  * timeline because it contains all the old timelines' data too. So only
798  * one switch check is required.
799  */
800  {
801  /*
802  * We need to re-read the timeline history in case it's been changed
803  * by a promotion or replay from a cascaded replica.
804  */
805  List *timelineHistory = readTimeLineHistory(currTLI);
806  XLogRecPtr endOfSegment;
807 
808  endOfSegment = ((wantPage / state->segcxt.ws_segsize) + 1) *
809  state->segcxt.ws_segsize - 1;
810  Assert(wantPage / state->segcxt.ws_segsize ==
811  endOfSegment / state->segcxt.ws_segsize);
812 
813  /*
814  * Find the timeline of the last LSN on the segment containing
815  * wantPage.
816  */
817  state->currTLI = tliOfPointInHistory(endOfSegment, timelineHistory);
818  state->currTLIValidUntil = tliSwitchPoint(state->currTLI, timelineHistory,
819  &state->nextTLI);
820 
821  Assert(state->currTLIValidUntil == InvalidXLogRecPtr ||
822  wantPage + wantLength < state->currTLIValidUntil);
823 
824  list_free_deep(timelineHistory);
825 
826  elog(DEBUG3, "switched to timeline %u valid until %X/%X",
827  state->currTLI,
828  LSN_FORMAT_ARGS(state->currTLIValidUntil));
829  }
830 }
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 Min(x, y)
Definition: c.h:937
#define DEBUG3
Definition: elog.h:24
void list_free_deep(List *list)
Definition: list.c:1559
Definition: pg_list.h:52
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References Assert(), DEBUG3, elog(), InvalidXLogRecPtr, list_free_deep(), LSN_FORMAT_ARGS, Min, readTimeLineHistory(), tliOfPointInHistory(), and tliSwitchPoint().

Referenced by logical_read_xlog_page(), and read_local_xlog_page_guts().

◆ XLogTruncateRelation()

void XLogTruncateRelation ( RelFileLocator  rlocator,
ForkNumber  forkNum,
BlockNumber  nblocks 
)

Definition at line 688 of file xlogutils.c.

690 {
691  forget_invalid_pages(rlocator, forkNum, nblocks);
692 }

References forget_invalid_pages().

Referenced by smgr_redo().

Variable Documentation

◆ ignore_invalid_pages

bool ignore_invalid_pages = false

Definition at line 37 of file xlogutils.c.

Referenced by log_invalid_page(), and XLogCheckInvalidPages().

◆ InRecovery

◆ invalid_page_tab

HTAB* invalid_page_tab = NULL
static

◆ standbyState