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
11 #include <linux/kernel.h>
12 #include <linux/dax.h>
13 #include <linux/gfp.h>
14 #include <linux/export.h>
15 #include <linux/blkdev.h>
16 #include <linux/backing-dev.h>
17 #include <linux/task_io_accounting_ops.h>
18 #include <linux/pagevec.h>
19 #include <linux/pagemap.h>
20 #include <linux/syscalls.h>
21 #include <linux/file.h>
22 #include <linux/mm_inline.h>
23 #include <linux/blk-cgroup.h>
24 #include <linux/fadvise.h>
29 * Initialise a struct file's readahead state. Assumes that the caller has
33 file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
35 ra->ra_pages = inode_to_bdi(mapping->host)->ra_pages;
38 EXPORT_SYMBOL_GPL(file_ra_state_init);
41 * see if a page needs releasing upon read_cache_pages() failure
42 * - the caller of read_cache_pages() may have set PG_private or PG_fscache
43 * before calling, such as the NFS fs marking pages that are cached locally
44 * on disk, thus we need to give the fs a chance to clean up in the event of
47 static void read_cache_pages_invalidate_page(struct address_space *mapping,
50 if (page_has_private(page)) {
51 if (!trylock_page(page))
53 page->mapping = mapping;
54 do_invalidatepage(page, 0, PAGE_SIZE);
62 * release a list of pages, invalidating them first if need be
64 static void read_cache_pages_invalidate_pages(struct address_space *mapping,
65 struct list_head *pages)
69 while (!list_empty(pages)) {
70 victim = lru_to_page(pages);
71 list_del(&victim->lru);
72 read_cache_pages_invalidate_page(mapping, victim);
77 * read_cache_pages - populate an address space with some pages & start reads against them
78 * @mapping: the address_space
79 * @pages: The address of a list_head which contains the target pages. These
80 * pages have their ->index populated and are otherwise uninitialised.
81 * @filler: callback routine for filling a single page.
82 * @data: private data for the callback routine.
84 * Hides the details of the LRU cache etc from the filesystems.
86 * Returns: %0 on success, error return by @filler otherwise
88 int read_cache_pages(struct address_space *mapping, struct list_head *pages,
89 int (*filler)(void *, struct page *), void *data)
94 while (!list_empty(pages)) {
95 page = lru_to_page(pages);
97 if (add_to_page_cache_lru(page, mapping, page->index,
98 readahead_gfp_mask(mapping))) {
99 read_cache_pages_invalidate_page(mapping, page);
104 ret = filler(data, page);
106 read_cache_pages_invalidate_pages(mapping, pages);
109 task_io_account_read(PAGE_SIZE);
114 EXPORT_SYMBOL(read_cache_pages);
116 static void read_pages(struct readahead_control *rac, struct list_head *pages,
119 const struct address_space_operations *aops = rac->mapping->a_ops;
121 struct blk_plug plug;
123 if (!readahead_count(rac))
126 blk_start_plug(&plug);
128 if (aops->readahead) {
129 aops->readahead(rac);
130 /* Clean up the remaining pages */
131 while ((page = readahead_page(rac))) {
135 } else if (aops->readpages) {
136 aops->readpages(rac->file, rac->mapping, pages,
137 readahead_count(rac));
138 /* Clean up the remaining pages */
139 put_pages_list(pages);
140 rac->_index += rac->_nr_pages;
143 while ((page = readahead_page(rac))) {
144 aops->readpage(rac->file, page);
149 blk_finish_plug(&plug);
151 BUG_ON(!list_empty(pages));
152 BUG_ON(readahead_count(rac));
160 * __do_page_cache_readahead() actually reads a chunk of disk. It allocates
161 * the pages first, then submits them for I/O. This avoids the very bad
162 * behaviour which would occur if page allocations are causing VM writeback.
163 * We really don't want to intermingle reads and writes like that.
165 void __do_page_cache_readahead(struct address_space *mapping,
166 struct file *filp, pgoff_t index, unsigned long nr_to_read,
167 unsigned long lookahead_size)
169 struct inode *inode = mapping->host;
171 unsigned long end_index; /* The last page we want to read */
172 LIST_HEAD(page_pool);
173 loff_t isize = i_size_read(inode);
174 gfp_t gfp_mask = readahead_gfp_mask(mapping);
175 struct readahead_control rac = {
185 end_index = ((isize - 1) >> PAGE_SHIFT);
188 * Preallocate as many pages as we will need.
190 for (i = 0; i < nr_to_read; i++) {
191 if (index + i > end_index)
194 BUG_ON(index + i != rac._index + rac._nr_pages);
196 page = xa_load(&mapping->i_pages, index + i);
197 if (page && !xa_is_value(page)) {
199 * Page already present? Kick off the current batch of
200 * contiguous pages before continuing with the next
203 read_pages(&rac, &page_pool, true);
207 page = __page_cache_alloc(gfp_mask);
210 if (mapping->a_ops->readpages) {
211 page->index = index + i;
212 list_add(&page->lru, &page_pool);
213 } else if (add_to_page_cache_lru(page, mapping, index + i,
216 read_pages(&rac, &page_pool, true);
219 if (i == nr_to_read - lookahead_size)
220 SetPageReadahead(page);
225 * Now start the IO. We ignore I/O errors - if the page is not
226 * uptodate then the caller will launch readpage again, and
227 * will then handle the error.
229 read_pages(&rac, &page_pool, false);
233 * Chunk the readahead into 2 megabyte units, so that we don't pin too much
236 void force_page_cache_readahead(struct address_space *mapping,
237 struct file *filp, pgoff_t index, unsigned long nr_to_read)
239 struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
240 struct file_ra_state *ra = &filp->f_ra;
241 unsigned long max_pages;
243 if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages &&
244 !mapping->a_ops->readahead))
248 * If the request exceeds the readahead window, allow the read to
249 * be up to the optimal hardware IO size
251 max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
252 nr_to_read = min(nr_to_read, max_pages);
254 unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
256 if (this_chunk > nr_to_read)
257 this_chunk = nr_to_read;
258 __do_page_cache_readahead(mapping, filp, index, this_chunk, 0);
261 nr_to_read -= this_chunk;
266 * Set the initial window size, round to next power of 2 and square
267 * for small size, x 4 for medium, and x 2 for large
268 * for 128k (32 page) max ra
269 * 1-8 page = 32k initial, > 8 page = 128k initial
271 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
273 unsigned long newsize = roundup_pow_of_two(size);
275 if (newsize <= max / 32)
276 newsize = newsize * 4;
277 else if (newsize <= max / 4)
278 newsize = newsize * 2;
286 * Get the previous window size, ramp it up, and
287 * return it as the new window size.
289 static unsigned long get_next_ra_size(struct file_ra_state *ra,
292 unsigned long cur = ra->size;
302 * On-demand readahead design.
304 * The fields in struct file_ra_state represent the most-recently-executed
307 * |<----- async_size ---------|
308 * |------------------- size -------------------->|
309 * |==================#===========================|
310 * ^start ^page marked with PG_readahead
312 * To overlap application thinking time and disk I/O time, we do
313 * `readahead pipelining': Do not wait until the application consumed all
314 * readahead pages and stalled on the missing page at readahead_index;
315 * Instead, submit an asynchronous readahead I/O as soon as there are
316 * only async_size pages left in the readahead window. Normally async_size
317 * will be equal to size, for maximum pipelining.
319 * In interleaved sequential reads, concurrent streams on the same fd can
320 * be invalidating each other's readahead state. So we flag the new readahead
321 * page at (start+size-async_size) with PG_readahead, and use it as readahead
322 * indicator. The flag won't be set on already cached pages, to avoid the
323 * readahead-for-nothing fuss, saving pointless page cache lookups.
325 * prev_pos tracks the last visited byte in the _previous_ read request.
326 * It should be maintained by the caller, and will be used for detecting
327 * small random reads. Note that the readahead algorithm checks loosely
328 * for sequential patterns. Hence interleaved reads might be served as
331 * There is a special-case: if the first page which the application tries to
332 * read happens to be the first page of the file, it is assumed that a linear
333 * read is about to happen and the window is immediately set to the initial size
334 * based on I/O request size and the max_readahead.
336 * The code ramps up the readahead size aggressively at first, but slow down as
337 * it approaches max_readhead.
341 * Count contiguously cached pages from @index-1 to @index-@max,
342 * this count is a conservative estimation of
343 * - length of the sequential read sequence, or
344 * - thrashing threshold in memory tight systems
346 static pgoff_t count_history_pages(struct address_space *mapping,
347 pgoff_t index, unsigned long max)
352 head = page_cache_prev_miss(mapping, index - 1, max);
355 return index - 1 - head;
359 * page cache context based read-ahead
361 static int try_context_readahead(struct address_space *mapping,
362 struct file_ra_state *ra,
364 unsigned long req_size,
369 size = count_history_pages(mapping, index, max);
372 * not enough history pages:
373 * it could be a random read
375 if (size <= req_size)
379 * starts from beginning of file:
380 * it is a strong indication of long-run stream (or whole-file-read)
386 ra->size = min(size + req_size, max);
393 * A minimal readahead algorithm for trivial sequential/random reads.
395 static void ondemand_readahead(struct address_space *mapping,
396 struct file_ra_state *ra, struct file *filp,
397 bool hit_readahead_marker, pgoff_t index,
398 unsigned long req_size)
400 struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
401 unsigned long max_pages = ra->ra_pages;
402 unsigned long add_pages;
406 * If the request exceeds the readahead window, allow the read to
407 * be up to the optimal hardware IO size
409 if (req_size > max_pages && bdi->io_pages > max_pages)
410 max_pages = min(req_size, bdi->io_pages);
416 goto initial_readahead;
419 * It's the expected callback index, assume sequential access.
420 * Ramp up sizes, and push forward the readahead window.
422 if ((index == (ra->start + ra->size - ra->async_size) ||
423 index == (ra->start + ra->size))) {
424 ra->start += ra->size;
425 ra->size = get_next_ra_size(ra, max_pages);
426 ra->async_size = ra->size;
431 * Hit a marked page without valid readahead state.
432 * E.g. interleaved reads.
433 * Query the pagecache for async_size, which normally equals to
434 * readahead size. Ramp it up and use it as the new readahead size.
436 if (hit_readahead_marker) {
440 start = page_cache_next_miss(mapping, index + 1, max_pages);
443 if (!start || start - index > max_pages)
447 ra->size = start - index; /* old async_size */
448 ra->size += req_size;
449 ra->size = get_next_ra_size(ra, max_pages);
450 ra->async_size = ra->size;
457 if (req_size > max_pages)
458 goto initial_readahead;
461 * sequential cache miss
462 * trivial case: (index - prev_index) == 1
463 * unaligned reads: (index - prev_index) == 0
465 prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
466 if (index - prev_index <= 1UL)
467 goto initial_readahead;
470 * Query the page cache and look for the traces(cached history pages)
471 * that a sequential stream would leave behind.
473 if (try_context_readahead(mapping, ra, index, req_size, max_pages))
477 * standalone, small random read
478 * Read as is, and do not pollute the readahead state.
480 __do_page_cache_readahead(mapping, filp, index, req_size, 0);
485 ra->size = get_init_ra_size(req_size, max_pages);
486 ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size;
490 * Will this read hit the readahead marker made by itself?
491 * If so, trigger the readahead marker hit now, and merge
492 * the resulted next readahead window into the current one.
493 * Take care of maximum IO pages as above.
495 if (index == ra->start && ra->size == ra->async_size) {
496 add_pages = get_next_ra_size(ra, max_pages);
497 if (ra->size + add_pages <= max_pages) {
498 ra->async_size = add_pages;
499 ra->size += add_pages;
501 ra->size = max_pages;
502 ra->async_size = max_pages >> 1;
506 ra_submit(ra, mapping, filp);
510 * page_cache_sync_readahead - generic file readahead
511 * @mapping: address_space which holds the pagecache and I/O vectors
512 * @ra: file_ra_state which holds the readahead state
513 * @filp: passed on to ->readpage() and ->readpages()
514 * @index: Index of first page to be read.
515 * @req_count: Total number of pages being read by the caller.
517 * page_cache_sync_readahead() should be called when a cache miss happened:
518 * it will submit the read. The readahead logic may decide to piggyback more
519 * pages onto the read request if access patterns suggest it will improve
522 void page_cache_sync_readahead(struct address_space *mapping,
523 struct file_ra_state *ra, struct file *filp,
524 pgoff_t index, unsigned long req_count)
530 if (blk_cgroup_congested())
534 if (filp && (filp->f_mode & FMODE_RANDOM)) {
535 force_page_cache_readahead(mapping, filp, index, req_count);
540 ondemand_readahead(mapping, ra, filp, false, index, req_count);
542 EXPORT_SYMBOL_GPL(page_cache_sync_readahead);
545 * page_cache_async_readahead - file readahead for marked pages
546 * @mapping: address_space which holds the pagecache and I/O vectors
547 * @ra: file_ra_state which holds the readahead state
548 * @filp: passed on to ->readpage() and ->readpages()
549 * @page: The page at @index which triggered the readahead call.
550 * @index: Index of first page to be read.
551 * @req_count: Total number of pages being read by the caller.
553 * page_cache_async_readahead() should be called when a page is used which
554 * is marked as PageReadahead; this is a marker to suggest that the application
555 * has used up enough of the readahead window that we should start pulling in
559 page_cache_async_readahead(struct address_space *mapping,
560 struct file_ra_state *ra, struct file *filp,
561 struct page *page, pgoff_t index,
562 unsigned long req_count)
569 * Same bit is used for PG_readahead and PG_reclaim.
571 if (PageWriteback(page))
574 ClearPageReadahead(page);
577 * Defer asynchronous read-ahead on IO congestion.
579 if (inode_read_congested(mapping->host))
582 if (blk_cgroup_congested())
586 ondemand_readahead(mapping, ra, filp, true, index, req_count);
588 EXPORT_SYMBOL_GPL(page_cache_async_readahead);
590 ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
597 if (!f.file || !(f.file->f_mode & FMODE_READ))
601 * The readahead() syscall is intended to run only on files
602 * that can execute readahead. If readahead is not possible
603 * on this file, then we must return -EINVAL.
606 if (!f.file->f_mapping || !f.file->f_mapping->a_ops ||
607 !S_ISREG(file_inode(f.file)->i_mode))
610 ret = vfs_fadvise(f.file, offset, count, POSIX_FADV_WILLNEED);
616 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
618 return ksys_readahead(fd, offset, count);