PostgreSQL Source Code  git master
xlogreader.c File Reference
#include "postgres.h"
#include <unistd.h>
#include "access/transam.h"
#include "access/xlog_internal.h"
#include "access/xlogreader.h"
#include "access/xlogrecord.h"
#include "catalog/pg_control.h"
#include "common/pg_lzcompress.h"
#include "replication/origin.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "utils/memutils.h"
Include dependency graph for xlogreader.c:

Go to the source code of this file.

Macros

#define MAX_ERRORMSG_LEN   1000
 
#define DEFAULT_DECODE_BUFFER_SIZE   (64 * 1024)
 
#define COPY_HEADER_FIELD(_dst, _size)
 

Functions

static void report_invalid_record (XLogReaderState *state, const char *fmt,...) pg_attribute_printf(2
 
static void static bool allocate_recordbuf (XLogReaderState *state, uint32 reclength)
 
static int ReadPageInternal (XLogReaderState *state, XLogRecPtr pageptr, int reqLen)
 
static void XLogReaderInvalReadState (XLogReaderState *state)
 
static XLogPageReadResult XLogDecodeNextRecord (XLogReaderState *state, bool nonblocking)
 
static bool ValidXLogRecordHeader (XLogReaderState *state, XLogRecPtr RecPtr, XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess)
 
static bool ValidXLogRecord (XLogReaderState *state, XLogRecord *record, XLogRecPtr recptr)
 
static void ResetDecoder (XLogReaderState *state)
 
static void WALOpenSegmentInit (WALOpenSegment *seg, WALSegmentContext *segcxt, int segsize, const char *waldir)
 
void XLogReaderSetDecodeBuffer (XLogReaderState *state, void *buffer, size_t size)
 
XLogReaderStateXLogReaderAllocate (int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
 
void XLogReaderFree (XLogReaderState *state)
 
void XLogBeginRead (XLogReaderState *state, XLogRecPtr RecPtr)
 
XLogRecPtr XLogReleasePreviousRecord (XLogReaderState *state)
 
DecodedXLogRecordXLogNextRecord (XLogReaderState *state, char **errormsg)
 
XLogRecordXLogReadRecord (XLogReaderState *state, char **errormsg)
 
static DecodedXLogRecordXLogReadRecordAlloc (XLogReaderState *state, size_t xl_tot_len, bool allow_oversized)
 
DecodedXLogRecordXLogReadAhead (XLogReaderState *state, bool nonblocking)
 
bool XLogReaderValidatePageHeader (XLogReaderState *state, XLogRecPtr recptr, char *phdr)
 
void XLogReaderResetError (XLogReaderState *state)
 
XLogRecPtr XLogFindNextRecord (XLogReaderState *state, XLogRecPtr RecPtr)
 
bool WALRead (XLogReaderState *state, char *buf, XLogRecPtr startptr, Size count, TimeLineID tli, WALReadError *errinfo)
 
size_t DecodeXLogRecordRequiredSpace (size_t xl_tot_len)
 
bool DecodeXLogRecord (XLogReaderState *state, DecodedXLogRecord *decoded, XLogRecord *record, XLogRecPtr lsn, char **errormsg)
 
void XLogRecGetBlockTag (XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum)
 
bool XLogRecGetBlockTagExtended (XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum, Buffer *prefetch_buffer)
 
char * XLogRecGetBlockData (XLogReaderState *record, uint8 block_id, Size *len)
 
bool RestoreBlockImage (XLogReaderState *record, uint8 block_id, char *page)
 
FullTransactionId XLogRecGetFullXid (XLogReaderState *record)
 

Macro Definition Documentation

◆ COPY_HEADER_FIELD

#define COPY_HEADER_FIELD (   _dst,
  _size 
)
Value:
do { \
if (remaining < _size) \
goto shortdata_err; \
memcpy(_dst, ptr, _size); \
ptr += _size; \
remaining -= _size; \
} while(0)
int remaining
Definition: informix.c:667

◆ DEFAULT_DECODE_BUFFER_SIZE

#define DEFAULT_DECODE_BUFFER_SIZE   (64 * 1024)

Definition at line 66 of file xlogreader.c.

◆ MAX_ERRORMSG_LEN

#define MAX_ERRORMSG_LEN   1000

Definition at line 60 of file xlogreader.c.

Function Documentation

◆ allocate_recordbuf()

static bool allocate_recordbuf ( XLogReaderState state,
uint32  reclength 
)
static

Definition at line 197 of file xlogreader.c.

198 {
199  uint32 newSize = reclength;
200 
201  newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
202  newSize = Max(newSize, 5 * Max(BLCKSZ, XLOG_BLCKSZ));
203 
204 #ifndef FRONTEND
205 
206  /*
207  * Note that in much unlucky circumstances, the random data read from a
208  * recycled segment can cause this routine to be called with a size
209  * causing a hard failure at allocation. For a standby, this would cause
210  * the instance to stop suddenly with a hard failure, preventing it to
211  * retry fetching WAL from one of its sources which could allow it to move
212  * on with replay without a manual restart. If the data comes from a past
213  * recycled segment and is still valid, then the allocation may succeed
214  * but record checks are going to fail so this would be short-lived. If
215  * the allocation fails because of a memory shortage, then this is not a
216  * hard failure either per the guarantee given by MCXT_ALLOC_NO_OOM.
217  */
218  if (!AllocSizeIsValid(newSize))
219  return false;
220 
221 #endif
222 
223  if (state->readRecordBuf)
224  pfree(state->readRecordBuf);
225  state->readRecordBuf =
226  (char *) palloc_extended(newSize, MCXT_ALLOC_NO_OOM);
227  if (state->readRecordBuf == NULL)
228  {
229  state->readRecordBufSize = 0;
230  return false;
231  }
232  state->readRecordBufSize = newSize;
233  return true;
234 }
unsigned int uint32
Definition: c.h:442
#define Max(x, y)
Definition: c.h:931
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:17
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc_extended(Size size, int flags)
Definition: mcxt.c:1263
#define AllocSizeIsValid(size)
Definition: memutils.h:42
Definition: regguts.h:318

References AllocSizeIsValid, Max, MCXT_ALLOC_NO_OOM, palloc_extended(), and pfree().

Referenced by XLogDecodeNextRecord(), and XLogReaderAllocate().

◆ DecodeXLogRecord()

bool DecodeXLogRecord ( XLogReaderState state,
DecodedXLogRecord decoded,
XLogRecord record,
XLogRecPtr  lsn,
char **  errormsg 
)

Definition at line 1651 of file xlogreader.c.

1656 {
1657  /*
1658  * read next _size bytes from record buffer, but check for overrun first.
1659  */
1660 #define COPY_HEADER_FIELD(_dst, _size) \
1661  do { \
1662  if (remaining < _size) \
1663  goto shortdata_err; \
1664  memcpy(_dst, ptr, _size); \
1665  ptr += _size; \
1666  remaining -= _size; \
1667  } while(0)
1668 
1669  char *ptr;
1670  char *out;
1671  uint32 remaining;
1672  uint32 datatotal;
1673  RelFileLocator *rlocator = NULL;
1674  uint8 block_id;
1675 
1676  decoded->header = *record;
1677  decoded->lsn = lsn;
1678  decoded->next = NULL;
1679  decoded->record_origin = InvalidRepOriginId;
1681  decoded->main_data = NULL;
1682  decoded->main_data_len = 0;
1683  decoded->max_block_id = -1;
1684  ptr = (char *) record;
1685  ptr += SizeOfXLogRecord;
1687 
1688  /* Decode the headers */
1689  datatotal = 0;
1690  while (remaining > datatotal)
1691  {
1692  COPY_HEADER_FIELD(&block_id, sizeof(uint8));
1693 
1694  if (block_id == XLR_BLOCK_ID_DATA_SHORT)
1695  {
1696  /* XLogRecordDataHeaderShort */
1697  uint8 main_data_len;
1698 
1699  COPY_HEADER_FIELD(&main_data_len, sizeof(uint8));
1700 
1701  decoded->main_data_len = main_data_len;
1702  datatotal += main_data_len;
1703  break; /* by convention, the main data fragment is
1704  * always last */
1705  }
1706  else if (block_id == XLR_BLOCK_ID_DATA_LONG)
1707  {
1708  /* XLogRecordDataHeaderLong */
1709  uint32 main_data_len;
1710 
1711  COPY_HEADER_FIELD(&main_data_len, sizeof(uint32));
1712  decoded->main_data_len = main_data_len;
1713  datatotal += main_data_len;
1714  break; /* by convention, the main data fragment is
1715  * always last */
1716  }
1717  else if (block_id == XLR_BLOCK_ID_ORIGIN)
1718  {
1719  COPY_HEADER_FIELD(&decoded->record_origin, sizeof(RepOriginId));
1720  }
1721  else if (block_id == XLR_BLOCK_ID_TOPLEVEL_XID)
1722  {
1723  COPY_HEADER_FIELD(&decoded->toplevel_xid, sizeof(TransactionId));
1724  }
1725  else if (block_id <= XLR_MAX_BLOCK_ID)
1726  {
1727  /* XLogRecordBlockHeader */
1728  DecodedBkpBlock *blk;
1729  uint8 fork_flags;
1730 
1731  /* mark any intervening block IDs as not in use */
1732  for (int i = decoded->max_block_id + 1; i < block_id; ++i)
1733  decoded->blocks[i].in_use = false;
1734 
1735  if (block_id <= decoded->max_block_id)
1736  {
1738  "out-of-order block_id %u at %X/%X",
1739  block_id,
1740  LSN_FORMAT_ARGS(state->ReadRecPtr));
1741  goto err;
1742  }
1743  decoded->max_block_id = block_id;
1744 
1745  blk = &decoded->blocks[block_id];
1746  blk->in_use = true;
1747  blk->apply_image = false;
1748 
1749  COPY_HEADER_FIELD(&fork_flags, sizeof(uint8));
1750  blk->forknum = fork_flags & BKPBLOCK_FORK_MASK;
1751  blk->flags = fork_flags;
1752  blk->has_image = ((fork_flags & BKPBLOCK_HAS_IMAGE) != 0);
1753  blk->has_data = ((fork_flags & BKPBLOCK_HAS_DATA) != 0);
1754 
1756 
1757  COPY_HEADER_FIELD(&blk->data_len, sizeof(uint16));
1758  /* cross-check that the HAS_DATA flag is set iff data_length > 0 */
1759  if (blk->has_data && blk->data_len == 0)
1760  {
1762  "BKPBLOCK_HAS_DATA set, but no data included at %X/%X",
1763  LSN_FORMAT_ARGS(state->ReadRecPtr));
1764  goto err;
1765  }
1766  if (!blk->has_data && blk->data_len != 0)
1767  {
1769  "BKPBLOCK_HAS_DATA not set, but data length is %u at %X/%X",
1770  (unsigned int) blk->data_len,
1771  LSN_FORMAT_ARGS(state->ReadRecPtr));
1772  goto err;
1773  }
1774  datatotal += blk->data_len;
1775 
1776  if (blk->has_image)
1777  {
1778  COPY_HEADER_FIELD(&blk->bimg_len, sizeof(uint16));
1779  COPY_HEADER_FIELD(&blk->hole_offset, sizeof(uint16));
1780  COPY_HEADER_FIELD(&blk->bimg_info, sizeof(uint8));
1781 
1782  blk->apply_image = ((blk->bimg_info & BKPIMAGE_APPLY) != 0);
1783 
1784  if (BKPIMAGE_COMPRESSED(blk->bimg_info))
1785  {
1786  if (blk->bimg_info & BKPIMAGE_HAS_HOLE)
1787  COPY_HEADER_FIELD(&blk->hole_length, sizeof(uint16));
1788  else
1789  blk->hole_length = 0;
1790  }
1791  else
1792  blk->hole_length = BLCKSZ - blk->bimg_len;
1793  datatotal += blk->bimg_len;
1794 
1795  /*
1796  * cross-check that hole_offset > 0, hole_length > 0 and
1797  * bimg_len < BLCKSZ if the HAS_HOLE flag is set.
1798  */
1799  if ((blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1800  (blk->hole_offset == 0 ||
1801  blk->hole_length == 0 ||
1802  blk->bimg_len == BLCKSZ))
1803  {
1805  "BKPIMAGE_HAS_HOLE set, but hole offset %u length %u block image length %u at %X/%X",
1806  (unsigned int) blk->hole_offset,
1807  (unsigned int) blk->hole_length,
1808  (unsigned int) blk->bimg_len,
1809  LSN_FORMAT_ARGS(state->ReadRecPtr));
1810  goto err;
1811  }
1812 
1813  /*
1814  * cross-check that hole_offset == 0 and hole_length == 0 if
1815  * the HAS_HOLE flag is not set.
1816  */
1817  if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1818  (blk->hole_offset != 0 || blk->hole_length != 0))
1819  {
1821  "BKPIMAGE_HAS_HOLE not set, but hole offset %u length %u at %X/%X",
1822  (unsigned int) blk->hole_offset,
1823  (unsigned int) blk->hole_length,
1824  LSN_FORMAT_ARGS(state->ReadRecPtr));
1825  goto err;
1826  }
1827 
1828  /*
1829  * Cross-check that bimg_len < BLCKSZ if it is compressed.
1830  */
1831  if (BKPIMAGE_COMPRESSED(blk->bimg_info) &&
1832  blk->bimg_len == BLCKSZ)
1833  {
1835  "BKPIMAGE_COMPRESSED set, but block image length %u at %X/%X",
1836  (unsigned int) blk->bimg_len,
1837  LSN_FORMAT_ARGS(state->ReadRecPtr));
1838  goto err;
1839  }
1840 
1841  /*
1842  * cross-check that bimg_len = BLCKSZ if neither HAS_HOLE is
1843  * set nor COMPRESSED().
1844  */
1845  if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1846  !BKPIMAGE_COMPRESSED(blk->bimg_info) &&
1847  blk->bimg_len != BLCKSZ)
1848  {
1850  "neither BKPIMAGE_HAS_HOLE nor BKPIMAGE_COMPRESSED set, but block image length is %u at %X/%X",
1851  (unsigned int) blk->data_len,
1852  LSN_FORMAT_ARGS(state->ReadRecPtr));
1853  goto err;
1854  }
1855  }
1856  if (!(fork_flags & BKPBLOCK_SAME_REL))
1857  {
1858  COPY_HEADER_FIELD(&blk->rlocator, sizeof(RelFileLocator));
1859  rlocator = &blk->rlocator;
1860  }
1861  else
1862  {
1863  if (rlocator == NULL)
1864  {
1866  "BKPBLOCK_SAME_REL set but no previous rel at %X/%X",
1867  LSN_FORMAT_ARGS(state->ReadRecPtr));
1868  goto err;
1869  }
1870 
1871  blk->rlocator = *rlocator;
1872  }
1873  COPY_HEADER_FIELD(&blk->blkno, sizeof(BlockNumber));
1874  }
1875  else
1876  {
1878  "invalid block_id %u at %X/%X",
1879  block_id, LSN_FORMAT_ARGS(state->ReadRecPtr));
1880  goto err;
1881  }
1882  }
1883 
1884  if (remaining != datatotal)
1885  goto shortdata_err;
1886 
1887  /*
1888  * Ok, we've parsed the fragment headers, and verified that the total
1889  * length of the payload in the fragments is equal to the amount of data
1890  * left. Copy the data of each fragment to contiguous space after the
1891  * blocks array, inserting alignment padding before the data fragments so
1892  * they can be cast to struct pointers by REDO routines.
1893  */
1894  out = ((char *) decoded) +
1895  offsetof(DecodedXLogRecord, blocks) +
1896  sizeof(decoded->blocks[0]) * (decoded->max_block_id + 1);
1897 
1898  /* block data first */
1899  for (block_id = 0; block_id <= decoded->max_block_id; block_id++)
1900  {
1901  DecodedBkpBlock *blk = &decoded->blocks[block_id];
1902 
1903  if (!blk->in_use)
1904  continue;
1905 
1906  Assert(blk->has_image || !blk->apply_image);
1907 
1908  if (blk->has_image)
1909  {
1910  /* no need to align image */
1911  blk->bkp_image = out;
1912  memcpy(out, ptr, blk->bimg_len);
1913  ptr += blk->bimg_len;
1914  out += blk->bimg_len;
1915  }
1916  if (blk->has_data)
1917  {
1918  out = (char *) MAXALIGN(out);
1919  blk->data = out;
1920  memcpy(blk->data, ptr, blk->data_len);
1921  ptr += blk->data_len;
1922  out += blk->data_len;
1923  }
1924  }
1925 
1926  /* and finally, the main data */
1927  if (decoded->main_data_len > 0)
1928  {
1929  out = (char *) MAXALIGN(out);
1930  decoded->main_data = out;
1931  memcpy(decoded->main_data, ptr, decoded->main_data_len);
1932  ptr += decoded->main_data_len;
1933  out += decoded->main_data_len;
1934  }
1935 
1936  /* Report the actual size we used. */
1937  decoded->size = MAXALIGN(out - (char *) decoded);
1939  decoded->size);
1940 
1941  return true;
1942 
1943 shortdata_err:
1945  "record with invalid length at %X/%X",
1946  LSN_FORMAT_ARGS(state->ReadRecPtr));
1947 err:
1948  *errormsg = state->errormsg_buf;
1949 
1950  return false;
1951 }
uint32 BlockNumber
Definition: block.h:31
#define InvalidBuffer
Definition: buf.h:25
unsigned short uint16
Definition: c.h:441
#define MAXALIGN(LEN)
Definition: c.h:747
unsigned char uint8
Definition: c.h:440
uint32 TransactionId
Definition: c.h:588
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
#define InvalidRepOriginId
Definition: origin.h:33
uint16 hole_length
Definition: xlogreader.h:140
char * bkp_image
Definition: xlogreader.h:138
Buffer prefetch_buffer
Definition: xlogreader.h:130
RelFileLocator rlocator
Definition: xlogreader.h:125
BlockNumber blkno
Definition: xlogreader.h:127
ForkNumber forknum
Definition: xlogreader.h:126
uint16 hole_offset
Definition: xlogreader.h:139
XLogRecord header
Definition: xlogreader.h:166
struct DecodedXLogRecord * next
Definition: xlogreader.h:161
TransactionId toplevel_xid
Definition: xlogreader.h:168
uint32 main_data_len
Definition: xlogreader.h:170
RepOriginId record_origin
Definition: xlogreader.h:167
DecodedBkpBlock blocks[FLEXIBLE_ARRAY_MEMBER]
Definition: xlogreader.h:172
XLogRecPtr lsn
Definition: xlogreader.h:164
uint32 xl_tot_len
Definition: xlogrecord.h:43
#define InvalidTransactionId
Definition: transam.h:31
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
uint16 RepOriginId
Definition: xlogdefs.h:65
static void report_invalid_record(XLogReaderState *state, const char *fmt,...) pg_attribute_printf(2
Definition: xlogreader.c:73
#define COPY_HEADER_FIELD(_dst, _size)
size_t DecodeXLogRecordRequiredSpace(size_t xl_tot_len)
Definition: xlogreader.c:1618
#define BKPBLOCK_FORK_MASK
Definition: xlogrecord.h:184
#define BKPBLOCK_HAS_DATA
Definition: xlogrecord.h:187
#define BKPIMAGE_APPLY
Definition: xlogrecord.h:147
#define BKPIMAGE_HAS_HOLE
Definition: xlogrecord.h:146
#define XLR_BLOCK_ID_DATA_LONG
Definition: xlogrecord.h:231
#define BKPIMAGE_COMPRESSED(info)
Definition: xlogrecord.h:153
#define XLR_BLOCK_ID_TOPLEVEL_XID
Definition: xlogrecord.h:233
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:230
#define XLR_MAX_BLOCK_ID
Definition: xlogrecord.h:228
#define BKPBLOCK_SAME_REL
Definition: xlogrecord.h:189
#define XLR_BLOCK_ID_ORIGIN
Definition: xlogrecord.h:232
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
#define BKPBLOCK_HAS_IMAGE
Definition: xlogrecord.h:186

References DecodedBkpBlock::apply_image, Assert(), DecodedBkpBlock::bimg_info, DecodedBkpBlock::bimg_len, DecodedBkpBlock::bkp_image, BKPBLOCK_FORK_MASK, BKPBLOCK_HAS_DATA, BKPBLOCK_HAS_IMAGE, BKPBLOCK_SAME_REL, BKPIMAGE_APPLY, BKPIMAGE_COMPRESSED, BKPIMAGE_HAS_HOLE, DecodedBkpBlock::blkno, DecodedXLogRecord::blocks, COPY_HEADER_FIELD, DecodedBkpBlock::data, DecodedBkpBlock::data_len, DecodeXLogRecordRequiredSpace(), DecodedBkpBlock::flags, DecodedBkpBlock::forknum, DecodedBkpBlock::has_data, DecodedBkpBlock::has_image, DecodedXLogRecord::header, DecodedBkpBlock::hole_length, DecodedBkpBlock::hole_offset, i, DecodedBkpBlock::in_use, InvalidBuffer, InvalidRepOriginId, InvalidTransactionId, DecodedXLogRecord::lsn, LSN_FORMAT_ARGS, DecodedXLogRecord::main_data, DecodedXLogRecord::main_data_len, DecodedXLogRecord::max_block_id, MAXALIGN, DecodedXLogRecord::next, DecodedBkpBlock::prefetch_buffer, DecodedXLogRecord::record_origin, remaining, report_invalid_record(), DecodedBkpBlock::rlocator, DecodedXLogRecord::size, SizeOfXLogRecord, DecodedXLogRecord::toplevel_xid, XLogRecord::xl_tot_len, XLR_BLOCK_ID_DATA_LONG, XLR_BLOCK_ID_DATA_SHORT, XLR_BLOCK_ID_ORIGIN, XLR_BLOCK_ID_TOPLEVEL_XID, and XLR_MAX_BLOCK_ID.

Referenced by XLogDecodeNextRecord(), and XLogInsertRecord().

◆ DecodeXLogRecordRequiredSpace()

size_t DecodeXLogRecordRequiredSpace ( size_t  xl_tot_len)

Definition at line 1618 of file xlogreader.c.

1619 {
1620  size_t size = 0;
1621 
1622  /* Account for the fixed size part of the decoded record struct. */
1623  size += offsetof(DecodedXLogRecord, blocks[0]);
1624  /* Account for the flexible blocks array of maximum possible size. */
1625  size += sizeof(DecodedBkpBlock) * (XLR_MAX_BLOCK_ID + 1);
1626  /* Account for all the raw main and block data. */
1627  size += xl_tot_len;
1628  /* We might insert padding before main_data. */
1629  size += (MAXIMUM_ALIGNOF - 1);
1630  /* We might insert padding before each block's data. */
1631  size += (MAXIMUM_ALIGNOF - 1) * (XLR_MAX_BLOCK_ID + 1);
1632  /* We might insert padding at the end. */
1633  size += (MAXIMUM_ALIGNOF - 1);
1634 
1635  return size;
1636 }

References XLR_MAX_BLOCK_ID.

Referenced by DecodeXLogRecord(), XLogInsertRecord(), and XLogReadRecordAlloc().

◆ ReadPageInternal()

static int ReadPageInternal ( XLogReaderState state,
XLogRecPtr  pageptr,
int  reqLen 
)
static

Definition at line 988 of file xlogreader.c.

989 {
990  int readLen;
991  uint32 targetPageOff;
992  XLogSegNo targetSegNo;
993  XLogPageHeader hdr;
994 
995  Assert((pageptr % XLOG_BLCKSZ) == 0);
996 
997  XLByteToSeg(pageptr, targetSegNo, state->segcxt.ws_segsize);
998  targetPageOff = XLogSegmentOffset(pageptr, state->segcxt.ws_segsize);
999 
1000  /* check whether we have all the requested data already */
1001  if (targetSegNo == state->seg.ws_segno &&
1002  targetPageOff == state->segoff && reqLen <= state->readLen)
1003  return state->readLen;
1004 
1005  /*
1006  * Invalidate contents of internal buffer before read attempt. Just set
1007  * the length to 0, rather than a full XLogReaderInvalReadState(), so we
1008  * don't forget the segment we last successfully read.
1009  */
1010  state->readLen = 0;
1011 
1012  /*
1013  * Data is not in our buffer.
1014  *
1015  * Every time we actually read the segment, even if we looked at parts of
1016  * it before, we need to do verification as the page_read callback might
1017  * now be rereading data from a different source.
1018  *
1019  * Whenever switching to a new WAL segment, we read the first page of the
1020  * file and validate its header, even if that's not where the target
1021  * record is. This is so that we can check the additional identification
1022  * info that is present in the first page's "long" header.
1023  */
1024  if (targetSegNo != state->seg.ws_segno && targetPageOff != 0)
1025  {
1026  XLogRecPtr targetSegmentPtr = pageptr - targetPageOff;
1027 
1028  readLen = state->routine.page_read(state, targetSegmentPtr, XLOG_BLCKSZ,
1029  state->currRecPtr,
1030  state->readBuf);
1031  if (readLen == XLREAD_WOULDBLOCK)
1032  return XLREAD_WOULDBLOCK;
1033  else if (readLen < 0)
1034  goto err;
1035 
1036  /* we can be sure to have enough WAL available, we scrolled back */
1037  Assert(readLen == XLOG_BLCKSZ);
1038 
1039  if (!XLogReaderValidatePageHeader(state, targetSegmentPtr,
1040  state->readBuf))
1041  goto err;
1042  }
1043 
1044  /*
1045  * First, read the requested data length, but at least a short page header
1046  * so that we can validate it.
1047  */
1048  readLen = state->routine.page_read(state, pageptr, Max(reqLen, SizeOfXLogShortPHD),
1049  state->currRecPtr,
1050  state->readBuf);
1051  if (readLen == XLREAD_WOULDBLOCK)
1052  return XLREAD_WOULDBLOCK;
1053  else if (readLen < 0)
1054  goto err;
1055 
1056  Assert(readLen <= XLOG_BLCKSZ);
1057 
1058  /* Do we have enough data to check the header length? */
1059  if (readLen <= SizeOfXLogShortPHD)
1060  goto err;
1061 
1062  Assert(readLen >= reqLen);
1063 
1064  hdr = (XLogPageHeader) state->readBuf;
1065 
1066  /* still not enough */
1067  if (readLen < XLogPageHeaderSize(hdr))
1068  {
1069  readLen = state->routine.page_read(state, pageptr, XLogPageHeaderSize(hdr),
1070  state->currRecPtr,
1071  state->readBuf);
1072  if (readLen == XLREAD_WOULDBLOCK)
1073  return XLREAD_WOULDBLOCK;
1074  else if (readLen < 0)
1075  goto err;
1076  }
1077 
1078  /*
1079  * Now that we know we have the full header, validate it.
1080  */
1081  if (!XLogReaderValidatePageHeader(state, pageptr, (char *) hdr))
1082  goto err;
1083 
1084  /* update read state information */
1085  state->seg.ws_segno = targetSegNo;
1086  state->segoff = targetPageOff;
1087  state->readLen = readLen;
1088 
1089  return readLen;
1090 
1091 err:
1093 
1094  return XLREAD_FAIL;
1095 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:54
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:52
#define XLogPageHeaderSize(hdr)
Definition: xlog_internal.h:84
uint64 XLogRecPtr
Definition: xlogdefs.h:21
uint64 XLogSegNo
Definition: xlogdefs.h:48
static void XLogReaderInvalReadState(XLogReaderState *state)
Definition: xlogreader.c:1101
bool XLogReaderValidatePageHeader(XLogReaderState *state, XLogRecPtr recptr, char *phdr)
Definition: xlogreader.c:1210
@ XLREAD_WOULDBLOCK
Definition: xlogreader.h:354
@ XLREAD_FAIL
Definition: xlogreader.h:353
static uint32 readLen
Definition: xlogrecovery.c:233

References Assert(), if(), Max, readLen, SizeOfXLogShortPHD, XLByteToSeg, XLogPageHeaderSize, XLogReaderInvalReadState(), XLogReaderValidatePageHeader(), XLogSegmentOffset, XLREAD_FAIL, and XLREAD_WOULDBLOCK.

Referenced by XLogDecodeNextRecord(), and XLogFindNextRecord().

◆ report_invalid_record()

static void report_invalid_record ( XLogReaderState state,
const char *  fmt,
  ... 
)
static

Definition at line 73 of file xlogreader.c.

74 {
75  va_list args;
76 
77  fmt = _(fmt);
78 
79  va_start(args, fmt);
80  vsnprintf(state->errormsg_buf, MAX_ERRORMSG_LEN, fmt, args);
81  va_end(args);
82 
83  state->errormsg_deferred = true;
84 }
#define _(x)
Definition: elog.c:91
static void const char * fmt
va_end(args)
va_start(args, fmt)
#define vsnprintf
Definition: port.h:237
#define MAX_ERRORMSG_LEN
Definition: xlogreader.c:60

References _, generate_unaccent_rules::args, fmt, MAX_ERRORMSG_LEN, va_end(), va_start(), and vsnprintf.

Referenced by DecodeXLogRecord(), RestoreBlockImage(), ValidXLogRecord(), ValidXLogRecordHeader(), XLogDecodeNextRecord(), and XLogReaderValidatePageHeader().

◆ ResetDecoder()

static void ResetDecoder ( XLogReaderState state)
static

Definition at line 1584 of file xlogreader.c.

1585 {
1586  DecodedXLogRecord *r;
1587 
1588  /* Reset the decoded record queue, freeing any oversized records. */
1589  while ((r = state->decode_queue_head) != NULL)
1590  {
1591  state->decode_queue_head = r->next;
1592  if (r->oversized)
1593  pfree(r);
1594  }
1595  state->decode_queue_tail = NULL;
1596  state->decode_queue_head = NULL;
1597  state->record = NULL;
1598 
1599  /* Reset the decode buffer to empty. */
1600  state->decode_buffer_tail = state->decode_buffer;
1601  state->decode_buffer_head = state->decode_buffer;
1602 
1603  /* Clear error state. */
1604  state->errormsg_buf[0] = '\0';
1605  state->errormsg_deferred = false;
1606 }

References DecodedXLogRecord::next, DecodedXLogRecord::oversized, and pfree().

Referenced by XLogBeginRead().

◆ RestoreBlockImage()

bool RestoreBlockImage ( XLogReaderState record,
uint8  block_id,
char *  page 
)

Definition at line 2045 of file xlogreader.c.

2046 {
2047  DecodedBkpBlock *bkpb;
2048  char *ptr;
2049  PGAlignedBlock tmp;
2050 
2051  if (block_id > record->record->max_block_id ||
2052  !record->record->blocks[block_id].in_use)
2053  {
2054  report_invalid_record(record,
2055  "could not restore image at %X/%X with invalid block %d specified",
2056  LSN_FORMAT_ARGS(record->ReadRecPtr),
2057  block_id);
2058  return false;
2059  }
2060  if (!record->record->blocks[block_id].has_image)
2061  {
2062  report_invalid_record(record, "could not restore image at %X/%X with invalid state, block %d",
2063  LSN_FORMAT_ARGS(record->ReadRecPtr),
2064  block_id);
2065  return false;
2066  }
2067 
2068  bkpb = &record->record->blocks[block_id];
2069  ptr = bkpb->bkp_image;
2070 
2071  if (BKPIMAGE_COMPRESSED(bkpb->bimg_info))
2072  {
2073  /* If a backup block image is compressed, decompress it */
2074  bool decomp_success = true;
2075 
2076  if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_PGLZ) != 0)
2077  {
2078  if (pglz_decompress(ptr, bkpb->bimg_len, tmp.data,
2079  BLCKSZ - bkpb->hole_length, true) < 0)
2080  decomp_success = false;
2081  }
2082  else if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_LZ4) != 0)
2083  {
2084 #ifdef USE_LZ4
2085  if (LZ4_decompress_safe(ptr, tmp.data,
2086  bkpb->bimg_len, BLCKSZ - bkpb->hole_length) <= 0)
2087  decomp_success = false;
2088 #else
2089  report_invalid_record(record, "could not restore image at %X/%X compressed with %s not supported by build, block %d",
2090  LSN_FORMAT_ARGS(record->ReadRecPtr),
2091  "LZ4",
2092  block_id);
2093  return false;
2094 #endif
2095  }
2096  else if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_ZSTD) != 0)
2097  {
2098 #ifdef USE_ZSTD
2099  size_t decomp_result = ZSTD_decompress(tmp.data,
2100  BLCKSZ - bkpb->hole_length,
2101  ptr, bkpb->bimg_len);
2102 
2103  if (ZSTD_isError(decomp_result))
2104  decomp_success = false;
2105 #else
2106  report_invalid_record(record, "could not restore image at %X/%X compressed with %s not supported by build, block %d",
2107  LSN_FORMAT_ARGS(record->ReadRecPtr),
2108  "zstd",
2109  block_id);
2110  return false;
2111 #endif
2112  }
2113  else
2114  {
2115  report_invalid_record(record, "could not restore image at %X/%X compressed with unknown method, block %d",
2116  LSN_FORMAT_ARGS(record->ReadRecPtr),
2117  block_id);
2118  return false;
2119  }
2120 
2121  if (!decomp_success)
2122  {
2123  report_invalid_record(record, "could not decompress image at %X/%X, block %d",
2124  LSN_FORMAT_ARGS(record->ReadRecPtr),
2125  block_id);
2126  return false;
2127  }
2128 
2129  ptr = tmp.data;
2130  }
2131 
2132  /* generate page, taking into account hole if necessary */
2133  if (bkpb->hole_length == 0)
2134  {
2135  memcpy(page, ptr, BLCKSZ);
2136  }
2137  else
2138  {
2139  memcpy(page, ptr, bkpb->hole_offset);
2140  /* must zero-fill the hole */
2141  MemSet(page + bkpb->hole_offset, 0, bkpb->hole_length);
2142  memcpy(page + (bkpb->hole_offset + bkpb->hole_length),
2143  ptr + bkpb->hole_offset,
2144  BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
2145  }
2146 
2147  return true;
2148 }
#define MemSet(start, val, len)
Definition: c.h:953
int32 pglz_decompress(const char *source, int32 slen, char *dest, int32 rawsize, bool check_complete)
DecodedXLogRecord * record
Definition: xlogreader.h:236
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:206
char data[BLCKSZ]
Definition: c.h:1079
#define BKPIMAGE_COMPRESS_ZSTD
Definition: xlogrecord.h:151
#define BKPIMAGE_COMPRESS_LZ4
Definition: xlogrecord.h:150
#define BKPIMAGE_COMPRESS_PGLZ
Definition: xlogrecord.h:149

