PostgreSQL Source Code git master
Loading...
Searching...
No Matches
xlogprefetcher.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * xlogprefetcher.c
4 * Prefetching support for recovery.
5 *
6 * Portions Copyright (c) 2022-2026, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/access/transam/xlogprefetcher.c
12 *
13 * This module provides a drop-in replacement for an XLogReader that tries to
14 * minimize I/O stalls by looking ahead in the WAL. If blocks that will be
15 * accessed in the near future are not already in the buffer pool, it initiates
16 * I/Os that might complete before the caller eventually needs the data. When
17 * referenced blocks are found in the buffer pool already, the buffer is
18 * recorded in the decoded record so that XLogReadBufferForRedo() can try to
19 * avoid a second buffer mapping table lookup.
20 *
21 * Currently, only the main fork is considered for prefetching. Currently,
22 * prefetching is only effective on systems where PrefetchBuffer() does
23 * something useful (mainly Linux).
24 *
25 *-------------------------------------------------------------------------
26 */
27
28#include "postgres.h"
29
31#include "access/xlogreader.h"
32#include "catalog/pg_control.h"
35#include "funcapi.h"
36#include "miscadmin.h"
37#include "port/atomics.h"
38#include "storage/bufmgr.h"
39#include "storage/fd.h"
40#include "storage/shmem.h"
41#include "storage/smgr.h"
42#include "storage/subsystems.h"
43#include "utils/fmgrprotos.h"
44#include "utils/guc_hooks.h"
45#include "utils/hsearch.h"
46#include "utils/timestamp.h"
47#include "utils/tuplestore.h"
48
49/*
50 * Every time we process this much WAL, we'll update the values in
51 * pg_stat_recovery_prefetch.
52 */
53#define XLOGPREFETCHER_STATS_DISTANCE BLCKSZ
54
55/*
56 * To detect repeated access to the same block and skip useless extra system
57 * calls, we remember a small window of recently prefetched blocks.
58 */
59#define XLOGPREFETCHER_SEQ_WINDOW_SIZE 4
60
61/*
62 * When maintenance_io_concurrency is not saturated, we're prepared to look
63 * ahead up to N times that number of block references.
64 */
65#define XLOGPREFETCHER_DISTANCE_MULTIPLIER 4
66
67/* Define to log internal debugging messages. */
68/* #define XLOGPREFETCHER_DEBUG_LEVEL LOG */
69
70/* GUCs */
72
73#ifdef USE_PREFETCH
74#define RecoveryPrefetchEnabled() \
75 (recovery_prefetch != RECOVERY_PREFETCH_OFF && \
76 maintenance_io_concurrency > 0)
77#else
78#define RecoveryPrefetchEnabled() false
79#endif
80
82
83/*
84 * Enum used to report whether an IO should be started.
85 */
92
93/*
94 * Type of callback that can decide which block to prefetch next. For now
95 * there is only one.
96 */
98 XLogRecPtr *lsn);
99
100/*
101 * A simple circular queue of LSNs, using to control the number of
102 * (potentially) inflight IOs. This stands in for a later more general IO
103 * control mechanism, which is why it has the apparently unnecessary
104 * indirection through a function pointer.
105 */
122
123/*
124 * A prefetcher. This is a mechanism that wraps an XLogReader, prefetching
125 * blocks that will be soon be referenced, to try to avoid IO stalls.
126 */
128{
129 /* WAL reader and current reading state. */
133
134 /* When to publish stats. */
136
137 /* Book-keeping to avoid accessing blocks that don't exist yet. */
140
141 /* Book-keeping to avoid repeat prefetches. */
145
146 /* Book-keeping to disable prefetching temporarily. */
148
149 /* IO depth manager. */
151
153
155};
156
157/*
158 * A temporary filter used to track block ranges that haven't been created
159 * yet, whole relations that haven't been created yet, and whole relations
160 * that (we assume) have already been dropped, or will be created by bulk WAL
161 * operators.
162 */
170
171/*
172 * Counters exposed in shared memory for pg_stat_recovery_prefetch.
173 */
174typedef struct XLogPrefetchStats
175{
176 pg_atomic_uint64 reset_time; /* Time of last reset. */
177 pg_atomic_uint64 prefetch; /* Prefetches initiated. */
178 pg_atomic_uint64 hit; /* Blocks already in cache. */
179 pg_atomic_uint64 skip_init; /* Zero-inited blocks skipped. */
180 pg_atomic_uint64 skip_new; /* New/missing blocks filtered. */
181 pg_atomic_uint64 skip_fpw; /* FPWs skipped. */
182 pg_atomic_uint64 skip_rep; /* Repeat accesses skipped. */
183
184 /* Dynamic values */
185 int wal_distance; /* Number of WAL bytes ahead. */
186 int block_distance; /* Number of block references ahead. */
187 int io_depth; /* Number of I/Os in progress. */
189
191 RelFileLocator rlocator,
192 BlockNumber blockno,
193 XLogRecPtr lsn);
195 RelFileLocator rlocator,
196 BlockNumber blockno);
200 XLogRecPtr *lsn);
201
203
204static void XLogPrefetchShmemRequest(void *arg);
205static void XLogPrefetchShmemInit(void *arg);
206
211
212static inline LsnReadQueue *
214 uint32 max_inflight,
215 uintptr_t lrq_private,
217{
219 uint32 size;
220
221 Assert(max_distance >= max_inflight);
222
223 size = max_distance + 1; /* full ring buffer has a gap */
224 lrq = palloc(offsetof(LsnReadQueue, queue) + sizeof(lrq->queue[0]) * size);
225 lrq->lrq_private = lrq_private;
226 lrq->max_inflight = max_inflight;
227 lrq->size = size;
228 lrq->next = next;
229 lrq->head = 0;
230 lrq->tail = 0;
231 lrq->inflight = 0;
232 lrq->completed = 0;
233
234 return lrq;
235}
236
237static inline void
242
243static inline uint32
245{
246 return lrq->inflight;
247}
248
249static inline uint32
251{
252 return lrq->completed;
253}
254
255static inline void
257{
258 /* Try to start as many IOs as we can within our limits. */
259 while (lrq->inflight < lrq->max_inflight &&
260 lrq->inflight + lrq->completed < lrq->size - 1)
261 {
262 Assert(((lrq->head + 1) % lrq->size) != lrq->tail);
263 switch (lrq->next(lrq->lrq_private, &lrq->queue[lrq->head].lsn))
264 {
265 case LRQ_NEXT_AGAIN:
266 return;
267 case LRQ_NEXT_IO:
268 lrq->queue[lrq->head].io = true;
269 lrq->inflight++;
270 break;
271 case LRQ_NEXT_NO_IO:
272 lrq->queue[lrq->head].io = false;
273 lrq->completed++;
274 break;
275 }
276 lrq->head++;
277 if (lrq->head == lrq->size)
278 lrq->head = 0;
279 }
280}
281
282static inline void
284{
285 /*
286 * We know that LSNs before 'lsn' have been replayed, so we can now assume
287 * that any IOs that were started before then have finished.
288 */
289 while (lrq->tail != lrq->head &&
290 lrq->queue[lrq->tail].lsn < lsn)
291 {
292 if (lrq->queue[lrq->tail].io)
293 lrq->inflight--;
294 else
295 lrq->completed--;
296 lrq->tail++;
297 if (lrq->tail == lrq->size)
298 lrq->tail = 0;
299 }
302}
303
304static void
306{
307 ShmemRequestStruct(.name = "XLogPrefetchStats",
308 .size = sizeof(XLogPrefetchStats),
309 .ptr = (void **) &SharedStats,
310 );
311}
312
313static void
324
325/*
326 * Reset all counters to zero.
327 */
328void
339
340
341/*
342 * Called when any GUC is changed that affects prefetching.
343 */
344void
349
350/*
351 * Increment a counter in shared memory. This is equivalent to *counter++ on a
352 * plain uint64 without any memory barrier or locking, except on platforms
353 * where readers can't read uint64 without possibly observing a torn value.
354 */
355static inline void
361
362/*
363 * Create a prefetcher that is ready to begin prefetching blocks referenced by
364 * WAL records.
365 */
368{
370 HASHCTL ctl;
371
373 prefetcher->reader = reader;
374
375 ctl.keysize = sizeof(RelFileLocator);
376 ctl.entrysize = sizeof(XLogPrefetcherFilter);
377 prefetcher->filter_table = hash_create("XLogPrefetcherFilterTable", 1024,
379 dlist_init(&prefetcher->filter_queue);
380
384
385 /* First usage will cause streaming_read to be allocated. */
386 prefetcher->reconfigure_count = XLogPrefetchReconfigureCount - 1;
387
388 return prefetcher;
389}
390
391/*
392 * Destroy a prefetcher and release all resources.
393 */
394void
396{
397 lrq_free(prefetcher->streaming_read);
398 hash_destroy(prefetcher->filter_table);
400}
401
402/*
403 * Provide access to the reader.
404 */
410
411/*
412 * Update the statistics visible in the pg_stat_recovery_prefetch view.
413 */
414void
416{
417 uint32 io_depth;
418 uint32 completed;
419 int64 wal_distance;
420
421
422 /* How far ahead of replay are we now? */
423 if (prefetcher->reader->decode_queue_tail)
424 {
425 wal_distance =
427 prefetcher->reader->decode_queue_head->lsn;
428 }
429 else
430 {
431 wal_distance = 0;
432 }
433
434 /* How many IOs are currently in flight and completed? */
435 io_depth = lrq_inflight(prefetcher->streaming_read);
436 completed = lrq_completed(prefetcher->streaming_read);
437
438 /* Update the instantaneous stats visible in pg_stat_recovery_prefetch. */
439 SharedStats->io_depth = io_depth;
440 SharedStats->block_distance = io_depth + completed;
441 SharedStats->wal_distance = wal_distance;
442
443 prefetcher->next_stats_shm_lsn =
444 prefetcher->reader->ReadRecPtr + XLOGPREFETCHER_STATS_DISTANCE;
445}
446
447/*
448 * A callback that examines the next block reference in the WAL, and possibly
449 * starts an IO so that a later read will be fast.
450 *
451 * Returns LRQ_NEXT_AGAIN if no more WAL data is available yet.
452 *
453 * Returns LRQ_NEXT_IO if the next block reference is for a main fork block
454 * that isn't in the buffer pool, and the kernel has been asked to start
455 * reading it to make a future read system call faster. An LSN is written to
456 * *lsn, and the I/O will be considered to have completed once that LSN is
457 * replayed.
458 *
459 * Returns LRQ_NEXT_NO_IO if we examined the next block reference and found
460 * that it was already in the buffer pool, or we decided for various reasons
461 * not to prefetch.
462 */
465{
467 XLogReaderState *reader = prefetcher->reader;
469
470 /*
471 * We keep track of the record and block we're up to between calls with
472 * prefetcher->record and prefetcher->next_block_id.
473 */
474 for (;;)
475 {
476 DecodedXLogRecord *record;
477
478 /* Try to read a new future record, if we don't already have one. */
479 if (prefetcher->record == NULL)
480 {
481 bool nonblocking;
482
483 /*
484 * If there are already records or an error queued up that could
485 * be replayed, we don't want to block here. Otherwise, it's OK
486 * to block waiting for more data: presumably the caller has
487 * nothing else to do.
488 */
489 nonblocking = XLogReaderHasQueuedRecordOrError(reader);
490
491 /* Readahead is disabled until we replay past a certain point. */
492 if (nonblocking && replaying_lsn <= prefetcher->no_readahead_until)
493 return LRQ_NEXT_AGAIN;
494
495 record = XLogReadAhead(prefetcher->reader, nonblocking);
496 if (record == NULL)
497 {
498 /*
499 * We can't read any more, due to an error or lack of data in
500 * nonblocking mode. Don't try to read ahead again until
501 * we've replayed everything already decoded.
502 */
503 if (nonblocking && prefetcher->reader->decode_queue_tail)
504 prefetcher->no_readahead_until =
505 prefetcher->reader->decode_queue_tail->lsn;
506
507 return LRQ_NEXT_AGAIN;
508 }
509
510 /*
511 * If prefetching is disabled, we don't need to analyze the record
512 * or issue any prefetches. We just need to cause one record to
513 * be decoded.
514 */
516 {
517 *lsn = InvalidXLogRecPtr;
518 return LRQ_NEXT_NO_IO;
519 }
520
521 /* We have a new record to process. */
522 prefetcher->record = record;
523 prefetcher->next_block_id = 0;
524 }
525 else
526 {
527 /* Continue to process from last call, or last loop. */
528 record = prefetcher->record;
529 }
530
531 /*
532 * Check for operations that require us to filter out block ranges, or
533 * pause readahead completely.
534 */
536 {
537 uint8 rmid = record->header.xl_rmid;
538 uint8 record_type = record->header.xl_info & ~XLR_INFO_MASK;
539
540 if (rmid == RM_XLOG_ID)
541 {
542 if (record_type == XLOG_CHECKPOINT_SHUTDOWN ||
543 record_type == XLOG_END_OF_RECOVERY)
544 {
545 /*
546 * These records might change the TLI. Avoid potential
547 * bugs if we were to allow "read TLI" and "replay TLI" to
548 * differ without more analysis.
549 */
550 prefetcher->no_readahead_until = record->lsn;
551
552#ifdef XLOGPREFETCHER_DEBUG_LEVEL
554 "suppressing all readahead until %X/%08X is replayed due to possible TLI change",
555 LSN_FORMAT_ARGS(record->lsn));
556#endif
557
558 /* Fall through so we move past this record. */
559 }
560 }
561 else if (rmid == RM_DBASE_ID)
562 {
563 /*
564 * When databases are created with the file-copy strategy,
565 * there are no WAL records to tell us about the creation of
566 * individual relations.
567 */
568 if (record_type == XLOG_DBASE_CREATE_FILE_COPY)
569 {
572 RelFileLocator rlocator =
574
575 /*
576 * Don't try to prefetch anything in this database until
577 * it has been created, or we might confuse the blocks of
578 * different generations, if a database OID or
579 * relfilenumber is reused. It's also more efficient than
580 * discovering that relations don't exist on disk yet with
581 * ENOENT errors.
582 */
583 XLogPrefetcherAddFilter(prefetcher, rlocator, 0, record->lsn);
584
585#ifdef XLOGPREFETCHER_DEBUG_LEVEL
587 "suppressing prefetch in database %u until %X/%08X is replayed due to raw file copy",
588 rlocator.dbOid,
589 LSN_FORMAT_ARGS(record->lsn));
590#endif
591 }
592 }
593 else if (rmid == RM_SMGR_ID)
594 {
595 if (record_type == XLOG_SMGR_CREATE)
596 {
598 record->main_data;
599
600 if (xlrec->forkNum == MAIN_FORKNUM)
601 {
602 /*
603 * Don't prefetch anything for this whole relation
604 * until it has been created. Otherwise we might
605 * confuse the blocks of different generations, if a
606 * relfilenumber is reused. This also avoids the need
607 * to discover the problem via extra syscalls that
608 * report ENOENT.
609 */
611 record->lsn);
612
613#ifdef XLOGPREFETCHER_DEBUG_LEVEL
615 "suppressing prefetch in relation %u/%u/%u until %X/%08X is replayed, which creates the relation",
616 xlrec->rlocator.spcOid,
617 xlrec->rlocator.dbOid,
618 xlrec->rlocator.relNumber,
619 LSN_FORMAT_ARGS(record->lsn));
620#endif
621 }
622 }
623 else if (record_type == XLOG_SMGR_TRUNCATE)
624 {
626 record->main_data;
627
628 /*
629 * Don't consider prefetching anything in the truncated
630 * range until the truncation has been performed.
631 */
633 xlrec->blkno,
634 record->lsn);
635
636#ifdef XLOGPREFETCHER_DEBUG_LEVEL
638 "suppressing prefetch in relation %u/%u/%u from block %u until %X/%08X is replayed, which truncates the relation",
639 xlrec->rlocator.spcOid,
640 xlrec->rlocator.dbOid,
641 xlrec->rlocator.relNumber,
642 xlrec->blkno,
643 LSN_FORMAT_ARGS(record->lsn));
644#endif
645 }
646 }
647 }
648
649 /* Scan the block references, starting where we left off last time. */
650 while (prefetcher->next_block_id <= record->max_block_id)
651 {
652 int block_id = prefetcher->next_block_id++;
653 DecodedBkpBlock *block = &record->blocks[block_id];
656
657 if (!block->in_use)
658 continue;
659
661
662 /*
663 * Record the LSN of this record. When it's replayed,
664 * LsnReadQueue will consider any IOs submitted for earlier LSNs
665 * to be finished.
666 */
667 *lsn = record->lsn;
668
669 /* We don't try to prefetch anything but the main fork for now. */
670 if (block->forknum != MAIN_FORKNUM)
671 {
672 return LRQ_NEXT_NO_IO;
673 }
674
675 /*
676 * If there is a full page image attached, we won't be reading the
677 * page, so don't bother trying to prefetch.
678 */
679 if (block->has_image)
680 {
682 return LRQ_NEXT_NO_IO;
683 }
684
685 /* There is no point in reading a page that will be zeroed. */
686 if (block->flags & BKPBLOCK_WILL_INIT)
687 {
689 return LRQ_NEXT_NO_IO;
690 }
691
692 /* Should we skip prefetching this block due to a filter? */
694 {
696 return LRQ_NEXT_NO_IO;
697 }
698
699 /* There is no point in repeatedly prefetching the same block. */
700 for (int i = 0; i < XLOGPREFETCHER_SEQ_WINDOW_SIZE; ++i)
701 {
702 if (block->blkno == prefetcher->recent_block[i] &&
703 RelFileLocatorEquals(block->rlocator, prefetcher->recent_rlocator[i]))
704 {
705 /*
706 * XXX If we also remembered where it was, we could set
707 * recent_buffer so that recovery could skip smgropen()
708 * and a buffer table lookup.
709 */
711 return LRQ_NEXT_NO_IO;
712 }
713 }
714 prefetcher->recent_rlocator[prefetcher->recent_idx] = block->rlocator;
715 prefetcher->recent_block[prefetcher->recent_idx] = block->blkno;
716 prefetcher->recent_idx =
717 (prefetcher->recent_idx + 1) % XLOGPREFETCHER_SEQ_WINDOW_SIZE;
718
719 /*
720 * We could try to have a fast path for repeated references to the
721 * same relation (with some scheme to handle invalidations
722 * safely), but for now we'll call smgropen() every time.
723 */
725
726 /*
727 * If the relation file doesn't exist on disk, for example because
728 * we're replaying after a crash and the file will be created and
729 * then unlinked by WAL that hasn't been replayed yet, suppress
730 * further prefetching in the relation until this record is
731 * replayed.
732 */
734 {
735#ifdef XLOGPREFETCHER_DEBUG_LEVEL
737 "suppressing all prefetch in relation %u/%u/%u until %X/%08X is replayed, because the relation does not exist on disk",
738 reln->smgr_rlocator.locator.spcOid,
739 reln->smgr_rlocator.locator.dbOid,
740 reln->smgr_rlocator.locator.relNumber,
741 LSN_FORMAT_ARGS(record->lsn));
742#endif
744 record->lsn);
746 return LRQ_NEXT_NO_IO;
747 }
748
749 /*
750 * If the relation isn't big enough to contain the referenced
751 * block yet, suppress prefetching of this block and higher until
752 * this record is replayed.
753 */
754 if (block->blkno >= smgrnblocks(reln, block->forknum))
755 {
756#ifdef XLOGPREFETCHER_DEBUG_LEVEL
758 "suppressing prefetch in relation %u/%u/%u from block %u until %X/%08X is replayed, because the relation is too small",
759 reln->smgr_rlocator.locator.spcOid,
760 reln->smgr_rlocator.locator.dbOid,
761 reln->smgr_rlocator.locator.relNumber,
762 block->blkno,
763 LSN_FORMAT_ARGS(record->lsn));
764#endif
766 record->lsn);
768 return LRQ_NEXT_NO_IO;
769 }
770
771 /* Try to initiate prefetching. */
772 result = PrefetchSharedBuffer(reln, block->forknum, block->blkno);
773 if (BufferIsValid(result.recent_buffer))
774 {
775 /* Cache hit, nothing to do. */
777 block->prefetch_buffer = result.recent_buffer;
778 return LRQ_NEXT_NO_IO;
779 }
780 else if (result.initiated_io)
781 {
782 /* Cache miss, I/O (presumably) started. */
785 return LRQ_NEXT_IO;
786 }
787 else if ((io_direct_flags & IO_DIRECT_DATA) == 0)
788 {
789 /*
790 * This shouldn't be possible, because we already determined
791 * that the relation exists on disk and is big enough.
792 * Something is wrong with the cache invalidation for
793 * smgrexists(), smgrnblocks(), or the file was unlinked or
794 * truncated beneath our feet?
795 */
796 elog(ERROR,
797 "could not prefetch relation %u/%u/%u block %u",
798 reln->smgr_rlocator.locator.spcOid,
799 reln->smgr_rlocator.locator.dbOid,
800 reln->smgr_rlocator.locator.relNumber,
801 block->blkno);
802 }
803 }
804
805 /*
806 * Several callsites need to be able to read exactly one record
807 * without any internal readahead. Examples: xlog.c reading
808 * checkpoint records with emode set to PANIC, which might otherwise
809 * cause XLogPageRead() to panic on some future page, and xlog.c
810 * determining where to start writing WAL next, which depends on the
811 * contents of the reader's internal buffer after reading one record.
812 * Therefore, don't even think about prefetching until the first
813 * record after XLogPrefetcherBeginRead() has been consumed.
814 */
815 if (prefetcher->reader->decode_queue_tail &&
816 prefetcher->reader->decode_queue_tail->lsn == prefetcher->begin_ptr)
817 return LRQ_NEXT_AGAIN;
818
819 /* Advance to the next record. */
820 prefetcher->record = NULL;
821 }
823}
824
825/*
826 * Expose statistics about recovery prefetching.
827 */
828Datum
855
856/*
857 * Don't prefetch any blocks >= 'blockno' from a given 'rlocator', until 'lsn'
858 * has been replayed.
859 */
860static inline void
862 BlockNumber blockno, XLogRecPtr lsn)
863{
864 XLogPrefetcherFilter *filter;
865 bool found;
866
867 filter = hash_search(prefetcher->filter_table, &rlocator, HASH_ENTER, &found);
868 if (!found)
869 {
870 /*
871 * Don't allow any prefetching of this block or higher until replayed.
872 */
873 filter->filter_until_replayed = lsn;
874 filter->filter_from_block = blockno;
875 dlist_push_head(&prefetcher->filter_queue, &filter->link);
876 }
877 else
878 {
879 /*
880 * We were already filtering this rlocator. Extend the filter's
881 * lifetime to cover this WAL record, but leave the lower of the block
882 * numbers there because we don't want to have to track individual
883 * blocks.
884 */
885 filter->filter_until_replayed = lsn;
886 dlist_delete(&filter->link);
887 dlist_push_head(&prefetcher->filter_queue, &filter->link);
888 filter->filter_from_block = Min(filter->filter_from_block, blockno);
889 }
890}
891
892/*
893 * Have we replayed any records that caused us to begin filtering a block
894 * range? That means that relations should have been created, extended or
895 * dropped as required, so we can stop filtering out accesses to a given
896 * relfilenumber.
897 */
898static inline void
900{
901 while (unlikely(!dlist_is_empty(&prefetcher->filter_queue)))
902 {
904 link,
905 &prefetcher->filter_queue);
906
908 break;
909
910 dlist_delete(&filter->link);
911 hash_search(prefetcher->filter_table, filter, HASH_REMOVE, NULL);
912 }
913}
914
915/*
916 * Check if a given block should be skipped due to a filter.
917 */
918static inline bool
920 BlockNumber blockno)
921{
922 /*
923 * Test for empty queue first, because we expect it to be empty most of
924 * the time and we can avoid the hash table lookup in that case.
925 */
926 if (unlikely(!dlist_is_empty(&prefetcher->filter_queue)))
927 {
928 XLogPrefetcherFilter *filter;
929
930 /* See if the block range is filtered. */
931 filter = hash_search(prefetcher->filter_table, &rlocator, HASH_FIND, NULL);
932 if (filter && filter->filter_from_block <= blockno)
933 {
934#ifdef XLOGPREFETCHER_DEBUG_LEVEL
936 "prefetch of %u/%u/%u block %u suppressed; filtering until LSN %X/%08X is replayed (blocks >= %u filtered)",
937 rlocator.spcOid, rlocator.dbOid, rlocator.relNumber, blockno,
939 filter->filter_from_block);
940#endif
941 return true;
942 }
943
944 /* See if the whole database is filtered. */
946 rlocator.spcOid = InvalidOid;
947 filter = hash_search(prefetcher->filter_table, &rlocator, HASH_FIND, NULL);
948 if (filter)
949 {
950#ifdef XLOGPREFETCHER_DEBUG_LEVEL
952 "prefetch of %u/%u/%u block %u suppressed; filtering until LSN %X/%08X is replayed (whole database)",
953 rlocator.spcOid, rlocator.dbOid, rlocator.relNumber, blockno,
955#endif
956 return true;
957 }
958 }
959
960 return false;
961}
962
963/*
964 * A wrapper for XLogBeginRead() that also resets the prefetcher.
965 */
966void
968{
969 /* This will forget about any in-flight IO. */
970 prefetcher->reconfigure_count--;
971
972 /* Book-keeping to avoid readahead on first read. */
973 prefetcher->begin_ptr = recPtr;
974
975 prefetcher->no_readahead_until = InvalidXLogRecPtr;
976
977 /* This will forget about any queued up records in the decoder. */
979}
980
981/*
982 * A wrapper for XLogReadRecord() that provides the same interface, but also
983 * tries to initiate I/O for blocks referenced in future WAL records.
984 */
987{
988 DecodedXLogRecord *record;
990
991 /*
992 * See if it's time to reset the prefetching machinery, because a relevant
993 * GUC was changed.
994 */
995 if (unlikely(XLogPrefetchReconfigureCount != prefetcher->reconfigure_count))
996 {
998 uint32 max_inflight;
999
1000 if (prefetcher->streaming_read)
1001 lrq_free(prefetcher->streaming_read);
1002
1004 {
1006 max_inflight = maintenance_io_concurrency;
1008 }
1009 else
1010 {
1011 max_inflight = 1;
1012 max_distance = 1;
1013 }
1014
1015 prefetcher->streaming_read = lrq_alloc(max_distance,
1016 max_inflight,
1019
1020 prefetcher->reconfigure_count = XLogPrefetchReconfigureCount;
1021 }
1022
1023 /*
1024 * Release last returned record, if there is one, as it's now been
1025 * replayed.
1026 */
1028
1029 /*
1030 * Can we drop any filters yet? If we were waiting for a relation to be
1031 * created or extended, it is now OK to access blocks in the covered
1032 * range.
1033 */
1035
1036 /*
1037 * All IO initiated by earlier WAL is now completed. This might trigger
1038 * further prefetching.
1039 */
1040 lrq_complete_lsn(prefetcher->streaming_read, replayed_up_to);
1041
1042 /*
1043 * If there's nothing queued yet, then start prefetching to cause at least
1044 * one record to be queued.
1045 */
1047 {
1048 Assert(lrq_inflight(prefetcher->streaming_read) == 0);
1049 Assert(lrq_completed(prefetcher->streaming_read) == 0);
1050 lrq_prefetch(prefetcher->streaming_read);
1051 }
1052
1053 /* Read the next record. */
1054 record = XLogNextRecord(prefetcher->reader, errmsg);
1055 if (!record)
1056 return NULL;
1057
1058 /*
1059 * The record we just got is the "current" one, for the benefit of the
1060 * XLogRecXXX() macros.
1061 */
1062 Assert(record == prefetcher->reader->record);
1063
1064 /*
1065 * If maintenance_io_concurrency is set very low, we might have started
1066 * prefetching some but not all of the blocks referenced in the record
1067 * we're about to return. Forget about the rest of the blocks in this
1068 * record by dropping the prefetcher's reference to it.
1069 */
1070 if (record == prefetcher->record)
1071 prefetcher->record = NULL;
1072
1073 /*
1074 * See if it's time to compute some statistics, because enough WAL has
1075 * been processed.
1076 */
1077 if (unlikely(record->lsn >= prefetcher->next_stats_shm_lsn))
1079
1080 Assert(record == prefetcher->reader->record);
1081
1082 return &record->header;
1083}
1084
1085bool
1087{
1088#ifndef USE_PREFETCH
1090 {
1091 GUC_check_errdetail("\"recovery_prefetch\" is not supported on platforms that lack support for issuing read-ahead advice.");
1092 return false;
1093 }
1094#endif
1095
1096 return true;
1097}
1098
1099void
1101{
1102 /* Reconfigure prefetching, because a setting it depends on changed. */
1104 if (AmStartupProcess())
1106}
static void pg_atomic_write_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition atomics.h:485
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition atomics.h:453
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition atomics.h:467
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
uint32 BlockNumber
Definition block.h:31
static int32 next
Definition blutils.c:225
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define InvalidBuffer
Definition buf.h:25
PrefetchBufferResult PrefetchSharedBuffer(SMgrRelation smgr_reln, ForkNumber forkNum, BlockNumber blockNum)
Definition bufmgr.c:697
int maintenance_io_concurrency
Definition bufmgr.c:207
static bool BufferIsValid(Buffer bufnum)
Definition bufmgr.h:419
#define Min(x, y)
Definition c.h:1091
uint8_t uint8
Definition c.h:622
#define Assert(condition)
Definition c.h:943
int64_t int64
Definition c.h:621
#define FLEXIBLE_ARRAY_MEMBER
Definition c.h:558
#define pg_unreachable()
Definition c.h:367
#define unlikely(x)
Definition c.h:438
uint32_t uint32
Definition c.h:624
uint32 result
#define XLOG_DBASE_CREATE_FILE_COPY
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
void hash_destroy(HTAB *hashp)
Definition dynahash.c:802
Datum arg
Definition elog.c:1322
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:227
int io_direct_flags
Definition fd.c:172
#define IO_DIRECT_DATA
Definition fd.h:54
#define palloc0_object(type)
Definition fe_memutils.h:75
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
void InitMaterializedSRF(FunctionCallInfo fcinfo, uint32 flags)
Definition funcapi.c:76
bool IsUnderPostmaster
Definition globals.c:122
#define GUC_check_errdetail
Definition guc.h:507
GucSource
Definition guc.h:112
@ HASH_FIND
Definition hsearch.h:108
@ HASH_REMOVE
Definition hsearch.h:110
@ HASH_ENTER
Definition hsearch.h:109
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
static void dlist_init(dlist_head *head)
Definition ilist.h:314
static void dlist_delete(dlist_node *node)
Definition ilist.h:405
#define dlist_tail_element(type, membername, lhead)
Definition ilist.h:612
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition ilist.h:347
static bool dlist_is_empty(const dlist_head *head)
Definition ilist.h:336
int i
Definition isn.c:77
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
#define AmStartupProcess()
Definition miscadmin.h:405
static char * errmsg
#define XLOG_CHECKPOINT_SHUTDOWN
Definition pg_control.h:72
#define XLOG_END_OF_RECOVERY
Definition pg_control.h:81
static rewind_source * source
Definition pg_rewind.c:89
static Datum Int64GetDatum(int64 X)
Definition postgres.h:413
uint64_t Datum
Definition postgres.h:70
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
#define InvalidOid
static int fb(int x)
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
tree ctl
Definition radixtree.h:1838
#define RelFileLocatorEquals(locator1, locator2)
@ MAIN_FORKNUM
Definition relpath.h:58
#define InvalidRelFileNumber
Definition relpath.h:26
#define ShmemRequestStruct(...)
Definition shmem.h:176
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition smgr.c:819
SMgrRelation smgropen(RelFileLocator rlocator, ProcNumber backend)
Definition smgr.c:240
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition smgr.c:462
#define XLOG_SMGR_CREATE
#define XLOG_SMGR_TRUNCATE
Buffer prefetch_buffer
Definition xlogreader.h:130
RelFileLocator rlocator
Definition xlogreader.h:125
BlockNumber blkno
Definition xlogreader.h:127
ForkNumber forknum
Definition xlogreader.h:126
XLogRecord header
Definition xlogreader.h:165
DecodedBkpBlock blocks[FLEXIBLE_ARRAY_MEMBER]
Definition xlogreader.h:171
XLogRecPtr lsn
LsnReadQueueNextFun next
uintptr_t lrq_private
struct LsnReadQueue::@17 queue[FLEXIBLE_ARRAY_MEMBER]
RelFileNumber relNumber
ShmemRequestCallback request_fn
Definition shmem.h:133
pg_atomic_uint64 skip_fpw
pg_atomic_uint64 skip_init
pg_atomic_uint64 reset_time
pg_atomic_uint64 hit
pg_atomic_uint64 prefetch
pg_atomic_uint64 skip_rep
pg_atomic_uint64 skip_new
RelFileLocator rlocator
XLogRecPtr filter_until_replayed
BlockNumber filter_from_block
dlist_head filter_queue
XLogRecPtr no_readahead_until
XLogReaderState * reader
XLogRecPtr begin_ptr
RelFileLocator recent_rlocator[XLOGPREFETCHER_SEQ_WINDOW_SIZE]
LsnReadQueue * streaming_read
DecodedXLogRecord * record
XLogRecPtr next_stats_shm_lsn
BlockNumber recent_block[XLOGPREFETCHER_SEQ_WINDOW_SIZE]
XLogRecPtr ReadRecPtr
Definition xlogreader.h:205
DecodedXLogRecord * decode_queue_tail
Definition xlogreader.h:260
uint8 xl_info
Definition xlogrecord.h:46
RmgrId xl_rmid
Definition xlogrecord.h:47
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:785
static Datum TimestampTzGetDatum(TimestampTz X)
Definition timestamp.h:52
const char * name
#define LSN_FORMAT_ARGS(lsn)
Definition xlogdefs.h:47
uint64 XLogRecPtr
Definition xlogdefs.h:21
#define InvalidXLogRecPtr
Definition xlogdefs.h:28
void XLogPrefetchResetStats(void)
static bool XLogPrefetcherIsFiltered(XLogPrefetcher *prefetcher, RelFileLocator rlocator, BlockNumber blockno)
void XLogPrefetcherComputeStats(XLogPrefetcher *prefetcher)
int recovery_prefetch
#define RecoveryPrefetchEnabled()
static void XLogPrefetcherCompleteFilters(XLogPrefetcher *prefetcher, XLogRecPtr replaying_lsn)
LsnReadQueueNextStatus(* LsnReadQueueNextFun)(uintptr_t lrq_private, XLogRecPtr *lsn)
static void lrq_free(LsnReadQueue *lrq)
static void lrq_prefetch(LsnReadQueue *lrq)
static int XLogPrefetchReconfigureCount
Datum pg_stat_get_recovery_prefetch(PG_FUNCTION_ARGS)
static void XLogPrefetchShmemRequest(void *arg)
XLogPrefetcher * XLogPrefetcherAllocate(XLogReaderState *reader)
static LsnReadQueueNextStatus XLogPrefetcherNextBlock(uintptr_t pgsr_private, XLogRecPtr *lsn)
static uint32 lrq_completed(LsnReadQueue *lrq)
static XLogPrefetchStats * SharedStats
static uint32 lrq_inflight(LsnReadQueue *lrq)
void XLogPrefetchReconfigure(void)
#define PG_STAT_GET_RECOVERY_PREFETCH_COLS
XLogRecord * XLogPrefetcherReadRecord(XLogPrefetcher *prefetcher, char **errmsg)
const ShmemCallbacks XLogPrefetchShmemCallbacks
XLogReaderState * XLogPrefetcherGetReader(XLogPrefetcher *prefetcher)
static LsnReadQueue * lrq_alloc(uint32 max_distance, uint32 max_inflight, uintptr_t lrq_private, LsnReadQueueNextFun next)
void XLogPrefetcherBeginRead(XLogPrefetcher *prefetcher, XLogRecPtr recPtr)
void assign_recovery_prefetch(int new_value, void *extra)
static void XLogPrefetchIncrement(pg_atomic_uint64 *counter)
#define XLOGPREFETCHER_SEQ_WINDOW_SIZE
static void lrq_complete_lsn(LsnReadQueue *lrq, XLogRecPtr lsn)
static void XLogPrefetchShmemInit(void *arg)
#define XLOGPREFETCHER_STATS_DISTANCE
static void XLogPrefetcherAddFilter(XLogPrefetcher *prefetcher, RelFileLocator rlocator, BlockNumber blockno, XLogRecPtr lsn)
#define XLOGPREFETCHER_DISTANCE_MULTIPLIER
void XLogPrefetcherFree(XLogPrefetcher *prefetcher)
bool check_recovery_prefetch(int *new_value, void **extra, GucSource source)
LsnReadQueueNextStatus
@ LRQ_NEXT_NO_IO
@ LRQ_NEXT_IO
@ LRQ_NEXT_AGAIN
@ RECOVERY_PREFETCH_ON
@ RECOVERY_PREFETCH_TRY
DecodedXLogRecord * XLogReadAhead(XLogReaderState *state, bool nonblocking)
Definition xlogreader.c:978
DecodedXLogRecord * XLogNextRecord(XLogReaderState *state, char **errormsg)
Definition xlogreader.c:327
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition xlogreader.c:233
XLogRecPtr XLogReleasePreviousRecord(XLogReaderState *state)
Definition xlogreader.c:251
static bool XLogReaderHasQueuedRecordOrError(XLogReaderState *state)
Definition xlogreader.h:324
#define BKPBLOCK_WILL_INIT
Definition xlogrecord.h:199