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-2022, 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 #ifdef USE_LZ4
22 #include <lz4.h>
23 #endif
24 #ifdef USE_ZSTD
25 #include <zstd.h>
26 #endif
27 
28 #include "access/transam.h"
29 #include "access/xlog_internal.h"
30 #include "access/xlogreader.h"
31 #include "access/xlogrecord.h"
32 #include "catalog/pg_control.h"
33 #include "common/pg_lzcompress.h"
34 #include "replication/origin.h"
35 
36 #ifndef FRONTEND
37 #include "miscadmin.h"
38 #include "pgstat.h"
39 #include "utils/memutils.h"
40 #else
41 #include "common/logging.h"
42 #endif
43 
44 static void report_invalid_record(XLogReaderState *state, const char *fmt,...)
45  pg_attribute_printf(2, 3);
46 static bool allocate_recordbuf(XLogReaderState *state, uint32 reclength);
48  int reqLen);
52  XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess);
53 static bool ValidXLogRecord(XLogReaderState *state, XLogRecord *record,
54  XLogRecPtr recptr);
55 static void ResetDecoder(XLogReaderState *state);
56 static void WALOpenSegmentInit(WALOpenSegment *seg, WALSegmentContext *segcxt,
57  int segsize, const char *waldir);
58 
59 /* size of the buffer allocated for error message. */
60 #define MAX_ERRORMSG_LEN 1000
61 
62 /*
63  * Default size; large enough that typical users of XLogReader won't often need
64  * to use the 'oversized' memory allocation code path.
65  */
66 #define DEFAULT_DECODE_BUFFER_SIZE (64 * 1024)
67 
68 /*
69  * Construct a string in state->errormsg_buf explaining what's wrong with
70  * the current record being read.
71  */
72 static void
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 }
85 
86 /*
87  * Set the size of the decoding buffer. A pointer to a caller supplied memory
88  * region may also be passed in, in which case non-oversized records will be
89  * decoded there.
90  */
91 void
92 XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
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 }
101 
102 /*
103  * Allocate and initialize a new XLogReader.
104  *
105  * Returns NULL if the xlogreader couldn't be allocated.
106  */
108 XLogReaderAllocate(int wal_segment_size, const char *waldir,
109  XLogReaderRoutine *routine, void *private_data)
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 }
168 
169 void
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 }
184 
185 /*
186  * Allocate readRecordBuf to fit a record of at least the given length.
187  * Returns true if successful, false if out of memory.
188  *
189  * readRecordBufSize is set to the new buffer size.
190  *
191  * To avoid useless small increases, round its size to a multiple of
192  * XLOG_BLCKSZ, and make sure it's at least 5*Max(BLCKSZ, XLOG_BLCKSZ) to start
193  * with. (That is enough for all "normal" records, but very large commit or
194  * abort records might need more space.)
195  */
196 static bool
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 }
235 
236 /*
237  * Initialize the passed segment structs.
238  */
239 static void
241  int segsize, const char *waldir)
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 }
251 
252 /*
253  * Begin reading WAL at 'RecPtr'.
254  *
255  * 'RecPtr' should point to the beginning of a valid WAL record. Pointing at
256  * the beginning of a page is also OK, if there is a new record right after
257  * the page header, i.e. not a continuation.
258  *
259  * This does not make any attempt to read the WAL yet, and hence cannot fail.
260  * If the starting address is not correct, the first call to XLogReadRecord()
261  * will error out.
262  */
263 void
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 }
276 
277 /*
278  * Release the last record that was returned by XLogNextRecord(), if any, to
279  * free up space. Returns the LSN past the end of the record.
280  */
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 }
344 
345 /*
346  * Attempt to read an XLOG record.
347  *
348  * XLogBeginRead() or XLogFindNextRecord() and then XLogReadAhead() must be
349  * called before the first call to XLogNextRecord(). This functions returns
350  * records and errors that were put into an internal queue by XLogReadAhead().
351  *
352  * On success, a record is returned.
353  *
354  * The returned record (or *errormsg) points to an internal buffer that's
355  * valid until the next call to XLogNextRecord.
356  */
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 }
404 
405 /*
406  * Attempt to read an XLOG record.
407  *
408  * XLogBeginRead() or XLogFindNextRecord() must be called before the first call
409  * to XLogReadRecord().
410  *
411  * If the page_read callback fails to read the requested data, NULL is
412  * returned. The callback is expected to have reported the error; errormsg
413  * is set to NULL.
414  *
415  * If the reading fails for some other reason, NULL is also returned, and
416  * *errormsg is set to a string with details of the failure.
417  *
418  * The returned pointer (or *errormsg) points to an internal buffer that's
419  * valid until the next call to XLogReadRecord.
420  */
421 XLogRecord *
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 }
455 
456 /*
457  * Allocate space for a decoded record. The only member of the returned
458  * object that is initialized is the 'oversized' flag, indicating that the
459  * decoded record wouldn't fit in the decode buffer and must eventually be
460  * freed explicitly.
461  *
462  * The caller is responsible for adjusting decode_buffer_tail with the real
463  * size after successfully decoding a record into this space. This way, if
464  * decoding fails, then there is nothing to undo unless the 'oversized' flag
465  * was set and pfree() must be called.
466  *
467  * Return NULL if there is no space in the decode buffer and allow_oversized
468  * is false, or if memory allocation fails for an oversized buffer.
469  */
470 static DecodedXLogRecord *
471 XLogReadRecordAlloc(XLogReaderState *state, size_t xl_tot_len, bool allow_oversized)
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 }
533 
534 static XLogPageReadResult
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 }
944 
945 /*
946  * Try to decode the next available record, and return it. The record will
947  * also be returned to XLogNextRecord(), which must be called to 'consume'
948  * each record.
949  *
950  * If nonblocking is true, may return NULL due to lack of data or WAL decoding
951  * space.
952  */
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 }
970 
971 /*
972  * Read a single xlog page including at least [pageptr, reqLen] of valid data
973  * via the page_read() callback.
974  *
975  * Returns XLREAD_FAIL if the required page cannot be read for some
976  * reason; errormsg_buf is set in that case (unless the error occurs in the
977  * page_read callback).
978  *
979  * Returns XLREAD_WOULDBLOCK if the requested data can't be read without
980  * waiting. This can be returned only if the installed page_read callback
981  * respects the state->nonblocking flag, and cannot read the requested data
982  * immediately.
983  *
984  * We fetch the page from a reader-local cache if we know we have the required
985  * data and if there hasn't been any error since caching the data.
986  */
987 static int
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 }
1096 
1097 /*
1098  * Invalidate the xlogreader's read state to force a re-read.
1099  */
1100 static void
1102 {
1103  state->seg.ws_segno = 0;
1104  state->segoff = 0;
1105  state->readLen = 0;
1106 }
1107 
1108 /*
1109  * Validate an XLOG record header.
1110  *
1111  * This is just a convenience subroutine to avoid duplicated code in
1112  * XLogReadRecord. It's not intended for use from anywhere else.
1113  */
1114 static bool
1116  XLogRecPtr PrevRecPtr, XLogRecord *record,
1117  bool randAccess)
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 }
1168 
1169 
1170 /*
1171  * CRC-check an XLOG record. We do not believe the contents of an XLOG
1172  * record (other than to the minimal extent of computing the amount of
1173  * data to read in) until we've checked the CRCs.
1174  *
1175  * We assume all of the record (that is, xl_tot_len bytes) has been read
1176  * into memory at *record. Also, ValidXLogRecordHeader() has accepted the
1177  * record's header, which means in particular that xl_tot_len is at least
1178  * SizeOfXLogRecord.
1179  */
1180 static bool
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 }
1202 
1203 /*
1204  * Validate a page header.
1205  *
1206  * Check if 'phdr' is valid as the header of the XLog page at position
1207  * 'recptr'.
1208  */
1209 bool
1211  char *phdr)
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 }
1346 
1347 /*
1348  * Forget about an error produced by XLogReaderValidatePageHeader().
1349  */
1350 void
1352 {
1353  state->errormsg_buf[0] = '\0';
1354  state->errormsg_deferred = false;
1355 }
1356 
1357 /*
1358  * Find the first record with an lsn >= RecPtr.
1359  *
1360  * This is different from XLogBeginRead() in that RecPtr doesn't need to point
1361  * to a valid record boundary. Useful for checking whether RecPtr is a valid
1362  * xlog address for reading, and to find the first valid address after some
1363  * address when dumping records for debugging purposes.
1364  *
1365  * This positions the reader, like XLogBeginRead(), so that the next call to
1366  * XLogReadRecord() will read the next valid record.
1367  */
1368 XLogRecPtr
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 }
1476 
1477 /*
1478  * Helper function to ease writing of XLogRoutine->page_read callbacks.
1479  * If this function is used, caller must supply a segment_open callback in
1480  * 'state', as that is used here.
1481  *
1482  * Read 'count' bytes into 'buf', starting at location 'startptr', from WAL
1483  * fetched from timeline 'tli'.
1484  *
1485  * Returns true if succeeded, false if an error occurs, in which case
1486  * 'errinfo' receives error details.
1487  *
1488  * XXX probably this should be improved to suck data directly from the
1489  * WAL buffers when possible.
1490  */
1491 bool
1493  char *buf, XLogRecPtr startptr, Size count, TimeLineID tli,
1494  WALReadError *errinfo)
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 }
1573 
1574 /* ----------------------------------------
1575  * Functions for decoding the data and block references in a record.
1576  * ----------------------------------------
1577  */
1578 
1579 /*
1580  * Private function to reset the state, forgetting all decoded records, if we
1581  * are asked to move to a new read position.
1582  */
1583 static void
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 }
1607 
1608 /*
1609  * Compute the maximum possible amount of padding that could be required to
1610  * decode a record, given xl_tot_len from the record's header. This is the
1611  * amount of output buffer space that we need to decode a record, though we
1612  * might not finish up using it all.
1613  *
1614  * This computation is pessimistic and assumes the maximum possible number of
1615  * blocks, due to lack of better information.
1616  */
1617 size_t
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 }
1637 
1638 /*
1639  * Decode a record. "decoded" must point to a MAXALIGNed memory area that has
1640  * space for at least DecodeXLogRecordRequiredSpace(record) bytes. On
1641  * success, decoded->size contains the actual space occupied by the decoded
1642  * record, which may turn out to be less.
1643  *
1644  * Only decoded->oversized member must be initialized already, and will not be
1645  * modified. Other members will be initialized as required.
1646  *
1647  * On error, a human-readable error message is returned in *errormsg, and
1648  * the return value is false.
1649  */
1650 bool
1652  DecodedXLogRecord *decoded,
1653  XLogRecord *record,
1654  XLogRecPtr lsn,
1655  char **errormsg)
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 }
1952 
1953 /*
1954  * Returns information about the block that a block reference refers to.
1955  *
1956  * This is like XLogRecGetBlockTagExtended, except that the block reference
1957  * must exist and there's no access to prefetch_buffer.
1958  */
1959 void
1961  RelFileLocator *rlocator, ForkNumber *forknum,
1962  BlockNumber *blknum)
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 }
1976 
1977 /*
1978  * Returns information about the block that a block reference refers to,
1979  * optionally including the buffer that the block may already be in.
1980  *
1981  * If the WAL record contains a block reference with the given ID, *rlocator,
1982  * *forknum, *blknum and *prefetch_buffer are filled in (if not NULL), and
1983  * returns true. Otherwise returns false.
1984  */
1985 bool
1987  RelFileLocator *rlocator, ForkNumber *forknum,
1988  BlockNumber *blknum,
1989  Buffer *prefetch_buffer)
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 }
2007 
2008 /*
2009  * Returns the data associated with a block reference, or NULL if there is
2010  * no data (e.g. because a full-page image was taken instead). The returned
2011  * pointer points to a MAXALIGNed buffer.
2012  */
2013 char *
2015 {
2016  DecodedBkpBlock *bkpb;
2017 
2018  if (block_id > record->record->max_block_id ||
2019  !record->record->blocks[block_id].in_use)
2020  return NULL;
2021 
2022  bkpb = &record->record->blocks[block_id];
2023 
2024  if (!bkpb->has_data)
2025  {
2026  if (len)
2027  *len = 0;
2028  return NULL;
2029  }
2030  else
2031  {
2032  if (len)
2033  *len = bkpb->data_len;
2034  return bkpb->data;
2035  }
2036 }
2037 
2038 /*
2039  * Restore a full-page image from a backup block attached to an XLOG record.
2040  *
2041  * Returns true if a full-page image is restored, and false on failure with
2042  * an error to be consumed by the caller.
2043  */
2044 bool
2045 RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
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 }
2149 
2150 #ifndef FRONTEND
2151 
2152 /*
2153  * Extract the FullTransactionId from a WAL record.
2154  */
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 }
2181 
2182 #endif
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
#define InvalidBuffer
Definition: buf.h:25
unsigned short uint16
Definition: c.h:441
unsigned int uint32
Definition: c.h:442
#define Min(x, y)
Definition: c.h:937
#define MAXALIGN(LEN)
Definition: c.h:747
signed int int32
Definition: c.h:430
#define Max(x, y)
Definition: c.h:931
#define pg_attribute_printf(f, a)
Definition: c.h:175
#define unlikely(x)
Definition: c.h:295
unsigned char uint8
Definition: c.h:440
#define MemSet(start, val, len)
Definition: c.h:953
uint32 TransactionId
Definition: c.h:588
size_t Size
Definition: c.h:541
#define _(x)
Definition: elog.c:91
#define ERROR
Definition: elog.h:39
#define MCXT_ALLOC_ZERO
Definition: fe_memutils.h:18
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:17
bool IsUnderPostmaster
Definition: globals.c:113
int remaining
Definition: informix.c:667
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
static void const char * fmt
va_end(args)
Assert(fmt[strlen(fmt) - 1] !='\n')
va_start(args, fmt)
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc_extended(Size size, int flags)
Definition: mcxt.c:1263
void * palloc(Size size)
Definition: mcxt.c:1199
#define AllocSizeIsValid(size)
Definition: memutils.h:42
#define AmStartupProcess()
Definition: miscadmin.h:440
#define InvalidRepOriginId
Definition: origin.h:33
#define pg_fatal(...)
#define MAXPGPATH
#define XLOG_SWITCH
Definition: pg_control.h:71
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
const void size_t len
return crc
int32 pglz_decompress(const char *source, int32 slen, char *dest, int32 rawsize, bool check_complete)
static void header(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:208
static char * buf
Definition: pg_test_fsync.c:67
#define vsnprintf
Definition: port.h:237
#define pg_pread
Definition: port.h:225
#define snprintf
Definition: port.h:238
ForkNumber
Definition: relpath.h:48
#define RmgrIdIsValid(rmid)
Definition: rmgr.h:53
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
XLogRecPtr next_lsn
Definition: xlogreader.h:165
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
FullTransactionId nextXid
Definition: transam.h:220
XLogSegNo ws_segno
Definition: xlogreader.h:48
TimeLineID ws_tli
Definition: xlogreader.h:49
WALOpenSegment wre_seg
Definition: xlogreader.h:389
char ws_dir[MAXPGPATH]
Definition: xlogreader.h:55
TimeLineID xlp_tli
Definition: xlog_internal.h:40
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
DecodedXLogRecord * record
Definition: xlogreader.h:236
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:206
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
pg_crc32c xl_crc
Definition: xlogrecord.h:49
uint8 xl_info
Definition: xlogrecord.h:46
uint32 xl_tot_len
Definition: xlogrecord.h:43
RmgrId xl_rmid
Definition: xlogrecord.h:47
Definition: regguts.h:318
struct state * next
Definition: regguts.h:327
#define InvalidTransactionId
Definition: transam.h:31
#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
char data[BLCKSZ]
Definition: c.h:1079
VariableCache ShmemVariableCache
Definition: varsup.c:34
@ 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
static const unsigned __int64 epoch
int wal_segment_size
Definition: xlog.c:146
#define XLP_FIRST_IS_CONTRECORD
Definition: xlog_internal.h:74
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:71
#define XLP_FIRST_IS_OVERWRITE_CONTRECORD
Definition: xlog_internal.h:80
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
#define MAXFNAMELEN
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:54
#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
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XRecOffIsValid(xlrp)
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:52
static void XLogFileName(char *fname, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)
#define XLogPageHeaderSize(hdr)
Definition: xlog_internal.h:84
#define XLByteInSeg(xlrp, logSegNo, wal_segsz_bytes)
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint16 RepOriginId
Definition: xlogdefs.h:65
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TimeLineID
Definition: xlogdefs.h:59
uint64 XLogSegNo
Definition: xlogdefs.h:48
static void static bool allocate_recordbuf(XLogReaderState *state, uint32 reclength)
Definition: xlogreader.c:197
bool XLogRecGetBlockTagExtended(XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum, Buffer *prefetch_buffer)
Definition: xlogreader.c:1986
static XLogPageReadResult XLogDecodeNextRecord(XLogReaderState *state, bool nonblocking)
Definition: xlogreader.c:535
void XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
Definition: xlogreader.c:92
static void WALOpenSegmentInit(WALOpenSegment *seg, WALSegmentContext *segcxt, int segsize, const char *waldir)
Definition: xlogreader.c:240
static int ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr, int reqLen)
Definition: xlogreader.c:988
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:422
static void report_invalid_record(XLogReaderState *state, const char *fmt,...) pg_attribute_printf(2
Definition: xlogreader.c:73
bool WALRead(XLogReaderState *state, char *buf, XLogRecPtr startptr, Size count, TimeLineID tli, WALReadError *errinfo)
Definition: xlogreader.c:1492
#define MAX_ERRORMSG_LEN
Definition: xlogreader.c:60
DecodedXLogRecord * XLogNextRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:358
void XLogReaderResetError(XLogReaderState *state)
Definition: xlogreader.c:1351
static void XLogReaderInvalReadState(XLogReaderState *state)
Definition: xlogreader.c:1101
#define COPY_HEADER_FIELD(_dst, _size)
bool XLogReaderValidatePageHeader(XLogReaderState *state, XLogRecPtr recptr, char *phdr)
Definition: xlogreader.c:1210
FullTransactionId XLogRecGetFullXid(XLogReaderState *record)
Definition: xlogreader.c:2156
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:170
void XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum)
Definition: xlogreader.c:1960
DecodedXLogRecord * XLogReadAhead(XLogReaderState *state, bool nonblocking)
Definition: xlogreader.c:954
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:108
static void ResetDecoder(XLogReaderState *state)
Definition: xlogreader.c:1584
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
char * XLogRecGetBlockData(XLogReaderState *record, uint8 block_id, Size *len)
Definition: xlogreader.c:2014
#define DEFAULT_DECODE_BUFFER_SIZE
Definition: xlogreader.c:66
size_t DecodeXLogRecordRequiredSpace(size_t xl_tot_len)
Definition: xlogreader.c:1618
XLogRecPtr XLogFindNextRecord(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:1369
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:264
bool RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
Definition: xlogreader.c:2045
static DecodedXLogRecord * XLogReadRecordAlloc(XLogReaderState *state, size_t xl_tot_len, bool allow_oversized)
Definition: xlogreader.c:471
XLogRecPtr XLogReleasePreviousRecord(XLogReaderState *state)
Definition: xlogreader.c:282
static bool ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr, XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess)
Definition: xlogreader.c:1115
static bool XLogReaderHasQueuedRecordOrError(XLogReaderState *state)
Definition: xlogreader.h:325
#define XLogRecGetXid(decoder)
Definition: xlogreader.h:413
XLogPageReadResult
Definition: xlogreader.h:351
@ XLREAD_WOULDBLOCK
Definition: xlogreader.h:354
@ XLREAD_SUCCESS
Definition: xlogreader.h:352
@ XLREAD_FAIL
Definition: xlogreader.h:353
#define XLogRecHasBlockRef(decoder, block_id)
Definition: xlogreader.h:421
#define BKPIMAGE_COMPRESS_ZSTD
Definition: xlogrecord.h:151
#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_COMPRESS_LZ4
Definition: xlogrecord.h:150
#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 XLR_INFO_MASK
Definition: xlogrecord.h:62
#define BKPBLOCK_SAME_REL
Definition: xlogrecord.h:189
#define BKPIMAGE_COMPRESS_PGLZ
Definition: xlogrecord.h:149
#define XLR_BLOCK_ID_ORIGIN
Definition: xlogrecord.h:232
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
#define BKPBLOCK_HAS_IMAGE
Definition: xlogrecord.h:186
static uint32 readOff
Definition: xlogrecovery.c:232
static uint32 readLen
Definition: xlogrecovery.c:233