References DecodedBkpBlock::bimg_info, DecodedBkpBlock::bimg_len, DecodedBkpBlock::bkp_image, BKPIMAGE_COMPRESS_LZ4, BKPIMAGE_COMPRESS_PGLZ, BKPIMAGE_COMPRESS_ZSTD, BKPIMAGE_COMPRESSED, DecodedXLogRecord::blocks, PGAlignedBlock::data, DecodedBkpBlock::has_image, DecodedBkpBlock::hole_length, DecodedBkpBlock::hole_offset, DecodedBkpBlock::in_use, LSN_FORMAT_ARGS, DecodedXLogRecord::max_block_id, MemSet, pglz_decompress(), XLogReaderState::ReadRecPtr, XLogReaderState::record, and report_invalid_record().

Referenced by verifyBackupPageConsistency(), and XLogReadBufferForRedoExtended().

◆ ValidXLogRecord()

static bool ValidXLogRecord ( XLogReaderState state,
XLogRecord record,
XLogRecPtr  recptr 
)
static

Definition at line 1181 of file xlogreader.c.

1182 {
1183  pg_crc32c crc;
1184 
1185  /* Calculate the CRC */
1186  INIT_CRC32C(crc);
1187  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
1188  /* include the record header last */
1189  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
1190  FIN_CRC32C(crc);
1191 
1192  if (!EQ_CRC32C(record->xl_crc, crc))
1193  {
1195  "incorrect resource manager data checksum in record at %X/%X",
1196  LSN_FORMAT_ARGS(recptr));
1197  return false;
1198  }
1199 
1200  return true;
1201 }
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
return crc

