1 // SPDX-License-Identifier: GPL-2.0-only
3 * mm/readahead.c - address_space-level file readahead.
5 * Copyright (C) 2002, Linus Torvalds
7 * 09Apr2002 Andrew Morton
12 * DOC: Readahead Overview
14 * Readahead is used to read content into the page cache before it is
15 * explicitly requested by the application. Readahead only ever
16 * attempts to read pages that are not yet in the page cache. If a
17 * page is present but not up-to-date, readahead will not try to read
18 * it. In that case a simple ->readpage() will be requested.
20 * Readahead is triggered when an application read request (whether a
21 * systemcall or a page fault) finds that the requested page is not in
22 * the page cache, or that it is in the page cache and has the
23 * %PG_readahead flag set. This flag indicates that the page was loaded
24 * as part of a previous read-ahead request and now that it has been
25 * accessed, it is time for the next read-ahead.
27 * Each readahead request is partly synchronous read, and partly async
28 * read-ahead. This is reflected in the struct file_ra_state which
29 * contains ->size being to total number of pages, and ->async_size
30 * which is the number of pages in the async section. The first page in
31 * this async section will have %PG_readahead set as a trigger for a
32 * subsequent read ahead. Once a series of sequential reads has been
33 * established, there should be no need for a synchronous component and
34 * all read ahead request will be fully asynchronous.
36 * When either of the triggers causes a readahead, three numbers need to
37 * be determined: the start of the region, the size of the region, and
38 * the size of the async tail.
40 * The start of the region is simply the first page address at or after
41 * the accessed address, which is not currently populated in the page
42 * cache. This is found with a simple search in the page cache.
44 * The size of the async tail is determined by subtracting the size that
45 * was explicitly requested from the determined request size, unless
46 * this would be less than zero - then zero is used. NOTE THIS
47 * CALCULATION IS WRONG WHEN THE START OF THE REGION IS NOT THE ACCESSED
50 * The size of the region is normally determined from the size of the
51 * previous readahead which loaded the preceding pages. This may be
52 * discovered from the struct file_ra_state for simple sequential reads,
53 * or from examining the state of the page cache when multiple
54 * sequential reads are interleaved. Specifically: where the readahead
55 * was triggered by the %PG_readahead flag, the size of the previous
56 * readahead is assumed to be the number of pages from the triggering
57 * page to the start of the new readahead. In these cases, the size of
58 * the previous readahead is scaled, often doubled, for the new
59 * readahead, though see get_next_ra_size() for details.
61 * If the size of the previous read cannot be determined, the number of
62 * preceding pages in the page cache is used to estimate the size of
63 * a previous read. This estimate could easily be misled by random
64 * reads being coincidentally adjacent, so it is ignored unless it is
65 * larger than the current request, and it is not scaled up, unless it
66 * is at the start of file.
68 * In general read ahead is accelerated at the start of the file, as
69 * reads from there are often sequential. There are other minor
70 * adjustments to the read ahead size in various special cases and these
71 * are best discovered by reading the code.
73 * The above calculation determines the readahead, to which any requested
74 * read size may be added.
76 * Readahead requests are sent to the filesystem using the ->readahead()
77 * address space operation, for which mpage_readahead() is a canonical
78 * implementation. ->readahead() should normally initiate reads on all
79 * pages, but may fail to read any or all pages without causing an IO
80 * error. The page cache reading code will issue a ->readpage() request
81 * for any page which ->readahead() does not provided, and only an error
82 * from this will be final.
84 * ->readahead() will generally call readahead_page() repeatedly to get
85 * each page from those prepared for read ahead. It may fail to read a
88 * * not calling readahead_page() sufficiently many times, effectively
89 * ignoring some pages, as might be appropriate if the path to
90 * storage is congested.
92 * * failing to actually submit a read request for a given page,
93 * possibly due to insufficient resources, or
95 * * getting an error during subsequent processing of a request.
97 * In the last two cases, the page should be unlocked to indicate that
98 * the read attempt has failed. In the first case the page will be
99 * unlocked by the caller.
101 * Those pages not in the final ``async_size`` of the request should be
102 * considered to be important and ->readahead() should not fail them due
103 * to congestion or temporary resource unavailability, but should wait
104 * for necessary resources (e.g. memory or indexing information) to
105 * become available. Pages in the final ``async_size`` may be
106 * considered less urgent and failure to read them is more acceptable.
107 * In this case it is best to use delete_from_page_cache() to remove the
108 * pages from the page cache as is automatically done for pages that
109 * were not fetched with readahead_page(). This will allow a
110 * subsequent synchronous read ahead request to try them again. If they
111 * are left in the page cache, then they will be read individually using
116 #include <linux/kernel.h>
117 #include <linux/dax.h>
118 #include <linux/gfp.h>
119 #include <linux/export.h>
120 #include <linux/backing-dev.h>
121 #include <linux/task_io_accounting_ops.h>
122 #include <linux/pagevec.h>
123 #include <linux/pagemap.h>
124 #include <linux/syscalls.h>
125 #include <linux/file.h>
126 #include <linux/mm_inline.h>
127 #include <linux/blk-cgroup.h>
128 #include <linux/fadvise.h>
129 #include <linux/sched/mm.h>
131 #include "internal.h"
134 * Initialise a struct file's readahead state. Assumes that the caller has
135 * memset *ra to zero.
138 file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
140 ra->ra_pages = inode_to_bdi(mapping->host)->ra_pages;
143 EXPORT_SYMBOL_GPL(file_ra_state_init);
145 static void read_pages(struct readahead_control *rac, struct list_head *pages,
148 const struct address_space_operations *aops = rac->mapping->a_ops;
150 struct blk_plug plug;
152 if (!readahead_count(rac))
155 blk_start_plug(&plug);
157 if (aops->readahead) {
158 aops->readahead(rac);
160 * Clean up the remaining pages. The sizes in ->ra
161 * maybe be used to size next read-ahead, so make sure
162 * they accurately reflect what happened.
164 while ((page = readahead_page(rac))) {
166 if (rac->ra->async_size > 0) {
167 rac->ra->async_size -= 1;
168 delete_from_page_cache(page);
173 } else if (aops->readpages) {
174 aops->readpages(rac->file, rac->mapping, pages,
175 readahead_count(rac));
176 /* Clean up the remaining pages */
177 put_pages_list(pages);
178 rac->_index += rac->_nr_pages;
181 while ((page = readahead_page(rac))) {
182 aops->readpage(rac->file, page);
187 blk_finish_plug(&plug);
189 BUG_ON(pages && !list_empty(pages));
190 BUG_ON(readahead_count(rac));
198 * page_cache_ra_unbounded - Start unchecked readahead.
199 * @ractl: Readahead control.
200 * @nr_to_read: The number of pages to read.
201 * @lookahead_size: Where to start the next readahead.
203 * This function is for filesystems to call when they want to start
204 * readahead beyond a file's stated i_size. This is almost certainly
205 * not the function you want to call. Use page_cache_async_readahead()
206 * or page_cache_sync_readahead() instead.
208 * Context: File is referenced by caller. Mutexes may be held by caller.
209 * May sleep, but will not reenter filesystem to reclaim memory.
211 void page_cache_ra_unbounded(struct readahead_control *ractl,
212 unsigned long nr_to_read, unsigned long lookahead_size)
214 struct address_space *mapping = ractl->mapping;
215 unsigned long index = readahead_index(ractl);
216 LIST_HEAD(page_pool);
217 gfp_t gfp_mask = readahead_gfp_mask(mapping);
221 * Partway through the readahead operation, we will have added
222 * locked pages to the page cache, but will not yet have submitted
223 * them for I/O. Adding another page may need to allocate memory,
224 * which can trigger memory reclaim. Telling the VM we're in
225 * the middle of a filesystem operation will cause it to not
226 * touch file-backed pages, preventing a deadlock. Most (all?)
227 * filesystems already specify __GFP_NOFS in their mapping's
228 * gfp_mask, but let's be explicit here.
230 unsigned int nofs = memalloc_nofs_save();
232 filemap_invalidate_lock_shared(mapping);
234 * Preallocate as many pages as we will need.
236 for (i = 0; i < nr_to_read; i++) {
237 struct folio *folio = xa_load(&mapping->i_pages, index + i);
239 if (folio && !xa_is_value(folio)) {
241 * Page already present? Kick off the current batch
242 * of contiguous pages before continuing with the
243 * next batch. This page may be the one we would
244 * have intended to mark as Readahead, but we don't
245 * have a stable reference to this page, and it's
246 * not worth getting one just for that.
248 read_pages(ractl, &page_pool, true);
249 i = ractl->_index + ractl->_nr_pages - index - 1;
253 folio = filemap_alloc_folio(gfp_mask, 0);
256 if (mapping->a_ops->readpages) {
257 folio->index = index + i;
258 list_add(&folio->lru, &page_pool);
259 } else if (filemap_add_folio(mapping, folio, index + i,
262 read_pages(ractl, &page_pool, true);
263 i = ractl->_index + ractl->_nr_pages - index - 1;
266 if (i == nr_to_read - lookahead_size)
267 folio_set_readahead(folio);
272 * Now start the IO. We ignore I/O errors - if the page is not
273 * uptodate then the caller will launch readpage again, and
274 * will then handle the error.
276 read_pages(ractl, &page_pool, false);
277 filemap_invalidate_unlock_shared(mapping);
278 memalloc_nofs_restore(nofs);
280 EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
283 * do_page_cache_ra() actually reads a chunk of disk. It allocates
284 * the pages first, then submits them for I/O. This avoids the very bad
285 * behaviour which would occur if page allocations are causing VM writeback.
286 * We really don't want to intermingle reads and writes like that.
288 static void do_page_cache_ra(struct readahead_control *ractl,
289 unsigned long nr_to_read, unsigned long lookahead_size)
291 struct inode *inode = ractl->mapping->host;
292 unsigned long index = readahead_index(ractl);
293 loff_t isize = i_size_read(inode);
294 pgoff_t end_index; /* The last page we want to read */
299 end_index = (isize - 1) >> PAGE_SHIFT;
300 if (index > end_index)
302 /* Don't read past the page containing the last byte of the file */
303 if (nr_to_read > end_index - index)
304 nr_to_read = end_index - index + 1;
306 page_cache_ra_unbounded(ractl, nr_to_read, lookahead_size);
310 * Chunk the readahead into 2 megabyte units, so that we don't pin too much
313 void force_page_cache_ra(struct readahead_control *ractl,
314 unsigned long nr_to_read)
316 struct address_space *mapping = ractl->mapping;
317 struct file_ra_state *ra = ractl->ra;
318 struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
319 unsigned long max_pages, index;
321 if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages &&
322 !mapping->a_ops->readahead))
326 * If the request exceeds the readahead window, allow the read to
327 * be up to the optimal hardware IO size
329 index = readahead_index(ractl);
330 max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
331 nr_to_read = min_t(unsigned long, nr_to_read, max_pages);
333 unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
335 if (this_chunk > nr_to_read)
336 this_chunk = nr_to_read;
337 ractl->_index = index;
338 do_page_cache_ra(ractl, this_chunk, 0);
341 nr_to_read -= this_chunk;
346 * Set the initial window size, round to next power of 2 and square
347 * for small size, x 4 for medium, and x 2 for large
348 * for 128k (32 page) max ra
349 * 1-2 page = 16k, 3-4 page 32k, 5-8 page = 64k, > 8 page = 128k initial
351 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
353 unsigned long newsize = roundup_pow_of_two(size);
355 if (newsize <= max / 32)
356 newsize = newsize * 4;
357 else if (newsize <= max / 4)
358 newsize = newsize * 2;
366 * Get the previous window size, ramp it up, and
367 * return it as the new window size.
369 static unsigned long get_next_ra_size(struct file_ra_state *ra,
372 unsigned long cur = ra->size;
382 * On-demand readahead design.
384 * The fields in struct file_ra_state represent the most-recently-executed
387 * |<----- async_size ---------|
388 * |------------------- size -------------------->|
389 * |==================#===========================|
390 * ^start ^page marked with PG_readahead
392 * To overlap application thinking time and disk I/O time, we do
393 * `readahead pipelining': Do not wait until the application consumed all
394 * readahead pages and stalled on the missing page at readahead_index;
395 * Instead, submit an asynchronous readahead I/O as soon as there are
396 * only async_size pages left in the readahead window. Normally async_size
397 * will be equal to size, for maximum pipelining.
399 * In interleaved sequential reads, concurrent streams on the same fd can
400 * be invalidating each other's readahead state. So we flag the new readahead
401 * page at (start+size-async_size) with PG_readahead, and use it as readahead
402 * indicator. The flag won't be set on already cached pages, to avoid the
403 * readahead-for-nothing fuss, saving pointless page cache lookups.
405 * prev_pos tracks the last visited byte in the _previous_ read request.
406 * It should be maintained by the caller, and will be used for detecting
407 * small random reads. Note that the readahead algorithm checks loosely
408 * for sequential patterns. Hence interleaved reads might be served as
411 * There is a special-case: if the first page which the application tries to
412 * read happens to be the first page of the file, it is assumed that a linear
413 * read is about to happen and the window is immediately set to the initial size
414 * based on I/O request size and the max_readahead.
416 * The code ramps up the readahead size aggressively at first, but slow down as
417 * it approaches max_readhead.
421 * Count contiguously cached pages from @index-1 to @index-@max,
422 * this count is a conservative estimation of
423 * - length of the sequential read sequence, or
424 * - thrashing threshold in memory tight systems
426 static pgoff_t count_history_pages(struct address_space *mapping,
427 pgoff_t index, unsigned long max)
432 head = page_cache_prev_miss(mapping, index - 1, max);
435 return index - 1 - head;
439 * page cache context based read-ahead
441 static int try_context_readahead(struct address_space *mapping,
442 struct file_ra_state *ra,
444 unsigned long req_size,
449 size = count_history_pages(mapping, index, max);
452 * not enough history pages:
453 * it could be a random read
455 if (size <= req_size)
459 * starts from beginning of file:
460 * it is a strong indication of long-run stream (or whole-file-read)
466 ra->size = min(size + req_size, max);
473 * There are some parts of the kernel which assume that PMD entries
474 * are exactly HPAGE_PMD_ORDER. Those should be fixed, but until then,
475 * limit the maximum allocation order to PMD size. I'm not aware of any
476 * assumptions about maximum order if THP are disabled, but 8 seems like
477 * a good order (that's 1MB if you're using 4kB pages)
479 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
480 #define MAX_PAGECACHE_ORDER HPAGE_PMD_ORDER
482 #define MAX_PAGECACHE_ORDER 8
485 static inline int ra_alloc_folio(struct readahead_control *ractl, pgoff_t index,
486 pgoff_t mark, unsigned int order, gfp_t gfp)
489 struct folio *folio = filemap_alloc_folio(gfp, order);
493 if (mark - index < (1UL << order))
494 folio_set_readahead(folio);
495 err = filemap_add_folio(ractl->mapping, folio, index, gfp);
499 ractl->_nr_pages += 1UL << order;
503 void page_cache_ra_order(struct readahead_control *ractl,
504 struct file_ra_state *ra, unsigned int new_order)
506 struct address_space *mapping = ractl->mapping;
507 pgoff_t index = readahead_index(ractl);
508 pgoff_t limit = (i_size_read(mapping->host) - 1) >> PAGE_SHIFT;
509 pgoff_t mark = index + ra->size - ra->async_size;
511 gfp_t gfp = readahead_gfp_mask(mapping);
513 if (!mapping_large_folio_support(mapping) || ra->size < 4)
516 limit = min(limit, index + ra->size - 1);
518 if (new_order < MAX_PAGECACHE_ORDER) {
520 if (new_order > MAX_PAGECACHE_ORDER)
521 new_order = MAX_PAGECACHE_ORDER;
522 while ((1 << new_order) > ra->size)
526 while (index <= limit) {
527 unsigned int order = new_order;
529 /* Align with smaller pages if needed */
530 if (index & ((1UL << order) - 1)) {
531 order = __ffs(index);
535 /* Don't allocate pages past EOF */
536 while (index + (1UL << order) - 1 > limit) {
540 err = ra_alloc_folio(ractl, index, mark, order, gfp);
543 index += 1UL << order;
547 ra->size += index - limit - 1;
548 ra->async_size += index - limit - 1;
551 read_pages(ractl, NULL, false);
554 * If there were already pages in the page cache, then we may have
555 * left some gaps. Let the regular readahead code take care of this
561 do_page_cache_ra(ractl, ra->size, ra->async_size);
565 * A minimal readahead algorithm for trivial sequential/random reads.
567 static void ondemand_readahead(struct readahead_control *ractl,
568 struct folio *folio, unsigned long req_size)
570 struct backing_dev_info *bdi = inode_to_bdi(ractl->mapping->host);
571 struct file_ra_state *ra = ractl->ra;
572 unsigned long max_pages = ra->ra_pages;
573 unsigned long add_pages;
574 unsigned long index = readahead_index(ractl);
578 * If the request exceeds the readahead window, allow the read to
579 * be up to the optimal hardware IO size
581 if (req_size > max_pages && bdi->io_pages > max_pages)
582 max_pages = min(req_size, bdi->io_pages);
588 goto initial_readahead;
591 * It's the expected callback index, assume sequential access.
592 * Ramp up sizes, and push forward the readahead window.
594 if ((index == (ra->start + ra->size - ra->async_size) ||
595 index == (ra->start + ra->size))) {
596 ra->start += ra->size;
597 ra->size = get_next_ra_size(ra, max_pages);
598 ra->async_size = ra->size;
603 * Hit a marked folio without valid readahead state.
604 * E.g. interleaved reads.
605 * Query the pagecache for async_size, which normally equals to
606 * readahead size. Ramp it up and use it as the new readahead size.
612 start = page_cache_next_miss(ractl->mapping, index + 1,
616 if (!start || start - index > max_pages)
620 ra->size = start - index; /* old async_size */
621 ra->size += req_size;
622 ra->size = get_next_ra_size(ra, max_pages);
623 ra->async_size = ra->size;
630 if (req_size > max_pages)
631 goto initial_readahead;
634 * sequential cache miss
635 * trivial case: (index - prev_index) == 1
636 * unaligned reads: (index - prev_index) == 0
638 prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
639 if (index - prev_index <= 1UL)
640 goto initial_readahead;
643 * Query the page cache and look for the traces(cached history pages)
644 * that a sequential stream would leave behind.
646 if (try_context_readahead(ractl->mapping, ra, index, req_size,
651 * standalone, small random read
652 * Read as is, and do not pollute the readahead state.
654 do_page_cache_ra(ractl, req_size, 0);
659 ra->size = get_init_ra_size(req_size, max_pages);
660 ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size;
664 * Will this read hit the readahead marker made by itself?
665 * If so, trigger the readahead marker hit now, and merge
666 * the resulted next readahead window into the current one.
667 * Take care of maximum IO pages as above.
669 if (index == ra->start && ra->size == ra->async_size) {
670 add_pages = get_next_ra_size(ra, max_pages);
671 if (ra->size + add_pages <= max_pages) {
672 ra->async_size = add_pages;
673 ra->size += add_pages;
675 ra->size = max_pages;
676 ra->async_size = max_pages >> 1;
680 ractl->_index = ra->start;
681 page_cache_ra_order(ractl, ra, folio ? folio_order(folio) : 0);
684 void page_cache_sync_ra(struct readahead_control *ractl,
685 unsigned long req_count)
687 bool do_forced_ra = ractl->file && (ractl->file->f_mode & FMODE_RANDOM);
690 * Even if read-ahead is disabled, issue this request as read-ahead
691 * as we'll need it to satisfy the requested range. The forced
692 * read-ahead will do the right thing and limit the read to just the
693 * requested range, which we'll set to 1 page for this case.
695 if (!ractl->ra->ra_pages || blk_cgroup_congested()) {
704 force_page_cache_ra(ractl, req_count);
709 ondemand_readahead(ractl, NULL, req_count);
711 EXPORT_SYMBOL_GPL(page_cache_sync_ra);
713 void page_cache_async_ra(struct readahead_control *ractl,
714 struct folio *folio, unsigned long req_count)
717 if (!ractl->ra->ra_pages)
721 * Same bit is used for PG_readahead and PG_reclaim.
723 if (folio_test_writeback(folio))
726 folio_clear_readahead(folio);
728 if (blk_cgroup_congested())
732 ondemand_readahead(ractl, folio, req_count);
734 EXPORT_SYMBOL_GPL(page_cache_async_ra);
736 ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
743 if (!f.file || !(f.file->f_mode & FMODE_READ))
747 * The readahead() syscall is intended to run only on files
748 * that can execute readahead. If readahead is not possible
749 * on this file, then we must return -EINVAL.
752 if (!f.file->f_mapping || !f.file->f_mapping->a_ops ||
753 !S_ISREG(file_inode(f.file)->i_mode))
756 ret = vfs_fadvise(f.file, offset, count, POSIX_FADV_WILLNEED);
762 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
764 return ksys_readahead(fd, offset, count);
768 * readahead_expand - Expand a readahead request
769 * @ractl: The request to be expanded
770 * @new_start: The revised start
771 * @new_len: The revised size of the request
773 * Attempt to expand a readahead request outwards from the current size to the
774 * specified size by inserting locked pages before and after the current window
775 * to increase the size to the new window. This may involve the insertion of
776 * THPs, in which case the window may get expanded even beyond what was
779 * The algorithm will stop if it encounters a conflicting page already in the
780 * pagecache and leave a smaller expansion than requested.
782 * The caller must check for this by examining the revised @ractl object for a
783 * different expansion than was requested.
785 void readahead_expand(struct readahead_control *ractl,
786 loff_t new_start, size_t new_len)
788 struct address_space *mapping = ractl->mapping;
789 struct file_ra_state *ra = ractl->ra;
790 pgoff_t new_index, new_nr_pages;
791 gfp_t gfp_mask = readahead_gfp_mask(mapping);
793 new_index = new_start / PAGE_SIZE;
795 /* Expand the leading edge downwards */
796 while (ractl->_index > new_index) {
797 unsigned long index = ractl->_index - 1;
798 struct page *page = xa_load(&mapping->i_pages, index);
800 if (page && !xa_is_value(page))
801 return; /* Page apparently present */
803 page = __page_cache_alloc(gfp_mask);
806 if (add_to_page_cache_lru(page, mapping, index, gfp_mask) < 0) {
812 ractl->_index = page->index;
815 new_len += new_start - readahead_pos(ractl);
816 new_nr_pages = DIV_ROUND_UP(new_len, PAGE_SIZE);
818 /* Expand the trailing edge upwards */
819 while (ractl->_nr_pages < new_nr_pages) {
820 unsigned long index = ractl->_index + ractl->_nr_pages;
821 struct page *page = xa_load(&mapping->i_pages, index);
823 if (page && !xa_is_value(page))
824 return; /* Page apparently present */
826 page = __page_cache_alloc(gfp_mask);
829 if (add_to_page_cache_lru(page, mapping, index, gfp_mask) < 0) {
840 EXPORT_SYMBOL(readahead_expand);