readahead: Remove read_cache_pages()
[linux-2.6-microblaze.git] / mm / readahead.c
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 static void read_pages(struct readahead_control *rac, struct list_head *pages,
146                 bool skip_page)
147 {
148         const struct address_space_operations *aops = rac->mapping->a_ops;
149         struct page *page;
150         struct blk_plug plug;
151
152         if (!readahead_count(rac))
153                 goto out;
154
155         blk_start_plug(&plug);
156
157         if (aops->readahead) {
158                 aops->readahead(rac);
159                 /*
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.
163                  */
164                 while ((page = readahead_page(rac))) {
165                         rac->ra->size -= 1;
166                         if (rac->ra->async_size > 0) {
167                                 rac->ra->async_size -= 1;
168                                 delete_from_page_cache(page);
169                         }
170                         unlock_page(page);
171                         put_page(page);
172                 }
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;
179                 rac->_nr_pages = 0;
180         } else {
181                 while ((page = readahead_page(rac))) {
182                         aops->readpage(rac->file, page);
183                         put_page(page);
184                 }
185         }
186
187         blk_finish_plug(&plug);
188
189         BUG_ON(pages && !list_empty(pages));
190         BUG_ON(readahead_count(rac));
191
192 out:
193         if (skip_page)
194                 rac->_index++;
195 }
196
197 /**
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.
202  *
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.
207  *
208  * Context: File is referenced by caller.  Mutexes may be held by caller.
209  * May sleep, but will not reenter filesystem to reclaim memory.
210  */
211 void page_cache_ra_unbounded(struct readahead_control *ractl,
212                 unsigned long nr_to_read, unsigned long lookahead_size)
213 {
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);
218         unsigned long i;
219
220         /*
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.
229          */
230         unsigned int nofs = memalloc_nofs_save();
231
232         filemap_invalidate_lock_shared(mapping);
233         /*
234          * Preallocate as many pages as we will need.
235          */
236         for (i = 0; i < nr_to_read; i++) {
237                 struct folio *folio = xa_load(&mapping->i_pages, index + i);
238
239                 if (folio && !xa_is_value(folio)) {
240                         /*
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.
247                          */
248                         read_pages(ractl, &page_pool, true);
249                         i = ractl->_index + ractl->_nr_pages - index - 1;
250                         continue;
251                 }
252
253                 folio = filemap_alloc_folio(gfp_mask, 0);
254                 if (!folio)
255                         break;
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,
260                                         gfp_mask) < 0) {
261                         folio_put(folio);
262                         read_pages(ractl, &page_pool, true);
263                         i = ractl->_index + ractl->_nr_pages - index - 1;
264                         continue;
265                 }
266                 if (i == nr_to_read - lookahead_size)
267                         folio_set_readahead(folio);
268                 ractl->_nr_pages++;
269         }
270
271         /*
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.
275          */
276         read_pages(ractl, &page_pool, false);
277         filemap_invalidate_unlock_shared(mapping);
278         memalloc_nofs_restore(nofs);
279 }
280 EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
281
282 /*
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.
287  */
288 static void do_page_cache_ra(struct readahead_control *ractl,
289                 unsigned long nr_to_read, unsigned long lookahead_size)
290 {
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 */
295
296         if (isize == 0)
297                 return;
298
299         end_index = (isize - 1) >> PAGE_SHIFT;
300         if (index > end_index)
301                 return;
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;
305
306         page_cache_ra_unbounded(ractl, nr_to_read, lookahead_size);
307 }
308
309 /*
310  * Chunk the readahead into 2 megabyte units, so that we don't pin too much
311  * memory at once.
312  */
313 void force_page_cache_ra(struct readahead_control *ractl,
314                 unsigned long nr_to_read)
315 {
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;
320
321         if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages &&
322                         !mapping->a_ops->readahead))
323                 return;
324
325         /*
326          * If the request exceeds the readahead window, allow the read to
327          * be up to the optimal hardware IO size
328          */
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);
332         while (nr_to_read) {
333                 unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
334
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);
339
340                 index += this_chunk;
341                 nr_to_read -= this_chunk;
342         }
343 }
344
345 /*
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
350  */
351 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
352 {
353         unsigned long newsize = roundup_pow_of_two(size);
354
355         if (newsize <= max / 32)
356                 newsize = newsize * 4;
357         else if (newsize <= max / 4)
358                 newsize = newsize * 2;
359         else
360                 newsize = max;
361
362         return newsize;
363 }
364
365 /*
366  *  Get the previous window size, ramp it up, and
367  *  return it as the new window size.
368  */
369 static unsigned long get_next_ra_size(struct file_ra_state *ra,
370                                       unsigned long max)
371 {
372         unsigned long cur = ra->size;
373
374         if (cur < max / 16)
375                 return 4 * cur;
376         if (cur <= max / 2)
377                 return 2 * cur;
378         return max;
379 }
380
381 /*
382  * On-demand readahead design.
383  *
384  * The fields in struct file_ra_state represent the most-recently-executed
385  * readahead attempt:
386  *
387  *                        |<----- async_size ---------|
388  *     |------------------- size -------------------->|
389  *     |==================#===========================|
390  *     ^start             ^page marked with PG_readahead
391  *
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.
398  *
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.
404  *
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
409  * sequential ones.
410  *
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.
415  *
416  * The code ramps up the readahead size aggressively at first, but slow down as
417  * it approaches max_readhead.
418  */
419
420 /*
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
425  */
426 static pgoff_t count_history_pages(struct address_space *mapping,
427                                    pgoff_t index, unsigned long max)
428 {
429         pgoff_t head;
430
431         rcu_read_lock();
432         head = page_cache_prev_miss(mapping, index - 1, max);
433         rcu_read_unlock();
434
435         return index - 1 - head;
436 }
437
438 /*
439  * page cache context based read-ahead
440  */
441 static int try_context_readahead(struct address_space *mapping,
442                                  struct file_ra_state *ra,
443                                  pgoff_t index,
444                                  unsigned long req_size,
445                                  unsigned long max)
446 {
447         pgoff_t size;
448
449         size = count_history_pages(mapping, index, max);
450
451         /*
452          * not enough history pages:
453          * it could be a random read
454          */
455         if (size <= req_size)
456                 return 0;
457
458         /*
459          * starts from beginning of file:
460          * it is a strong indication of long-run stream (or whole-file-read)
461          */
462         if (size >= index)
463                 size *= 2;
464
465         ra->start = index;
466         ra->size = min(size + req_size, max);
467         ra->async_size = 1;
468
469         return 1;
470 }
471
472 /*
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)
478  */
479 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
480 #define MAX_PAGECACHE_ORDER     HPAGE_PMD_ORDER
481 #else
482 #define MAX_PAGECACHE_ORDER     8
483 #endif
484
485 static inline int ra_alloc_folio(struct readahead_control *ractl, pgoff_t index,
486                 pgoff_t mark, unsigned int order, gfp_t gfp)
487 {
488         int err;
489         struct folio *folio = filemap_alloc_folio(gfp, order);
490
491         if (!folio)
492                 return -ENOMEM;
493         if (mark - index < (1UL << order))
494                 folio_set_readahead(folio);
495         err = filemap_add_folio(ractl->mapping, folio, index, gfp);
496         if (err)
497                 folio_put(folio);
498         else
499                 ractl->_nr_pages += 1UL << order;
500         return err;
501 }
502
503 void page_cache_ra_order(struct readahead_control *ractl,
504                 struct file_ra_state *ra, unsigned int new_order)
505 {
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;
510         int err = 0;
511         gfp_t gfp = readahead_gfp_mask(mapping);
512
513         if (!mapping_large_folio_support(mapping) || ra->size < 4)
514                 goto fallback;
515
516         limit = min(limit, index + ra->size - 1);
517
518         if (new_order < MAX_PAGECACHE_ORDER) {
519                 new_order += 2;
520                 if (new_order > MAX_PAGECACHE_ORDER)
521                         new_order = MAX_PAGECACHE_ORDER;
522                 while ((1 << new_order) > ra->size)
523                         new_order--;
524         }
525
526         while (index <= limit) {
527                 unsigned int order = new_order;
528
529                 /* Align with smaller pages if needed */
530                 if (index & ((1UL << order) - 1)) {
531                         order = __ffs(index);
532                         if (order == 1)
533                                 order = 0;
534                 }
535                 /* Don't allocate pages past EOF */
536                 while (index + (1UL << order) - 1 > limit) {
537                         if (--order == 1)
538                                 order = 0;
539                 }
540                 err = ra_alloc_folio(ractl, index, mark, order, gfp);
541                 if (err)
542                         break;
543                 index += 1UL << order;
544         }
545
546         if (index > limit) {
547                 ra->size += index - limit - 1;
548                 ra->async_size += index - limit - 1;
549         }
550
551         read_pages(ractl, NULL, false);
552
553         /*
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
556          * situation.
557          */
558         if (!err)
559                 return;
560 fallback:
561         do_page_cache_ra(ractl, ra->size, ra->async_size);
562 }
563
564 /*
565  * A minimal readahead algorithm for trivial sequential/random reads.
566  */
567 static void ondemand_readahead(struct readahead_control *ractl,
568                 struct folio *folio, unsigned long req_size)
569 {
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);
575         pgoff_t prev_index;
576
577         /*
578          * If the request exceeds the readahead window, allow the read to
579          * be up to the optimal hardware IO size
580          */
581         if (req_size > max_pages && bdi->io_pages > max_pages)
582                 max_pages = min(req_size, bdi->io_pages);
583
584         /*
585          * start of file
586          */
587         if (!index)
588                 goto initial_readahead;
589
590         /*
591          * It's the expected callback index, assume sequential access.
592          * Ramp up sizes, and push forward the readahead window.
593          */
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;
599                 goto readit;
600         }
601
602         /*
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.
607          */
608         if (folio) {
609                 pgoff_t start;
610
611                 rcu_read_lock();
612                 start = page_cache_next_miss(ractl->mapping, index + 1,
613                                 max_pages);
614                 rcu_read_unlock();
615
616                 if (!start || start - index > max_pages)
617                         return;
618
619                 ra->start = start;
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;
624                 goto readit;
625         }
626
627         /*
628          * oversize read
629          */
630         if (req_size > max_pages)
631                 goto initial_readahead;
632
633         /*
634          * sequential cache miss
635          * trivial case: (index - prev_index) == 1
636          * unaligned reads: (index - prev_index) == 0
637          */
638         prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
639         if (index - prev_index <= 1UL)
640                 goto initial_readahead;
641
642         /*
643          * Query the page cache and look for the traces(cached history pages)
644          * that a sequential stream would leave behind.
645          */
646         if (try_context_readahead(ractl->mapping, ra, index, req_size,
647                         max_pages))
648                 goto readit;
649
650         /*
651          * standalone, small random read
652          * Read as is, and do not pollute the readahead state.
653          */
654         do_page_cache_ra(ractl, req_size, 0);
655         return;
656
657 initial_readahead:
658         ra->start = index;
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;
661
662 readit:
663         /*
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.
668          */
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;
674                 } else {
675                         ra->size = max_pages;
676                         ra->async_size = max_pages >> 1;
677                 }
678         }
679
680         ractl->_index = ra->start;
681         page_cache_ra_order(ractl, ra, folio ? folio_order(folio) : 0);
682 }
683
684 void page_cache_sync_ra(struct readahead_control *ractl,
685                 unsigned long req_count)
686 {
687         bool do_forced_ra = ractl->file && (ractl->file->f_mode & FMODE_RANDOM);
688
689         /*
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.
694          */
695         if (!ractl->ra->ra_pages || blk_cgroup_congested()) {
696                 if (!ractl->file)
697                         return;
698                 req_count = 1;
699                 do_forced_ra = true;
700         }
701
702         /* be dumb */
703         if (do_forced_ra) {
704                 force_page_cache_ra(ractl, req_count);
705                 return;
706         }
707
708         /* do read-ahead */
709         ondemand_readahead(ractl, NULL, req_count);
710 }
711 EXPORT_SYMBOL_GPL(page_cache_sync_ra);
712
713 void page_cache_async_ra(struct readahead_control *ractl,
714                 struct folio *folio, unsigned long req_count)
715 {
716         /* no read-ahead */
717         if (!ractl->ra->ra_pages)
718                 return;
719
720         /*
721          * Same bit is used for PG_readahead and PG_reclaim.
722          */
723         if (folio_test_writeback(folio))
724                 return;
725
726         folio_clear_readahead(folio);
727
728         if (blk_cgroup_congested())
729                 return;
730
731         /* do read-ahead */
732         ondemand_readahead(ractl, folio, req_count);
733 }
734 EXPORT_SYMBOL_GPL(page_cache_async_ra);
735
736 ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
737 {
738         ssize_t ret;
739         struct fd f;
740
741         ret = -EBADF;
742         f = fdget(fd);
743         if (!f.file || !(f.file->f_mode & FMODE_READ))
744                 goto out;
745
746         /*
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.
750          */
751         ret = -EINVAL;
752         if (!f.file->f_mapping || !f.file->f_mapping->a_ops ||
753             !S_ISREG(file_inode(f.file)->i_mode))
754                 goto out;
755
756         ret = vfs_fadvise(f.file, offset, count, POSIX_FADV_WILLNEED);
757 out:
758         fdput(f);
759         return ret;
760 }
761
762 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
763 {
764         return ksys_readahead(fd, offset, count);
765 }
766
767 /**
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
772  *
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
777  * requested.
778  *
779  * The algorithm will stop if it encounters a conflicting page already in the
780  * pagecache and leave a smaller expansion than requested.
781  *
782  * The caller must check for this by examining the revised @ractl object for a
783  * different expansion than was requested.
784  */
785 void readahead_expand(struct readahead_control *ractl,
786                       loff_t new_start, size_t new_len)
787 {
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);
792
793         new_index = new_start / PAGE_SIZE;
794
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);
799
800                 if (page && !xa_is_value(page))
801                         return; /* Page apparently present */
802
803                 page = __page_cache_alloc(gfp_mask);
804                 if (!page)
805                         return;
806                 if (add_to_page_cache_lru(page, mapping, index, gfp_mask) < 0) {
807                         put_page(page);
808                         return;
809                 }
810
811                 ractl->_nr_pages++;
812                 ractl->_index = page->index;
813         }
814
815         new_len += new_start - readahead_pos(ractl);
816         new_nr_pages = DIV_ROUND_UP(new_len, PAGE_SIZE);
817
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);
822
823                 if (page && !xa_is_value(page))
824                         return; /* Page apparently present */
825
826                 page = __page_cache_alloc(gfp_mask);
827                 if (!page)
828                         return;
829                 if (add_to_page_cache_lru(page, mapping, index, gfp_mask) < 0) {
830                         put_page(page);
831                         return;
832                 }
833                 ractl->_nr_pages++;
834                 if (ra) {
835                         ra->size++;
836                         ra->async_size++;
837                 }
838         }
839 }
840 EXPORT_SYMBOL(readahead_expand);