References COMP_CRC32C, crc, EQ_CRC32C, FIN_CRC32C, INIT_CRC32C, LSN_FORMAT_ARGS, report_invalid_record(), SizeOfXLogRecord, XLogRecord::xl_crc, and XLogRecord::xl_tot_len.

Referenced by XLogDecodeNextRecord().

◆ ValidXLogRecordHeader()

static bool ValidXLogRecordHeader ( XLogReaderState state,
XLogRecPtr  RecPtr,
XLogRecPtr  PrevRecPtr,
XLogRecord record,
bool  randAccess 
)
static

Definition at line 1115 of file xlogreader.c.

1118 {
1119  if (record->xl_tot_len < SizeOfXLogRecord)
1120  {
1122  "invalid record length at %X/%X: wanted %u, got %u",
1123  LSN_FORMAT_ARGS(RecPtr),
1124  (uint32) SizeOfXLogRecord, record->xl_tot_len);
1125  return false;
1126  }
1127  if (!RmgrIdIsValid(record->xl_rmid))
1128  {
1130  "invalid resource manager ID %u at %X/%X",
1131  record->xl_rmid, LSN_FORMAT_ARGS(RecPtr));
1132  return false;
1133  }
1134  if (randAccess)
1135  {
1136  /*
1137  * We can't exactly verify the prev-link, but surely it should be less
1138  * than the record's own address.
1139  */
1140  if (!(record->xl_prev < RecPtr))
1141  {
1143  "record with incorrect prev-link %X/%X at %X/%X",
1144  LSN_FORMAT_ARGS(record->xl_prev),
1145  LSN_FORMAT_ARGS(RecPtr));
1146  return false;
1147  }
1148  }
1149  else
1150  {
1151  /*
1152  * Record's prev-link should exactly match our previous location. This
1153  * check guards against torn WAL pages where a stale but valid-looking
1154  * WAL record starts on a sector boundary.
1155  */
1156  if (record->xl_prev != PrevRecPtr)
1157  {
1159  "record with incorrect prev-link %X/%X at %X/%X",
1160  LSN_FORMAT_ARGS(record->xl_prev),
1161  LSN_FORMAT_ARGS(RecPtr));
1162  return false;
1163  }
1164  }
1165 
1166  return true;
1167 }
#define RmgrIdIsValid(rmid)
Definition: rmgr.h:53
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
RmgrId xl_rmid
Definition: xlogrecord.h:47

