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-2023, 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  * Note: This routine should *never* be called for xl_tot_len until the header
197  * of the record has been fully validated.
198  */
199 static bool
201 {
202  uint32 newSize = reclength;
203 
204  newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
205  newSize = Max(newSize, 5 * Max(BLCKSZ, XLOG_BLCKSZ));
206 
207  if (state->readRecordBuf)
208  pfree(state->readRecordBuf);
209  state->readRecordBuf =
210  (char *) palloc_extended(newSize, MCXT_ALLOC_NO_OOM);
211  if (state->readRecordBuf == NULL)
212  {
213  state->readRecordBufSize = 0;
214  return false;
215  }
216  state->readRecordBufSize = newSize;
217  return true;
218 }
219 
220 /*
221  * Initialize the passed segment structs.
222  */
223 static void
225  int segsize, const char *waldir)
226 {
227  seg->ws_file = -1;
228  seg->ws_segno = 0;
229  seg->ws_tli = 0;
230 
231  segcxt->ws_segsize = segsize;
232  if (waldir)
233  snprintf(segcxt->ws_dir, MAXPGPATH, "%s", waldir);
234 }
235 
236 /*
237  * Begin reading WAL at 'RecPtr'.
238  *
239  * 'RecPtr' should point to the beginning of a valid WAL record. Pointing at
240  * the beginning of a page is also OK, if there is a new record right after
241  * the page header, i.e. not a continuation.
242  *
243  * This does not make any attempt to read the WAL yet, and hence cannot fail.
244  * If the starting address is not correct, the first call to XLogReadRecord()
245  * will error out.
246  */
247 void
249 {
250  Assert(!XLogRecPtrIsInvalid(RecPtr));
251 
253 
254  /* Begin at the passed-in record pointer. */
255  state->EndRecPtr = RecPtr;
256  state->NextRecPtr = RecPtr;
257  state->ReadRecPtr = InvalidXLogRecPtr;
258  state->DecodeRecPtr = InvalidXLogRecPtr;
259 }
260 
261 /*
262  * Release the last record that was returned by XLogNextRecord(), if any, to
263  * free up space. Returns the LSN past the end of the record.
264  */
267 {
268  DecodedXLogRecord *record;
269  XLogRecPtr next_lsn;
270 
271  if (!state->record)
272  return InvalidXLogRecPtr;
273 
274  /*
275  * Remove it from the decoded record queue. It must be the oldest item
276  * decoded, decode_queue_head.
277  */
278  record = state->record;
279  next_lsn = record->next_lsn;
280  Assert(record == state->decode_queue_head);
281  state->record = NULL;
282  state->decode_queue_head = record->next;
283 
284  /* It might also be the newest item decoded, decode_queue_tail. */
285  if (state->decode_queue_tail == record)
286  state->decode_queue_tail = NULL;
287 
288  /* Release the space. */
289  if (unlikely(record->oversized))
290  {
291  /* It's not in the decode buffer, so free it to release space. */
292  pfree(record);
293  }
294  else
295  {
296  /* It must be the head (oldest) record in the decode buffer. */
297  Assert(state->decode_buffer_head == (char *) record);
298 
299  /*
300  * We need to update head to point to the next record that is in the
301  * decode buffer, if any, being careful to skip oversized ones
302  * (they're not in the decode buffer).
303  */
304  record = record->next;
305  while (unlikely(record && record->oversized))
306  record = record->next;
307 
308  if (record)
309  {
310  /* Adjust head to release space up to the next record. */
311  state->decode_buffer_head = (char *) record;
312  }
313  else
314  {
315  /*
316  * Otherwise we might as well just reset head and tail to the
317  * start of the buffer space, because we're empty. This means
318  * we'll keep overwriting the same piece of memory if we're not
319  * doing any prefetching.
320  */
321  state->decode_buffer_head = state->decode_buffer;
322  state->decode_buffer_tail = state->decode_buffer;
323  }
324  }
325 
326  return next_lsn;
327 }
328 
329 /*
330  * Attempt to read an XLOG record.
331  *
332  * XLogBeginRead() or XLogFindNextRecord() and then XLogReadAhead() must be
333  * called before the first call to XLogNextRecord(). This functions returns
334  * records and errors that were put into an internal queue by XLogReadAhead().
335  *
336  * On success, a record is returned.
337  *
338  * The returned record (or *errormsg) points to an internal buffer that's
339  * valid until the next call to XLogNextRecord.
340  */
343 {
344  /* Release the last record returned by XLogNextRecord(). */
346 
347  if (state->decode_queue_head == NULL)
348  {
349  *errormsg = NULL;
350  if (state->errormsg_deferred)
351  {
352  if (state->errormsg_buf[0] != '\0')
353  *errormsg = state->errormsg_buf;
354  state->errormsg_deferred = false;
355  }
356 
357  /*
358  * state->EndRecPtr is expected to have been set by the last call to
359  * XLogBeginRead() or XLogNextRecord(), and is the location of the
360  * error.
361  */
362  Assert(!XLogRecPtrIsInvalid(state->EndRecPtr));
363 
364  return NULL;
365  }
366 
367  /*
368  * Record this as the most recent record returned, so that we'll release
369  * it next time. This also exposes it to the traditional
370  * XLogRecXXX(xlogreader) macros, which work with the decoder rather than
371  * the record for historical reasons.
372  */
373  state->record = state->decode_queue_head;
374 
375  /*
376  * Update the pointers to the beginning and one-past-the-end of this
377  * record, again for the benefit of historical code that expected the
378  * decoder to track this rather than accessing these fields of the record
379  * itself.
380  */
381  state->ReadRecPtr = state->record->lsn;
382  state->EndRecPtr = state->record->next_lsn;
383 
384  *errormsg = NULL;
385 
386  return state->record;
387 }
388 
389 /*
390  * Attempt to read an XLOG record.
391  *
392  * XLogBeginRead() or XLogFindNextRecord() must be called before the first call
393  * to XLogReadRecord().
394  *
395  * If the page_read callback fails to read the requested data, NULL is
396  * returned. The callback is expected to have reported the error; errormsg
397  * is set to NULL.
398  *
399  * If the reading fails for some other reason, NULL is also returned, and
400  * *errormsg is set to a string with details of the failure.
401  *
402  * The returned pointer (or *errormsg) points to an internal buffer that's
403  * valid until the next call to XLogReadRecord.
404  */
405 XLogRecord *
407 {
408  DecodedXLogRecord *decoded;
409 
410  /*
411  * Release last returned record, if there is one. We need to do this so
412  * that we can check for empty decode queue accurately.
413  */
415 
416  /*
417  * Call XLogReadAhead() in blocking mode to make sure there is something
418  * in the queue, though we don't use the result.
419  */
421  XLogReadAhead(state, false /* nonblocking */ );
422 
423  /* Consume the head record or error. */
424  decoded = XLogNextRecord(state, errormsg);
425  if (decoded)
426  {
427  /*
428  * This function returns a pointer to the record's header, not the
429  * actual decoded record. The caller will access the decoded record
430  * through the XLogRecGetXXX() macros, which reach the decoded
431  * recorded as xlogreader->record.
432  */
433  Assert(state->record == decoded);
434  return &decoded->header;
435  }
436 
437  return NULL;
438 }
439 
440 /*
441  * Allocate space for a decoded record. The only member of the returned
442  * object that is initialized is the 'oversized' flag, indicating that the
443  * decoded record wouldn't fit in the decode buffer and must eventually be
444  * freed explicitly.
445  *
446  * The caller is responsible for adjusting decode_buffer_tail with the real
447  * size after successfully decoding a record into this space. This way, if
448  * decoding fails, then there is nothing to undo unless the 'oversized' flag
449  * was set and pfree() must be called.
450  *
451  * Return NULL if there is no space in the decode buffer and allow_oversized
452  * is false, or if memory allocation fails for an oversized buffer.
453  */
454 static DecodedXLogRecord *
455 XLogReadRecordAlloc(XLogReaderState *state, size_t xl_tot_len, bool allow_oversized)
456 {
457  size_t required_space = DecodeXLogRecordRequiredSpace(xl_tot_len);
458  DecodedXLogRecord *decoded = NULL;
459 
460  /* Allocate a circular decode buffer if we don't have one already. */
461  if (unlikely(state->decode_buffer == NULL))
462  {
463  if (state->decode_buffer_size == 0)
464  state->decode_buffer_size = DEFAULT_DECODE_BUFFER_SIZE;
465  state->decode_buffer = palloc(state->decode_buffer_size);
466  state->decode_buffer_head = state->decode_buffer;
467  state->decode_buffer_tail = state->decode_buffer;
468  state->free_decode_buffer = true;
469  }
470 
471  /* Try to allocate space in the circular decode buffer. */
472  if (state->decode_buffer_tail >= state->decode_buffer_head)
473  {
474  /* Empty, or tail is to the right of head. */
475  if (state->decode_buffer_tail + required_space <=
476  state->decode_buffer + state->decode_buffer_size)
477  {
478  /* There is space between tail and end. */
479  decoded = (DecodedXLogRecord *) state->decode_buffer_tail;
480  decoded->oversized = false;
481  return decoded;
482  }
483  else if (state->decode_buffer + required_space <
484  state->decode_buffer_head)
485  {
486  /* There is space between start and head. */
487  decoded = (DecodedXLogRecord *) state->decode_buffer;
488  decoded->oversized = false;
489  return decoded;
490  }
491  }
492  else
493  {
494  /* Tail is to the left of head. */
495  if (state->decode_buffer_tail + required_space <
496  state->decode_buffer_head)
497  {
498  /* There is space between tail and head. */
499  decoded = (DecodedXLogRecord *) state->decode_buffer_tail;
500  decoded->oversized = false;
501  return decoded;
502  }
503  }
504 
505  /* Not enough space in the decode buffer. Are we allowed to allocate? */
506  if (allow_oversized)
507  {
508  decoded = palloc_extended(required_space, MCXT_ALLOC_NO_OOM);
509  if (decoded == NULL)
510  return NULL;
511  decoded->oversized = true;
512  return decoded;
513  }
514 
515  return NULL;
516 }
517 
518 static XLogPageReadResult
520 {
521  XLogRecPtr RecPtr;
522  XLogRecord *record;
523  XLogRecPtr targetPagePtr;
524  bool randAccess;
525  uint32 len,
526  total_len;
527  uint32 targetRecOff;
528  uint32 pageHeaderSize;
529  bool assembled;
530  bool gotheader;
531  int readOff;
532  DecodedXLogRecord *decoded;
533  char *errormsg; /* not used */
534 
535  /*
536  * randAccess indicates whether to verify the previous-record pointer of
537  * the record we're reading. We only do this if we're reading
538  * sequentially, which is what we initially assume.
539  */
540  randAccess = false;
541 
542  /* reset error state */
543  state->errormsg_buf[0] = '\0';
544  decoded = NULL;
545 
546  state->abortedRecPtr = InvalidXLogRecPtr;
547  state->missingContrecPtr = InvalidXLogRecPtr;
548 
549  RecPtr = state->NextRecPtr;
550 
551  if (state->DecodeRecPtr != InvalidXLogRecPtr)
552  {
553  /* read the record after the one we just read */
554 
555  /*
556  * NextRecPtr is pointing to end+1 of the previous WAL record. If
557  * we're at a page boundary, no more records can fit on the current
558  * page. We must skip over the page header, but we can't do that until
559  * we've read in the page, since the header size is variable.
560  */
561  }
562  else
563  {
564  /*
565  * Caller supplied a position to start at.
566  *
567  * In this case, NextRecPtr should already be pointing either to a
568  * valid record starting position or alternatively to the beginning of
569  * a page. See the header comments for XLogBeginRead.
570  */
571  Assert(RecPtr % XLOG_BLCKSZ == 0 || XRecOffIsValid(RecPtr));
572  randAccess = true;
573  }
574 
575 restart:
576  state->nonblocking = nonblocking;
577  state->currRecPtr = RecPtr;
578  assembled = false;
579 
580  targetPagePtr = RecPtr - (RecPtr % XLOG_BLCKSZ);
581  targetRecOff = RecPtr % XLOG_BLCKSZ;
582 
583  /*
584  * Read the page containing the record into state->readBuf. Request enough
585  * byte to cover the whole record header, or at least the part of it that
586  * fits on the same page.
587  */
588  readOff = ReadPageInternal(state, targetPagePtr,
589  Min(targetRecOff + SizeOfXLogRecord, XLOG_BLCKSZ));
590  if (readOff == XLREAD_WOULDBLOCK)
591  return XLREAD_WOULDBLOCK;
592  else if (readOff < 0)
593  goto err;
594 
595  /*
596  * ReadPageInternal always returns at least the page header, so we can
597  * examine it now.
598  */
599  pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
600  if (targetRecOff == 0)
601  {
602  /*
603  * At page start, so skip over page header.
604  */
605  RecPtr += pageHeaderSize;
606  targetRecOff = pageHeaderSize;
607  }
608  else if (targetRecOff < pageHeaderSize)
609  {
610  report_invalid_record(state, "invalid record offset at %X/%X: expected at least %u, got %u",
611  LSN_FORMAT_ARGS(RecPtr),
612  pageHeaderSize, targetRecOff);
613  goto err;
614  }
615 
616  if ((((XLogPageHeader) state->readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
617  targetRecOff == pageHeaderSize)
618  {
619  report_invalid_record(state, "contrecord is requested by %X/%X",
620  LSN_FORMAT_ARGS(RecPtr));
621  goto err;
622  }
623 
624  /* ReadPageInternal has verified the page header */
625  Assert(pageHeaderSize <= readOff);
626 
627  /*
628  * Read the record length.
629  *
630  * NB: Even though we use an XLogRecord pointer here, the whole record
631  * header might not fit on this page. xl_tot_len is the first field of the
632  * struct, so it must be on this page (the records are MAXALIGNed), but we
633  * cannot access any other fields until we've verified that we got the
634  * whole header.
635  */
636  record = (XLogRecord *) (state->readBuf + RecPtr % XLOG_BLCKSZ);
637  total_len = record->xl_tot_len;
638 
639  /*
640  * If the whole record header is on this page, validate it immediately.
641  * Otherwise do just a basic sanity check on xl_tot_len, and validate the
642  * rest of the header after reading it from the next page. The xl_tot_len
643  * check is necessary here to ensure that we enter the "Need to reassemble
644  * record" code path below; otherwise we might fail to apply
645  * ValidXLogRecordHeader at all.
646  */
647  if (targetRecOff <= XLOG_BLCKSZ - SizeOfXLogRecord)
648  {
649  if (!ValidXLogRecordHeader(state, RecPtr, state->DecodeRecPtr, record,
650  randAccess))
651  goto err;
652  gotheader = true;
653  }
654  else
655  {
656  /* There may be no next page if it's too small. */
657  if (total_len < SizeOfXLogRecord)
658  {
660  "invalid record length at %X/%X: expected at least %u, got %u",
661  LSN_FORMAT_ARGS(RecPtr),
662  (uint32) SizeOfXLogRecord, total_len);
663  goto err;
664  }
665  /* We'll validate the header once we have the next page. */
666  gotheader = false;
667  }
668 
669  /*
670  * Try to find space to decode this record, if we can do so without
671  * calling palloc. If we can't, we'll try again below after we've
672  * validated that total_len isn't garbage bytes from a recycled WAL page.
673  */
674  decoded = XLogReadRecordAlloc(state,
675  total_len,
676  false /* allow_oversized */ );
677  if (decoded == NULL && nonblocking)
678  {
679  /*
680  * There is no space in the circular decode buffer, and the caller is
681  * only reading ahead. The caller should consume existing records to
682  * make space.
683  */
684  return XLREAD_WOULDBLOCK;
685  }
686 
687  len = XLOG_BLCKSZ - RecPtr % XLOG_BLCKSZ;
688  if (total_len > len)
689  {
690  /* Need to reassemble record */
691  char *contdata;
692  XLogPageHeader pageHeader;
693  char *buffer;
694  uint32 gotlen;
695 
696  assembled = true;
697 
698  /*
699  * We always have space for a couple of pages, enough to validate a
700  * boundary-spanning record header.
701  */
702  Assert(state->readRecordBufSize >= XLOG_BLCKSZ * 2);
703  Assert(state->readRecordBufSize >= len);
704 
705  /* Copy the first fragment of the record from the first page. */
706  memcpy(state->readRecordBuf,
707  state->readBuf + RecPtr % XLOG_BLCKSZ, len);
708  buffer = state->readRecordBuf + len;
709  gotlen = len;
710 
711  do
712  {
713  /* Calculate pointer to beginning of next page */
714  targetPagePtr += XLOG_BLCKSZ;
715 
716  /* Wait for the next page to become available */
717  readOff = ReadPageInternal(state, targetPagePtr,
718  Min(total_len - gotlen + SizeOfXLogShortPHD,
719  XLOG_BLCKSZ));
720 
721  if (readOff == XLREAD_WOULDBLOCK)
722  return XLREAD_WOULDBLOCK;
723  else if (readOff < 0)
724  goto err;
725 
727 
728  pageHeader = (XLogPageHeader) state->readBuf;
729 
730  /*
731  * If we were expecting a continuation record and got an
732  * "overwrite contrecord" flag, that means the continuation record
733  * was overwritten with a different record. Restart the read by
734  * assuming the address to read is the location where we found
735  * this flag; but keep track of the LSN of the record we were
736  * reading, for later verification.
737  */
739  {
740  state->overwrittenRecPtr = RecPtr;
741  RecPtr = targetPagePtr;
742  goto restart;
743  }
744 
745  /* Check that the continuation on next page looks valid */
746  if (!(pageHeader->xlp_info & XLP_FIRST_IS_CONTRECORD))
747  {
749  "there is no contrecord flag at %X/%X",
750  LSN_FORMAT_ARGS(RecPtr));
751  goto err;
752  }
753 
754  /*
755  * Cross-check that xlp_rem_len agrees with how much of the record
756  * we expect there to be left.
757  */
758  if (pageHeader->xlp_rem_len == 0 ||
759  total_len != (pageHeader->xlp_rem_len + gotlen))
760  {
762  "invalid contrecord length %u (expected %lld) at %X/%X",
763  pageHeader->xlp_rem_len,
764  ((long long) total_len) - gotlen,
765  LSN_FORMAT_ARGS(RecPtr));
766  goto err;
767  }
768 
769  /* Append the continuation from this page to the buffer */
770  pageHeaderSize = XLogPageHeaderSize(pageHeader);
771 
772  if (readOff < pageHeaderSize)
773  readOff = ReadPageInternal(state, targetPagePtr,
774  pageHeaderSize);
775 
776  Assert(pageHeaderSize <= readOff);
777 
778  contdata = (char *) state->readBuf + pageHeaderSize;
779  len = XLOG_BLCKSZ - pageHeaderSize;
780  if (pageHeader->xlp_rem_len < len)
781  len = pageHeader->xlp_rem_len;
782 
783  if (readOff < pageHeaderSize + len)
784  readOff = ReadPageInternal(state, targetPagePtr,
785  pageHeaderSize + len);
786 
787  memcpy(buffer, (char *) contdata, len);
788  buffer += len;
789  gotlen += len;
790 
791  /* If we just reassembled the record header, validate it. */
792  if (!gotheader)
793  {
794  record = (XLogRecord *) state->readRecordBuf;
795  if (!ValidXLogRecordHeader(state, RecPtr, state->DecodeRecPtr,
796  record, randAccess))
797  goto err;
798  gotheader = true;
799  }
800 
801  /*
802  * We might need a bigger buffer. We have validated the record
803  * header, in the case that it split over a page boundary. We've
804  * also cross-checked total_len against xlp_rem_len on the second
805  * page, and verified xlp_pageaddr on both.
806  */
807  if (total_len > state->readRecordBufSize)
808  {
809  char save_copy[XLOG_BLCKSZ * 2];
810 
811  /*
812  * Save and restore the data we already had. It can't be more
813  * than two pages.
814  */
815  Assert(gotlen <= lengthof(save_copy));
816  Assert(gotlen <= state->readRecordBufSize);
817  memcpy(save_copy, state->readRecordBuf, gotlen);
818  if (!allocate_recordbuf(state, total_len))
819  {
820  /* We treat this as a "bogus data" condition */
821  report_invalid_record(state, "record length %u at %X/%X too long",
822  total_len, LSN_FORMAT_ARGS(RecPtr));
823  goto err;
824  }
825  memcpy(state->readRecordBuf, save_copy, gotlen);
826  buffer = state->readRecordBuf + gotlen;
827  }
828  } while (gotlen < total_len);
829  Assert(gotheader);
830 
831  record = (XLogRecord *) state->readRecordBuf;
832  if (!ValidXLogRecord(state, record, RecPtr))
833  goto err;
834 
835  pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
836  state->DecodeRecPtr = RecPtr;
837  state->NextRecPtr = targetPagePtr + pageHeaderSize
838  + MAXALIGN(pageHeader->xlp_rem_len);
839  }
840  else
841  {
842  /* Wait for the record data to become available */
843  readOff = ReadPageInternal(state, targetPagePtr,
844  Min(targetRecOff + total_len, XLOG_BLCKSZ));
845  if (readOff == XLREAD_WOULDBLOCK)
846  return XLREAD_WOULDBLOCK;
847  else if (readOff < 0)
848  goto err;
849 
850  /* Record does not cross a page boundary */
851  if (!ValidXLogRecord(state, record, RecPtr))
852  goto err;
853 
854  state->NextRecPtr = RecPtr + MAXALIGN(total_len);
855 
856  state->DecodeRecPtr = RecPtr;
857  }
858 
859  /*
860  * Special processing if it's an XLOG SWITCH record
861  */
862  if (record->xl_rmid == RM_XLOG_ID &&
863  (record->xl_info & ~XLR_INFO_MASK) == XLOG_SWITCH)
864  {
865  /* Pretend it extends to end of segment */
866  state->NextRecPtr += state->segcxt.ws_segsize - 1;
867  state->NextRecPtr -= XLogSegmentOffset(state->NextRecPtr, state->segcxt.ws_segsize);
868  }
869 
870  /*
871  * If we got here without a DecodedXLogRecord, it means we needed to
872  * validate total_len before trusting it, but by now now we've done that.
873  */
874  if (decoded == NULL)
875  {
876  Assert(!nonblocking);
877  decoded = XLogReadRecordAlloc(state,
878  total_len,
879  true /* allow_oversized */ );
880  if (decoded == NULL)
881  {
882  /*
883  * We failed to allocate memory for an oversized record. As
884  * above, we currently treat this as a "bogus data" condition.
885  */
887  "out of memory while trying to decode a record of length %u", total_len);
888  goto err;
889  }
890  }
891 
892  if (DecodeXLogRecord(state, decoded, record, RecPtr, &errormsg))
893  {
894  /* Record the location of the next record. */
895  decoded->next_lsn = state->NextRecPtr;
896 
897  /*
898  * If it's in the decode buffer, mark the decode buffer space as
899  * occupied.
900  */
901  if (!decoded->oversized)
902  {
903  /* The new decode buffer head must be MAXALIGNed. */
904  Assert(decoded->size == MAXALIGN(decoded->size));
905  if ((char *) decoded == state->decode_buffer)
906  state->decode_buffer_tail = state->decode_buffer + decoded->size;
907  else
908  state->decode_buffer_tail += decoded->size;
909  }
910 
911  /* Insert it into the queue of decoded records. */
912  Assert(state->decode_queue_tail != decoded);
913  if (state->decode_queue_tail)
914  state->decode_queue_tail->next = decoded;
915  state->decode_queue_tail = decoded;
916  if (!state->decode_queue_head)
917  state->decode_queue_head = decoded;
918  return XLREAD_SUCCESS;
919  }
920 
921 err:
922  if (assembled)
923  {
924  /*
925  * We get here when a record that spans multiple pages needs to be
926  * assembled, but something went wrong -- perhaps a contrecord piece
927  * was lost. If caller is WAL replay, it will know where the aborted
928  * record was and where to direct followup WAL to be written, marking
929  * the next piece with XLP_FIRST_IS_OVERWRITE_CONTRECORD, which will
930  * in turn signal downstream WAL consumers that the broken WAL record
931  * is to be ignored.
932  */
933  state->abortedRecPtr = RecPtr;
934  state->missingContrecPtr = targetPagePtr;
935 
936  /*
937  * If we got here without reporting an error, make sure an error is
938  * queued so that XLogPrefetcherReadRecord() doesn't bring us back a
939  * second time and clobber the above state.
940  */
941  state->errormsg_deferred = true;
942  }
943 
944  if (decoded && decoded->oversized)
945  pfree(decoded);
946 
947  /*
948  * Invalidate the read state. We might read from a different source after
949  * failure.
950  */
952 
953  /*
954  * If an error was written to errmsg_buf, it'll be returned to the caller
955  * of XLogReadRecord() after all successfully decoded records from the
956  * read queue.
957  */
958 
959  return XLREAD_FAIL;
960 }
961 
962 /*
963  * Try to decode the next available record, and return it. The record will
964  * also be returned to XLogNextRecord(), which must be called to 'consume'
965  * each record.
966  *
967  * If nonblocking is true, may return NULL due to lack of data or WAL decoding
968  * space.
969  */
972 {
973  XLogPageReadResult result;
974 
975  if (state->errormsg_deferred)
976  return NULL;
977 
978  result = XLogDecodeNextRecord(state, nonblocking);
979  if (result == XLREAD_SUCCESS)
980  {
981  Assert(state->decode_queue_tail != NULL);
982  return state->decode_queue_tail;
983  }
984 
985  return NULL;
986 }
987 
988 /*
989  * Read a single xlog page including at least [pageptr, reqLen] of valid data
990  * via the page_read() callback.
991  *
992  * Returns XLREAD_FAIL if the required page cannot be read for some
993  * reason; errormsg_buf is set in that case (unless the error occurs in the
994  * page_read callback).
995  *
996  * Returns XLREAD_WOULDBLOCK if the requested data can't be read without
997  * waiting. This can be returned only if the installed page_read callback
998  * respects the state->nonblocking flag, and cannot read the requested data
999  * immediately.
1000  *
1001  * We fetch the page from a reader-local cache if we know we have the required
1002  * data and if there hasn't been any error since caching the data.
1003  */
1004 static int
1006 {
1007  int readLen;
1008  uint32 targetPageOff;
1009  XLogSegNo targetSegNo;
1010  XLogPageHeader hdr;
1011 
1012  Assert((pageptr % XLOG_BLCKSZ) == 0);
1013 
1014  XLByteToSeg(pageptr, targetSegNo, state->segcxt.ws_segsize);
1015  targetPageOff = XLogSegmentOffset(pageptr, state->segcxt.ws_segsize);
1016 
1017  /* check whether we have all the requested data already */
1018  if (targetSegNo == state->seg.ws_segno &&
1019  targetPageOff == state->segoff && reqLen <= state->readLen)
1020  return state->readLen;
1021 
1022  /*
1023  * Invalidate contents of internal buffer before read attempt. Just set
1024  * the length to 0, rather than a full XLogReaderInvalReadState(), so we
1025  * don't forget the segment we last successfully read.
1026  */
1027  state->readLen = 0;
1028 
1029  /*
1030  * Data is not in our buffer.
1031  *
1032  * Every time we actually read the segment, even if we looked at parts of
1033  * it before, we need to do verification as the page_read callback might
1034  * now be rereading data from a different source.
1035  *
1036  * Whenever switching to a new WAL segment, we read the first page of the
1037  * file and validate its header, even if that's not where the target
1038  * record is. This is so that we can check the additional identification
1039  * info that is present in the first page's "long" header.
1040  */
1041  if (targetSegNo != state->seg.ws_segno && targetPageOff != 0)
1042  {
1043  XLogRecPtr targetSegmentPtr = pageptr - targetPageOff;
1044 
1045  readLen = state->routine.page_read(state, targetSegmentPtr, XLOG_BLCKSZ,
1046  state->currRecPtr,
1047  state->readBuf);
1048  if (readLen == XLREAD_WOULDBLOCK)
1049  return XLREAD_WOULDBLOCK;
1050  else if (readLen < 0)
1051  goto err;
1052 
1053  /* we can be sure to have enough WAL available, we scrolled back */
1054  Assert(readLen == XLOG_BLCKSZ);
1055 
1056  if (!XLogReaderValidatePageHeader(state, targetSegmentPtr,
1057  state->readBuf))
1058  goto err;
1059  }
1060 
1061  /*
1062  * First, read the requested data length, but at least a short page header
1063  * so that we can validate it.
1064  */
1065  readLen = state->routine.page_read(state, pageptr, Max(reqLen, SizeOfXLogShortPHD),
1066  state->currRecPtr,
1067  state->readBuf);
1068  if (readLen == XLREAD_WOULDBLOCK)
1069  return XLREAD_WOULDBLOCK;
1070  else if (readLen < 0)
1071  goto err;
1072 
1073  Assert(readLen <= XLOG_BLCKSZ);
1074 
1075  /* Do we have enough data to check the header length? */
1076  if (readLen <= SizeOfXLogShortPHD)
1077  goto err;
1078 
1079  Assert(readLen >= reqLen);
1080 
1081  hdr = (XLogPageHeader) state->readBuf;
1082 
1083  /* still not enough */
1084  if (readLen < XLogPageHeaderSize(hdr))
1085  {
1086  readLen = state->routine.page_read(state, pageptr, XLogPageHeaderSize(hdr),
1087  state->currRecPtr,
1088  state->readBuf);
1089  if (readLen == XLREAD_WOULDBLOCK)
1090  return XLREAD_WOULDBLOCK;
1091  else if (readLen < 0)
1092  goto err;
1093  }
1094 
1095  /*
1096  * Now that we know we have the full header, validate it.
1097  */
1098  if (!XLogReaderValidatePageHeader(state, pageptr, (char *) hdr))
1099  goto err;
1100 
1101  /* update read state information */
1102  state->seg.ws_segno = targetSegNo;
1103  state->segoff = targetPageOff;
1104  state->readLen = readLen;
1105 
1106  return readLen;
1107 
1108 err:
1110 
1111  return XLREAD_FAIL;
1112 }
1113 
1114 /*
1115  * Invalidate the xlogreader's read state to force a re-read.
1116  */
1117 static void
1119 {
1120  state->seg.ws_segno = 0;
1121  state->segoff = 0;
1122  state->readLen = 0;
1123 }
1124 
1125 /*
1126  * Validate an XLOG record header.
1127  *
1128  * This is just a convenience subroutine to avoid duplicated code in
1129  * XLogReadRecord. It's not intended for use from anywhere else.
1130  */
1131 static bool
1133  XLogRecPtr PrevRecPtr, XLogRecord *record,
1134  bool randAccess)
1135 {
1136  if (record->xl_tot_len < SizeOfXLogRecord)
1137  {
1139  "invalid record length at %X/%X: expected at least %u, got %u",
1140  LSN_FORMAT_ARGS(RecPtr),
1141  (uint32) SizeOfXLogRecord, record->xl_tot_len);
1142  return false;
1143  }
1144  if (!RmgrIdIsValid(record->xl_rmid))
1145  {
1147  "invalid resource manager ID %u at %X/%X",
1148  record->xl_rmid, LSN_FORMAT_ARGS(RecPtr));
1149  return false;
1150  }
1151  if (randAccess)
1152  {
1153  /*
1154  * We can't exactly verify the prev-link, but surely it should be less
1155  * than the record's own address.
1156  */
1157  if (!(record->xl_prev < RecPtr))
1158  {
1160  "record with incorrect prev-link %X/%X at %X/%X",
1161  LSN_FORMAT_ARGS(record->xl_prev),
1162  LSN_FORMAT_ARGS(RecPtr));
1163  return false;
1164  }
1165  }
1166  else
1167  {
1168  /*
1169  * Record's prev-link should exactly match our previous location. This
1170  * check guards against torn WAL pages where a stale but valid-looking
1171  * WAL record starts on a sector boundary.
1172  */
1173  if (record->xl_prev != PrevRecPtr)
1174  {
1176  "record with incorrect prev-link %X/%X at %X/%X",
1177  LSN_FORMAT_ARGS(record->xl_prev),
1178  LSN_FORMAT_ARGS(RecPtr));
1179  return false;
1180  }
1181  }
1182 
1183  return true;
1184 }
1185 
1186 
1187 /*
1188  * CRC-check an XLOG record. We do not believe the contents of an XLOG
1189  * record (other than to the minimal extent of computing the amount of
1190  * data to read in) until we've checked the CRCs.
1191  *
1192  * We assume all of the record (that is, xl_tot_len bytes) has been read
1193  * into memory at *record. Also, ValidXLogRecordHeader() has accepted the
1194  * record's header, which means in particular that xl_tot_len is at least
1195  * SizeOfXLogRecord.
1196  */
1197 static bool
1199 {
1200  pg_crc32c crc;
1201 
1202  Assert(record->xl_tot_len >= SizeOfXLogRecord);
1203 
1204  /* Calculate the CRC */
1205  INIT_CRC32C(crc);
1206  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
1207  /* include the record header last */
1208  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
1209  FIN_CRC32C(crc);
1210 
1211  if (!EQ_CRC32C(record->xl_crc, crc))
1212  {
1214  "incorrect resource manager data checksum in record at %X/%X",
1215  LSN_FORMAT_ARGS(recptr));
1216  return false;
1217  }
1218 
1219  return true;
1220 }
1221 
1222 /*
1223  * Validate a page header.
1224  *
1225  * Check if 'phdr' is valid as the header of the XLog page at position
1226  * 'recptr'.
1227  */
1228 bool
1230  char *phdr)
1231 {
1232  XLogSegNo segno;
1233  int32 offset;
1234  XLogPageHeader hdr = (XLogPageHeader) phdr;
1235 
1236  Assert((recptr % XLOG_BLCKSZ) == 0);
1237 
1238  XLByteToSeg(recptr, segno, state->segcxt.ws_segsize);
1239  offset = XLogSegmentOffset(recptr, state->segcxt.ws_segsize);
1240 
1241  if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
1242  {
1243  char fname[MAXFNAMELEN];
1244 
1245  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1246 
1248  "invalid magic number %04X in WAL segment %s, LSN %X/%X, offset %u",
1249  hdr->xlp_magic,
1250  fname,
1251  LSN_FORMAT_ARGS(recptr),
1252  offset);
1253  return false;
1254  }
1255 
1256  if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
1257  {
1258  char fname[MAXFNAMELEN];
1259 
1260  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1261 
1263  "invalid info bits %04X in WAL segment %s, LSN %X/%X, offset %u",
1264  hdr->xlp_info,
1265  fname,
1266  LSN_FORMAT_ARGS(recptr),
1267  offset);
1268  return false;
1269  }
1270 
1271  if (hdr->xlp_info & XLP_LONG_HEADER)
1272  {
1273  XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
1274 
1275  if (state->system_identifier &&
1276  longhdr->xlp_sysid != state->system_identifier)
1277  {
1279  "WAL file is from different database system: WAL file database system identifier is %llu, pg_control database system identifier is %llu",
1280  (unsigned long long) longhdr->xlp_sysid,
1281  (unsigned long long) state->system_identifier);
1282  return false;
1283  }
1284  else if (longhdr->xlp_seg_size != state->segcxt.ws_segsize)
1285  {
1287  "WAL file is from different database system: incorrect segment size in page header");
1288  return false;
1289  }
1290  else if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
1291  {
1293  "WAL file is from different database system: incorrect XLOG_BLCKSZ in page header");
1294  return false;
1295  }
1296  }
1297  else if (offset == 0)
1298  {
1299  char fname[MAXFNAMELEN];
1300 
1301  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1302 
1303  /* hmm, first page of file doesn't have a long header? */
1305  "invalid info bits %04X in WAL segment %s, LSN %X/%X, offset %u",
1306  hdr->xlp_info,
1307  fname,
1308  LSN_FORMAT_ARGS(recptr),
1309  offset);
1310  return false;
1311  }
1312 
1313  /*
1314  * Check that the address on the page agrees with what we expected. This
1315  * check typically fails when an old WAL segment is recycled, and hasn't
1316  * yet been overwritten with new data yet.
1317  */
1318  if (hdr->xlp_pageaddr != recptr)
1319  {
1320  char fname[MAXFNAMELEN];
1321 
1322  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1323 
1325  "unexpected pageaddr %X/%X in WAL segment %s, LSN %X/%X, offset %u",
1327  fname,
1328  LSN_FORMAT_ARGS(recptr),
1329  offset);
1330  return false;
1331  }
1332 
1333  /*
1334  * Since child timelines are always assigned a TLI greater than their
1335  * immediate parent's TLI, we should never see TLI go backwards across
1336  * successive pages of a consistent WAL sequence.
1337  *
1338  * Sometimes we re-read a segment that's already been (partially) read. So
1339  * we only verify TLIs for pages that are later than the last remembered
1340  * LSN.
1341  */
1342  if (recptr > state->latestPagePtr)
1343  {
1344  if (hdr->xlp_tli < state->latestPageTLI)
1345  {
1346  char fname[MAXFNAMELEN];
1347 
1348  XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
1349 
1351  "out-of-sequence timeline ID %u (after %u) in WAL segment %s, LSN %X/%X, offset %u",
1352  hdr->xlp_tli,
1353  state->latestPageTLI,
1354  fname,
1355  LSN_FORMAT_ARGS(recptr),
1356  offset);
1357  return false;
1358  }
1359  }
1360  state->latestPagePtr = recptr;
1361  state->latestPageTLI = hdr->xlp_tli;
1362 
1363  return true;
1364 }
1365 
1366 /*
1367  * Forget about an error produced by XLogReaderValidatePageHeader().
1368  */
1369 void
1371 {
1372  state->errormsg_buf[0] = '\0';
1373  state->errormsg_deferred = false;
1374 }
1375 
1376 /*
1377  * Find the first record with an lsn >= RecPtr.
1378  *
1379  * This is different from XLogBeginRead() in that RecPtr doesn't need to point
1380  * to a valid record boundary. Useful for checking whether RecPtr is a valid
1381  * xlog address for reading, and to find the first valid address after some
1382  * address when dumping records for debugging purposes.
1383  *
1384  * This positions the reader, like XLogBeginRead(), so that the next call to
1385  * XLogReadRecord() will read the next valid record.
1386  */
1387 XLogRecPtr
1389 {
1390  XLogRecPtr tmpRecPtr;
1391  XLogRecPtr found = InvalidXLogRecPtr;
1392  XLogPageHeader header;
1393  char *errormsg;
1394 
1395  Assert(!XLogRecPtrIsInvalid(RecPtr));
1396 
1397  /* Make sure ReadPageInternal() can't return XLREAD_WOULDBLOCK. */
1398  state->nonblocking = false;
1399 
1400  /*
1401  * skip over potential continuation data, keeping in mind that it may span
1402  * multiple pages
1403  */
1404  tmpRecPtr = RecPtr;
1405  while (true)
1406  {
1407  XLogRecPtr targetPagePtr;
1408  int targetRecOff;
1409  uint32 pageHeaderSize;
1410  int readLen;
1411 
1412  /*
1413  * Compute targetRecOff. It should typically be equal or greater than
1414  * short page-header since a valid record can't start anywhere before
1415  * that, except when caller has explicitly specified the offset that
1416  * falls somewhere there or when we are skipping multi-page
1417  * continuation record. It doesn't matter though because
1418  * ReadPageInternal() is prepared to handle that and will read at
1419  * least short page-header worth of data
1420  */
1421  targetRecOff = tmpRecPtr % XLOG_BLCKSZ;
1422 
1423  /* scroll back to page boundary */
1424  targetPagePtr = tmpRecPtr - targetRecOff;
1425 
1426  /* Read the page containing the record */
1427  readLen = ReadPageInternal(state, targetPagePtr, targetRecOff);
1428  if (readLen < 0)
1429  goto err;
1430 
1431  header = (XLogPageHeader) state->readBuf;
1432 
1433  pageHeaderSize = XLogPageHeaderSize(header);
1434 
1435  /* make sure we have enough data for the page header */
1436  readLen = ReadPageInternal(state, targetPagePtr, pageHeaderSize);
1437  if (readLen < 0)
1438  goto err;
1439 
1440  /* skip over potential continuation data */
1441  if (header->xlp_info & XLP_FIRST_IS_CONTRECORD)
1442  {
1443  /*
1444  * If the length of the remaining continuation data is more than
1445  * what can fit in this page, the continuation record crosses over
1446  * this page. Read the next page and try again. xlp_rem_len in the
1447  * next page header will contain the remaining length of the
1448  * continuation data
1449  *
1450  * Note that record headers are MAXALIGN'ed
1451  */
1452  if (MAXALIGN(header->xlp_rem_len) >= (XLOG_BLCKSZ - pageHeaderSize))
1453  tmpRecPtr = targetPagePtr + XLOG_BLCKSZ;
1454  else
1455  {
1456  /*
1457  * The previous continuation record ends in this page. Set
1458  * tmpRecPtr to point to the first valid record
1459  */
1460  tmpRecPtr = targetPagePtr + pageHeaderSize
1461  + MAXALIGN(header->xlp_rem_len);
1462  break;
1463  }
1464  }
1465  else
1466  {
1467  tmpRecPtr = targetPagePtr + pageHeaderSize;
1468  break;
1469  }
1470  }
1471 
1472  /*
1473  * we know now that tmpRecPtr is an address pointing to a valid XLogRecord
1474  * because either we're at the first record after the beginning of a page
1475  * or we just jumped over the remaining data of a continuation.
1476  */
1477  XLogBeginRead(state, tmpRecPtr);
1478  while (XLogReadRecord(state, &errormsg) != NULL)
1479  {
1480  /* past the record we've found, break out */
1481  if (RecPtr <= state->ReadRecPtr)
1482  {
1483  /* Rewind the reader to the beginning of the last record. */
1484  found = state->ReadRecPtr;
1485  XLogBeginRead(state, found);
1486  return found;
1487  }
1488  }
1489 
1490 err:
1492 
1493  return InvalidXLogRecPtr;
1494 }
1495 
1496 /*
1497  * Helper function to ease writing of XLogReaderRoutine->page_read callbacks.
1498  * If this function is used, caller must supply a segment_open callback in
1499  * 'state', as that is used here.
1500  *
1501  * Read 'count' bytes into 'buf', starting at location 'startptr', from WAL
1502  * fetched from timeline 'tli'.
1503  *
1504  * Returns true if succeeded, false if an error occurs, in which case
1505  * 'errinfo' receives error details.
1506  *
1507  * XXX probably this should be improved to suck data directly from the
1508  * WAL buffers when possible.
1509  */
1510 bool
1512  char *buf, XLogRecPtr startptr, Size count, TimeLineID tli,
1513  WALReadError *errinfo)
1514 {
1515  char *p;
1516  XLogRecPtr recptr;
1517  Size nbytes;
1518 
1519  p = buf;
1520  recptr = startptr;
1521  nbytes = count;
1522 
1523  while (nbytes > 0)
1524  {
1525  uint32 startoff;
1526  int segbytes;
1527  int readbytes;
1528 
1529  startoff = XLogSegmentOffset(recptr, state->segcxt.ws_segsize);
1530 
1531  /*
1532  * If the data we want is not in a segment we have open, close what we
1533  * have (if anything) and open the next one, using the caller's
1534  * provided segment_open callback.
1535  */
1536  if (state->seg.ws_file < 0 ||
1537  !XLByteInSeg(recptr, state->seg.ws_segno, state->segcxt.ws_segsize) ||
1538  tli != state->seg.ws_tli)
1539  {
1540  XLogSegNo nextSegNo;
1541 
1542  if (state->seg.ws_file >= 0)
1543  state->routine.segment_close(state);
1544 
1545  XLByteToSeg(recptr, nextSegNo, state->segcxt.ws_segsize);
1546  state->routine.segment_open(state, nextSegNo, &tli);
1547 
1548  /* This shouldn't happen -- indicates a bug in segment_open */
1549  Assert(state->seg.ws_file >= 0);
1550 
1551  /* Update the current segment info. */
1552  state->seg.ws_tli = tli;
1553  state->seg.ws_segno = nextSegNo;
1554  }
1555 
1556  /* How many bytes are within this segment? */
1557  if (nbytes > (state->segcxt.ws_segsize - startoff))
1558  segbytes = state->segcxt.ws_segsize - startoff;
1559  else
1560  segbytes = nbytes;
1561 
1562 #ifndef FRONTEND
1563  pgstat_report_wait_start(WAIT_EVENT_WAL_READ);
1564 #endif
1565 
1566  /* Reset errno first; eases reporting non-errno-affecting errors */
1567  errno = 0;
1568  readbytes = pg_pread(state->seg.ws_file, p, segbytes, (off_t) startoff);
1569 
1570 #ifndef FRONTEND
1572 #endif
1573 
1574  if (readbytes <= 0)
1575  {
1576  errinfo->wre_errno = errno;
1577  errinfo->wre_req = segbytes;
1578  errinfo->wre_read = readbytes;
1579  errinfo->wre_off = startoff;
1580  errinfo->wre_seg = state->seg;
1581  return false;
1582  }
1583 
1584  /* Update state for read */
1585  recptr += readbytes;
1586  nbytes -= readbytes;
1587  p += readbytes;
1588  }
1589 
1590  return true;
1591 }
1592 
1593 /* ----------------------------------------
1594  * Functions for decoding the data and block references in a record.
1595  * ----------------------------------------
1596  */
1597 
1598 /*
1599  * Private function to reset the state, forgetting all decoded records, if we
1600  * are asked to move to a new read position.
1601  */
1602 static void
1604 {
1605  DecodedXLogRecord *r;
1606 
1607  /* Reset the decoded record queue, freeing any oversized records. */
1608  while ((r = state->decode_queue_head) != NULL)
1609  {
1610  state->decode_queue_head = r->next;
1611  if (r->oversized)
1612  pfree(r);
1613  }
1614  state->decode_queue_tail = NULL;
1615  state->decode_queue_head = NULL;
1616  state->record = NULL;
1617 
1618  /* Reset the decode buffer to empty. */
1619  state->decode_buffer_tail = state->decode_buffer;
1620  state->decode_buffer_head = state->decode_buffer;
1621 
1622  /* Clear error state. */
1623  state->errormsg_buf[0] = '\0';
1624  state->errormsg_deferred = false;
1625 }
1626 
1627 /*
1628  * Compute the maximum possible amount of padding that could be required to
1629  * decode a record, given xl_tot_len from the record's header. This is the
1630  * amount of output buffer space that we need to decode a record, though we
1631  * might not finish up using it all.
1632  *
1633  * This computation is pessimistic and assumes the maximum possible number of
1634  * blocks, due to lack of better information.
1635  */
1636 size_t
1638 {
1639  size_t size = 0;
1640 
1641  /* Account for the fixed size part of the decoded record struct. */
1642  size += offsetof(DecodedXLogRecord, blocks[0]);
1643  /* Account for the flexible blocks array of maximum possible size. */
1644  size += sizeof(DecodedBkpBlock) * (XLR_MAX_BLOCK_ID + 1);
1645  /* Account for all the raw main and block data. */
1646  size += xl_tot_len;
1647  /* We might insert padding before main_data. */
1648  size += (MAXIMUM_ALIGNOF - 1);
1649  /* We might insert padding before each block's data. */
1650  size += (MAXIMUM_ALIGNOF - 1) * (XLR_MAX_BLOCK_ID + 1);
1651  /* We might insert padding at the end. */
1652  size += (MAXIMUM_ALIGNOF - 1);
1653 
1654  return size;
1655 }
1656 
1657 /*
1658  * Decode a record. "decoded" must point to a MAXALIGNed memory area that has
1659  * space for at least DecodeXLogRecordRequiredSpace(record) bytes. On
1660  * success, decoded->size contains the actual space occupied by the decoded
1661  * record, which may turn out to be less.
1662  *
1663  * Only decoded->oversized member must be initialized already, and will not be
1664  * modified. Other members will be initialized as required.
1665  *
1666  * On error, a human-readable error message is returned in *errormsg, and
1667  * the return value is false.
1668  */
1669 bool
1671  DecodedXLogRecord *decoded,
1672  XLogRecord *record,
1673  XLogRecPtr lsn,
1674  char **errormsg)
1675 {
1676  /*
1677  * read next _size bytes from record buffer, but check for overrun first.
1678  */
1679 #define COPY_HEADER_FIELD(_dst, _size) \
1680  do { \
1681  if (remaining < _size) \
1682  goto shortdata_err; \
1683  memcpy(_dst, ptr, _size); \
1684  ptr += _size; \
1685  remaining -= _size; \
1686  } while(0)
1687 
1688  char *ptr;
1689  char *out;
1690  uint32 remaining;
1691  uint32 datatotal;
1692  RelFileLocator *rlocator = NULL;
1693  uint8 block_id;
1694 
1695  decoded->header = *record;
1696  decoded->lsn = lsn;
1697  decoded->next = NULL;
1698  decoded->record_origin = InvalidRepOriginId;
1700  decoded->main_data = NULL;
1701  decoded->main_data_len = 0;
1702  decoded->max_block_id = -1;
1703  ptr = (char *) record;
1704  ptr += SizeOfXLogRecord;
1706 
1707  /* Decode the headers */
1708  datatotal = 0;
1709  while (remaining > datatotal)
1710  {
1711  COPY_HEADER_FIELD(&block_id, sizeof(uint8));
1712 
1713  if (block_id == XLR_BLOCK_ID_DATA_SHORT)
1714  {
1715  /* XLogRecordDataHeaderShort */
1716  uint8 main_data_len;
1717 
1718  COPY_HEADER_FIELD(&main_data_len, sizeof(uint8));
1719 
1720  decoded->main_data_len = main_data_len;
1721  datatotal += main_data_len;
1722  break; /* by convention, the main data fragment is
1723  * always last */
1724  }
1725  else if (block_id == XLR_BLOCK_ID_DATA_LONG)
1726  {
1727  /* XLogRecordDataHeaderLong */
1728  uint32 main_data_len;
1729 
1730  COPY_HEADER_FIELD(&main_data_len, sizeof(uint32));
1731  decoded->main_data_len = main_data_len;
1732  datatotal += main_data_len;
1733  break; /* by convention, the main data fragment is
1734  * always last */
1735  }
1736  else if (block_id == XLR_BLOCK_ID_ORIGIN)
1737  {
1738  COPY_HEADER_FIELD(&decoded->record_origin, sizeof(RepOriginId));
1739  }
1740  else if (block_id == XLR_BLOCK_ID_TOPLEVEL_XID)
1741  {
1742  COPY_HEADER_FIELD(&decoded->toplevel_xid, sizeof(TransactionId));
1743  }
1744  else if (block_id <= XLR_MAX_BLOCK_ID)
1745  {
1746  /* XLogRecordBlockHeader */
1747  DecodedBkpBlock *blk;
1748  uint8 fork_flags;
1749 
1750  /* mark any intervening block IDs as not in use */
1751  for (int i = decoded->max_block_id + 1; i < block_id; ++i)
1752  decoded->blocks[i].in_use = false;
1753 
1754  if (block_id <= decoded->max_block_id)
1755  {
1757  "out-of-order block_id %u at %X/%X",
1758  block_id,
1759  LSN_FORMAT_ARGS(state->ReadRecPtr));
1760  goto err;
1761  }
1762  decoded->max_block_id = block_id;
1763 
1764  blk = &decoded->blocks[block_id];
1765  blk->in_use = true;
1766  blk->apply_image = false;
1767 
1768  COPY_HEADER_FIELD(&fork_flags, sizeof(uint8));
1769  blk->forknum = fork_flags & BKPBLOCK_FORK_MASK;
1770  blk->flags = fork_flags;
1771  blk->has_image = ((fork_flags & BKPBLOCK_HAS_IMAGE) != 0);
1772  blk->has_data = ((fork_flags & BKPBLOCK_HAS_DATA) != 0);
1773 
1775 
1776  COPY_HEADER_FIELD(&blk->data_len, sizeof(uint16));
1777  /* cross-check that the HAS_DATA flag is set iff data_length > 0 */
1778  if (blk->has_data && blk->data_len == 0)
1779  {
1781  "BKPBLOCK_HAS_DATA set, but no data included at %X/%X",
1782  LSN_FORMAT_ARGS(state->ReadRecPtr));
1783  goto err;
1784  }
1785  if (!blk->has_data && blk->data_len != 0)
1786  {
1788  "BKPBLOCK_HAS_DATA not set, but data length is %u at %X/%X",
1789  (unsigned int) blk->data_len,
1790  LSN_FORMAT_ARGS(state->ReadRecPtr));
1791  goto err;
1792  }
1793  datatotal += blk->data_len;
1794 
1795  if (blk->has_image)
1796  {
1797  COPY_HEADER_FIELD(&blk->bimg_len, sizeof(uint16));
1798  COPY_HEADER_FIELD(&blk->hole_offset, sizeof(uint16));
1799  COPY_HEADER_FIELD(&blk->bimg_info, sizeof(uint8));
1800 
1801  blk->apply_image = ((blk->bimg_info & BKPIMAGE_APPLY) != 0);
1802 
1803  if (BKPIMAGE_COMPRESSED(blk->bimg_info))
1804  {
1805  if (blk->bimg_info & BKPIMAGE_HAS_HOLE)
1806  COPY_HEADER_FIELD(&blk->hole_length, sizeof(uint16));
1807  else
1808  blk->hole_length = 0;
1809  }
1810  else
1811  blk->hole_length = BLCKSZ - blk->bimg_len;
1812  datatotal += blk->bimg_len;
1813 
1814  /*
1815  * cross-check that hole_offset > 0, hole_length > 0 and
1816  * bimg_len < BLCKSZ if the HAS_HOLE flag is set.
1817  */
1818  if ((blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1819  (blk->hole_offset == 0 ||
1820  blk->hole_length == 0 ||
1821  blk->bimg_len == BLCKSZ))
1822  {
1824  "BKPIMAGE_HAS_HOLE set, but hole offset %u length %u block image length %u at %X/%X",
1825  (unsigned int) blk->hole_offset,
1826  (unsigned int) blk->hole_length,
1827  (unsigned int) blk->bimg_len,
1828  LSN_FORMAT_ARGS(state->ReadRecPtr));
1829  goto err;
1830  }
1831 
1832  /*
1833  * cross-check that hole_offset == 0 and hole_length == 0 if
1834  * the HAS_HOLE flag is not set.
1835  */
1836  if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1837  (blk->hole_offset != 0 || blk->hole_length != 0))
1838  {
1840  "BKPIMAGE_HAS_HOLE not set, but hole offset %u length %u at %X/%X",
1841  (unsigned int) blk->hole_offset,
1842  (unsigned int) blk->hole_length,
1843  LSN_FORMAT_ARGS(state->ReadRecPtr));
1844  goto err;
1845  }
1846 
1847  /*
1848  * Cross-check that bimg_len < BLCKSZ if it is compressed.
1849  */
1850  if (BKPIMAGE_COMPRESSED(blk->bimg_info) &&
1851  blk->bimg_len == BLCKSZ)
1852  {
1854  "BKPIMAGE_COMPRESSED set, but block image length %u at %X/%X",
1855  (unsigned int) blk->bimg_len,
1856  LSN_FORMAT_ARGS(state->ReadRecPtr));
1857  goto err;
1858  }
1859 
1860  /*
1861  * cross-check that bimg_len = BLCKSZ if neither HAS_HOLE is
1862  * set nor COMPRESSED().
1863  */
1864  if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
1865  !BKPIMAGE_COMPRESSED(blk->bimg_info) &&
1866  blk->bimg_len != BLCKSZ)
1867  {
1869  "neither BKPIMAGE_HAS_HOLE nor BKPIMAGE_COMPRESSED set, but block image length is %u at %X/%X",
1870  (unsigned int) blk->data_len,
1871  LSN_FORMAT_ARGS(state->ReadRecPtr));
1872  goto err;
1873  }
1874  }
1875  if (!(fork_flags & BKPBLOCK_SAME_REL))
1876  {
1877  COPY_HEADER_FIELD(&blk->rlocator, sizeof(RelFileLocator));
1878  rlocator = &blk->rlocator;
1879  }
1880  else
1881  {
1882  if (rlocator == NULL)
1883  {
1885  "BKPBLOCK_SAME_REL set but no previous rel at %X/%X",
1886  LSN_FORMAT_ARGS(state->ReadRecPtr));
1887  goto err;
1888  }
1889 
1890  blk->rlocator = *rlocator;
1891  }
1892  COPY_HEADER_FIELD(&blk->blkno, sizeof(BlockNumber));
1893  }
1894  else
1895  {
1897  "invalid block_id %u at %X/%X",
1898  block_id, LSN_FORMAT_ARGS(state->ReadRecPtr));
1899  goto err;
1900  }
1901  }
1902 
1903  if (remaining != datatotal)
1904  goto shortdata_err;
1905 
1906  /*
1907  * Ok, we've parsed the fragment headers, and verified that the total
1908  * length of the payload in the fragments is equal to the amount of data
1909  * left. Copy the data of each fragment to contiguous space after the
1910  * blocks array, inserting alignment padding before the data fragments so
1911  * they can be cast to struct pointers by REDO routines.
1912  */
1913  out = ((char *) decoded) +
1914  offsetof(DecodedXLogRecord, blocks) +
1915  sizeof(decoded->blocks[0]) * (decoded->max_block_id + 1);
1916 
1917  /* block data first */
1918  for (block_id = 0; block_id <= decoded->max_block_id; block_id++)
1919  {
1920  DecodedBkpBlock *blk = &decoded->blocks[block_id];
1921 
1922  if (!blk->in_use)
1923  continue;
1924 
1925  Assert(blk->has_image || !blk->apply_image);
1926 
1927  if (blk->has_image)
1928  {
1929  /* no need to align image */
1930  blk->bkp_image = out;
1931  memcpy(out, ptr, blk->bimg_len);
1932  ptr += blk->bimg_len;
1933  out += blk->bimg_len;
1934  }
1935  if (blk->has_data)
1936  {
1937  out = (char *) MAXALIGN(out);
1938  blk->data = out;
1939  memcpy(blk->data, ptr, blk->data_len);
1940  ptr += blk->data_len;
1941  out += blk->data_len;
1942  }
1943  }
1944 
1945  /* and finally, the main data */
1946  if (decoded->main_data_len > 0)
1947  {
1948  out = (char *) MAXALIGN(out);
1949  decoded->main_data = out;
1950  memcpy(decoded->main_data, ptr, decoded->main_data_len);
1951  ptr += decoded->main_data_len;
1952  out += decoded->main_data_len;
1953  }
1954 
1955  /* Report the actual size we used. */
1956  decoded->size = MAXALIGN(out - (char *) decoded);
1958  decoded->size);
1959 
1960  return true;
1961 
1962 shortdata_err:
1964  "record with invalid length at %X/%X",
1965  LSN_FORMAT_ARGS(state->ReadRecPtr));
1966 err:
1967  *errormsg = state->errormsg_buf;
1968 
1969  return false;
1970 }
1971 
1972 /*
1973  * Returns information about the block that a block reference refers to.
1974  *
1975  * This is like XLogRecGetBlockTagExtended, except that the block reference
1976  * must exist and there's no access to prefetch_buffer.
1977  */
1978 void
1980  RelFileLocator *rlocator, ForkNumber *forknum,
1981  BlockNumber *blknum)
1982 {
1983  if (!XLogRecGetBlockTagExtended(record, block_id, rlocator, forknum,
1984  blknum, NULL))
1985  {
1986 #ifndef FRONTEND
1987  elog(ERROR, "could not locate backup block with ID %d in WAL record",
1988  block_id);
1989 #else
1990  pg_fatal("could not locate backup block with ID %d in WAL record",
1991  block_id);
1992 #endif
1993  }
1994 }
1995 
1996 /*
1997  * Returns information about the block that a block reference refers to,
1998  * optionally including the buffer that the block may already be in.
1999  *
2000  * If the WAL record contains a block reference with the given ID, *rlocator,
2001  * *forknum, *blknum and *prefetch_buffer are filled in (if not NULL), and
2002  * returns true. Otherwise returns false.
2003  */
2004 bool
2006  RelFileLocator *rlocator, ForkNumber *forknum,
2007  BlockNumber *blknum,
2008  Buffer *prefetch_buffer)
2009 {
2010  DecodedBkpBlock *bkpb;
2011 
2012  if (!XLogRecHasBlockRef(record, block_id))
2013  return false;
2014 
2015  bkpb = &record->record->blocks[block_id];
2016  if (rlocator)
2017  *rlocator = bkpb->rlocator;
2018  if (forknum)
2019  *forknum = bkpb->forknum;
2020  if (blknum)
2021  *blknum = bkpb->blkno;
2022  if (prefetch_buffer)
2023  *prefetch_buffer = bkpb->prefetch_buffer;
2024  return true;
2025 }
2026 
2027 /*
2028  * Returns the data associated with a block reference, or NULL if there is
2029  * no data (e.g. because a full-page image was taken instead). The returned
2030  * pointer points to a MAXALIGNed buffer.
2031  */
2032 char *
2034 {
2035  DecodedBkpBlock *bkpb;
2036 
2037  if (block_id > record->record->max_block_id ||
2038  !record->record->blocks[block_id].in_use)
2039  return NULL;
2040 
2041  bkpb = &record->record->blocks[block_id];
2042 
2043  if (!bkpb->has_data)
2044  {
2045  if (len)
2046  *len = 0;
2047  return NULL;
2048  }
2049  else
2050  {
2051  if (len)
2052  *len = bkpb->data_len;
2053  return bkpb->data;
2054  }
2055 }
2056 
2057 /*
2058  * Restore a full-page image from a backup block attached to an XLOG record.
2059  *
2060  * Returns true if a full-page image is restored, and false on failure with
2061  * an error to be consumed by the caller.
2062  */
2063 bool
2064 RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
2065 {
2066  DecodedBkpBlock *bkpb;
2067  char *ptr;
2068  PGAlignedBlock tmp;
2069 
2070  if (block_id > record->record->max_block_id ||
2071  !record->record->blocks[block_id].in_use)
2072  {
2073  report_invalid_record(record,
2074  "could not restore image at %X/%X with invalid block %d specified",
2075  LSN_FORMAT_ARGS(record->ReadRecPtr),
2076  block_id);
2077  return false;
2078  }
2079  if (!record->record->blocks[block_id].has_image)
2080  {
2081  report_invalid_record(record, "could not restore image at %X/%X with invalid state, block %d",
2082  LSN_FORMAT_ARGS(record->ReadRecPtr),
2083  block_id);
2084  return false;
2085  }
2086 
2087  bkpb = &record->record->blocks[block_id];
2088  ptr = bkpb->bkp_image;
2089 
2090  if (BKPIMAGE_COMPRESSED(bkpb->bimg_info))
2091  {
2092  /* If a backup block image is compressed, decompress it */
2093  bool decomp_success = true;
2094 
2095  if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_PGLZ) != 0)
2096  {
2097  if (pglz_decompress(ptr, bkpb->bimg_len, tmp.data,
2098  BLCKSZ - bkpb->hole_length, true) < 0)
2099  decomp_success = false;
2100  }
2101  else if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_LZ4) != 0)
2102  {
2103 #ifdef USE_LZ4
2104  if (LZ4_decompress_safe(ptr, tmp.data,
2105  bkpb->bimg_len, BLCKSZ - bkpb->hole_length) <= 0)
2106  decomp_success = false;
2107 #else
2108  report_invalid_record(record, "could not restore image at %X/%X compressed with %s not supported by build, block %d",
2109  LSN_FORMAT_ARGS(record->ReadRecPtr),
2110  "LZ4",
2111  block_id);
2112  return false;
2113 #endif
2114  }
2115  else if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_ZSTD) != 0)
2116  {
2117 #ifdef USE_ZSTD
2118  size_t decomp_result = ZSTD_decompress(tmp.data,
2119  BLCKSZ - bkpb->hole_length,
2120  ptr, bkpb->bimg_len);
2121 
2122  if (ZSTD_isError(decomp_result))
2123  decomp_success = false;
2124 #else
2125  report_invalid_record(record, "could not restore image at %X/%X compressed with %s not supported by build, block %d",
2126  LSN_FORMAT_ARGS(record->ReadRecPtr),
2127  "zstd",
2128  block_id);
2129  return false;
2130 #endif
2131  }
2132  else
2133  {
2134  report_invalid_record(record, "could not restore image at %X/%X compressed with unknown method, block %d",
2135  LSN_FORMAT_ARGS(record->ReadRecPtr),
2136  block_id);
2137  return false;
2138  }
2139 
2140  if (!decomp_success)
2141  {
2142  report_invalid_record(record, "could not decompress image at %X/%X, block %d",
2143  LSN_FORMAT_ARGS(record->ReadRecPtr),
2144  block_id);
2145  return false;
2146  }
2147 
2148  ptr = tmp.data;
2149  }
2150 
2151  /* generate page, taking into account hole if necessary */
2152  if (bkpb->hole_length == 0)
2153  {
2154  memcpy(page, ptr, BLCKSZ);
2155  }
2156  else
2157  {
2158  memcpy(page, ptr, bkpb->hole_offset);
2159  /* must zero-fill the hole */
2160  MemSet(page + bkpb->hole_offset, 0, bkpb->hole_length);
2161  memcpy(page + (bkpb->hole_offset + bkpb->hole_length),
2162  ptr + bkpb->hole_offset,
2163  BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
2164  }
2165 
2166  return true;
2167 }
2168 
2169 #ifndef FRONTEND
2170 
2171 /*
2172  * Extract the FullTransactionId from a WAL record.
2173  */
2176 {
2177  TransactionId xid,
2178  next_xid;
2179  uint32 epoch;
2180 
2181  /*
2182  * This function is only safe during replay, because it depends on the
2183  * replay state. See AdvanceNextFullTransactionIdPastXid() for more.
2184  */
2186 
2187  xid = XLogRecGetXid(record);
2190 
2191  /*
2192  * If xid is numerically greater than next_xid, it has to be from the last
2193  * epoch.
2194  */
2195  if (unlikely(xid > next_xid))
2196  --epoch;
2197 
2199 }
2200 
2201 #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:494
unsigned int uint32
Definition: c.h:495
#define Min(x, y)
Definition: c.h:993
#define MAXALIGN(LEN)
Definition: c.h:800
signed int int32
Definition: c.h:483
#define Max(x, y)
Definition: c.h:987
#define pg_attribute_printf(f, a)
Definition: c.h:180
#define unlikely(x)
Definition: c.h:300
#define lengthof(array)
Definition: c.h:777
unsigned char uint8
Definition: c.h:493
#define MemSet(start, val, len)
Definition: c.h:1009
uint32 TransactionId
Definition: c.h:641
size_t Size
Definition: c.h:594
#define _(x)
Definition: elog.c:91
#define ERROR
Definition: elog.h:39
void err(int eval, const char *fmt,...)
Definition: err.c:43
#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:1456
void * palloc_extended(Size size, int flags)
Definition: mcxt.c:1290
void * palloc(Size size)
Definition: mcxt.c:1226
#define AmStartupProcess()
Definition: miscadmin.h:452
#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:98
#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:103
const void size_t len
return crc
int32 pglz_decompress(const char *source, int32 slen, char *dest, int32 rawsize, bool check_complete)
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:388
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:323
struct state * next
Definition: regguts.h:332
#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:1132
VariableCache ShmemVariableCache
Definition: varsup.c:34
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
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:200
bool XLogRecGetBlockTagExtended(XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum, Buffer *prefetch_buffer)
Definition: xlogreader.c:2005
static XLogPageReadResult XLogDecodeNextRecord(XLogReaderState *state, bool nonblocking)
Definition: xlogreader.c:519
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:224
static int ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr, int reqLen)
Definition: xlogreader.c:1005
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:406
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:1511
#define MAX_ERRORMSG_LEN
Definition: xlogreader.c:60
DecodedXLogRecord * XLogNextRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:342
void XLogReaderResetError(XLogReaderState *state)
Definition: xlogreader.c:1370
static void XLogReaderInvalReadState(XLogReaderState *state)
Definition: xlogreader.c:1118
#define COPY_HEADER_FIELD(_dst, _size)
bool XLogReaderValidatePageHeader(XLogReaderState *state, XLogRecPtr recptr, char *phdr)
Definition: xlogreader.c:1229
FullTransactionId XLogRecGetFullXid(XLogReaderState *record)
Definition: xlogreader.c:2175
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:170
void XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum)
Definition: xlogreader.c:1979
DecodedXLogRecord * XLogReadAhead(XLogReaderState *state, bool nonblocking)
Definition: xlogreader.c:971
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:1603
bool DecodeXLogRecord(XLogReaderState *state, DecodedXLogRecord *decoded, XLogRecord *record, XLogRecPtr lsn, char **errormsg)
Definition: xlogreader.c:1670
static bool ValidXLogRecord(XLogReaderState *state, XLogRecord *record, XLogRecPtr recptr)
Definition: xlogreader.c:1198
char * XLogRecGetBlockData(XLogReaderState *record, uint8 block_id, Size *len)
Definition: xlogreader.c:2033
#define DEFAULT_DECODE_BUFFER_SIZE
Definition: xlogreader.c:66
size_t DecodeXLogRecordRequiredSpace(size_t xl_tot_len)
Definition: xlogreader.c:1637
XLogRecPtr XLogFindNextRecord(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:1388
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:248
bool RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
Definition: xlogreader.c:2064
static DecodedXLogRecord * XLogReadRecordAlloc(XLogReaderState *state, size_t xl_tot_len, bool allow_oversized)
Definition: xlogreader.c:455
XLogRecPtr XLogReleasePreviousRecord(XLogReaderState *state)
Definition: xlogreader.c:266
static bool ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr, XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess)
Definition: xlogreader.c:1132
static bool XLogReaderHasQueuedRecordOrError(XLogReaderState *state)
Definition: xlogreader.h:325
#define XLogRecGetXid(decoder)
Definition: xlogreader.h:412
XLogPageReadResult
Definition: xlogreader.h:350
@ XLREAD_WOULDBLOCK
Definition: xlogreader.h:353
@ XLREAD_SUCCESS
Definition: xlogreader.h:351
@ XLREAD_FAIL
Definition: xlogreader.h:352
#define XLogRecHasBlockRef(decoder, block_id)
Definition: xlogreader.h:420
#define BKPIMAGE_COMPRESS_ZSTD
Definition: xlogrecord.h:162
#define BKPBLOCK_FORK_MASK
Definition: xlogrecord.h:195
#define BKPBLOCK_HAS_DATA
Definition: xlogrecord.h:198
#define BKPIMAGE_APPLY
Definition: xlogrecord.h:158
#define BKPIMAGE_HAS_HOLE
Definition: xlogrecord.h:157
#define XLR_BLOCK_ID_DATA_LONG
Definition: xlogrecord.h:242
#define BKPIMAGE_COMPRESS_LZ4
Definition: xlogrecord.h:161
#define BKPIMAGE_COMPRESSED(info)
Definition: xlogrecord.h:164
#define XLR_BLOCK_ID_TOPLEVEL_XID
Definition: xlogrecord.h:244
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:241
#define XLR_MAX_BLOCK_ID
Definition: xlogrecord.h:239
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define BKPBLOCK_SAME_REL
Definition: xlogrecord.h:200
#define BKPIMAGE_COMPRESS_PGLZ
Definition: xlogrecord.h:160
#define XLR_BLOCK_ID_ORIGIN
Definition: xlogrecord.h:243
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
#define BKPBLOCK_HAS_IMAGE
Definition: xlogrecord.h:197
static uint32 readOff
Definition: xlogrecovery.c:232
static uint32 readLen
Definition: xlogrecovery.c:233