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;
170 LIST_HEAD(page_pool);
171 loff_t isize = i_size_read(inode);
172 gfp_t gfp_mask = readahead_gfp_mask(mapping);
173 struct readahead_control rac = {
179 pgoff_t end_index; /* The last page we want to read */
184 end_index = (isize - 1) >> PAGE_SHIFT;
185 if (index > end_index)
187 /* Don't read past the page containing the last byte of the file */
188 if (nr_to_read > end_index - index)
189 nr_to_read = end_index - index + 1;
192 * Preallocate as many pages as we will need.
194 for (i = 0; i < nr_to_read; i++) {
195 struct page *page = xa_load(&mapping->i_pages, index + i);
197 BUG_ON(index + i != rac._index + rac._nr_pages);
199 if (page && !xa_is_value(page)) {
201 * Page already present? Kick off the current batch of
202 * contiguous pages before continuing with the next
205 read_pages(&rac, &page_pool, true);
209 page = __page_cache_alloc(gfp_mask);
212 if (mapping->a_ops->readpages) {
213 page->index = index + i;
214 list_add(&page->lru, &page_pool);
215 } else if (add_to_page_cache_lru(page, mapping, index + i,
218 read_pages(&rac, &page_pool, true);
221 if (i == nr_to_read - lookahead_size)
222 SetPageReadahead(page);
227 * Now start the IO. We ignore I/O errors - if the page is not
228 * uptodate then the caller will launch readpage again, and
229 * will then handle the error.
231 read_pages(&rac, &page_pool, false);
235 * Chunk the readahead into 2 megabyte units, so that we don't pin too much
238 void force_page_cache_readahead(struct address_space *mapping,
239 struct file *filp, pgoff_t index, unsigned long nr_to_read)
241 struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
242 struct file_ra_state *ra = &filp->f_ra;
243 unsigned long max_pages;
245 if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages &&
246 !mapping->a_ops->readahead))
250 * If the request exceeds the readahead window, allow the read to
251 * be up to the optimal hardware IO size
253 max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
254 nr_to_read = min(nr_to_read, max_pages);
256 unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
258 if (this_chunk > nr_to_read)
259 this_chunk = nr_to_read;
260 __do_page_cache_readahead(mapping, filp, index, this_chunk, 0);
263 nr_to_read -= this_chunk;
268 * Set the initial window size, round to next power of 2 and square
269 * for small size, x 4 for medium, and x 2 for large
270 * for 128k (32 page) max ra
271 * 1-8 page = 32k initial, > 8 page = 128k initial
273 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
275 unsigned long newsize = roundup_pow_of_two(size);
277 if (newsize <= max / 32)
278 newsize = newsize * 4;
279 else if (newsize <= max / 4)
280 newsize = newsize * 2;
288 * Get the previous window size, ramp it up, and
289 * return it as the new window size.
291 static unsigned long get_next_ra_size(struct file_ra_state *ra,
294 unsigned long cur = ra->size;
304 * On-demand readahead design.
306 * The fields in struct file_ra_state represent the most-recently-executed
309 * |<----- async_size ---------|
310 * |------------------- size -------------------->|
311 * |==================#===========================|
312 * ^start ^page marked with PG_readahead
314 * To overlap application thinking time and disk I/O time, we do
315 * `readahead pipelining': Do not wait until the application consumed all
316 * readahead pages and stalled on the missing page at readahead_index;
317 * Instead, submit an asynchronous readahead I/O as soon as there are
318 * only async_size pages left in the readahead window. Normally async_size
319 * will be equal to size, for maximum pipelining.
321 * In interleaved sequential reads, concurrent streams on the same fd can
322 * be invalidating each other's readahead state. So we flag the new readahead
323 * page at (start+size-async_size) with PG_readahead, and use it as readahead
324 * indicator. The flag won't be set on already cached pages, to avoid the
325 * readahead-for-nothing fuss, saving pointless page cache lookups.
327 * prev_pos tracks the last visited byte in the _previous_ read request.
328 * It should be maintained by the caller, and will be used for detecting
329 * small random reads. Note that the readahead algorithm checks loosely
330 * for sequential patterns. Hence interleaved reads might be served as
333 * There is a special-case: if the first page which the application tries to
334 * read happens to be the first page of the file, it is assumed that a linear
335 * read is about to happen and the window is immediately set to the initial size
336 * based on I/O request size and the max_readahead.
338 * The code ramps up the readahead size aggressively at first, but slow down as
339 * it approaches max_readhead.
343 * Count contiguously cached pages from @index-1 to @index-@max,
344 * this count is a conservative estimation of
345 * - length of the sequential read sequence, or
346 * - thrashing threshold in memory tight systems
348 static pgoff_t count_history_pages(struct address_space *mapping,
349 pgoff_t index, unsigned long max)
354 head = page_cache_prev_miss(mapping, index - 1, max);
357 return index - 1 - head;
361 * page cache context based read-ahead
363 static int try_context_readahead(struct address_space *mapping,
364 struct file_ra_state *ra,
366 unsigned long req_size,
371 size = count_history_pages(mapping, index, max);
374 * not enough history pages:
375 * it could be a random read
377 if (size <= req_size)
381 * starts from beginning of file:
382 * it is a strong indication of long-run stream (or whole-file-read)
388 ra->size = min(size + req_size, max);
395 * A minimal readahead algorithm for trivial sequential/random reads.
397 static void ondemand_readahead(struct address_space *mapping,
398 struct file_ra_state *ra, struct file *filp,
399 bool hit_readahead_marker, pgoff_t index,
400 unsigned long req_size)
402 struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
403 unsigned long max_pages = ra->ra_pages;
404 unsigned long add_pages;
408 * If the request exceeds the readahead window, allow the read to
409 * be up to the optimal hardware IO size
411 if (req_size > max_pages && bdi->io_pages > max_pages)
412 max_pages = min(req_size, bdi->io_pages);
418 goto initial_readahead;
421 * It's the expected callback index, assume sequential access.
422 * Ramp up sizes, and push forward the readahead window.
424 if ((index == (ra->start + ra->size - ra->async_size) ||
425 index == (ra->start + ra->size))) {
426 ra->start += ra->size;
427 ra->size = get_next_ra_size(ra, max_pages);
428 ra->async_size = ra->size;
433 * Hit a marked page without valid readahead state.
434 * E.g. interleaved reads.
435 * Query the pagecache for async_size, which normally equals to
436 * readahead size. Ramp it up and use it as the new readahead size.
438 if (hit_readahead_marker) {
442 start = page_cache_next_miss(mapping, index + 1, max_pages);
445 if (!start || start - index > max_pages)
449 ra->size = start - index; /* old async_size */
450 ra->size += req_size;
451 ra->size = get_next_ra_size(ra, max_pages);
452 ra->async_size = ra->size;
459 if (req_size > max_pages)
460 goto initial_readahead;
463 * sequential cache miss
464 * trivial case: (index - prev_index) == 1
465 * unaligned reads: (index - prev_index) == 0
467 prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
468 if (index - prev_index <= 1UL)
469 goto initial_readahead;
472 * Query the page cache and look for the traces(cached history pages)
473 * that a sequential stream would leave behind.
475 if (try_context_readahead(mapping, ra, index, req_size, max_pages))
479 * standalone, small random read
480 * Read as is, and do not pollute the readahead state.
482 __do_page_cache_readahead(mapping, filp, index, req_size, 0);
487 ra->size = get_init_ra_size(req_size, max_pages);
488 ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size;
492 * Will this read hit the readahead marker made by itself?
493 * If so, trigger the readahead marker hit now, and merge
494 * the resulted next readahead window into the current one.
495 * Take care of maximum IO pages as above.
497 if (index == ra->start && ra->size == ra->async_size) {
498 add_pages = get_next_ra_size(ra, max_pages);
499 if (ra->size + add_pages <= max_pages) {
500 ra->async_size = add_pages;
501 ra->size += add_pages;
503 ra->size = max_pages;
504 ra->async_size = max_pages >> 1;
508 ra_submit(ra, mapping, filp);
512 * page_cache_sync_readahead - generic file readahead
513 * @mapping: address_space which holds the pagecache and I/O vectors
514 * @ra: file_ra_state which holds the readahead state
515 * @filp: passed on to ->readpage() and ->readpages()
516 * @index: Index of first page to be read.
517 * @req_count: Total number of pages being read by the caller.
519 * page_cache_sync_readahead() should be called when a cache miss happened:
520 * it will submit the read. The readahead logic may decide to piggyback more
521 * pages onto the read request if access patterns suggest it will improve
524 void page_cache_sync_readahead(struct address_space *mapping,
525 struct file_ra_state *ra, struct file *filp,
526 pgoff_t index, unsigned long req_count)
532 if (blk_cgroup_congested())
536 if (filp && (filp->f_mode & FMODE_RANDOM)) {
537 force_page_cache_readahead(mapping, filp, index, req_count);
542 ondemand_readahead(mapping, ra, filp, false, index, req_count);
544 EXPORT_SYMBOL_GPL(page_cache_sync_readahead);
547 * page_cache_async_readahead - file readahead for marked pages
548 * @mapping: address_space which holds the pagecache and I/O vectors
549 * @ra: file_ra_state which holds the readahead state
550 * @filp: passed on to ->readpage() and ->readpages()
551 * @page: The page at @index which triggered the readahead call.
552 * @index: Index of first page to be read.
553 * @req_count: Total number of pages being read by the caller.
555 * page_cache_async_readahead() should be called when a page is used which
556 * is marked as PageReadahead; this is a marker to suggest that the application
557 * has used up enough of the readahead window that we should start pulling in
561 page_cache_async_readahead(struct address_space *mapping,
562 struct file_ra_state *ra, struct file *filp,
563 struct page *page, pgoff_t index,
564 unsigned long req_count)
571 * Same bit is used for PG_readahead and PG_reclaim.
573 if (PageWriteback(page))
576 ClearPageReadahead(page);
579 * Defer asynchronous read-ahead on IO congestion.
581 if (inode_read_congested(mapping->host))
584 if (blk_cgroup_congested())
588 ondemand_readahead(mapping, ra, filp, true, index, req_count);
590 EXPORT_SYMBOL_GPL(page_cache_async_readahead);
592 ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
599 if (!f.file || !(f.file->f_mode & FMODE_READ))
603 * The readahead() syscall is intended to run only on files
604 * that can execute readahead. If readahead is not possible
605 * on this file, then we must return -EINVAL.
608 if (!f.file->f_mapping || !f.file->f_mapping->a_ops ||
609 !S_ISREG(file_inode(f.file)->i_mode))
612 ret = vfs_fadvise(f.file, offset, count, POSIX_FADV_WILLNEED);
618 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
620 return ksys_readahead(fd, offset, count);