References LSN_FORMAT_ARGS, report_invalid_record(), RmgrIdIsValid, SizeOfXLogRecord, XLogRecord::xl_prev, XLogRecord::xl_rmid, and XLogRecord::xl_tot_len.

Referenced by XLogDecodeNextRecord().

◆ WALOpenSegmentInit()

static void WALOpenSegmentInit ( WALOpenSegment seg,
WALSegmentContext segcxt,
int  segsize,
const char *  waldir 
)
static

Definition at line 240 of file xlogreader.c.

242 {
243  seg->ws_file = -1;
244  seg->ws_segno = 0;
245  seg->ws_tli = 0;
246 
247  segcxt->ws_segsize = segsize;
248  if (waldir)
249  snprintf(segcxt->ws_dir, MAXPGPATH, "%s", waldir);
250 }
#define MAXPGPATH
#define snprintf
Definition: port.h:238
XLogSegNo ws_segno
Definition: xlogreader.h:48
TimeLineID ws_tli
Definition: xlogreader.h:49
char ws_dir[MAXPGPATH]
Definition: xlogreader.h:55

References MAXPGPATH, snprintf, WALSegmentContext::ws_dir, WALOpenSegment::ws_file, WALOpenSegment::ws_segno, WALSegmentContext::ws_segsize, and WALOpenSegment::ws_tli.

Referenced by XLogReaderAllocate().

◆ WALRead()

bool WALRead ( XLogReaderState state,
char *  buf,
XLogRecPtr  startptr,
Size  count,
TimeLineID  tli,
WALReadError errinfo 
)

Definition at line 1492 of file xlogreader.c.

1495 {
1496  char *p;
1497  XLogRecPtr recptr;
1498  Size nbytes;
1499 
1500  p = buf;
1501  recptr = startptr;
1502  nbytes = count;
1503 
1504  while (nbytes > 0)
1505  {
1506  uint32 startoff;
1507  int segbytes;
1508  int readbytes;
1509 
1510  startoff = XLogSegmentOffset(recptr, state->segcxt.ws_segsize);
1511 
1512  /*
1513  * If the data we want is not in a segment we have open, close what we
1514  * have (if anything) and open the next one, using the caller's
1515  * provided openSegment callback.
1516  */
1517  if (state->seg.ws_file < 0 ||
1518  !XLByteInSeg(recptr, state->seg.ws_segno, state->segcxt.ws_segsize) ||
1519  tli != state->seg.ws_tli)
1520  {
1521  XLogSegNo nextSegNo;
1522 
1523  if (state->seg.ws_file >= 0)
1524  state->routine.segment_close(state);
1525 
1526  XLByteToSeg(recptr, nextSegNo, state->segcxt.ws_segsize);
1527  state->routine.segment_open(state, nextSegNo, &tli);
1528 
1529  /* This shouldn't happen -- indicates a bug in segment_open */
1530  Assert(state->seg.ws_file >= 0);
1531 
1532  /* Update the current segment info. */
1533  state->seg.ws_tli = tli;
1534  state->seg.ws_segno = nextSegNo;
1535  }
1536 
1537  /* How many bytes are within this segment? */
1538  if (nbytes > (state->segcxt.ws_segsize - startoff))
1539  segbytes = state->segcxt.ws_segsize - startoff;
1540  else
1541  segbytes = nbytes;
1542 
1543 #ifndef FRONTEND
1545 #endif
1546 
1547  /* Reset errno first; eases reporting non-errno-affecting errors */
1548  errno = 0;
1549  readbytes = pg_pread(state->seg.ws_file, p, segbytes, (off_t) startoff);
1550 
1551 #ifndef FRONTEND
1553 #endif
1554 
1555  if (readbytes <= 0)
1556  {
1557  errinfo->wre_errno = errno;
1558  errinfo->wre_req = segbytes;
1559  errinfo->wre_read = readbytes;
1560  errinfo->wre_off = startoff;
1561  errinfo->wre_seg = state->seg;
1562  return false;
1563  }
1564 
1565  /* Update state for read */
1566  recptr += readbytes;
1567  nbytes -= readbytes;
1568  p += readbytes;
1569  }
1570 
1571  return true;
1572 }
size_t Size
Definition: c.h:541
static char * buf
Definition: pg_test_fsync.c:67
#define pg_pread
Definition: port.h:225
WALOpenSegment wre_seg
Definition: xlogreader.h:389
@ WAIT_EVENT_WAL_READ
Definition: wait_event.h:231
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:268
static void pgstat_report_wait_end(void)
Definition: wait_event.h:284
#define XLByteInSeg(xlrp, logSegNo, wal_segsz_bytes)

References Assert(), buf, pg_pread, pgstat_report_wait_end(), pgstat_report_wait_start(), WAIT_EVENT_WAL_READ, WALReadError::wre_errno, WALReadError::wre_off, WALReadError::wre_read, WALReadError::wre_req, WALReadError::wre_seg, XLByteInSeg, XLByteToSeg, and XLogSegmentOffset.

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

◆ XLogBeginRead()

void XLogBeginRead ( XLogReaderState state,
XLogRecPtr  RecPtr 
)

Definition at line 264 of file xlogreader.c.

265 {
266  Assert(!XLogRecPtrIsInvalid(RecPtr));
267 
269 
270  /* Begin at the passed-in record pointer. */
271  state->EndRecPtr = RecPtr;
272  state->NextRecPtr = RecPtr;
273  state->ReadRecPtr = InvalidXLogRecPtr;
274  state->DecodeRecPtr = InvalidXLogRecPtr;
275 }
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
static void ResetDecoder(XLogReaderState *state)
Definition: xlogreader.c:1584

References Assert(), InvalidXLogRecPtr, ResetDecoder(), and XLogRecPtrIsInvalid.

Referenced by DecodingContextFindStartpoint(), extractPageMap(), findLastCheckpoint(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), readOneRecord(), StartLogicalReplication(), XLogFindNextRecord(), XLogPrefetcherBeginRead(), and XlogReadTwoPhaseData().

◆ XLogDecodeNextRecord()

static XLogPageReadResult XLogDecodeNextRecord ( XLogReaderState state,
bool  nonblocking 
)
static

Definition at line 535 of file xlogreader.c.

