PostgreSQL Source Code  git master
xlogreader.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * xlogreader.c
4  * Generic XLog reading facility
5  *
6  * Portions Copyright (c) 2013-2020, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  * src/backend/access/transam/xlogreader.c
10  *
11  * NOTES
12  * See xlogreader.h for more notes on this facility.
13  *
14  * This file is compiled as both front-end and backend code, so it
15  * may not use ereport, server-defined static variables, etc.
16  *-------------------------------------------------------------------------
17  */
18 #include "postgres.h"
19 
20 #include <unistd.h>
21 
22 #include "access/transam.h"
23 #include "access/xlog_internal.h"
24 #include "access/xlogreader.h"
25 #include "access/xlogrecord.h"
26 #include "catalog/pg_control.h"
27 #include "common/pg_lzcompress.h"
28 #include "replication/origin.h"
29 
30 #ifndef FRONTEND
31 #include "miscadmin.h"
32 #include "pgstat.h"
33 #include "utils/memutils.h"
34 #endif
35 
36 static void report_invalid_record(XLogReaderState *state, const char *fmt,...)
37  pg_attribute_printf(2, 3);
38 static bool allocate_recordbuf(XLogReaderState *state, uint32 reclength);
39 static int ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr,
40  int reqLen);
41 static void XLogReaderInvalReadState(XLogReaderState *state);
42 static bool ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr,
43  XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess);
44 static bool ValidXLogRecord(XLogReaderState *state, XLogRecord *record,
45  XLogRecPtr recptr);
46 static void ResetDecoder(XLogReaderState *state);
47 static void WALOpenSegmentInit(WALOpenSegment *seg, WALSegmentContext *segcxt,
48  int segsize, const char *waldir);
49 
50 /* size of the buffer allocated for error message. */
51 #define MAX_ERRORMSG_LEN 1000
52 
53 /*
54  * Construct a string in state->errormsg_buf explaining what's wrong with
55  * the current record being read.
56  */
57 static void
58 report_invalid_record(XLogReaderState *state, const char *fmt,...)
59 {
60  va_list args;
61 
62  fmt = _(fmt);
63 
64  va_start(args, fmt);
65  vsnprintf(state->errormsg_buf, MAX_ERRORMSG_LEN, fmt, args);
66  va_end(args);
67 }
68 
69 /*
70  * Allocate and initialize a new XLogReader.
71  *
72  * Returns NULL if the xlogreader couldn't be allocated.
73  */
75 XLogReaderAllocate(int wal_segment_size, const char *waldir,
76  XLogReaderRoutine *routine, void *private_data)
77 {
78  XLogReaderState *state;
79 
80  state = (XLogReaderState *)
83  if (!state)
84  return NULL;
85 
86  /* initialize caller-provided support functions */
87  state->routine = *routine;
88 
89  state->max_block_id = -1;
90 
91  /*
92  * Permanently allocate readBuf. We do it this way, rather than just
93  * making a static array, for two reasons: (1) no need to waste the
94  * storage in most instantiations of the backend; (2) a static char array
95  * isn't guaranteed to have any particular alignment, whereas
96  * palloc_extended() will provide MAXALIGN'd storage.
97  */
98  state->readBuf = (char *) palloc_extended(XLOG_BLCKSZ,
100  if (!state->readBuf)
101  {
102  pfree(state);
103  return NULL;
104  }
105 
106  /* Initialize segment info. */
107  WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
108  waldir);
109 
110  /* system_identifier initialized to zeroes above */
111  state->private_data = private_data;
112  /* ReadRecPtr, EndRecPtr and readLen initialized to zeroes above */
115  if (!state->errormsg_buf)
116  {
117  pfree(state->readBuf);
118  pfree(state);
119  return NULL;
120  }
121  state->errormsg_buf[0] = '\0';
122 
123  /*
124  * Allocate an initial readRecordBuf of minimal size, which can later be
125  * enlarged if necessary.
126  */
127  if (!allocate_recordbuf(state, 0))
128  {
129  pfree(state->errormsg_buf);
130  pfree(state->readBuf);
131  pfree(state);
132  return NULL;
133  }
134 
135  return state;
136 }
137 
138 void
140 {
141  int block_id;
142 
143  if (state->seg.ws_file != -1)
144  state->routine.segment_close(state);
145 
146  for (block_id = 0; block_id <= XLR_MAX_BLOCK_ID; block_id++)
147  {
148  if (state->blocks[block_id].data)
149  pfree(state->blocks[block_id].data);
150  }
151  if (state->main_data)
152  pfree(state->main_data);
153 
154  pfree(state->errormsg_buf);
155  if (state->readRecordBuf)
156  pfree(state->readRecordBuf);
157  pfree(state->readBuf);
158  pfree(state);
159 }
160 
161 /*
162  * Allocate readRecordBuf to fit a record of at least the given length.
163  * Returns true if successful, false if out of memory.
164  *
165  * readRecordBufSize is set to the new buffer size.
166  *
167  * To avoid useless small increases, round its size to a multiple of
168  * XLOG_BLCKSZ, and make sure it's at least 5*Max(BLCKSZ, XLOG_BLCKSZ) to start
169  * with. (That is enough for all "normal" records, but very large commit or
170  * abort records might need more space.)
171  */
172 static bool
174 {
175  uint32 newSize = reclength;
176 
177  newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
178  newSize = Max(newSize, 5 * Max(BLCKSZ, XLOG_BLCKSZ));
179 
180 #ifndef FRONTEND
181 
182  /*
183  * Note that in much unlucky circumstances, the random data read from a
184  * recycled segment can cause this routine to be called with a size
185  * causing a hard failure at allocation. For a standby, this would cause
186  * the instance to stop suddenly with a hard failure, preventing it to
187  * retry fetching WAL from one of its sources which could allow it to move
188  * on with replay without a manual restart. If the data comes from a past
189  * recycled segment and is still valid, then the allocation may succeed
190  * but record checks are going to fail so this would be short-lived. If
191  * the allocation fails because of a memory shortage, then this is not a
192  * hard failure either per the guarantee given by MCXT_ALLOC_NO_OOM.
193  */
194  if (!AllocSizeIsValid(newSize))
195  return false;
196 
197 #endif
198 
199  if (state->readRecordBuf)
200  pfree(state->readRecordBuf);
201  state->readRecordBuf =
202  (char *) palloc_extended(newSize, MCXT_ALLOC_NO_OOM);
203  if (state->readRecordBuf == NULL)
204  {
205  state->readRecordBufSize = 0;
206  return false;
207  }
208  state->readRecordBufSize = newSize;
209  return true;
210 }
211 
212 /*
213  * Initialize the passed segment structs.
214  */
215 static void
217  int segsize, const char *waldir)
218 {
219  seg->ws_file = -1;
220  seg->ws_segno = 0;
221  seg->ws_tli = 0;
222 
223  segcxt->ws_segsize = segsize;
224  if (waldir)
225  snprintf(segcxt->ws_dir, MAXPGPATH, "%s", waldir);
226 }
227 
228 /*
229  * Begin reading WAL at 'RecPtr'.
230  *
231  * 'RecPtr' should point to the beginnning of a valid WAL record. Pointing at
232  * the beginning of a page is also OK, if there is a new record right after
233  * the page header, i.e. not a continuation.
234  *
235  * This does not make any attempt to read the WAL yet, and hence cannot fail.
236  * If the starting address is not correct, the first call to XLogReadRecord()
237  * will error out.
238  */
239 void
241 {
242  Assert(!XLogRecPtrIsInvalid(RecPtr));
243 
244  ResetDecoder(state);
245 
246  /* Begin at the passed-in record pointer. */
247  state->EndRecPtr = RecPtr;
248  state->ReadRecPtr = InvalidXLogRecPtr;
249 }
250 
251 /*
252  * Attempt to read an XLOG record.
253  *
254  * XLogBeginRead() or XLogFindNextRecord() must be called before the first call
255  * to XLogReadRecord().
256  *
257  * If the page_read callback fails to read the requested data, NULL is
258  * returned. The callback is expected to have reported the error; errormsg
259  * is set to NULL.
260  *
261  * If the reading fails for some other reason, NULL is also returned, and
262  * *errormsg is set to a string with details of the failure.
263  *
264  * The returned pointer (or *errormsg) points to an internal buffer that's
265  * valid until the next call to XLogReadRecord.
266  */
267 XLogRecord *
268 XLogReadRecord(XLogReaderState *state, char **errormsg)
269 {
270  XLogRecPtr RecPtr;
271  XLogRecord *record;
272  XLogRecPtr targetPagePtr;
273  bool randAccess;
274  uint32 len,
275  total_len;
276  uint32 targetRecOff;
277  uint32 pageHeaderSize;
278  bool gotheader;
279  int readOff;
280 
281  /*
282  * randAccess indicates whether to verify the previous-record pointer of
283  * the record we're reading. We only do this if we're reading
284  * sequentially, which is what we initially assume.
285  */
286  randAccess = false;
287 
288  /* reset error state */
289  *errormsg = NULL;
290  state->errormsg_buf[0] = '\0';
291 
292  ResetDecoder(state);
293 
294  RecPtr = state->EndRecPtr;
295 
296  if (state->ReadRecPtr != InvalidXLogRecPtr)
297  {
298  /* read the record after the one we just read */
299 
300  /*
301  * EndRecPtr is pointing to end+1 of the previous WAL record. If
302  * we're at a page boundary, no more records can fit on the current
303  * page. We must skip over the page header, but we can't do that until
304  * we've read in the page, since the header size is variable.
305  */
306  }
307  else
308  {
309  /*
310  * Caller supplied a position to start at.
311  *
312  * In this case, EndRecPtr should already be pointing to a valid
313  * record starting position.
314  */
315  Assert(XRecOffIsValid(RecPtr));
316  randAccess = true;
317  }
318 
319  state->currRecPtr = RecPtr;
320 
321  targetPagePtr = RecPtr - (RecPtr % XLOG_BLCKSZ);
322  targetRecOff = RecPtr % XLOG_BLCKSZ;
323 
324  /*
325  * Read the page containing the record into state->readBuf. Request enough
326  * byte to cover the whole record header, or at least the part of it that
327  * fits on the same page.
328  */
329  readOff = ReadPageInternal(state, targetPagePtr,
330  Min(targetRecOff + SizeOfXLogRecord, XLOG_BLCKSZ));
331  if (readOff < 0)
332  goto err;
333 
334  /*
335  * ReadPageInternal always returns at least the page header, so we can
336  * examine it now.
337  */
338  pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
339  if (targetRecOff == 0)
340  {
341  /*
342  * At page start, so skip over page header.
343  */
344  RecPtr += pageHeaderSize;
345  targetRecOff = pageHeaderSize;
346  }
347  else if (targetRecOff < pageHeaderSize)
348  {
349  report_invalid_record(state, "invalid record offset at %X/%X",
350  (uint32) (RecPtr >> 32), (uint32) RecPtr);
351  goto err;
352  }
353 
354  if ((((XLogPageHeader) state->readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
355  targetRecOff == pageHeaderSize)
356  {
357  report_invalid_record(state, "contrecord is requested by %X/%X",
358  (uint32) (RecPtr >> 32), (uint32) RecPtr);
359  goto err;
360  }
361 
362  /* ReadPageInternal has verified the page header */
363  Assert(pageHeaderSize <= readOff);
364 
365  /*
366  * Read the record length.
367  *
368  * NB: Even though we use an XLogRecord pointer here, the whole record
369  * header might not fit on this page. xl_tot_len is the first field of the
370  * struct, so it must be on this page (the records are MAXALIGNed), but we
371  * cannot access any other fields until we've verified that we got the
372  * whole header.
373  */
374  record = (XLogRecord *) (state->readBuf + RecPtr % XLOG_BLCKSZ);
375  total_len = record->xl_tot_len;
376 
377  /*
378  * If the whole record header is on this page, validate it immediately.
379  * Otherwise do just a basic sanity check on xl_tot_len, and validate the
380  * rest of the header after reading it from the next page. The xl_tot_len
381  * check is necessary here to ensure that we enter the "Need to reassemble
382  * record" code path below; otherwise we might fail to apply
383  * ValidXLogRecordHeader at all.
384  */
385  if (targetRecOff <= XLOG_BLCKSZ - SizeOfXLogRecord)
386  {
387  if (!ValidXLogRecordHeader(state, RecPtr, state->ReadRecPtr, record,
388  randAccess))
389  goto err;
390  gotheader = true;
391  }
392  else
393  {
394  /* XXX: more validation should be done here */
395  if (total_len < SizeOfXLogRecord)
396  {
397  report_invalid_record(state,
398  "invalid record length at %X/%X: wanted %u, got %u",
399  (uint32) (RecPtr >> 32), (uint32) RecPtr,
400  (uint32) SizeOfXLogRecord, total_len);
401  goto err;
402  }
403  gotheader = false;
404  }
405 
406  len = XLOG_BLCKSZ - RecPtr % XLOG_BLCKSZ;
407  if (total_len > len)
408  {
409  /* Need to reassemble record */
410  char *contdata;
411  XLogPageHeader pageHeader;
412  char *buffer;
413  uint32 gotlen;
414 
415  /*
416  * Enlarge readRecordBuf as needed.
417  */
418  if (total_len > state->readRecordBufSize &&
419  !allocate_recordbuf(state, total_len))
420  {
421  /* We treat this as a "bogus data" condition */
422  report_invalid_record(state, "record length %u at %X/%X too long",
423  total_len,
424  (uint32) (RecPtr >> 32), (uint32) RecPtr);
425  goto err;
426  }
427 
428  /* Copy the first fragment of the record from the first page. */
429  memcpy(state->readRecordBuf,
430  state->readBuf + RecPtr % XLOG_BLCKSZ, len);
431  buffer = state->readRecordBuf + len;
432  gotlen = len;
433 
434  do
435  {
436  /* Calculate pointer to beginning of next page */
437  targetPagePtr += XLOG_BLCKSZ;
438 
439  /* Wait for the next page to become available */
440  readOff = ReadPageInternal(state, targetPagePtr,
441  Min(total_len - gotlen + SizeOfXLogShortPHD,
442  XLOG_BLCKSZ));
443 
444  if (readOff < 0)
445  goto err;
446 
447  Assert(SizeOfXLogShortPHD <= readOff);
448 
449  /* Check that the continuation on next page looks valid */
450  pageHeader = (XLogPageHeader) state->readBuf;
451  if (!(pageHeader->xlp_info & XLP_FIRST_IS_CONTRECORD))
452  {
453  report_invalid_record(state,
454  "there is no contrecord flag at %X/%X",
455  (uint32) (RecPtr >> 32), (uint32) RecPtr);
456  goto err;
457  }
458 
459  /*
460  * Cross-check that xlp_rem_len agrees with how much of the record
461  * we expect there to be left.
462  */
463  if (pageHeader->xlp_rem_len == 0 ||
464  total_len != (pageHeader->xlp_rem_len + gotlen))
465  {
466  report_invalid_record(state,
467  "invalid contrecord length %u at %X/%X",
468  pageHeader->xlp_rem_len,
469  (uint32) (RecPtr >> 32), (uint32) RecPtr);
470  goto err;
471  }
472 
473  /* Append the continuation from this page to the buffer */
474  pageHeaderSize = XLogPageHeaderSize(pageHeader);
475 
476  if (readOff < pageHeaderSize)
477  readOff = ReadPageInternal(state, targetPagePtr,
478  pageHeaderSize);
479 
480  Assert(pageHeaderSize <= readOff);
481 
482  contdata = (char *) state->readBuf + pageHeaderSize;
483  len = XLOG_BLCKSZ - pageHeaderSize;
484  if (pageHeader->xlp_rem_len < len)
485  len = pageHeader->xlp_rem_len;
486 
487  if (readOff < pageHeaderSize + len)
488  readOff = ReadPageInternal(state, targetPagePtr,
489  pageHeaderSize + len);
490 
491  memcpy(buffer, (char *) contdata, len);
492  buffer += len;
493  gotlen += len;
494 
495  /* If we just reassembled the record header, validate it. */
496  if (!gotheader)
497  {
498  record = (XLogRecord *) state->readRecordBuf;
499  if (!ValidXLogRecordHeader(state, RecPtr, state->ReadRecPtr,
500  record, randAccess))
501  goto err;
502  gotheader = true;
503  }
504  } while (gotlen < total_len);
505 
506  Assert(gotheader);
507 
508  record = (XLogRecord *) state->readRecordBuf;
509  if (!ValidXLogRecord(state, record, RecPtr))
510  goto err;
511 
512  pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
513  state->ReadRecPtr = RecPtr;
514  state->EndRecPtr = targetPagePtr + pageHeaderSize
515  + MAXALIGN(pageHeader->xlp_rem_len);
516  }
517  else
518  {
519  /* Wait for the record data to become available */
520  readOff = ReadPageInternal(state, targetPagePtr,
521  Min(targetRecOff + total_len, XLOG_BLCKSZ));
522  if (readOff < 0)
523  goto err;
524 
525  /* Record does not cross a page boundary */
526  if (!ValidXLogRecord(state, record, RecPtr))
527  goto err;
528 
529  state->EndRecPtr = RecPtr + MAXALIGN(total_len);
530 
531  state->ReadRecPtr = RecPtr;
532  }
533 
534  /*
535  * Special processing if it's an XLOG SWITCH record
536  */
537  if (record->xl_rmid == RM_XLOG_ID &&
538  (record->xl_info & ~XLR_INFO_MASK) == XLOG_SWITCH)
539  {
540  /* Pretend it extends to end of segment */
541  state->EndRecPtr += state->segcxt.ws_segsize - 1;
542  state->EndRecPtr -= XLogSegmentOffset(state->EndRecPtr, state->segcxt.ws_segsize);
543  }
544 
545  if (DecodeXLogRecord(state, record, errormsg))
546  return record;
547  else
548  return NULL;
549 
550 err:
551 
552  /*
553  * Invalidate the read state. We might read from a different source after
554  * failure.
555  */
557 
558  if (state->errormsg_buf[0] != '\0')
559  *errormsg = state->errormsg_buf;
560 
561  return NULL;
562 }
563 
564 /*
565  * Read a single xlog page including at least [pageptr, reqLen] of valid data
566  * via the page_read() callback.
567  *
568  * Returns -1 if the required page cannot be read for some reason; errormsg_buf
569  * is set in that case (unless the error occurs in the page_read callback).
570  *
571  * We fetch the page from a reader-local cache if we know we have the required
572  * data and if there hasn't been any error since caching the data.
573  */
574 static int
575 ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr, int reqLen)
576 {
577  int readLen;
578  uint32 targetPageOff;
579  XLogSegNo targetSegNo;
580  XLogPageHeader hdr;
581 
582  Assert((pageptr % XLOG_BLCKSZ) == 0);
583 
584  XLByteToSeg(pageptr, targetSegNo, state->segcxt.ws_segsize);
585  targetPageOff = XLogSegmentOffset(pageptr, state->segcxt.ws_segsize);
586 
587  /* check whether we have all the requested data already */
588  if (targetSegNo == state->seg.ws_segno &&
589  targetPageOff == state->segoff && reqLen <= state->readLen)
590  return state->readLen;
591 
592  /*
593  * Data is not in our buffer.
594  *
595  * Every time we actually read the segment, even if we looked at parts of
596  * it before, we need to do verification as the page_read callback might
597  * now be rereading data from a different source.
598  *
599  * Whenever switching to a new WAL segment, we read the first page of the
600  * file and validate its header, even if that's not where the target
601  * record is. This is so that we can check the additional identification
602  * info that is present in the first page's "long" header.
603  */
604  if (targetSegNo != state->seg.ws_segno && targetPageOff != 0)
605  {
606  XLogRecPtr targetSegmentPtr = pageptr - targetPageOff;
607 
608  readLen = state->routine.page_read(state, targetSegmentPtr, XLOG_BLCKSZ,
609  state->currRecPtr,
610  state->readBuf);
611  if (readLen < 0)
612  goto err;
613 
614  /* we can be sure to have enough WAL available, we scrolled back */
615  Assert(readLen == XLOG_BLCKSZ);
616 
617  if (!XLogReaderValidatePageHeader(state, targetSegmentPtr,
618  state->readBuf))
619  goto err;
620  }
621 
622  /*
623  * First, read the requested data length, but at least a short page header
624  * so that we can validate it.
625  */
626  readLen = state->routine.page_read(state, pageptr, Max(reqLen, SizeOfXLogShortPHD),
627  state->currRecPtr,
628  state->readBuf);
629  if (readLen < 0)
630  goto err;
631 
632  Assert(readLen <= XLOG_BLCKSZ);
633 
634  /* Do we have enough data to check the header length? */
635  if (readLen <= SizeOfXLogShortPHD)
636  goto err;
637 
638  Assert(readLen >= reqLen);
639 
640  hdr = (XLogPageHeader) state->readBuf;
641 
642  /* still not enough */
643  if (readLen < XLogPageHeaderSize(hdr))
644  {
645  readLen = state->routine.page_read(state, pageptr, XLogPageHeaderSize(hdr),
646  state->currRecPtr,
647  state->readBuf);
648  if (readLen < 0)
649  goto err;
650  }
651 
652  /*
653  * Now that we know we have the full header, validate it.
654  */
655  if (!XLogReaderValidatePageHeader(state, pageptr, (char *) hdr))
656  goto err;
657 
658  /* update read state information */
659  state->seg.ws_segno = targetSegNo;
660  state->segoff = targetPageOff;
661  state->readLen = readLen;
662 
663  return readLen;
664 
665 err:
667  return -1;
668 }
669 
670 /*
671  * Invalidate the xlogreader's read state to force a re-read.
672  */
673 static void
675 {
676  state->seg.ws_segno = 0;
677  state->segoff = 0;
678  state->readLen = 0;
679 }
680 
681 /*
682  * Validate an XLOG record header.
683  *
684  * This is just a convenience subroutine to avoid duplicated code in
685  * XLogReadRecord. It's not intended for use from anywhere else.
686  */
687 static bool
689  XLogRecPtr PrevRecPtr, XLogRecord *record,
690  bool randAccess)
691 {
692  if (record->xl_tot_len < SizeOfXLogRecord)
693  {
694  report_invalid_record(state,
695  "invalid record length at %X/%X: wanted %u, got %u",
696  (uint32) (RecPtr >> 32), (uint32) RecPtr,
697  (uint32) SizeOfXLogRecord, record->xl_tot_len);
698  return false;
699  }
700  if (record->xl_rmid > RM_MAX_ID)
701  {
702  report_invalid_record(state,
703  "invalid resource manager ID %u at %X/%X",
704  record->xl_rmid, (uint32) (RecPtr >> 32),
705  (uint32) RecPtr);
706  return false;
707  }
708  if (randAccess)
709  {
710  /*
711  * We can't exactly verify the prev-link, but surely it should be less
712  * than the record's own address.
713  */
714  if (!(record->xl_prev < RecPtr))
715  {
716  report_invalid_record(state,
717  "record with incorrect prev-link %X/%X at %X/%X",
718  (uint32) (record->xl_prev >> 32),
719  (uint32) record->xl_prev,
720  (uint32) (RecPtr >> 32), (uint32) RecPtr);
721  return false;
722  }
723  }
724  else
725  {
726  /*
727  * Record's prev-link should exactly match our previous location. This
728  * check guards against torn WAL pages where a stale but valid-looking
729  * WAL record starts on a sector boundary.
730  */
731  if (record->xl_prev != PrevRecPtr)
732  {
733  report_invalid_record(state,
734  "record with incorrect prev-link %X/%X at %X/%X",
735  (uint32) (record->xl_prev >> 32),
736  (uint32) record->xl_prev,
737  (uint32) (RecPtr >> 32), (uint32) RecPtr);
738  return false;
739  }
740  }
741 
742  return true;
743 }
744 
745 
746 /*
747  * CRC-check an XLOG record. We do not believe the contents of an XLOG
748  * record (other than to the minimal extent of computing the amount of
749  * data to read in) until we've checked the CRCs.
750  *
751  * We assume all of the record (that is, xl_tot_len bytes) has been read
752  * into memory at *record. Also, ValidXLogRecordHeader() has accepted the
753  * record's header, which means in particular that xl_tot_len is at least
754  * SizeOfXLogRecord.
755  */
756 static bool
758 {
759  pg_crc32c crc;
760 
761  /* Calculate the CRC */
762  INIT_CRC32C(crc);
763  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
764  /* include the record header last */
765  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
766  FIN_CRC32C(crc);
767 
768  if (!EQ_CRC32C(record->xl_crc, crc))
769  {
770  report_invalid_record(state,
771  "incorrect resource manager data checksum in record at %X/%X",
772  (uint32) (recptr >> 32), (uint32) recptr);
773  return false;
774  }
775 
776  return true;
777 }
778 
779 /*
780  * Validate a page header.
781  *
782  * Check if 'phdr' is valid as the header of the XLog page at position
783  * 'recptr'.
784  */
785 bool
787  char *phdr)
788 {
789  XLogRecPtr recaddr;
790  XLogSegNo segno;
791  int32 offset;
792  XLogPageHeader hdr = (XLogPageHeader) phdr;
793 
794  Assert((recptr % XLOG_BLCKSZ) == 0);
795 
796  XLByteToSeg(recptr, segno, state->segcxt.ws_segsize);
797  offset = XLogSegmentOffset(recptr, state->segcxt.ws_segsize);
798 
799  XLogSegNoOffsetToRecPtr(segno, offset, state->segcxt.ws_segsize, recaddr);
800 
801  if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
802  {
803  char fname[MAXFNAMELEN];
804 
805  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
806 
807  report_invalid_record(state,
808  "invalid magic number %04X in log segment %s, offset %u",
809  hdr->xlp_magic,
810  fname,
811  offset);
812  return false;
813  }
814 
815  if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
816  {
817  char fname[MAXFNAMELEN];
818 
819  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
820 
821  report_invalid_record(state,
822  "invalid info bits %04X in log segment %s, offset %u",
823  hdr->xlp_info,
824  fname,
825  offset);
826  return false;
827  }
828 
829  if (hdr->xlp_info & XLP_LONG_HEADER)
830  {
831  XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
832 
833  if (state->system_identifier &&
834  longhdr->xlp_sysid != state->system_identifier)
835  {
836  report_invalid_record(state,
837  "WAL file is from different database system: WAL file database system identifier is %llu, pg_control database system identifier is %llu",
838  (unsigned long long) longhdr->xlp_sysid,
839  (unsigned long long) state->system_identifier);
840  return false;
841  }
842  else if (longhdr->xlp_seg_size != state->segcxt.ws_segsize)
843  {
844  report_invalid_record(state,
845  "WAL file is from different database system: incorrect segment size in page header");
846  return false;
847  }
848  else if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
849  {
850  report_invalid_record(state,
851  "WAL file is from different database system: incorrect XLOG_BLCKSZ in page header");
852  return false;
853  }
854  }
855  else if (offset == 0)
856  {
857  char fname[MAXFNAMELEN];
858 
859  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
860 
861  /* hmm, first page of file doesn't have a long header? */
862  report_invalid_record(state,
863  "invalid info bits %04X in log segment %s, offset %u",
864  hdr->xlp_info,
865  fname,
866  offset);
867  return false;
868  }
869 
870  /*
871  * Check that the address on the page agrees with what we expected. This
872  * check typically fails when an old WAL segment is recycled, and hasn't
873  * yet been overwritten with new data yet.
874  */
875  if (hdr->xlp_pageaddr != recaddr)
876  {
877  char fname[MAXFNAMELEN];
878 
879  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
880 
881  report_invalid_record(state,
882  "unexpected pageaddr %X/%X in log segment %s, offset %u",
883  (uint32) (hdr->xlp_pageaddr >> 32), (uint32) hdr->xlp_pageaddr,
884  fname,
885  offset);
886  return false;
887  }
888 
889  /*
890  * Since child timelines are always assigned a TLI greater than their
891  * immediate parent's TLI, we should never see TLI go backwards across
892  * successive pages of a consistent WAL sequence.
893  *
894  * Sometimes we re-read a segment that's already been (partially) read. So
895  * we only verify TLIs for pages that are later than the last remembered
896  * LSN.
897  */
898  if (recptr > state->latestPagePtr)
899  {
900  if (hdr->xlp_tli < state->latestPageTLI)
901  {
902  char fname[MAXFNAMELEN];
903 
904  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
905 
906  report_invalid_record(state,
907  "out-of-sequence timeline ID %u (after %u) in log segment %s, offset %u",
908  hdr->xlp_tli,
909  state->latestPageTLI,
910  fname,
911  offset);
912  return false;
913  }
914  }
915  state->latestPagePtr = recptr;
916  state->latestPageTLI = hdr->xlp_tli;
917 
918  return true;
919 }
920 
921 #ifdef FRONTEND
922 /*
923  * Functions that are currently not needed in the backend, but are better
924  * implemented inside xlogreader.c because of the internal facilities available
925  * here.
926  */
927 
928 /*
929  * Find the first record with an lsn >= RecPtr.
930  *
931  * This is different from XLogBeginRead() in that RecPtr doesn't need to point
932  * to a valid record boundary. Useful for checking whether RecPtr is a valid
933  * xlog address for reading, and to find the first valid address after some
934  * address when dumping records for debugging purposes.
935  *
936  * This positions the reader, like XLogBeginRead(), so that the next call to
937  * XLogReadRecord() will read the next valid record.
938  */
940 XLogFindNextRecord(XLogReaderState *state, XLogRecPtr RecPtr)
941 {
942  XLogRecPtr tmpRecPtr;
945  char *errormsg;
946 
947  Assert(!XLogRecPtrIsInvalid(RecPtr));
948 
949  /*
950  * skip over potential continuation data, keeping in mind that it may span
951  * multiple pages
952  */
953  tmpRecPtr = RecPtr;
954  while (true)
955  {
956  XLogRecPtr targetPagePtr;
957  int targetRecOff;
958  uint32 pageHeaderSize;
959  int readLen;
960 
961  /*
962  * Compute targetRecOff. It should typically be equal or greater than
963  * short page-header since a valid record can't start anywhere before
964  * that, except when caller has explicitly specified the offset that
965  * falls somewhere there or when we are skipping multi-page
966  * continuation record. It doesn't matter though because
967  * ReadPageInternal() is prepared to handle that and will read at
968  * least short page-header worth of data
969  */
970  targetRecOff = tmpRecPtr % XLOG_BLCKSZ;
971 
972  /* scroll back to page boundary */
973  targetPagePtr = tmpRecPtr - targetRecOff;
974 
975  /* Read the page containing the record */
976  readLen = ReadPageInternal(state, targetPagePtr, targetRecOff);
977  if (readLen < 0)
978  goto err;
979 
980  header = (XLogPageHeader) state->readBuf;
981 
982  pageHeaderSize = XLogPageHeaderSize(header);
983 
984  /* make sure we have enough data for the page header */
985  readLen = ReadPageInternal(state, targetPagePtr, pageHeaderSize);
986  if (readLen < 0)
987  goto err;
988 
989  /* skip over potential continuation data */
990  if (header->xlp_info & XLP_FIRST_IS_CONTRECORD)
991  {
992  /*
993  * If the length of the remaining continuation data is more than
994  * what can fit in this page, the continuation record crosses over
995  * this page. Read the next page and try again. xlp_rem_len in the
996  * next page header will contain the remaining length of the
997  * continuation data
998  *
999  * Note that record headers are MAXALIGN'ed
1000  */
1001  if (MAXALIGN(header->xlp_rem_len) >= (XLOG_BLCKSZ - pageHeaderSize))
1002  tmpRecPtr = targetPagePtr + XLOG_BLCKSZ;
1003  else
1004  {
1005  /*
1006  * The previous continuation record ends in this page. Set
1007  * tmpRecPtr to point to the first valid record
1008  */
1009  tmpRecPtr = targetPagePtr + pageHeaderSize
1010  + MAXALIGN(header->xlp_rem_len);
1011  break;
1012  }
1013  }
1014  else
1015  {
1016  tmpRecPtr = targetPagePtr + pageHeaderSize;
1017  break;
1018  }
1019  }
1020 
1021  /*
1022  * we know now that tmpRecPtr is an address pointing to a valid XLogRecord
1023  * because either we're at the first record after the beginning of a page
1024  * or we just jumped over the remaining data of a continuation.
1025  */
1026  XLogBeginRead(state, tmpRecPtr);
1027  while (XLogReadRecord(state, &errormsg) != NULL)
1028  {
1029  /* past the record we've found, break out */
1030  if (RecPtr <= state->ReadRecPtr)
1031  {
1032  /* Rewind the reader to the beginning of the last record. */
1033  found = state->ReadRecPtr;
1034  XLogBeginRead(state, found);
1035  return found;
1036  }
1037  }
1038 
1039 err:
1040  XLogReaderInvalReadState(state);
1041 
1042  return InvalidXLogRecPtr;
1043 }
1044 
1045 #endif /* FRONTEND */
1046 
1047 /*
1048  * Helper function to ease writing of XLogRoutine->page_read callbacks.
1049  * If this function is used, caller must supply a segment_open callback in
1050  * 'state', as that is used here.
1051  *
1052  * Read 'count' bytes into 'buf', starting at location 'startptr', from WAL
1053  * fetched from timeline 'tli'.
1054  *
1055  * Returns true if succeeded, false if an error occurs, in which case
1056  * 'errinfo' receives error details.
1057  *
1058  * XXX probably this should be improved to suck data directly from the
1059  * WAL buffers when possible.
1060  */
1061 bool
1063  char *buf, XLogRecPtr startptr, Size count, TimeLineID tli,
1064  WALReadError *errinfo)
1065 {
1066  char *p;
1067  XLogRecPtr recptr;
1068  Size nbytes;
1069 
1070  p = buf;
1071  recptr = startptr;
1072  nbytes = count;
1073 
1074  while (nbytes > 0)
1075  {
1076  uint32 startoff;
1077  int segbytes;
1078  int readbytes;
1079 
1080  startoff = XLogSegmentOffset(recptr, state->segcxt.ws_segsize);
1081 
1082  /*
1083  * If the data we want is not in a segment we have open, close what we
1084  * have (if anything) and open the next one, using the caller's
1085  * provided openSegment callback.
1086  */
1087  if (state->seg.ws_file < 0 ||
1088  !XLByteInSeg(recptr, state->seg.ws_segno, state->segcxt.ws_segsize) ||
1089  tli != state->seg.ws_tli)
1090  {
1091  XLogSegNo nextSegNo;
1092 
1093  if (state->seg.ws_file >= 0)
1094  state->routine.segment_close(state);
1095 
1096  XLByteToSeg(recptr, nextSegNo, state->segcxt.ws_segsize);
1097  state->routine.segment_open(state, nextSegNo, &tli);
1098 
1099  /* This shouldn't happen -- indicates a bug in segment_open */
1100  Assert(state->seg.ws_file >= 0);
1101 
1102  /* Update the current segment info. */
1103  state->seg.ws_tli = tli;
1104  state->seg.ws_segno = nextSegNo;
1105  }
1106 
1107  /* How many bytes are within this segment? */
1108  if (nbytes > (state->segcxt.ws_segsize - startoff))
1109  segbytes = state->segcxt.ws_segsize - startoff;
1110  else
1111  segbytes = nbytes;
1112 
1113 #ifndef FRONTEND
1115 #endif
1116 
1117  /* Reset errno first; eases reporting non-errno-affecting errors */
1118  errno = 0;
1119  readbytes = pg_pread(state->seg.ws_file, p, segbytes, (off_t) startoff);
1120 
1121 #ifndef FRONTEND
1123 #endif
1124 
1125  if (readbytes <= 0)
1126  {
1127  errinfo->wre_errno = errno;
1128  errinfo->wre_req = segbytes;
1129  errinfo->wre_read = readbytes;
1130  errinfo->wre_off = startoff;
1131  errinfo->wre_seg = state->seg;
1132  return false;
1133  }
1134 
1135  /* Update state for read */
1136  recptr += readbytes;
1137  nbytes -= readbytes;
1138  p += readbytes;
1139  }
1140 
1141  return true;
1142 }
1143 
1144 /* ----------------------------------------
1145  * Functions for decoding the data and block references in a record.
1146  * ----------------------------------------
1147  */
1148 
1149 /* private function to reset the state between records */
1150 static void
1152 {
1153  int block_id;
1154 
1155  state->decoded_record = NULL;
1156 
1157  state->main_data_len = 0;
1158 
1159  for (block_id = 0; block_id <= state->max_block_id; block_id++)
1160  {
1161  state->blocks[block_id].in_use = false;
1162  state->blocks[block_id].has_image = false;
1163  state->blocks[block_id].has_data = false;
1164  state->blocks[block_id].apply_image = false;
1165  }
1166  state->max_block_id = -1;
1167 }
1168 
1169 /*
1170  * Decode the previously read record.
1171  *
1172  * On error, a human-readable error message is returned in *errormsg, and
1173  * the return value is false.
1174  */
1175 bool
1176 DecodeXLogRecord(XLogReaderState *state, XLogRecord *record, char **errormsg)
1177 {
1178  /*
1179  * read next _size bytes from record buffer, but check for overrun first.
1180  */
1181 #define COPY_HEADER_FIELD(_dst, _size) \
1182  do { \
1183  if (remaining < _size) \
1184  goto shortdata_err; \
1185  memcpy(_dst, ptr, _size); \
1186  ptr += _size; \
1187  remaining -= _size; \
1188  } while(0)
1189 
1190  char *ptr;
1191  uint32 remaining;
1192  uint32 datatotal;
1193  RelFileNode *rnode = NULL;
1194  uint8 block_id;
1195 
1196  ResetDecoder(state);
1197 
1198  state->decoded_record = record;
1201 
1202  ptr = (char *) record;
1203  ptr += SizeOfXLogRecord;
1204  remaining = record->xl_tot_len - SizeOfXLogRecord;
1205 
1206  /* Decode the headers */
1207  datatotal = 0;
1208  while (remaining > datatotal)
1209  {
1210  COPY_HEADER_FIELD(&block_id, sizeof(uint8));
1211 
1212  if (block_id == XLR_BLOCK_ID_DATA_SHORT)
1213  {
1214  /* XLogRecordDataHeaderShort */
1215  uint8 main_data_len;
1216 
1217  COPY_HEADER_FIELD(&main_data_len, sizeof(uint8));
1218 
1219  state->main_data_len = main_data_len;
1220  datatotal += main_data_len;
1221  break; /* by convention, the main data fragment is
1222  * always last */
1223  }
1224  else if (block_id == XLR_BLOCK_ID_DATA_LONG)
1225  {
1226  /* XLogRecordDataHeaderLong */
1227  uint32 main_data_len;
1228 
1229  COPY_HEADER_FIELD(&main_data_len, sizeof(uint32));
1230  state->main_data_len = main_data_len;
1231  datatotal += main_data_len;
1232  break; /* by convention, the main data fragment is
1233  * always last */
1234  }
1235  else if (block_id == XLR_BLOCK_ID_ORIGIN)
1236  {
1237  COPY_HEADER_FIELD(&state->record_origin, sizeof(RepOriginId));
1238  }
1239  else if (block_id == XLR_BLOCK_ID_TOPLEVEL_XID)
1240  {
1241  COPY_HEADER_FIELD(&state->toplevel_xid, sizeof(TransactionId));
1242  }
1243  else if (block_id <= XLR_MAX_BLOCK_ID)
1244  {
1245  /* XLogRecordBlockHeader */
1246  DecodedBkpBlock *blk;
1247  uint8 fork_flags;
1248 
1249  if (block_id <= state->max_block_id)
1250  {
1251  report_invalid_record(state,
1252  "out-of-order block_id %u at %X/%X",
1253  block_id,
1254  (uint32) (state->ReadRecPtr >> 32),
1255  (uint32) state->ReadRecPtr);
1256  goto err;
1257  }
1258  state->max_block_id = block_id;
1259 
1260  blk = &state->blocks[block_id];
1261  blk->in_use = true;
1262  blk->apply_image = false;
1263 
1264  COPY_HEADER_FIELD(&fork_flags, sizeof(uint8));
1265  blk->forknum = fork_flags & BKPBLOCK_FORK_MASK;
1266  blk->flags = fork_flags;
1267  blk->has_image = ((fork_flags & BKPBLOCK_HAS_IMAGE) != 0);
1268  blk->has_data = ((fork_flags & BKPBLOCK_HAS_DATA) != 0);
1269 
1270  COPY_HEADER_FIELD(&blk->data_len, sizeof(uint16));
1271  /* cross-check that the HAS_DATA flag is set iff data_length > 0 */
1272  if (blk->has_data && blk->data_len == 0)
1273  {
1274  report_invalid_record(state,
1275  "BKPBLOCK_HAS_DATA set, but no data included at %X/%X",
1276  (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
1277  goto err;
1278  }
1279  if (!blk->has_data && blk->data_len != 0)
1280  {
1281  report_invalid_record(state,
1282  "BKPBLOCK_HAS_DATA not set, but data length is %u at %X/%X",
1283  (unsigned int) blk->data_len,
1284  (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
1285  goto err;
1286  }
1287  datatotal += blk->data_len;
1288 
1289  if (blk->has_image)
1290  {
1291  COPY_HEADER_FIELD(&blk->bimg_len, sizeof(uint16));
1292  COPY_HEADER_FIELD(&blk->hole_offset, sizeof(uint16));
1293  COPY_HEADER_FIELD(&blk->bimg_info, sizeof(uint8));
1294 
1295  blk->apply_image = ((blk->bimg_info & BKPIMAGE_APPLY) != 0);
1296 
1297  if (blk->bimg_info & BKPIMAGE_IS_COMPRESSED)
1298  {
1299  if (blk->bimg_info & BKPIMAGE_HAS_HOLE)
1300  COPY_HEADER_FIELD(&blk->hole_length, sizeof(uint16));
1301  else
1302  blk->hole_length = 0;
1303  }
1304  else
1305  blk->hole_length = BLCKSZ - blk->bimg_len;
1306  datatotal += blk->bimg_len;
1307 
1308  /*
1309  * cross-check that hole_offset > 0, hole_length > 0 and
1310  * bimg_len < BLCKSZ if the HAS_HOLE flag is set.
1311  */
1312  if ((blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1313  (blk->hole_offset == 0 ||
1314  blk->hole_length == 0 ||
1315  blk->bimg_len == BLCKSZ))
1316  {
1317  report_invalid_record(state,
1318  "BKPIMAGE_HAS_HOLE set, but hole offset %u length %u block image length %u at %X/%X",
1319  (unsigned int) blk->hole_offset,
1320  (unsigned int) blk->hole_length,
1321  (unsigned int) blk->bimg_len,
1322  (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
1323  goto err;
1324  }
1325 
1326  /*
1327  * cross-check that hole_offset == 0 and hole_length == 0 if
1328  * the HAS_HOLE flag is not set.
1329  */
1330  if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1331  (blk->hole_offset != 0 || blk->hole_length != 0))
1332  {
1333  report_invalid_record(state,
1334  "BKPIMAGE_HAS_HOLE not set, but hole offset %u length %u at %X/%X",
1335  (unsigned int) blk->hole_offset,
1336  (unsigned int) blk->hole_length,
1337  (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
1338  goto err;
1339  }
1340 
1341  /*
1342  * cross-check that bimg_len < BLCKSZ if the IS_COMPRESSED
1343  * flag is set.
1344  */
1345  if ((blk->bimg_info & BKPIMAGE_IS_COMPRESSED) &&
1346  blk->bimg_len == BLCKSZ)
1347  {
1348  report_invalid_record(state,
1349  "BKPIMAGE_IS_COMPRESSED set, but block image length %u at %X/%X",
1350  (unsigned int) blk->bimg_len,
1351  (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
1352  goto err;
1353  }
1354 
1355  /*
1356  * cross-check that bimg_len = BLCKSZ if neither HAS_HOLE nor
1357  * IS_COMPRESSED flag is set.
1358  */
1359  if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1360  !(blk->bimg_info & BKPIMAGE_IS_COMPRESSED) &&
1361  blk->bimg_len != BLCKSZ)
1362  {
1363  report_invalid_record(state,
1364  "neither BKPIMAGE_HAS_HOLE nor BKPIMAGE_IS_COMPRESSED set, but block image length is %u at %X/%X",
1365  (unsigned int) blk->data_len,
1366  (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
1367  goto err;
1368  }
1369  }
1370  if (!(fork_flags & BKPBLOCK_SAME_REL))
1371  {
1372  COPY_HEADER_FIELD(&blk->rnode, sizeof(RelFileNode));
1373  rnode = &blk->rnode;
1374  }
1375  else
1376  {
1377  if (rnode == NULL)
1378  {
1379  report_invalid_record(state,
1380  "BKPBLOCK_SAME_REL set but no previous rel at %X/%X",
1381  (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
1382  goto err;
1383  }
1384 
1385  blk->rnode = *rnode;
1386  }
1387  COPY_HEADER_FIELD(&blk->blkno, sizeof(BlockNumber));
1388  }
1389  else
1390  {
1391  report_invalid_record(state,
1392  "invalid block_id %u at %X/%X",
1393  block_id,
1394  (uint32) (state->ReadRecPtr >> 32),
1395  (uint32) state->ReadRecPtr);
1396  goto err;
1397  }
1398  }
1399 
1400  if (remaining != datatotal)
1401  goto shortdata_err;
1402 
1403  /*
1404  * Ok, we've parsed the fragment headers, and verified that the total
1405  * length of the payload in the fragments is equal to the amount of data
1406  * left. Copy the data of each fragment to a separate buffer.
1407  *
1408  * We could just set up pointers into readRecordBuf, but we want to align
1409  * the data for the convenience of the callers. Backup images are not
1410  * copied, however; they don't need alignment.
1411  */
1412 
1413  /* block data first */
1414  for (block_id = 0; block_id <= state->max_block_id; block_id++)
1415  {
1416  DecodedBkpBlock *blk = &state->blocks[block_id];
1417 
1418  if (!blk->in_use)
1419  continue;
1420 
1421  Assert(blk->has_image || !blk->apply_image);
1422 
1423  if (blk->has_image)
1424  {
1425  blk->bkp_image = ptr;
1426  ptr += blk->bimg_len;
1427  }
1428  if (blk->has_data)
1429  {
1430  if (!blk->data || blk->data_len > blk->data_bufsz)
1431  {
1432  if (blk->data)
1433  pfree(blk->data);
1434 
1435  /*
1436  * Force the initial request to be BLCKSZ so that we don't
1437  * waste time with lots of trips through this stanza as a
1438  * result of WAL compression.
1439  */
1440  blk->data_bufsz = MAXALIGN(Max(blk->data_len, BLCKSZ));
1441  blk->data = palloc(blk->data_bufsz);
1442  }
1443  memcpy(blk->data, ptr, blk->data_len);
1444  ptr += blk->data_len;
1445  }
1446  }
1447 
1448  /* and finally, the main data */
1449  if (state->main_data_len > 0)
1450  {
1451  if (!state->main_data || state->main_data_len > state->main_data_bufsz)
1452  {
1453  if (state->main_data)
1454  pfree(state->main_data);
1455 
1456  /*
1457  * main_data_bufsz must be MAXALIGN'ed. In many xlog record
1458  * types, we omit trailing struct padding on-disk to save a few
1459  * bytes; but compilers may generate accesses to the xlog struct
1460  * that assume that padding bytes are present. If the palloc
1461  * request is not large enough to include such padding bytes then
1462  * we'll get valgrind complaints due to otherwise-harmless fetches
1463  * of the padding bytes.
1464  *
1465  * In addition, force the initial request to be reasonably large
1466  * so that we don't waste time with lots of trips through this
1467  * stanza. BLCKSZ / 2 seems like a good compromise choice.
1468  */
1469  state->main_data_bufsz = MAXALIGN(Max(state->main_data_len,
1470  BLCKSZ / 2));
1471  state->main_data = palloc(state->main_data_bufsz);
1472  }
1473  memcpy(state->main_data, ptr, state->main_data_len);
1474  ptr += state->main_data_len;
1475  }
1476 
1477  return true;
1478 
1479 shortdata_err:
1480  report_invalid_record(state,
1481  "record with invalid length at %X/%X",
1482  (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
1483 err:
1484  *errormsg = state->errormsg_buf;
1485 
1486  return false;
1487 }
1488 
1489 /*
1490  * Returns information about the block that a block reference refers to.
1491  *
1492  * If the WAL record contains a block reference with the given ID, *rnode,
1493  * *forknum, and *blknum are filled in (if not NULL), and returns true.
1494  * Otherwise returns false.
1495  */
1496 bool
1498  RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
1499 {
1500  DecodedBkpBlock *bkpb;
1501 
1502  if (!record->blocks[block_id].in_use)
1503  return false;
1504 
1505  bkpb = &record->blocks[block_id];
1506  if (rnode)
1507  *rnode = bkpb->rnode;
1508  if (forknum)
1509  *forknum = bkpb->forknum;
1510  if (blknum)
1511  *blknum = bkpb->blkno;
1512  return true;
1513 }
1514 
1515 /*
1516  * Returns the data associated with a block reference, or NULL if there is
1517  * no data (e.g. because a full-page image was taken instead). The returned
1518  * pointer points to a MAXALIGNed buffer.
1519  */
1520 char *
1522 {
1523  DecodedBkpBlock *bkpb;
1524 
1525  if (!record->blocks[block_id].in_use)
1526  return NULL;
1527 
1528  bkpb = &record->blocks[block_id];
1529 
1530  if (!bkpb->has_data)
1531  {
1532  if (len)
1533  *len = 0;
1534  return NULL;
1535  }
1536  else
1537  {
1538  if (len)
1539  *len = bkpb->data_len;
1540  return bkpb->data;
1541  }
1542 }
1543 
1544 /*
1545  * Restore a full-page image from a backup block attached to an XLOG record.
1546  *
1547  * Returns the buffer number containing the page.
1548  */
1549 bool
1550 RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
1551 {
1552  DecodedBkpBlock *bkpb;
1553  char *ptr;
1554  PGAlignedBlock tmp;
1555 
1556  if (!record->blocks[block_id].in_use)
1557  return false;
1558  if (!record->blocks[block_id].has_image)
1559  return false;
1560 
1561  bkpb = &record->blocks[block_id];
1562  ptr = bkpb->bkp_image;
1563 
1564  if (bkpb->bimg_info & BKPIMAGE_IS_COMPRESSED)
1565  {
1566  /* If a backup block image is compressed, decompress it */
1567  if (pglz_decompress(ptr, bkpb->bimg_len, tmp.data,
1568  BLCKSZ - bkpb->hole_length, true) < 0)
1569  {
1570  report_invalid_record(record, "invalid compressed image at %X/%X, block %d",
1571  (uint32) (record->ReadRecPtr >> 32),
1572  (uint32) record->ReadRecPtr,
1573  block_id);
1574  return false;
1575  }
1576  ptr = tmp.data;
1577  }
1578 
1579  /* generate page, taking into account hole if necessary */
1580  if (bkpb->hole_length == 0)
1581  {
1582  memcpy(page, ptr, BLCKSZ);
1583  }
1584  else
1585  {
1586  memcpy(page, ptr, bkpb->hole_offset);
1587  /* must zero-fill the hole */
1588  MemSet(page + bkpb->hole_offset, 0, bkpb->hole_length);
1589  memcpy(page + (bkpb->hole_offset + bkpb->hole_length),
1590  ptr + bkpb->hole_offset,
1591  BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
1592  }
1593 
1594  return true;
1595 }
1596 
1597 #ifndef FRONTEND
1598 
1599 /*
1600  * Extract the FullTransactionId from a WAL record.
1601  */
1604 {
1605  TransactionId xid,
1606  next_xid;
1607  uint32 epoch;
1608 
1609  /*
1610  * This function is only safe during replay, because it depends on the
1611  * replay state. See AdvanceNextFullTransactionIdPastXid() for more.
1612  */
1614 
1615  xid = XLogRecGetXid(record);
1618 
1619  /*
1620  * If xid is numerically greater than next_xid, it has to be from the last
1621  * epoch.
1622  */
1623  if (unlikely(xid > next_xid))
1624  --epoch;
1625 
1626  return FullTransactionIdFromEpochAndXid(epoch, xid);
1627 }
1628 
1629 #endif
int remaining
Definition: informix.c:667
WALOpenSegment wre_seg
Definition: xlogreader.h:291
BlockNumber blkno
Definition: xlogreader.h:126
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define AmStartupProcess()
Definition: miscadmin.h:431
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
char ws_dir[MAXPGPATH]
Definition: xlogreader.h:54
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
WALSegmentCloseCB segment_close
Definition: xlogreader.h:113
#define BKPIMAGE_HAS_HOLE
Definition: xlogrecord.h:146
char * readRecordBuf
Definition: xlogreader.h:250
static void WALOpenSegmentInit(WALOpenSegment *seg, WALSegmentContext *segcxt, int segsize, const char *waldir)
Definition: xlogreader.c:216
uint32 TimeLineID
Definition: xlogdefs.h:52
int wal_segment_size
Definition: xlog.c:116
uint32 TransactionId
Definition: c.h:520
#define XLogPageHeaderSize(hdr)
Definition: xlog_internal.h:85
#define XLR_BLOCK_ID_DATA_LONG
Definition: xlogrecord.h:224
static XLogRecPtr ReadRecPtr
Definition: xlog.c:850
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define Min(x, y)
Definition: c.h:927
uint16 hole_offset
Definition: xlogreader.h:135
unsigned char uint8
Definition: c.h:372
uint16 RepOriginId
Definition: xlogdefs.h:58
void * palloc_extended(Size size, int flags)
Definition: mcxt.c:1013
static void report_invalid_record(XLogReaderState *state, const char *fmt,...) pg_attribute_printf(2
Definition: xlogreader.c:58
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:18
#define MemSet(start, val, len)
Definition: c.h:978
RmgrId xl_rmid
Definition: xlogrecord.h:47
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:57
uint32 BlockNumber
Definition: block.h:31
FullTransactionId nextFullXid
Definition: transam.h:178
void * private_data
Definition: xlogreader.h:168
bool DecodeXLogRecord(XLogReaderState *state, XLogRecord *record, char **errormsg)
Definition: xlogreader.c:1176
static int ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr, int reqLen)
Definition: xlogreader.c:575
int32 pglz_decompress(const char *source, int32 slen, char *dest, int32 rawsize, bool check_complete)
XLogPageReadCB page_read
Definition: xlogreader.h:93
#define MAX_ERRORMSG_LEN
Definition: xlogreader.c:51
signed int int32
Definition: c.h:362
bool XLogReaderValidatePageHeader(XLogReaderState *state, XLogRecPtr recptr, char *phdr)
Definition: xlogreader.c:786
#define pg_attribute_printf(f, a)
Definition: c.h:130
XLogRecPtr EndRecPtr
Definition: xlogreader.h:176
#define XidFromFullTransactionId(x)
Definition: transam.h:48
ssize_t pg_pread(int fd, void *buf, size_t nbyte, off_t offset)
Definition: pread.c:27
#define XLByteInSeg(xlrp, logSegNo, wal_segsz_bytes)
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:74
WALOpenSegment seg
Definition: xlogreader.h:215
char data[BLCKSZ]
Definition: c.h:1111
unsigned short uint16
Definition: c.h:373
void pfree(void *pointer)
Definition: mcxt.c:1056
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:268
XLogRecPtr latestPagePtr
Definition: xlogreader.h:222
static uint32 readOff
Definition: xlog.c:813
uint16 hole_length
Definition: xlogreader.h:136
#define XLR_BLOCK_ID_TOPLEVEL_XID
Definition: xlogrecord.h:226
static void XLogReaderInvalReadState(XLogReaderState *state)
Definition: xlogreader.c:674
uint32 xl_tot_len
Definition: xlogrecord.h:43
#define XLOG_PAGE_MAGIC
Definition: xlog_internal.h:34
uint32 main_data_len
Definition: xlogreader.h:189
#define vsnprintf
Definition: port.h:192
#define MAXPGPATH
static void static bool allocate_recordbuf(XLogReaderState *state, uint32 reclength)
Definition: xlogreader.c:173
#define BKPIMAGE_APPLY
Definition: xlogrecord.h:148
static char * buf
Definition: pg_test_fsync.c:67
bool IsUnderPostmaster
Definition: globals.c:109
uint64 XLogSegNo
Definition: xlogdefs.h:41
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:175
XLogRecord * decoded_record
Definition: xlogreader.h:186
XLogSegNo ws_segno
Definition: xlogreader.h:47
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define COPY_HEADER_FIELD(_dst, _size)
#define InvalidTransactionId
Definition: transam.h:31
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:240
unsigned int uint32
Definition: c.h:374
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1381
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:75
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
#define AllocSizeIsValid(size)
Definition: memutils.h:42
ForkNumber
Definition: relpath.h:40
TimeLineID xlp_tli
Definition: xlog_internal.h:40
#define XLR_MAX_BLOCK_ID
Definition: xlogrecord.h:221
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint32 readRecordBufSize
Definition: xlogreader.h:251
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:139
#define MAXFNAMELEN
#define RM_MAX_ID
Definition: rmgr.h:33
bool XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
Definition: xlogreader.c:1497
#define XLogRecGetXid(decoder)
Definition: xlogreader.h:307
char * XLogRecGetBlockData(XLogReaderState *record, uint8 block_id, Size *len)
Definition: xlogreader.c:1521
#define BKPBLOCK_SAME_REL
Definition: xlogrecord.h:183
#define BKPIMAGE_IS_COMPRESSED
Definition: xlogrecord.h:147
TransactionId toplevel_xid
Definition: xlogreader.h:194
#define BKPBLOCK_HAS_IMAGE
Definition: xlogrecord.h:180
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
ForkNumber forknum
Definition: xlogreader.h:125
#define EpochFromFullTransactionId(x)
Definition: transam.h:47
#define XLP_ALL_FLAGS
Definition: xlog_internal.h:83
XLogRecPtr currRecPtr
Definition: xlogreader.h:226
#define Max(x, y)
Definition: c.h:921
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:745
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define XLP_LONG_HEADER
Definition: xlog_internal.h:79
Definition: regguts.h:298
static bool ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr, XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess)
Definition: xlogreader.c:688
uint16 data_bufsz
Definition: xlogreader.h:144
#define MCXT_ALLOC_ZERO
Definition: fe_memutils.h:19
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:55
size_t Size
Definition: c.h:473
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1357
uint8 xl_info
Definition: xlogrecord.h:46
FullTransactionId XLogRecGetFullXid(XLogReaderState *record)
Definition: xlogreader.c:1603
#define XLR_BLOCK_ID_ORIGIN
Definition: xlogrecord.h:225
#define XLP_FIRST_IS_CONTRECORD
Definition: xlog_internal.h:77
static FullTransactionId FullTransactionIdFromEpochAndXid(uint32 epoch, TransactionId xid)
Definition: transam.h:69
#define MAXALIGN(LEN)
Definition: c.h:698
#define XLOG_SWITCH
Definition: pg_control.h:71
static void header(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:208
TimeLineID ws_tli
Definition: xlogreader.h:48
#define InvalidRepOriginId
Definition: origin.h:33
char * bkp_image
Definition: xlogreader.h:134
bool RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
Definition: xlogreader.c:1550
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:223
uint32 main_data_bufsz
Definition: xlogreader.h:190
static bool ValidXLogRecord(XLogReaderState *state, XLogRecord *record, XLogRecPtr recptr)
Definition: xlogreader.c:757
#define BKPBLOCK_FORK_MASK
Definition: xlogrecord.h:178
#define XRecOffIsValid(xlrp)
void * palloc(Size size)
Definition: mcxt.c:949
static const unsigned __int64 epoch
Definition: gettimeofday.c:34
#define unlikely(x)
Definition: c.h:206
uint64 system_identifier
Definition: xlogreader.h:163
bool WALRead(XLogReaderState *state, char *buf, XLogRecPtr startptr, Size count, TimeLineID tli, WALReadError *errinfo)
Definition: xlogreader.c:1062
WALSegmentContext segcxt
Definition: xlogreader.h:214
WALSegmentOpenCB segment_open
Definition: xlogreader.h:107
char * errormsg_buf
Definition: xlogreader.h:254
char * main_data
Definition: xlogreader.h:188
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
TimeLineID latestPageTLI
Definition: xlogreader.h:223
XLogReaderRoutine routine
Definition: xlogreader.h:152
RelFileNode rnode
Definition: xlogreader.h:124
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
#define snprintf
Definition: port.h:193
static uint32 readLen
Definition: xlog.c:814
#define _(x)
Definition: elog.c:88
RepOriginId record_origin
Definition: xlogreader.h:192
static void ResetDecoder(XLogReaderState *state)
Definition: xlogreader.c:1151
#define offsetof(type, field)
Definition: c.h:668
DecodedBkpBlock blocks[XLR_MAX_BLOCK_ID+1]
Definition: xlogreader.h:197
static XLogRecPtr startptr
Definition: basebackup.c:116
#define BKPBLOCK_HAS_DATA
Definition: xlogrecord.h:181
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)