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