536 {
537  XLogRecPtr RecPtr;
538  XLogRecord *record;
539  XLogRecPtr targetPagePtr;
540  bool randAccess;
541  uint32 len,
542  total_len;
543  uint32 targetRecOff;
544  uint32 pageHeaderSize;
545  bool assembled;
546  bool gotheader;
547  int readOff;
548  DecodedXLogRecord *decoded;
549  char *errormsg; /* not used */
550 
551  /*
552  * randAccess indicates whether to verify the previous-record pointer of
553  * the record we're reading. We only do this if we're reading
554  * sequentially, which is what we initially assume.
555  */
556  randAccess = false;
557 
558  /* reset error state */
559  state->errormsg_buf[0] = '\0';
560  decoded = NULL;
561 
562  state->abortedRecPtr = InvalidXLogRecPtr;
563  state->missingContrecPtr = InvalidXLogRecPtr;
564 
565  RecPtr = state->NextRecPtr;
566 
567  if (state->DecodeRecPtr != InvalidXLogRecPtr)
568  {
569  /* read the record after the one we just read */
570 
571  /*
572  * NextRecPtr is pointing to end+1 of the previous WAL record. If
573  * we're at a page boundary, no more records can fit on the current
574  * page. We must skip over the page header, but we can't do that until
575  * we've read in the page, since the header size is variable.
576  */
577  }
578  else
579  {
580  /*
581  * Caller supplied a position to start at.
582  *
583  * In this case, NextRecPtr should already be pointing either to a
584  * valid record starting position or alternatively to the beginning of
585  * a page. See the header comments for XLogBeginRead.
586  */
587  Assert(RecPtr % XLOG_BLCKSZ == 0 || XRecOffIsValid(RecPtr));
588  randAccess = true;
589  }
590 
591 restart:
592  state->nonblocking = nonblocking;
593  state->currRecPtr = RecPtr;
594  assembled = false;
595 
596  targetPagePtr = RecPtr - (RecPtr % XLOG_BLCKSZ);
597  targetRecOff = RecPtr % XLOG_BLCKSZ;
598 
599  /*
600  * Read the page containing the record into state->readBuf. Request enough
601  * byte to cover the whole record header, or at least the part of it that
602  * fits on the same page.
603  */
604  readOff = ReadPageInternal(state, targetPagePtr,
605  Min(targetRecOff + SizeOfXLogRecord, XLOG_BLCKSZ));
606  if (readOff == XLREAD_WOULDBLOCK)
607  return XLREAD_WOULDBLOCK;
608  else if (readOff < 0)
609  goto err;
610 
611  /*
612  * ReadPageInternal always returns at least the page header, so we can
613  * examine it now.
614  */
615  pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
616  if (targetRecOff == 0)
617  {
618  /*
619  * At page start, so skip over page header.
620  */
621  RecPtr += pageHeaderSize;
622  targetRecOff = pageHeaderSize;
623  }
624  else if (targetRecOff < pageHeaderSize)
625  {
626  report_invalid_record(state, "invalid record offset at %X/%X",
627  LSN_FORMAT_ARGS(RecPtr));
628  goto err;
629  }
630 
631  if ((((XLogPageHeader) state->readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
632  targetRecOff == pageHeaderSize)
633  {
634  report_invalid_record(state, "contrecord is requested by %X/%X",
635  LSN_FORMAT_ARGS(RecPtr));
636  goto err;
637  }
638 
639  /* ReadPageInternal has verified the page header */
640  Assert(pageHeaderSize <= readOff);
641 
642  /*
643  * Read the record length.
644  *
645  * NB: Even though we use an XLogRecord pointer here, the whole record
646  * header might not fit on this page. xl_tot_len is the first field of the
647  * struct, so it must be on this page (the records are MAXALIGNed), but we
648  * cannot access any other fields until we've verified that we got the
649  * whole header.
650  */
651  record = (XLogRecord *) (state->readBuf + RecPtr % XLOG_BLCKSZ);
652  total_len = record->xl_tot_len;
653 
654  /*
655  * If the whole record header is on this page, validate it immediately.
656  * Otherwise do just a basic sanity check on xl_tot_len, and validate the
657  * rest of the header after reading it from the next page. The xl_tot_len
658  * check is necessary here to ensure that we enter the "Need to reassemble
659  * record" code path below; otherwise we might fail to apply
660  * ValidXLogRecordHeader at all.
661  */
662  if (targetRecOff <= XLOG_BLCKSZ - SizeOfXLogRecord)
663  {
664  if (!ValidXLogRecordHeader(state, RecPtr, state->DecodeRecPtr, record,
665  randAccess))
666  goto err;
667  gotheader = true;
668  }
669  else
670  {
671  /* XXX: more validation should be done here */
672  if (total_len < SizeOfXLogRecord)
673  {
675  "invalid record length at %X/%X: wanted %u, got %u",
676  LSN_FORMAT_ARGS(RecPtr),
677  (uint32) SizeOfXLogRecord, total_len);
678  goto err;
679  }
680  gotheader = false;
681  }
682 
683  /*
684  * Find space to decode this record. Don't allow oversized allocation if
685  * the caller requested nonblocking. Otherwise, we *have* to try to
686  * decode the record now because the caller has nothing else to do, so
687  * allow an oversized record to be palloc'd if that turns out to be
688  * necessary.
689  */
690  decoded = XLogReadRecordAlloc(state,
691  total_len,
692  !nonblocking /* allow_oversized */ );
693  if (decoded == NULL)
694  {
695  /*
696  * There is no space in the decode buffer. The caller should help
697  * with that problem by consuming some records.
698  */
699  if (nonblocking)
700  return XLREAD_WOULDBLOCK;
701 
702  /* We failed to allocate memory for an oversized record. */
704  "out of memory while trying to decode a record of length %u", total_len);
705  goto err;
706  }
707 
708  len = XLOG_BLCKSZ - RecPtr % XLOG_BLCKSZ;
709  if (total_len > len)
710  {
711  /* Need to reassemble record */
712  char *contdata;
713  XLogPageHeader pageHeader;
714  char *buffer;
715  uint32 gotlen;
716 
717  assembled = true;
718 
719  /*
720  * Enlarge readRecordBuf as needed.
721  */
722  if (total_len > state->readRecordBufSize &&
723  !allocate_recordbuf(state, total_len))
724  {
725  /* We treat this as a "bogus data" condition */
726  report_invalid_record(state, "record length %u at %X/%X too long",
727  total_len, LSN_FORMAT_ARGS(RecPtr));
728  goto err;
729  }
730 
731  /* Copy the first fragment of the record from the first page. */
732  memcpy(state->readRecordBuf,
733  state->readBuf + RecPtr % XLOG_BLCKSZ, len);
734  buffer = state->readRecordBuf + len;
735  gotlen = len;
736 
737  do
738  {
739  /* Calculate pointer to beginning of next page */
740  targetPagePtr += XLOG_BLCKSZ;
741 
742  /* Wait for the next page to become available */
743  readOff = ReadPageInternal(state, targetPagePtr,
744  Min(total_len - gotlen + SizeOfXLogShortPHD,
745  XLOG_BLCKSZ));
746 
747  if (readOff == XLREAD_WOULDBLOCK)
748  return XLREAD_WOULDBLOCK;
749  else if (readOff < 0)
750  goto err;
751 
753 
754  pageHeader = (XLogPageHeader) state->readBuf;
755 
756  /*
757  * If we were expecting a continuation record and got an
758  * "overwrite contrecord" flag, that means the continuation record
759  * was overwritten with a different record. Restart the read by
760  * assuming the address to read is the location where we found
761  * this flag; but keep track of the LSN of the record we were
762  * reading, for later verification.
763  */
765  {
766  state->overwrittenRecPtr = RecPtr;
767  RecPtr = targetPagePtr;
768  goto restart;
769  }
770 
771  /* Check that the continuation on next page looks valid */
772  if (!(pageHeader->xlp_info & XLP_FIRST_IS_CONTRECORD))
773  {
775  "there is no contrecord flag at %X/%X",
776  LSN_FORMAT_ARGS(RecPtr));
777  goto err;
778  }
779 
780  /*
781  * Cross-check that xlp_rem_len agrees with how much of the record
782  * we expect there to be left.
783  */
784  if (pageHeader->xlp_rem_len == 0 ||
785  total_len != (pageHeader->xlp_rem_len + gotlen))
786  {
788  "invalid contrecord length %u (expected %lld) at %X/%X",
789  pageHeader->xlp_rem_len,
790  ((long long) total_len) - gotlen,
791  LSN_FORMAT_ARGS(RecPtr));
792  goto err;
793  }
794 
795  /* Append the continuation from this page to the buffer */
796  pageHeaderSize = XLogPageHeaderSize(pageHeader);
797 
798  if (readOff < pageHeaderSize)
799  readOff = ReadPageInternal(state, targetPagePtr,
800  pageHeaderSize);
801 
802  Assert(pageHeaderSize <= readOff);
803 
804  contdata = (char *) state->readBuf + pageHeaderSize;
805  len = XLOG_BLCKSZ - pageHeaderSize;
806  if (pageHeader->xlp_rem_len < len)
807  len = pageHeader->xlp_rem_len;
808 
809  if (readOff < pageHeaderSize + len)
810  readOff = ReadPageInternal(state, targetPagePtr,
811  pageHeaderSize + len);
812 
813  memcpy(buffer, (char *) contdata, len);
814  buffer += len;
815  gotlen += len;
816 
817  /* If we just reassembled the record header, validate it. */
818  if (!gotheader)
819  {
820  record = (XLogRecord *) state->readRecordBuf;
821  if (!ValidXLogRecordHeader(state, RecPtr, state->DecodeRecPtr,
822  record, randAccess))
823  goto err;
824  gotheader = true;
825  }
826  } while (gotlen < total_len);
827 
828  Assert(gotheader);
829 
830  record = (XLogRecord *) state->readRecordBuf;
831  if (!ValidXLogRecord(state, record, RecPtr))
832  goto err;
833 
834  pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
835  state->DecodeRecPtr = RecPtr;
836  state->NextRecPtr = targetPagePtr + pageHeaderSize
837  + MAXALIGN(pageHeader->xlp_rem_len);
838  }
839  else
840  {
841  /* Wait for the record data to become available */
842  readOff = ReadPageInternal(state, targetPagePtr,
843  Min(targetRecOff + total_len, XLOG_BLCKSZ));
844  if (readOff == XLREAD_WOULDBLOCK)
845  return XLREAD_WOULDBLOCK;
846  else if (readOff < 0)
847  goto err;
848 
849  /* Record does not cross a page boundary */
850  if (!ValidXLogRecord(state, record, RecPtr))
851  goto err;
852 
853  state->NextRecPtr = RecPtr + MAXALIGN(total_len);
854 
855  state->DecodeRecPtr = RecPtr;
856  }
857 
858  /*
859  * Special processing if it's an XLOG SWITCH record
860  */
861  if (record->xl_rmid == RM_XLOG_ID &&
862  (record->xl_info & ~XLR_INFO_MASK) == XLOG_SWITCH)
863  {
864  /* Pretend it extends to end of segment */
865  state->NextRecPtr += state->segcxt.ws_segsize - 1;
866  state->NextRecPtr -= XLogSegmentOffset(state->NextRecPtr, state->segcxt.ws_segsize);
867  }
868 
869  if (DecodeXLogRecord(state, decoded, record, RecPtr, &errormsg))
870  {
871  /* Record the location of the next record. */
872  decoded->next_lsn = state->NextRecPtr;
873 
874  /*
875  * If it's in the decode buffer, mark the decode buffer space as
876  * occupied.
877  */
878  if (!decoded->oversized)
879  {
880  /* The new decode buffer head must be MAXALIGNed. */
881  Assert(decoded->size == MAXALIGN(decoded->size));
882  if ((char *) decoded == state->decode_buffer)
883  state->decode_buffer_tail = state->decode_buffer + decoded->size;
884  else
885  state->decode_buffer_tail += decoded->size;
886  }
887 
888  /* Insert it into the queue of decoded records. */
889  Assert(state->decode_queue_tail != decoded);
890  if (state->decode_queue_tail)
891  state->decode_queue_tail->next = decoded;
892  state->decode_queue_tail = decoded;
893  if (!state->decode_queue_head)
894  state->decode_queue_head = decoded;
895  return XLREAD_SUCCESS;
896  }
897  else
898  return XLREAD_FAIL;
899 
900 err:
901  if (assembled)
902  {
903  /*
904  * We get here when a record that spans multiple pages needs to be
905  * assembled, but something went wrong -- perhaps a contrecord piece
906  * was lost. If caller is WAL replay, it will know where the aborted
907  * record was and where to direct followup WAL to be written, marking
908  * the next piece with XLP_FIRST_IS_OVERWRITE_CONTRECORD, which will
909  * in turn signal downstream WAL consumers that the broken WAL record
910  * is to be ignored.
911  */
912  state->abortedRecPtr = RecPtr;
913  state->missingContrecPtr = targetPagePtr;
914 
915  /*
916  * If we got here without reporting an error, report one now so that
917  * XLogPrefetcherReadRecord() doesn't bring us back a second time and
918  * clobber the above state. Otherwise, the existing error takes
919  * precedence.
920  */
921  if (!state->errormsg_buf[0])
923  "missing contrecord at %X/%X",
924  LSN_FORMAT_ARGS(RecPtr));
925  }
926 
927  if (decoded && decoded->oversized)
928  pfree(decoded);
929 
930  /*
931  * Invalidate the read state. We might read from a different source after
932  * failure.
933  */
935 
936  /*
937  * If an error was written to errmsg_buf, it'll be returned to the caller
938  * of XLogReadRecord() after all successfully decoded records from the
939  * read queue.
940  */
941 
942  return XLREAD_FAIL;
943 }
#define Min(x, y)
Definition: c.h:937
#define XLOG_SWITCH
Definition: pg_control.h:71
const void size_t len
XLogRecPtr next_lsn
Definition: xlogreader.h:165
uint8 xl_info
Definition: xlogrecord.h:46
struct state * next
Definition: regguts.h:327
#define XLP_FIRST_IS_CONTRECORD
Definition: xlog_internal.h:74
#define XLP_FIRST_IS_OVERWRITE_CONTRECORD
Definition: xlog_internal.h:80
#define XRecOffIsValid(xlrp)
static void static bool allocate_recordbuf(XLogReaderState *state, uint32 reclength)
Definition: xlogreader.c:197
static int ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr, int reqLen)
Definition: xlogreader.c:988
bool DecodeXLogRecord(XLogReaderState *state, DecodedXLogRecord *decoded, XLogRecord *record, XLogRecPtr lsn, char **errormsg)
Definition: xlogreader.c:1651
static bool ValidXLogRecord(XLogReaderState *state, XLogRecord *record, XLogRecPtr recptr)
Definition: xlogreader.c:1181
static DecodedXLogRecord * XLogReadRecordAlloc(XLogReaderState *state, size_t xl_tot_len, bool allow_oversized)
Definition: xlogreader.c:471
static bool ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr, XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess)
Definition: xlogreader.c:1115
@ XLREAD_SUCCESS
Definition: xlogreader.h:352
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
static uint32 readOff
Definition: xlogrecovery.c:232

