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