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->readpages) {
129 aops->readpages(rac->file, rac->mapping, pages,
130 readahead_count(rac));
131 /* Clean up the remaining pages */
132 put_pages_list(pages);
133 rac->_index += rac->_nr_pages;
136 while ((page = readahead_page(rac))) {
137 aops->readpage(rac->file, page);
142 blk_finish_plug(&plug);
144 BUG_ON(!list_empty(pages));
145 BUG_ON(readahead_count(rac));
153 * __do_page_cache_readahead() actually reads a chunk of disk. It allocates
154 * the pages first, then submits them for I/O. This avoids the very bad
155 * behaviour which would occur if page allocations are causing VM writeback.
156 * We really don't want to intermingle reads and writes like that.
158 void __do_page_cache_readahead(struct address_space *mapping,
159 struct file *filp, pgoff_t index, unsigned long nr_to_read,
160 unsigned long lookahead_size)
162 struct inode *inode = mapping->host;
164 unsigned long end_index; /* The last page we want to read */
165 LIST_HEAD(page_pool);
166 loff_t isize = i_size_read(inode);
167 gfp_t gfp_mask = readahead_gfp_mask(mapping);
168 struct readahead_control rac = {
178 end_index = ((isize - 1) >> PAGE_SHIFT);
181 * Preallocate as many pages as we will need.
183 for (i = 0; i < nr_to_read; i++) {
184 if (index + i > end_index)
187 BUG_ON(index + i != rac._index + rac._nr_pages);
189 page = xa_load(&mapping->i_pages, index + i);
190 if (page && !xa_is_value(page)) {
192 * Page already present? Kick off the current batch of
193 * contiguous pages before continuing with the next
196 read_pages(&rac, &page_pool, true);
200 page = __page_cache_alloc(gfp_mask);
203 if (mapping->a_ops->readpages) {
204 page->index = index + i;
205 list_add(&page->lru, &page_pool);
206 } else if (add_to_page_cache_lru(page, mapping, index + i,
209 read_pages(&rac, &page_pool, true);
212 if (i == nr_to_read - lookahead_size)
213 SetPageReadahead(page);
218 * Now start the IO. We ignore I/O errors - if the page is not
219 * uptodate then the caller will launch readpage again, and
220 * will then handle the error.
222 read_pages(&rac, &page_pool, false);
226 * Chunk the readahead into 2 megabyte units, so that we don't pin too much
229 void force_page_cache_readahead(struct address_space *mapping,
230 struct file *filp, pgoff_t index, unsigned long nr_to_read)
232 struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
233 struct file_ra_state *ra = &filp->f_ra;
234 unsigned long max_pages;
236 if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages))
240 * If the request exceeds the readahead window, allow the read to
241 * be up to the optimal hardware IO size
243 max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
244 nr_to_read = min(nr_to_read, max_pages);
246 unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
248 if (this_chunk > nr_to_read)
249 this_chunk = nr_to_read;
250 __do_page_cache_readahead(mapping, filp, index, this_chunk, 0);
253 nr_to_read -= this_chunk;
258 * Set the initial window size, round to next power of 2 and square
259 * for small size, x 4 for medium, and x 2 for large
260 * for 128k (32 page) max ra
261 * 1-8 page = 32k initial, > 8 page = 128k initial
263 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
265 unsigned long newsize = roundup_pow_of_two(size);
267 if (newsize <= max / 32)
268 newsize = newsize * 4;
269 else if (newsize <= max / 4)
270 newsize = newsize * 2;
278 * Get the previous window size, ramp it up, and
279 * return it as the new window size.
281 static unsigned long get_next_ra_size(struct file_ra_state *ra,
284 unsigned long cur = ra->size;
294 * On-demand readahead design.
296 * The fields in struct file_ra_state represent the most-recently-executed
299 * |<----- async_size ---------|
300 * |------------------- size -------------------->|
301 * |==================#===========================|
302 * ^start ^page marked with PG_readahead
304 * To overlap application thinking time and disk I/O time, we do
305 * `readahead pipelining': Do not wait until the application consumed all
306 * readahead pages and stalled on the missing page at readahead_index;
307 * Instead, submit an asynchronous readahead I/O as soon as there are
308 * only async_size pages left in the readahead window. Normally async_size
309 * will be equal to size, for maximum pipelining.
311 * In interleaved sequential reads, concurrent streams on the same fd can
312 * be invalidating each other's readahead state. So we flag the new readahead
313 * page at (start+size-async_size) with PG_readahead, and use it as readahead
314 * indicator. The flag won't be set on already cached pages, to avoid the
315 * readahead-for-nothing fuss, saving pointless page cache lookups.
317 * prev_pos tracks the last visited byte in the _previous_ read request.
318 * It should be maintained by the caller, and will be used for detecting
319 * small random reads. Note that the readahead algorithm checks loosely
320 * for sequential patterns. Hence interleaved reads might be served as
323 * There is a special-case: if the first page which the application tries to
324 * read happens to be the first page of the file, it is assumed that a linear
325 * read is about to happen and the window is immediately set to the initial size
326 * based on I/O request size and the max_readahead.
328 * The code ramps up the readahead size aggressively at first, but slow down as
329 * it approaches max_readhead.
333 * Count contiguously cached pages from @index-1 to @index-@max,
334 * this count is a conservative estimation of
335 * - length of the sequential read sequence, or
336 * - thrashing threshold in memory tight systems
338 static pgoff_t count_history_pages(struct address_space *mapping,
339 pgoff_t index, unsigned long max)
344 head = page_cache_prev_miss(mapping, index - 1, max);
347 return index - 1 - head;
351 * page cache context based read-ahead
353 static int try_context_readahead(struct address_space *mapping,
354 struct file_ra_state *ra,
356 unsigned long req_size,
361 size = count_history_pages(mapping, index, max);
364 * not enough history pages:
365 * it could be a random read
367 if (size <= req_size)
371 * starts from beginning of file:
372 * it is a strong indication of long-run stream (or whole-file-read)
378 ra->size = min(size + req_size, max);
385 * A minimal readahead algorithm for trivial sequential/random reads.
387 static void ondemand_readahead(struct address_space *mapping,
388 struct file_ra_state *ra, struct file *filp,
389 bool hit_readahead_marker, pgoff_t index,
390 unsigned long req_size)
392 struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
393 unsigned long max_pages = ra->ra_pages;
394 unsigned long add_pages;
398 * If the request exceeds the readahead window, allow the read to
399 * be up to the optimal hardware IO size
401 if (req_size > max_pages && bdi->io_pages > max_pages)
402 max_pages = min(req_size, bdi->io_pages);
408 goto initial_readahead;
411 * It's the expected callback index, assume sequential access.
412 * Ramp up sizes, and push forward the readahead window.
414 if ((index == (ra->start + ra->size - ra->async_size) ||
415 index == (ra->start + ra->size))) {
416 ra->start += ra->size;
417 ra->size = get_next_ra_size(ra, max_pages);
418 ra->async_size = ra->size;
423 * Hit a marked page without valid readahead state.
424 * E.g. interleaved reads.
425 * Query the pagecache for async_size, which normally equals to
426 * readahead size. Ramp it up and use it as the new readahead size.
428 if (hit_readahead_marker) {
432 start = page_cache_next_miss(mapping, index + 1, max_pages);
435 if (!start || start - index > max_pages)
439 ra->size = start - index; /* old async_size */
440 ra->size += req_size;
441 ra->size = get_next_ra_size(ra, max_pages);
442 ra->async_size = ra->size;
449 if (req_size > max_pages)
450 goto initial_readahead;
453 * sequential cache miss
454 * trivial case: (index - prev_index) == 1
455 * unaligned reads: (index - prev_index) == 0
457 prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
458 if (index - prev_index <= 1UL)
459 goto initial_readahead;
462 * Query the page cache and look for the traces(cached history pages)
463 * that a sequential stream would leave behind.
465 if (try_context_readahead(mapping, ra, index, req_size, max_pages))
469 * standalone, small random read
470 * Read as is, and do not pollute the readahead state.
472 __do_page_cache_readahead(mapping, filp, index, req_size, 0);
477 ra->size = get_init_ra_size(req_size, max_pages);
478 ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size;
482 * Will this read hit the readahead marker made by itself?
483 * If so, trigger the readahead marker hit now, and merge
484 * the resulted next readahead window into the current one.
485 * Take care of maximum IO pages as above.
487 if (index == ra->start && ra->size == ra->async_size) {
488 add_pages = get_next_ra_size(ra, max_pages);
489 if (ra->size + add_pages <= max_pages) {
490 ra->async_size = add_pages;
491 ra->size += add_pages;
493 ra->size = max_pages;
494 ra->async_size = max_pages >> 1;
498 ra_submit(ra, mapping, filp);
502 * page_cache_sync_readahead - generic file readahead
503 * @mapping: address_space which holds the pagecache and I/O vectors
504 * @ra: file_ra_state which holds the readahead state
505 * @filp: passed on to ->readpage() and ->readpages()
506 * @index: Index of first page to be read.
507 * @req_count: Total number of pages being read by the caller.
509 * page_cache_sync_readahead() should be called when a cache miss happened:
510 * it will submit the read. The readahead logic may decide to piggyback more
511 * pages onto the read request if access patterns suggest it will improve
514 void page_cache_sync_readahead(struct address_space *mapping,
515 struct file_ra_state *ra, struct file *filp,
516 pgoff_t index, unsigned long req_count)
522 if (blk_cgroup_congested())
526 if (filp && (filp->f_mode & FMODE_RANDOM)) {
527 force_page_cache_readahead(mapping, filp, index, req_count);
532 ondemand_readahead(mapping, ra, filp, false, index, req_count);
534 EXPORT_SYMBOL_GPL(page_cache_sync_readahead);
537 * page_cache_async_readahead - file readahead for marked pages
538 * @mapping: address_space which holds the pagecache and I/O vectors
539 * @ra: file_ra_state which holds the readahead state
540 * @filp: passed on to ->readpage() and ->readpages()
541 * @page: The page at @index which triggered the readahead call.
542 * @index: Index of first page to be read.
543 * @req_count: Total number of pages being read by the caller.
545 * page_cache_async_readahead() should be called when a page is used which
546 * is marked as PageReadahead; this is a marker to suggest that the application
547 * has used up enough of the readahead window that we should start pulling in
551 page_cache_async_readahead(struct address_space *mapping,
552 struct file_ra_state *ra, struct file *filp,
553 struct page *page, pgoff_t index,
554 unsigned long req_count)
561 * Same bit is used for PG_readahead and PG_reclaim.
563 if (PageWriteback(page))
566 ClearPageReadahead(page);
569 * Defer asynchronous read-ahead on IO congestion.
571 if (inode_read_congested(mapping->host))
574 if (blk_cgroup_congested())
578 ondemand_readahead(mapping, ra, filp, true, index, req_count);
580 EXPORT_SYMBOL_GPL(page_cache_async_readahead);
582 ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
589 if (!f.file || !(f.file->f_mode & FMODE_READ))
593 * The readahead() syscall is intended to run only on files
594 * that can execute readahead. If readahead is not possible
595 * on this file, then we must return -EINVAL.
598 if (!f.file->f_mapping || !f.file->f_mapping->a_ops ||
599 !S_ISREG(file_inode(f.file)->i_mode))
602 ret = vfs_fadvise(f.file, offset, count, POSIX_FADV_WILLNEED);
608 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
610 return ksys_readahead(fd, offset, count);