References allocate_recordbuf(), Assert(), DecodeXLogRecord(), if(), InvalidXLogRecPtr, len, LSN_FORMAT_ARGS, MAXALIGN, Min, state::next, DecodedXLogRecord::next_lsn, DecodedXLogRecord::oversized, pfree(), readOff, ReadPageInternal(), report_invalid_record(), DecodedXLogRecord::size, SizeOfXLogRecord, SizeOfXLogShortPHD, ValidXLogRecord(), ValidXLogRecordHeader(), XLogRecord::xl_info, XLogRecord::xl_rmid, XLogRecord::xl_tot_len, XLOG_SWITCH, XLogPageHeaderSize, XLogReaderInvalReadState(), XLogReadRecordAlloc(), XLogSegmentOffset, XLP_FIRST_IS_CONTRECORD, XLP_FIRST_IS_OVERWRITE_CONTRECORD, XLogPageHeaderData::xlp_info, XLogPageHeaderData::xlp_rem_len, XLR_INFO_MASK, XLREAD_FAIL, XLREAD_SUCCESS, XLREAD_WOULDBLOCK, and XRecOffIsValid.

Referenced by XLogReadAhead().

◆ XLogFindNextRecord()

XLogRecPtr XLogFindNextRecord ( XLogReaderState state,
XLogRecPtr  RecPtr 
)

Definition at line 1369 of file xlogreader.c.

