xref: /openbmc/linux/mm/readahead.c (revision 22a41e9a5044bf3519f05b4a00e99af34bfeb40c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * mm/readahead.c - address_space-level file readahead.
4  *
5  * Copyright (C) 2002, Linus Torvalds
6  *
7  * 09Apr2002	Andrew Morton
8  *		Initial version.
9  */
10 
11 /**
12  * DOC: Readahead Overview
13  *
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.
19  *
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.
26  *
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.
35  *
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.
39  *
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.
43  *
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
48  * PAGE.
49  *
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.
60  *
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.
67  *
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.
72  *
73  * The above calculation determines the readahead, to which any requested
74  * read size may be added.
75  *
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.
83  *
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
86  * page by:
87  *
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.
91  *
92  * * failing to actually submit a read request for a given page,
93  *   possibly due to insufficient resources, or
94  *
95  * * getting an error during subsequent processing of a request.
96  *
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.
100  *
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
112  * ->readpage().
113  *
114  */
115 
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>
130 
131 #include "internal.h"
132 
133 /*
134  * Initialise a struct file's readahead state.  Assumes that the caller has
135  * memset *ra to zero.
136  */
137 void
138 file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
139 {
140 	ra->ra_pages = inode_to_bdi(mapping->host)->ra_pages;
141 	ra->prev_pos = -1;
142 }
143 EXPORT_SYMBOL_GPL(file_ra_state_init);
144 
145 /*
146  * see if a page needs releasing upon read_cache_pages() failure
147  * - the caller of read_cache_pages() may have set PG_private or PG_fscache
148  *   before calling, such as the NFS fs marking pages that are cached locally
149  *   on disk, thus we need to give the fs a chance to clean up in the event of
150  *   an error
151  */
152 static void read_cache_pages_invalidate_page(struct address_space *mapping,
153 					     struct page *page)
154 {
155 	if (page_has_private(page)) {
156 		if (!trylock_page(page))
157 			BUG();
158 		page->mapping = mapping;
159 		folio_invalidate(page_folio(page), 0, PAGE_SIZE);
160 		page->mapping = NULL;
161 		unlock_page(page);
162 	}
163 	put_page(page);
164 }
165 
166 /*
167  * release a list of pages, invalidating them first if need be
168  */
169 static void read_cache_pages_invalidate_pages(struct address_space *mapping,
170 					      struct list_head *pages)
171 {
172 	struct page *victim;
173 
174 	while (!list_empty(pages)) {
175 		victim = lru_to_page(pages);
176 		list_del(&victim->lru);
177 		read_cache_pages_invalidate_page(mapping, victim);
178 	}
179 }
180 
181 /**
182  * read_cache_pages - populate an address space with some pages & start reads against them
183  * @mapping: the address_space
184  * @pages: The address of a list_head which contains the target pages.  These
185  *   pages have their ->index populated and are otherwise uninitialised.
186  * @filler: callback routine for filling a single page.
187  * @data: private data for the callback routine.
188  *
189  * Hides the details of the LRU cache etc from the filesystems.
190  *
191  * Returns: %0 on success, error return by @filler otherwise
192  */
193 int read_cache_pages(struct address_space *mapping, struct list_head *pages,
194 			int (*filler)(void *, struct page *), void *data)
195 {
196 	struct page *page;
197 	int ret = 0;
198 
199 	while (!list_empty(pages)) {
200 		page = lru_to_page(pages);
201 		list_del(&page->lru);
202 		if (add_to_page_cache_lru(page, mapping, page->index,
203 				readahead_gfp_mask(mapping))) {
204 			read_cache_pages_invalidate_page(mapping, page);
205 			continue;
206 		}
207 		put_page(page);
208 
209 		ret = filler(data, page);
210 		if (unlikely(ret)) {
211 			read_cache_pages_invalidate_pages(mapping, pages);
212 			break;
213 		}
214 		task_io_account_read(PAGE_SIZE);
215 	}
216 	return ret;
217 }
218 
219 EXPORT_SYMBOL(read_cache_pages);
220 
221 static void read_pages(struct readahead_control *rac, struct list_head *pages,
222 		bool skip_page)
223 {
224 	const struct address_space_operations *aops = rac->mapping->a_ops;
225 	struct page *page;
226 	struct blk_plug plug;
227 
228 	if (!readahead_count(rac))
229 		goto out;
230 
231 	blk_start_plug(&plug);
232 
233 	if (aops->readahead) {
234 		aops->readahead(rac);
235 		/*
236 		 * Clean up the remaining pages.  The sizes in ->ra
237 		 * maybe be used to size next read-ahead, so make sure
238 		 * they accurately reflect what happened.
239 		 */
240 		while ((page = readahead_page(rac))) {
241 			rac->ra->size -= 1;
242 			if (rac->ra->async_size > 0) {
243 				rac->ra->async_size -= 1;
244 				delete_from_page_cache(page);
245 			}
246 			unlock_page(page);
247 			put_page(page);
248 		}
249 	} else if (aops->readpages) {
250 		aops->readpages(rac->file, rac->mapping, pages,
251 				readahead_count(rac));
252 		/* Clean up the remaining pages */
253 		put_pages_list(pages);
254 		rac->_index += rac->_nr_pages;
255 		rac->_nr_pages = 0;
256 	} else {
257 		while ((page = readahead_page(rac))) {
258 			aops->readpage(rac->file, page);
259 			put_page(page);
260 		}
261 	}
262 
263 	blk_finish_plug(&plug);
264 
265 	BUG_ON(pages && !list_empty(pages));
266 	BUG_ON(readahead_count(rac));
267 
268 out:
269 	if (skip_page)
270 		rac->_index++;
271 }
272 
273 /**
274  * page_cache_ra_unbounded - Start unchecked readahead.
275  * @ractl: Readahead control.
276  * @nr_to_read: The number of pages to read.
277  * @lookahead_size: Where to start the next readahead.
278  *
279  * This function is for filesystems to call when they want to start
280  * readahead beyond a file's stated i_size.  This is almost certainly
281  * not the function you want to call.  Use page_cache_async_readahead()
282  * or page_cache_sync_readahead() instead.
283  *
284  * Context: File is referenced by caller.  Mutexes may be held by caller.
285  * May sleep, but will not reenter filesystem to reclaim memory.
286  */
287 void page_cache_ra_unbounded(struct readahead_control *ractl,
288 		unsigned long nr_to_read, unsigned long lookahead_size)
289 {
290 	struct address_space *mapping = ractl->mapping;
291 	unsigned long index = readahead_index(ractl);
292 	LIST_HEAD(page_pool);
293 	gfp_t gfp_mask = readahead_gfp_mask(mapping);
294 	unsigned long i;
295 
296 	/*
297 	 * Partway through the readahead operation, we will have added
298 	 * locked pages to the page cache, but will not yet have submitted
299 	 * them for I/O.  Adding another page may need to allocate memory,
300 	 * which can trigger memory reclaim.  Telling the VM we're in
301 	 * the middle of a filesystem operation will cause it to not
302 	 * touch file-backed pages, preventing a deadlock.  Most (all?)
303 	 * filesystems already specify __GFP_NOFS in their mapping's
304 	 * gfp_mask, but let's be explicit here.
305 	 */
306 	unsigned int nofs = memalloc_nofs_save();
307 
308 	filemap_invalidate_lock_shared(mapping);
309 	/*
310 	 * Preallocate as many pages as we will need.
311 	 */
312 	for (i = 0; i < nr_to_read; i++) {
313 		struct folio *folio = xa_load(&mapping->i_pages, index + i);
314 
315 		if (folio && !xa_is_value(folio)) {
316 			/*
317 			 * Page already present?  Kick off the current batch
318 			 * of contiguous pages before continuing with the
319 			 * next batch.  This page may be the one we would
320 			 * have intended to mark as Readahead, but we don't
321 			 * have a stable reference to this page, and it's
322 			 * not worth getting one just for that.
323 			 */
324 			read_pages(ractl, &page_pool, true);
325 			i = ractl->_index + ractl->_nr_pages - index - 1;
326 			continue;
327 		}
328 
329 		folio = filemap_alloc_folio(gfp_mask, 0);
330 		if (!folio)
331 			break;
332 		if (mapping->a_ops->readpages) {
333 			folio->index = index + i;
334 			list_add(&folio->lru, &page_pool);
335 		} else if (filemap_add_folio(mapping, folio, index + i,
336 					gfp_mask) < 0) {
337 			folio_put(folio);
338 			read_pages(ractl, &page_pool, true);
339 			i = ractl->_index + ractl->_nr_pages - index - 1;
340 			continue;
341 		}
342 		if (i == nr_to_read - lookahead_size)
343 			folio_set_readahead(folio);
344 		ractl->_nr_pages++;
345 	}
346 
347 	/*
348 	 * Now start the IO.  We ignore I/O errors - if the page is not
349 	 * uptodate then the caller will launch readpage again, and
350 	 * will then handle the error.
351 	 */
352 	read_pages(ractl, &page_pool, false);
353 	filemap_invalidate_unlock_shared(mapping);
354 	memalloc_nofs_restore(nofs);
355 }
356 EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
357 
358 /*
359  * do_page_cache_ra() actually reads a chunk of disk.  It allocates
360  * the pages first, then submits them for I/O. This avoids the very bad
361  * behaviour which would occur if page allocations are causing VM writeback.
362  * We really don't want to intermingle reads and writes like that.
363  */
364 static void do_page_cache_ra(struct readahead_control *ractl,
365 		unsigned long nr_to_read, unsigned long lookahead_size)
366 {
367 	struct inode *inode = ractl->mapping->host;
368 	unsigned long index = readahead_index(ractl);
369 	loff_t isize = i_size_read(inode);
370 	pgoff_t end_index;	/* The last page we want to read */
371 
372 	if (isize == 0)
373 		return;
374 
375 	end_index = (isize - 1) >> PAGE_SHIFT;
376 	if (index > end_index)
377 		return;
378 	/* Don't read past the page containing the last byte of the file */
379 	if (nr_to_read > end_index - index)
380 		nr_to_read = end_index - index + 1;
381 
382 	page_cache_ra_unbounded(ractl, nr_to_read, lookahead_size);
383 }
384 
385 /*
386  * Chunk the readahead into 2 megabyte units, so that we don't pin too much
387  * memory at once.
388  */
389 void force_page_cache_ra(struct readahead_control *ractl,
390 		unsigned long nr_to_read)
391 {
392 	struct address_space *mapping = ractl->mapping;
393 	struct file_ra_state *ra = ractl->ra;
394 	struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
395 	unsigned long max_pages, index;
396 
397 	if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages &&
398 			!mapping->a_ops->readahead))
399 		return;
400 
401 	/*
402 	 * If the request exceeds the readahead window, allow the read to
403 	 * be up to the optimal hardware IO size
404 	 */
405 	index = readahead_index(ractl);
406 	max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
407 	nr_to_read = min_t(unsigned long, nr_to_read, max_pages);
408 	while (nr_to_read) {
409 		unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
410 
411 		if (this_chunk > nr_to_read)
412 			this_chunk = nr_to_read;
413 		ractl->_index = index;
414 		do_page_cache_ra(ractl, this_chunk, 0);
415 
416 		index += this_chunk;
417 		nr_to_read -= this_chunk;
418 	}
419 }
420 
421 /*
422  * Set the initial window size, round to next power of 2 and square
423  * for small size, x 4 for medium, and x 2 for large
424  * for 128k (32 page) max ra
425  * 1-2 page = 16k, 3-4 page 32k, 5-8 page = 64k, > 8 page = 128k initial
426  */
427 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
428 {
429 	unsigned long newsize = roundup_pow_of_two(size);
430 
431 	if (newsize <= max / 32)
432 		newsize = newsize * 4;
433 	else if (newsize <= max / 4)
434 		newsize = newsize * 2;
435 	else
436 		newsize = max;
437 
438 	return newsize;
439 }
440 
441 /*
442  *  Get the previous window size, ramp it up, and
443  *  return it as the new window size.
444  */
445 static unsigned long get_next_ra_size(struct file_ra_state *ra,
446 				      unsigned long max)
447 {
448 	unsigned long cur = ra->size;
449 
450 	if (cur < max / 16)
451 		return 4 * cur;
452 	if (cur <= max / 2)
453 		return 2 * cur;
454 	return max;
455 }
456 
457 /*
458  * On-demand readahead design.
459  *
460  * The fields in struct file_ra_state represent the most-recently-executed
461  * readahead attempt:
462  *
463  *                        |<----- async_size ---------|
464  *     |------------------- size -------------------->|
465  *     |==================#===========================|
466  *     ^start             ^page marked with PG_readahead
467  *
468  * To overlap application thinking time and disk I/O time, we do
469  * `readahead pipelining': Do not wait until the application consumed all
470  * readahead pages and stalled on the missing page at readahead_index;
471  * Instead, submit an asynchronous readahead I/O as soon as there are
472  * only async_size pages left in the readahead window. Normally async_size
473  * will be equal to size, for maximum pipelining.
474  *
475  * In interleaved sequential reads, concurrent streams on the same fd can
476  * be invalidating each other's readahead state. So we flag the new readahead
477  * page at (start+size-async_size) with PG_readahead, and use it as readahead
478  * indicator. The flag won't be set on already cached pages, to avoid the
479  * readahead-for-nothing fuss, saving pointless page cache lookups.
480  *
481  * prev_pos tracks the last visited byte in the _previous_ read request.
482  * It should be maintained by the caller, and will be used for detecting
483  * small random reads. Note that the readahead algorithm checks loosely
484  * for sequential patterns. Hence interleaved reads might be served as
485  * sequential ones.
486  *
487  * There is a special-case: if the first page which the application tries to
488  * read happens to be the first page of the file, it is assumed that a linear
489  * read is about to happen and the window is immediately set to the initial size
490  * based on I/O request size and the max_readahead.
491  *
492  * The code ramps up the readahead size aggressively at first, but slow down as
493  * it approaches max_readhead.
494  */
495 
496 /*
497  * Count contiguously cached pages from @index-1 to @index-@max,
498  * this count is a conservative estimation of
499  * 	- length of the sequential read sequence, or
500  * 	- thrashing threshold in memory tight systems
501  */
502 static pgoff_t count_history_pages(struct address_space *mapping,
503 				   pgoff_t index, unsigned long max)
504 {
505 	pgoff_t head;
506 
507 	rcu_read_lock();
508 	head = page_cache_prev_miss(mapping, index - 1, max);
509 	rcu_read_unlock();
510 
511 	return index - 1 - head;
512 }
513 
514 /*
515  * page cache context based read-ahead
516  */
517 static int try_context_readahead(struct address_space *mapping,
518 				 struct file_ra_state *ra,
519 				 pgoff_t index,
520 				 unsigned long req_size,
521 				 unsigned long max)
522 {
523 	pgoff_t size;
524 
525 	size = count_history_pages(mapping, index, max);
526 
527 	/*
528 	 * not enough history pages:
529 	 * it could be a random read
530 	 */
531 	if (size <= req_size)
532 		return 0;
533 
534 	/*
535 	 * starts from beginning of file:
536 	 * it is a strong indication of long-run stream (or whole-file-read)
537 	 */
538 	if (size >= index)
539 		size *= 2;
540 
541 	ra->start = index;
542 	ra->size = min(size + req_size, max);
543 	ra->async_size = 1;
544 
545 	return 1;
546 }
547 
548 /*
549  * There are some parts of the kernel which assume that PMD entries
550  * are exactly HPAGE_PMD_ORDER.  Those should be fixed, but until then,
551  * limit the maximum allocation order to PMD size.  I'm not aware of any
552  * assumptions about maximum order if THP are disabled, but 8 seems like
553  * a good order (that's 1MB if you're using 4kB pages)
554  */
555 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
556 #define MAX_PAGECACHE_ORDER	HPAGE_PMD_ORDER
557 #else
558 #define MAX_PAGECACHE_ORDER	8
559 #endif
560 
561 static inline int ra_alloc_folio(struct readahead_control *ractl, pgoff_t index,
562 		pgoff_t mark, unsigned int order, gfp_t gfp)
563 {
564 	int err;
565 	struct folio *folio = filemap_alloc_folio(gfp, order);
566 
567 	if (!folio)
568 		return -ENOMEM;
569 	if (mark - index < (1UL << order))
570 		folio_set_readahead(folio);
571 	err = filemap_add_folio(ractl->mapping, folio, index, gfp);
572 	if (err)
573 		folio_put(folio);
574 	else
575 		ractl->_nr_pages += 1UL << order;
576 	return err;
577 }
578 
579 void page_cache_ra_order(struct readahead_control *ractl,
580 		struct file_ra_state *ra, unsigned int new_order)
581 {
582 	struct address_space *mapping = ractl->mapping;
583 	pgoff_t index = readahead_index(ractl);
584 	pgoff_t limit = (i_size_read(mapping->host) - 1) >> PAGE_SHIFT;
585 	pgoff_t mark = index + ra->size - ra->async_size;
586 	int err = 0;
587 	gfp_t gfp = readahead_gfp_mask(mapping);
588 
589 	if (!mapping_large_folio_support(mapping) || ra->size < 4)
590 		goto fallback;
591 
592 	limit = min(limit, index + ra->size - 1);
593 
594 	if (new_order < MAX_PAGECACHE_ORDER) {
595 		new_order += 2;
596 		if (new_order > MAX_PAGECACHE_ORDER)
597 			new_order = MAX_PAGECACHE_ORDER;
598 		while ((1 << new_order) > ra->size)
599 			new_order--;
600 	}
601 
602 	while (index <= limit) {
603 		unsigned int order = new_order;
604 
605 		/* Align with smaller pages if needed */
606 		if (index & ((1UL << order) - 1)) {
607 			order = __ffs(index);
608 			if (order == 1)
609 				order = 0;
610 		}
611 		/* Don't allocate pages past EOF */
612 		while (index + (1UL << order) - 1 > limit) {
613 			if (--order == 1)
614 				order = 0;
615 		}
616 		err = ra_alloc_folio(ractl, index, mark, order, gfp);
617 		if (err)
618 			break;
619 		index += 1UL << order;
620 	}
621 
622 	if (index > limit) {
623 		ra->size += index - limit - 1;
624 		ra->async_size += index - limit - 1;
625 	}
626 
627 	read_pages(ractl, NULL, false);
628 
629 	/*
630 	 * If there were already pages in the page cache, then we may have
631 	 * left some gaps.  Let the regular readahead code take care of this
632 	 * situation.
633 	 */
634 	if (!err)
635 		return;
636 fallback:
637 	do_page_cache_ra(ractl, ra->size, ra->async_size);
638 }
639 
640 /*
641  * A minimal readahead algorithm for trivial sequential/random reads.
642  */
643 static void ondemand_readahead(struct readahead_control *ractl,
644 		struct folio *folio, unsigned long req_size)
645 {
646 	struct backing_dev_info *bdi = inode_to_bdi(ractl->mapping->host);
647 	struct file_ra_state *ra = ractl->ra;
648 	unsigned long max_pages = ra->ra_pages;
649 	unsigned long add_pages;
650 	unsigned long index = readahead_index(ractl);
651 	pgoff_t prev_index;
652 
653 	/*
654 	 * If the request exceeds the readahead window, allow the read to
655 	 * be up to the optimal hardware IO size
656 	 */
657 	if (req_size > max_pages && bdi->io_pages > max_pages)
658 		max_pages = min(req_size, bdi->io_pages);
659 
660 	/*
661 	 * start of file
662 	 */
663 	if (!index)
664 		goto initial_readahead;
665 
666 	/*
667 	 * It's the expected callback index, assume sequential access.
668 	 * Ramp up sizes, and push forward the readahead window.
669 	 */
670 	if ((index == (ra->start + ra->size - ra->async_size) ||
671 	     index == (ra->start + ra->size))) {
672 		ra->start += ra->size;
673 		ra->size = get_next_ra_size(ra, max_pages);
674 		ra->async_size = ra->size;
675 		goto readit;
676 	}
677 
678 	/*
679 	 * Hit a marked folio without valid readahead state.
680 	 * E.g. interleaved reads.
681 	 * Query the pagecache for async_size, which normally equals to
682 	 * readahead size. Ramp it up and use it as the new readahead size.
683 	 */
684 	if (folio) {
685 		pgoff_t start;
686 
687 		rcu_read_lock();
688 		start = page_cache_next_miss(ractl->mapping, index + 1,
689 				max_pages);
690 		rcu_read_unlock();
691 
692 		if (!start || start - index > max_pages)
693 			return;
694 
695 		ra->start = start;
696 		ra->size = start - index;	/* old async_size */
697 		ra->size += req_size;
698 		ra->size = get_next_ra_size(ra, max_pages);
699 		ra->async_size = ra->size;
700 		goto readit;
701 	}
702 
703 	/*
704 	 * oversize read
705 	 */
706 	if (req_size > max_pages)
707 		goto initial_readahead;
708 
709 	/*
710 	 * sequential cache miss
711 	 * trivial case: (index - prev_index) == 1
712 	 * unaligned reads: (index - prev_index) == 0
713 	 */
714 	prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
715 	if (index - prev_index <= 1UL)
716 		goto initial_readahead;
717 
718 	/*
719 	 * Query the page cache and look for the traces(cached history pages)
720 	 * that a sequential stream would leave behind.
721 	 */
722 	if (try_context_readahead(ractl->mapping, ra, index, req_size,
723 			max_pages))
724 		goto readit;
725 
726 	/*
727 	 * standalone, small random read
728 	 * Read as is, and do not pollute the readahead state.
729 	 */
730 	do_page_cache_ra(ractl, req_size, 0);
731 	return;
732 
733 initial_readahead:
734 	ra->start = index;
735 	ra->size = get_init_ra_size(req_size, max_pages);
736 	ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size;
737 
738 readit:
739 	/*
740 	 * Will this read hit the readahead marker made by itself?
741 	 * If so, trigger the readahead marker hit now, and merge
742 	 * the resulted next readahead window into the current one.
743 	 * Take care of maximum IO pages as above.
744 	 */
745 	if (index == ra->start && ra->size == ra->async_size) {
746 		add_pages = get_next_ra_size(ra, max_pages);
747 		if (ra->size + add_pages <= max_pages) {
748 			ra->async_size = add_pages;
749 			ra->size += add_pages;
750 		} else {
751 			ra->size = max_pages;
752 			ra->async_size = max_pages >> 1;
753 		}
754 	}
755 
756 	ractl->_index = ra->start;
757 	page_cache_ra_order(ractl, ra, folio ? folio_order(folio) : 0);
758 }
759 
760 void page_cache_sync_ra(struct readahead_control *ractl,
761 		unsigned long req_count)
762 {
763 	bool do_forced_ra = ractl->file && (ractl->file->f_mode & FMODE_RANDOM);
764 
765 	/*
766 	 * Even if read-ahead is disabled, issue this request as read-ahead
767 	 * as we'll need it to satisfy the requested range. The forced
768 	 * read-ahead will do the right thing and limit the read to just the
769 	 * requested range, which we'll set to 1 page for this case.
770 	 */
771 	if (!ractl->ra->ra_pages || blk_cgroup_congested()) {
772 		if (!ractl->file)
773 			return;
774 		req_count = 1;
775 		do_forced_ra = true;
776 	}
777 
778 	/* be dumb */
779 	if (do_forced_ra) {
780 		force_page_cache_ra(ractl, req_count);
781 		return;
782 	}
783 
784 	/* do read-ahead */
785 	ondemand_readahead(ractl, NULL, req_count);
786 }
787 EXPORT_SYMBOL_GPL(page_cache_sync_ra);
788 
789 void page_cache_async_ra(struct readahead_control *ractl,
790 		struct folio *folio, unsigned long req_count)
791 {
792 	/* no read-ahead */
793 	if (!ractl->ra->ra_pages)
794 		return;
795 
796 	/*
797 	 * Same bit is used for PG_readahead and PG_reclaim.
798 	 */
799 	if (folio_test_writeback(folio))
800 		return;
801 
802 	folio_clear_readahead(folio);
803 
804 	if (blk_cgroup_congested())
805 		return;
806 
807 	/* do read-ahead */
808 	ondemand_readahead(ractl, folio, req_count);
809 }
810 EXPORT_SYMBOL_GPL(page_cache_async_ra);
811 
812 ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
813 {
814 	ssize_t ret;
815 	struct fd f;
816 
817 	ret = -EBADF;
818 	f = fdget(fd);
819 	if (!f.file || !(f.file->f_mode & FMODE_READ))
820 		goto out;
821 
822 	/*
823 	 * The readahead() syscall is intended to run only on files
824 	 * that can execute readahead. If readahead is not possible
825 	 * on this file, then we must return -EINVAL.
826 	 */
827 	ret = -EINVAL;
828 	if (!f.file->f_mapping || !f.file->f_mapping->a_ops ||
829 	    !S_ISREG(file_inode(f.file)->i_mode))
830 		goto out;
831 
832 	ret = vfs_fadvise(f.file, offset, count, POSIX_FADV_WILLNEED);
833 out:
834 	fdput(f);
835 	return ret;
836 }
837 
838 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
839 {
840 	return ksys_readahead(fd, offset, count);
841 }
842 
843 /**
844  * readahead_expand - Expand a readahead request
845  * @ractl: The request to be expanded
846  * @new_start: The revised start
847  * @new_len: The revised size of the request
848  *
849  * Attempt to expand a readahead request outwards from the current size to the
850  * specified size by inserting locked pages before and after the current window
851  * to increase the size to the new window.  This may involve the insertion of
852  * THPs, in which case the window may get expanded even beyond what was
853  * requested.
854  *
855  * The algorithm will stop if it encounters a conflicting page already in the
856  * pagecache and leave a smaller expansion than requested.
857  *
858  * The caller must check for this by examining the revised @ractl object for a
859  * different expansion than was requested.
860  */
861 void readahead_expand(struct readahead_control *ractl,
862 		      loff_t new_start, size_t new_len)
863 {
864 	struct address_space *mapping = ractl->mapping;
865 	struct file_ra_state *ra = ractl->ra;
866 	pgoff_t new_index, new_nr_pages;
867 	gfp_t gfp_mask = readahead_gfp_mask(mapping);
868 
869 	new_index = new_start / PAGE_SIZE;
870 
871 	/* Expand the leading edge downwards */
872 	while (ractl->_index > new_index) {
873 		unsigned long index = ractl->_index - 1;
874 		struct page *page = xa_load(&mapping->i_pages, index);
875 
876 		if (page && !xa_is_value(page))
877 			return; /* Page apparently present */
878 
879 		page = __page_cache_alloc(gfp_mask);
880 		if (!page)
881 			return;
882 		if (add_to_page_cache_lru(page, mapping, index, gfp_mask) < 0) {
883 			put_page(page);
884 			return;
885 		}
886 
887 		ractl->_nr_pages++;
888 		ractl->_index = page->index;
889 	}
890 
891 	new_len += new_start - readahead_pos(ractl);
892 	new_nr_pages = DIV_ROUND_UP(new_len, PAGE_SIZE);
893 
894 	/* Expand the trailing edge upwards */
895 	while (ractl->_nr_pages < new_nr_pages) {
896 		unsigned long index = ractl->_index + ractl->_nr_pages;
897 		struct page *page = xa_load(&mapping->i_pages, index);
898 
899 		if (page && !xa_is_value(page))
900 			return; /* Page apparently present */
901 
902 		page = __page_cache_alloc(gfp_mask);
903 		if (!page)
904 			return;
905 		if (add_to_page_cache_lru(page, mapping, index, gfp_mask) < 0) {
906 			put_page(page);
907 			return;
908 		}
909 		ractl->_nr_pages++;
910 		if (ra) {
911 			ra->size++;
912 			ra->async_size++;
913 		}
914 	}
915 }
916 EXPORT_SYMBOL(readahead_expand);
917