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