1370 {
1371  XLogRecPtr tmpRecPtr;
1372  XLogRecPtr found = InvalidXLogRecPtr;
1374  char *errormsg;
1375 
1376  Assert(!XLogRecPtrIsInvalid(RecPtr));
1377 
1378  /* Make sure ReadPageInternal() can't return XLREAD_WOULDBLOCK. */
1379  state->nonblocking = false;
1380 
1381  /*
1382  * skip over potential continuation data, keeping in mind that it may span
1383  * multiple pages
1384  */
1385  tmpRecPtr = RecPtr;
1386  while (true)
1387  {
1388  XLogRecPtr targetPagePtr;
1389  int targetRecOff;
1390  uint32 pageHeaderSize;
1391  int readLen;
1392 
1393  /*
1394  * Compute targetRecOff. It should typically be equal or greater than
1395  * short page-header since a valid record can't start anywhere before
1396  * that, except when caller has explicitly specified the offset that
1397  * falls somewhere there or when we are skipping multi-page
1398  * continuation record. It doesn't matter though because
1399  * ReadPageInternal() is prepared to handle that and will read at
1400  * least short page-header worth of data
1401  */
1402  targetRecOff = tmpRecPtr % XLOG_BLCKSZ;
1403 
1404  /* scroll back to page boundary */
1405  targetPagePtr = tmpRecPtr - targetRecOff;
1406 
1407  /* Read the page containing the record */
1408  readLen = ReadPageInternal(state, targetPagePtr, targetRecOff);
1409  if (readLen < 0)
1410  goto err;
1411 
1412  header = (XLogPageHeader) state->readBuf;
1413 
1414  pageHeaderSize = XLogPageHeaderSize(header);
1415 
1416  /* make sure we have enough data for the page header */
1417  readLen = ReadPageInternal(state, targetPagePtr, pageHeaderSize);
1418  if (readLen < 0)
1419  goto err;
1420 
1421  /* skip over potential continuation data */
1422  if (header->xlp_info & XLP_FIRST_IS_CONTRECORD)
1423  {
1424  /*
1425  * If the length of the remaining continuation data is more than
1426  * what can fit in this page, the continuation record crosses over
1427  * this page. Read the next page and try again. xlp_rem_len in the
1428  * next page header will contain the remaining length of the
1429  * continuation data
1430  *
1431  * Note that record headers are MAXALIGN'ed
1432  */
1433  if (MAXALIGN(header->xlp_rem_len) >= (XLOG_BLCKSZ - pageHeaderSize))
1434  tmpRecPtr = targetPagePtr + XLOG_BLCKSZ;
1435  else
1436  {
1437  /*
1438  * The previous continuation record ends in this page. Set
1439  * tmpRecPtr to point to the first valid record
1440  */
1441  tmpRecPtr = targetPagePtr + pageHeaderSize
1442  + MAXALIGN(header->xlp_rem_len);
1443  break;
1444  }
1445  }
1446  else
1447  {
1448  tmpRecPtr = targetPagePtr + pageHeaderSize;
1449  break;
1450  }
1451  }
1452 
1453  /*
1454  * we know now that tmpRecPtr is an address pointing to a valid XLogRecord
1455  * because either we're at the first record after the beginning of a page
1456  * or we just jumped over the remaining data of a continuation.
1457  */
1458  XLogBeginRead(state, tmpRecPtr);
1459  while (XLogReadRecord(state, &errormsg) != NULL)
1460  {
1461  /* past the record we've found, break out */
1462  if (RecPtr <= state->ReadRecPtr)
1463  {
1464  /* Rewind the reader to the beginning of the last record. */
1465  found = state->ReadRecPtr;
1466  XLogBeginRead(state, found);
1467  return found;
1468  }
1469  }
1470 
1471 err:
1473 
1474  return InvalidXLogRecPtr;
1475 }
static void header(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:208
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:422
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:264

References Assert(), header(), InvalidXLogRecPtr, MAXALIGN, readLen, ReadPageInternal(), XLogBeginRead(), XLogPageHeaderSize, XLogReaderInvalReadState(), XLogReadRecord(), XLogRecPtrIsInvalid, and XLP_FIRST_IS_CONTRECORD.

Referenced by InitXLogReaderState(), and main().

◆ XLogNextRecord()

DecodedXLogRecord* XLogNextRecord ( XLogReaderState state,
char **  errormsg 
)

Definition at line 358 of file xlogreader.c.

359 {
360  /* Release the last record returned by XLogNextRecord(). */
362 
363  if (state->decode_queue_head == NULL)
364  {
365  *errormsg = NULL;
366  if (state->errormsg_deferred)
367  {
368  if (state->errormsg_buf[0] != '\0')
369  *errormsg = state->errormsg_buf;
370  state->errormsg_deferred = false;
371  }
372 
373  /*
374  * state->EndRecPtr is expected to have been set by the last call to
375  * XLogBeginRead() or XLogNextRecord(), and is the location of the
376  * error.
377  */
378  Assert(!XLogRecPtrIsInvalid(state->EndRecPtr));
379 
380  return NULL;
381  }
382 
383  /*
384  * Record this as the most recent record returned, so that we'll release
385  * it next time. This also exposes it to the traditional
386  * XLogRecXXX(xlogreader) macros, which work with the decoder rather than
387  * the record for historical reasons.
388  */
389  state->record = state->decode_queue_head;
390 
391  /*
392  * Update the pointers to the beginning and one-past-the-end of this
393  * record, again for the benefit of historical code that expected the
394  * decoder to track this rather than accessing these fields of the record
395  * itself.
396  */
397  state->ReadRecPtr = state->record->lsn;
398  state->EndRecPtr = state->record->next_lsn;
399 
400  *errormsg = NULL;
401 
402  return state->record;
403 }
XLogRecPtr XLogReleasePreviousRecord(XLogReaderState *state)
Definition: xlogreader.c:282

References Assert(), XLogRecPtrIsInvalid, and XLogReleasePreviousRecord().

Referenced by XLogPrefetcherReadRecord(), and XLogReadRecord().

◆ XLogReadAhead()

DecodedXLogRecord* XLogReadAhead ( XLogReaderState state,
bool  nonblocking 
)

Definition at line 954 of file xlogreader.c.

955 {
956  XLogPageReadResult result;
957 
958  if (state->errormsg_deferred)
959  return NULL;
960 
961  result = XLogDecodeNextRecord(state, nonblocking);
962  if (result == XLREAD_SUCCESS)
963  {
964  Assert(state->decode_queue_tail != NULL);
965  return state->decode_queue_tail;
966  }
967 
968  return NULL;
969 }
static XLogPageReadResult XLogDecodeNextRecord(XLogReaderState *state, bool nonblocking)
Definition: xlogreader.c:535
XLogPageReadResult
Definition: xlogreader.h:351

References Assert(), XLogDecodeNextRecord(), and XLREAD_SUCCESS.

Referenced by XLogPrefetcherNextBlock(), and XLogReadRecord().

◆ XLogReaderAllocate()

XLogReaderState* XLogReaderAllocate ( int  wal_segment_size,
const char *  waldir,
XLogReaderRoutine routine,
void *  private_data 
)

Definition at line 108 of file xlogreader.c.

110 {
112 
113  state = (XLogReaderState *)
116  if (!state)
117  return NULL;
118 
119  /* initialize caller-provided support functions */
120  state->routine = *routine;
121 
122  /*
123  * Permanently allocate readBuf. We do it this way, rather than just
124  * making a static array, for two reasons: (1) no need to waste the
125  * storage in most instantiations of the backend; (2) a static char array
126  * isn't guaranteed to have any particular alignment, whereas
127  * palloc_extended() will provide MAXALIGN'd storage.
128  */
129  state->readBuf = (char *) palloc_extended(XLOG_BLCKSZ,
131  if (!state->readBuf)
132  {
133  pfree(state);
134  return NULL;
135  }
136 
137  /* Initialize segment info. */
139  waldir);
140 
141  /* system_identifier initialized to zeroes above */
142  state->private_data = private_data;
143  /* ReadRecPtr, EndRecPtr and readLen initialized to zeroes above */
144  state->errormsg_buf = palloc_extended(MAX_ERRORMSG_LEN + 1,
146  if (!state->errormsg_buf)
147  {
148  pfree(state->readBuf);
149  pfree(state);
150  return NULL;
151  }
152  state->errormsg_buf[0] = '\0';
153 
154  /*
155  * Allocate an initial readRecordBuf of minimal size, which can later be
156  * enlarged if necessary.
157  */
158  if (!allocate_recordbuf(state, 0))
159  {
160  pfree(state->errormsg_buf);
161  pfree(state->readBuf);
162  pfree(state);
163  return NULL;
164  }
165 
166  return state;
167 }
#define MCXT_ALLOC_ZERO
Definition: fe_memutils.h:18
int wal_segment_size
Definition: xlog.c:146
static void WALOpenSegmentInit(WALOpenSegment *seg, WALSegmentContext *segcxt, int segsize, const char *waldir)
Definition: xlogreader.c:240

References allocate_recordbuf(), MAX_ERRORMSG_LEN, MCXT_ALLOC_NO_OOM, MCXT_ALLOC_ZERO, palloc_extended(), pfree(), wal_segment_size, and WALOpenSegmentInit().

Referenced by extractPageMap(), findLastCheckpoint(), InitWalRecovery(), InitXLogReaderState(), main(), readOneRecord(), StartReplication(), StartupDecodingContext(), XLogInsertRecord(), and XlogReadTwoPhaseData().

◆ XLogReaderFree()

void XLogReaderFree ( XLogReaderState state)

Definition at line 170 of file xlogreader.c.

171 {
172  if (state->seg.ws_file != -1)
173  state->routine.segment_close(state);
174 
175  if (state->decode_buffer && state->free_decode_buffer)
176  pfree(state->decode_buffer);
177 
178  pfree(state->errormsg_buf);
179  if (state->readRecordBuf)
180  pfree(state->readRecordBuf);
181  pfree(state->readBuf);
182  pfree(state);
183 }

References pfree().

Referenced by extractPageMap(), findLastCheckpoint(), FreeDecodingContext(), main(), pg_get_wal_record_info(), readOneRecord(), ShutdownWalRecovery(), and XlogReadTwoPhaseData().

◆ XLogReaderInvalReadState()

static void XLogReaderInvalReadState ( XLogReaderState state)
static

Definition at line 1101 of file xlogreader.c.

1102 {
1103  state->seg.ws_segno = 0;
1104  state->segoff = 0;
1105  state->readLen = 0;
1106 }

Referenced by ReadPageInternal(), XLogDecodeNextRecord(), and XLogFindNextRecord().

◆ XLogReaderResetError()

void XLogReaderResetError ( XLogReaderState state)

Definition at line 1351 of file xlogreader.c.

1352 {
1353  state->errormsg_buf[0] = '\0';
1354  state->errormsg_deferred = false;
1355 }

Referenced by XLogPageRead().

◆ XLogReaderSetDecodeBuffer()

void XLogReaderSetDecodeBuffer ( XLogReaderState state,
void *  buffer,
size_t  size 
)

Definition at line 92 of file xlogreader.c.

93 {
94  Assert(state->decode_buffer == NULL);
95 
96  state->decode_buffer = buffer;
97  state->decode_buffer_size = size;
98  state->decode_buffer_tail = buffer;
99  state->decode_buffer_head = buffer;
100 }

References Assert().

Referenced by InitWalRecovery().

◆ XLogReaderValidatePageHeader()

bool XLogReaderValidatePageHeader ( XLogReaderState state,
XLogRecPtr  recptr,
char *  phdr 
)

Definition at line 1210 of file xlogreader.c.

1212 {
1213  XLogSegNo segno;
1214  int32 offset;
1215  XLogPageHeader hdr = (XLogPageHeader) phdr;
1216 
1217  Assert((recptr % XLOG_BLCKSZ) == 0);
1218 
1219  XLByteToSeg(recptr, segno, state->segcxt.ws_segsize);
1220  offset = XLogSegmentOffset(recptr, state->segcxt.ws_segsize);
1221 
1222  if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
1223  {
1224  char fname[MAXFNAMELEN];
1225 
1226  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1227 
1229  "invalid magic number %04X in WAL segment %s, LSN %X/%X, offset %u",
1230  hdr->xlp_magic,
1231  fname,
1232  LSN_FORMAT_ARGS(recptr),
1233  offset);
1234  return false;
1235  }
1236 
1237  if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
1238  {
1239  char fname[MAXFNAMELEN];
1240 
1241  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1242 
1244  "invalid info bits %04X in WAL segment %s, LSN %X/%X, offset %u",
1245  hdr->xlp_info,
1246  fname,
1247  LSN_FORMAT_ARGS(recptr),
1248  offset);
1249  return false;
1250  }
1251 
1252  if (hdr->xlp_info & XLP_LONG_HEADER)
1253  {
1254  XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
1255 
1256  if (state->system_identifier &&
1257  longhdr->xlp_sysid != state->system_identifier)
1258  {
1260  "WAL file is from different database system: WAL file database system identifier is %llu, pg_control database system identifier is %llu",
1261  (unsigned long long) longhdr->xlp_sysid,
1262  (unsigned long long) state->system_identifier);
1263  return false;
1264  }
1265  else if (longhdr->xlp_seg_size != state->segcxt.ws_segsize)
1266  {
1268  "WAL file is from different database system: incorrect segment size in page header");
1269  return false;
1270  }
1271  else if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
1272  {
1274  "WAL file is from different database system: incorrect XLOG_BLCKSZ in page header");
1275  return false;
1276  }
1277  }
1278  else if (offset == 0)
1279  {
1280  char fname[MAXFNAMELEN];
1281 
1282  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1283 
1284  /* hmm, first page of file doesn't have a long header? */
1286  "invalid info bits %04X in WAL segment %s, LSN %X/%X, offset %u",
1287  hdr->xlp_info,
1288  fname,
1289  LSN_FORMAT_ARGS(recptr),
1290  offset);
1291  return false;
1292  }
1293 
1294  /*
1295  * Check that the address on the page agrees with what we expected. This
1296  * check typically fails when an old WAL segment is recycled, and hasn't
1297  * yet been overwritten with new data yet.
1298  */
1299  if (hdr->xlp_pageaddr != recptr)
1300  {
1301  char fname[MAXFNAMELEN];
1302 
1303  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1304 
1306  "unexpected pageaddr %X/%X in WAL segment %s, LSN %X/%X, offset %u",
1308  fname,
1309  LSN_FORMAT_ARGS(recptr),
1310  offset);
1311  return false;
1312  }
1313 
1314  /*
1315  * Since child timelines are always assigned a TLI greater than their
1316  * immediate parent's TLI, we should never see TLI go backwards across
1317  * successive pages of a consistent WAL sequence.
1318  *
1319  * Sometimes we re-read a segment that's already been (partially) read. So
1320  * we only verify TLIs for pages that are later than the last remembered
1321  * LSN.
1322  */
1323  if (recptr > state->latestPagePtr)
1324  {
1325  if (hdr->xlp_tli < state->latestPageTLI)
1326  {
1327  char fname[MAXFNAMELEN];
1328 
1329  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1330 
1332  "out-of-sequence timeline ID %u (after %u) in WAL segment %s, LSN %X/%X, offset %u",
1333  hdr->xlp_tli,
1334  state->latestPageTLI,
1335  fname,
1336  LSN_FORMAT_ARGS(recptr),
1337  offset);
1338  return false;
1339  }
1340  }
1341  state->latestPagePtr = recptr;
1342  state->latestPageTLI = hdr->xlp_tli;
1343 
1344  return true;
1345 }
signed int int32
Definition: c.h:430
TimeLineID xlp_tli
Definition: xlog_internal.h:40
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:71
#define MAXFNAMELEN
#define XLP_LONG_HEADER
Definition: xlog_internal.h:76
#define XLP_ALL_FLAGS
Definition: xlog_internal.h:82
#define XLOG_PAGE_MAGIC
Definition: xlog_internal.h:34
static void XLogFileName(char *fname, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)

References Assert(), LSN_FORMAT_ARGS, MAXFNAMELEN, report_invalid_record(), XLByteToSeg, XLOG_PAGE_MAGIC, XLogFileName(), XLogSegmentOffset, XLP_ALL_FLAGS, XLogPageHeaderData::xlp_info, XLP_LONG_HEADER, XLogPageHeaderData::xlp_magic, XLogPageHeaderData::xlp_pageaddr, XLogLongPageHeaderData::xlp_seg_size, XLogLongPageHeaderData::xlp_sysid, XLogPageHeaderData::xlp_tli, and XLogLongPageHeaderData::xlp_xlog_blcksz.

Referenced by ReadPageInternal(), and XLogPageRead().

◆ XLogReadRecord()

XLogRecord* XLogReadRecord ( XLogReaderState state,
char **  errormsg 
)

Definition at line 422 of file xlogreader.c.

