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