423 {
424  DecodedXLogRecord *decoded;
425 
426  /*
427  * Release last returned record, if there is one. We need to do this so
428  * that we can check for empty decode queue accurately.
429  */
431 
432  /*
433  * Call XLogReadAhead() in blocking mode to make sure there is something
434  * in the queue, though we don't use the result.
435  */
437  XLogReadAhead(state, false /* nonblocking */ );
438 
439  /* Consume the head record or error. */
440  decoded = XLogNextRecord(state, errormsg);
441  if (decoded)
442  {
443  /*
444  * This function returns a pointer to the record's header, not the
445  * actual decoded record. The caller will access the decoded record
446  * through the XLogRecGetXXX() macros, which reach the decoded
447  * recorded as xlogreader->record.
448  */
449  Assert(state->record == decoded);
450  return &decoded->header;
451  }
452 
453  return NULL;
454 }
DecodedXLogRecord * XLogNextRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:358
DecodedXLogRecord * XLogReadAhead(XLogReaderState *state, bool nonblocking)
Definition: xlogreader.c:954
static bool XLogReaderHasQueuedRecordOrError(XLogReaderState *state)
Definition: xlogreader.h:325

References Assert(), DecodedXLogRecord::header, XLogNextRecord(), XLogReadAhead(), XLogReaderHasQueuedRecordOrError(), and XLogReleasePreviousRecord().

Referenced by DecodingContextFindStartpoint(), extractPageMap(), findLastCheckpoint(), main(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), ReadNextXLogRecord(), readOneRecord(), XLogFindNextRecord(), XlogReadTwoPhaseData(), and XLogSendLogical().

◆ XLogReadRecordAlloc()

static DecodedXLogRecord* XLogReadRecordAlloc ( XLogReaderState state,
size_t  xl_tot_len,
bool  allow_oversized 
)
static

Definition at line 471 of file xlogreader.c.

472 {
473  size_t required_space = DecodeXLogRecordRequiredSpace(xl_tot_len);
474  DecodedXLogRecord *decoded = NULL;
475 
476  /* Allocate a circular decode buffer if we don't have one already. */
477  if (unlikely(state->decode_buffer == NULL))
478  {
479  if (state->decode_buffer_size == 0)
480  state->decode_buffer_size = DEFAULT_DECODE_BUFFER_SIZE;
481  state->decode_buffer = palloc(state->decode_buffer_size);
482  state->decode_buffer_head = state->decode_buffer;
483  state->decode_buffer_tail = state->decode_buffer;
484  state->free_decode_buffer = true;
485  }
486 
487  /* Try to allocate space in the circular decode buffer. */
488  if (state->decode_buffer_tail >= state->decode_buffer_head)
489  {
490  /* Empty, or tail is to the right of head. */
491  if (state->decode_buffer_tail + required_space <=
492  state->decode_buffer + state->decode_buffer_size)
493  {
494  /* There is space between tail and end. */
495  decoded = (DecodedXLogRecord *) state->decode_buffer_tail;
496  decoded->oversized = false;
497  return decoded;
498  }
499  else if (state->decode_buffer + required_space <
500  state->decode_buffer_head)
501  {
502  /* There is space between start and head. */
503  decoded = (DecodedXLogRecord *) state->decode_buffer;
504  decoded->oversized = false;
505  return decoded;
506  }
507  }
508  else
509  {
510  /* Tail is to the left of head. */
511  if (state->decode_buffer_tail + required_space <
512  state->decode_buffer_head)
513  {
514  /* There is space between tail and head. */
515  decoded = (DecodedXLogRecord *) state->decode_buffer_tail;
516  decoded->oversized = false;
517  return decoded;
518  }
519  }
520 
521  /* Not enough space in the decode buffer. Are we allowed to allocate? */
522  if (allow_oversized)
523  {
524  decoded = palloc_extended(required_space, MCXT_ALLOC_NO_OOM);
525  if (decoded == NULL)
526  return NULL;
527  decoded->oversized = true;
528  return decoded;
529  }
530 
531  return NULL;
532 }
#define unlikely(x)
Definition: c.h:295
void * palloc(Size size)
Definition: mcxt.c:1199
#define DEFAULT_DECODE_BUFFER_SIZE
Definition: xlogreader.c:66

References DecodeXLogRecordRequiredSpace(), DEFAULT_DECODE_BUFFER_SIZE, MCXT_ALLOC_NO_OOM, DecodedXLogRecord::oversized, palloc(), palloc_extended(), and unlikely.

Referenced by XLogDecodeNextRecord().

◆ XLogRecGetBlockData()

char* XLogRecGetBlockData ( XLogReaderState record,
uint8  block_id,
Size len 
)

◆ XLogRecGetBlockTag()

void XLogRecGetBlockTag ( XLogReaderState record,
uint8  block_id,
RelFileLocator rlocator,
ForkNumber forknum,
BlockNumber blknum 
)

Definition at line 1960 of file xlogreader.c.

1963 {
1964  if (!XLogRecGetBlockTagExtended(record, block_id, rlocator, forknum,
1965  blknum, NULL))
1966  {
1967 #ifndef FRONTEND
1968  elog(ERROR, "could not locate backup block with ID %d in WAL record",
1969  block_id);
1970 #else
1971  pg_fatal("could not locate backup block with ID %d in WAL record",
1972  block_id);
1973 #endif
1974  }
1975 }
#define ERROR
Definition: elog.h:39
#define pg_fatal(...)
bool XLogRecGetBlockTagExtended(XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum, Buffer *prefetch_buffer)
Definition: xlogreader.c:1986

References elog(), ERROR, pg_fatal, and XLogRecGetBlockTagExtended().

Referenced by brin_xlog_revmap_extend(), btree_xlog_delete(), btree_xlog_split(), DecodeDelete(), DecodeInsert(), DecodeMultiInsert(), DecodeSpecConfirm(), DecodeUpdate(), gistRedoDeleteRecord(), gistRedoPageSplitRecord(), hash_xlog_add_ovfl_page(), hash_xlog_init_bitmap_page(), hash_xlog_init_meta_page(), hash_xlog_vacuum_one_page(), heap_xlog_delete(), heap_xlog_freeze_page(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_prune(), heap_xlog_update(), heap_xlog_vacuum(), heap_xlog_visible(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), and spgRedoVacuumRedirect().

◆ XLogRecGetBlockTagExtended()

bool XLogRecGetBlockTagExtended ( XLogReaderState record,
uint8  block_id,
RelFileLocator rlocator,
ForkNumber forknum,
BlockNumber blknum,
Buffer prefetch_buffer 
)

Definition at line 1986 of file xlogreader.c.

1990 {
1991  DecodedBkpBlock *bkpb;
1992 
1993  if (!XLogRecHasBlockRef(record, block_id))
1994  return false;
1995 
1996  bkpb = &record->record->blocks[block_id];
1997  if (rlocator)
1998  *rlocator = bkpb->rlocator;
1999  if (forknum)
2000  *forknum = bkpb->forknum;
2001  if (blknum)
2002  *blknum = bkpb->blkno;
2003  if (prefetch_buffer)
2004  *prefetch_buffer = bkpb->prefetch_buffer;
2005  return true;
2006 }
#define XLogRecHasBlockRef(decoder, block_id)
Definition: xlogreader.h:421

References DecodedBkpBlock::blkno, DecodedXLogRecord::blocks, DecodedBkpBlock::forknum, DecodedBkpBlock::prefetch_buffer, XLogReaderState::record, DecodedBkpBlock::rlocator, and XLogRecHasBlockRef.

Referenced by btree_xlog_split(), extractPageInfo(), heap_xlog_update(), verifyBackupPageConsistency(), xlog_block_info(), XLogReadBufferForRedoExtended(), XLogRecGetBlockRefInfo(), XLogRecGetBlockTag(), and XLogRecordMatchesRelationBlock().

◆ XLogRecGetFullXid()

FullTransactionId XLogRecGetFullXid ( XLogReaderState record)

Definition at line 2156 of file xlogreader.c.

2157 {
2158  TransactionId xid,
2159  next_xid;
2160  uint32 epoch;
2161 
2162  /*
2163  * This function is only safe during replay, because it depends on the
2164  * replay state. See AdvanceNextFullTransactionIdPastXid() for more.
2165  */
2167 
2168  xid = XLogRecGetXid(record);
2171 
2172  /*
2173  * If xid is numerically greater than next_xid, it has to be from the last
2174  * epoch.
2175  */
2176  if (unlikely(xid > next_xid))
2177  --epoch;
2178 
2180 }
bool IsUnderPostmaster
Definition: globals.c:113
#define AmStartupProcess()
Definition: miscadmin.h:440
FullTransactionId nextXid
Definition: transam.h:220
#define EpochFromFullTransactionId(x)
Definition: transam.h:47
#define XidFromFullTransactionId(x)
Definition: transam.h:48
static FullTransactionId FullTransactionIdFromEpochAndXid(uint32 epoch, TransactionId xid)
Definition: transam.h:71
VariableCache ShmemVariableCache
Definition: varsup.c:34
static const unsigned __int64 epoch
#define XLogRecGetXid(decoder)
Definition: xlogreader.h:413

References AmStartupProcess, Assert(), epoch, EpochFromFullTransactionId, FullTransactionIdFromEpochAndXid(), IsUnderPostmaster, VariableCacheData::nextXid, ShmemVariableCache, unlikely, XidFromFullTransactionId, and XLogRecGetXid.

◆ XLogReleasePreviousRecord()

XLogRecPtr XLogReleasePreviousRecord ( XLogReaderState state)

Definition at line 282 of file xlogreader.c.

283 {
284  DecodedXLogRecord *record;
285  XLogRecPtr next_lsn;
286 
287  if (!state->record)
288  return InvalidXLogRecPtr;
289 
290  /*
291  * Remove it from the decoded record queue. It must be the oldest item
292  * decoded, decode_queue_head.
293  */
294  record = state->record;
295  next_lsn = record->next_lsn;
296  Assert(record == state->decode_queue_head);
297  state->record = NULL;
298  state->decode_queue_head = record->next;
299 
300  /* It might also be the newest item decoded, decode_queue_tail. */
301  if (state->decode_queue_tail == record)
302  state->decode_queue_tail = NULL;
303 
304  /* Release the space. */
305  if (unlikely(record->oversized))
306  {
307  /* It's not in the decode buffer, so free it to release space. */
308  pfree(record);
309  }
310  else
311  {
312  /* It must be the head (oldest) record in the decode buffer. */
313  Assert(state->decode_buffer_head == (char *) record);
314 
315  /*
316  * We need to update head to point to the next record that is in the
317  * decode buffer, if any, being careful to skip oversized ones
318  * (they're not in the decode buffer).
319  */
320  record = record->next;
321  while (unlikely(record && record->oversized))
322  record = record->next;
323 
324  if (record)
325  {
326  /* Adjust head to release space up to the next record. */
327  state->decode_buffer_head = (char *) record;
328  }
329  else
330  {
331  /*
332  * Otherwise we might as well just reset head and tail to the
333  * start of the buffer space, because we're empty. This means
334  * we'll keep overwriting the same piece of memory if we're not
335  * doing any prefetching.
336  */
337  state->decode_buffer_head = state->decode_buffer;
338  state->decode_buffer_tail = state->decode_buffer;
339  }
340  }
341 
342  return next_lsn;
343 }

References Assert(), InvalidXLogRecPtr, DecodedXLogRecord::next, DecodedXLogRecord::next_lsn, DecodedXLogRecord::oversized, pfree(), and unlikely.

Referenced by XLogNextRecord(), XLogPrefetcherReadRecord(), and XLogReadRecord().