Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * mm/readahead.c - address_space-level file readahead.
0004  *
0005  * Copyright (C) 2002, Linus Torvalds
0006  *
0007  * 09Apr2002    Andrew Morton
0008  *      Initial version.
0009  */
0010 
0011 /**
0012  * DOC: Readahead Overview
0013  *
0014  * Readahead is used to read content into the page cache before it is
0015  * explicitly requested by the application.  Readahead only ever
0016  * attempts to read folios that are not yet in the page cache.  If a
0017  * folio is present but not up-to-date, readahead will not try to read
0018  * it. In that case a simple ->read_folio() will be requested.
0019  *
0020  * Readahead is triggered when an application read request (whether a
0021  * system call or a page fault) finds that the requested folio is not in
0022  * the page cache, or that it is in the page cache and has the
0023  * readahead flag set.  This flag indicates that the folio was read
0024  * as part of a previous readahead request and now that it has been
0025  * accessed, it is time for the next readahead.
0026  *
0027  * Each readahead request is partly synchronous read, and partly async
0028  * readahead.  This is reflected in the struct file_ra_state which
0029  * contains ->size being the total number of pages, and ->async_size
0030  * which is the number of pages in the async section.  The readahead
0031  * flag will be set on the first folio in this async section to trigger
0032  * a subsequent readahead.  Once a series of sequential reads has been
0033  * established, there should be no need for a synchronous component and
0034  * all readahead request will be fully asynchronous.
0035  *
0036  * When either of the triggers causes a readahead, three numbers need
0037  * to be determined: the start of the region to read, the size of the
0038  * region, and the size of the async tail.
0039  *
0040  * The start of the region is simply the first page address at or after
0041  * the accessed address, which is not currently populated in the page
0042  * cache.  This is found with a simple search in the page cache.
0043  *
0044  * The size of the async tail is determined by subtracting the size that
0045  * was explicitly requested from the determined request size, unless
0046  * this would be less than zero - then zero is used.  NOTE THIS
0047  * CALCULATION IS WRONG WHEN THE START OF THE REGION IS NOT THE ACCESSED
0048  * PAGE.  ALSO THIS CALCULATION IS NOT USED CONSISTENTLY.
0049  *
0050  * The size of the region is normally determined from the size of the
0051  * previous readahead which loaded the preceding pages.  This may be
0052  * discovered from the struct file_ra_state for simple sequential reads,
0053  * or from examining the state of the page cache when multiple
0054  * sequential reads are interleaved.  Specifically: where the readahead
0055  * was triggered by the readahead flag, the size of the previous
0056  * readahead is assumed to be the number of pages from the triggering
0057  * page to the start of the new readahead.  In these cases, the size of
0058  * the previous readahead is scaled, often doubled, for the new
0059  * readahead, though see get_next_ra_size() for details.
0060  *
0061  * If the size of the previous read cannot be determined, the number of
0062  * preceding pages in the page cache is used to estimate the size of
0063  * a previous read.  This estimate could easily be misled by random
0064  * reads being coincidentally adjacent, so it is ignored unless it is
0065  * larger than the current request, and it is not scaled up, unless it
0066  * is at the start of file.
0067  *
0068  * In general readahead is accelerated at the start of the file, as
0069  * reads from there are often sequential.  There are other minor
0070  * adjustments to the readahead size in various special cases and these
0071  * are best discovered by reading the code.
0072  *
0073  * The above calculation, based on the previous readahead size,
0074  * determines the size of the readahead, to which any requested read
0075  * size may be added.
0076  *
0077  * Readahead requests are sent to the filesystem using the ->readahead()
0078  * address space operation, for which mpage_readahead() is a canonical
0079  * implementation.  ->readahead() should normally initiate reads on all
0080  * folios, but may fail to read any or all folios without causing an I/O
0081  * error.  The page cache reading code will issue a ->read_folio() request
0082  * for any folio which ->readahead() did not read, and only an error
0083  * from this will be final.
0084  *
0085  * ->readahead() will generally call readahead_folio() repeatedly to get
0086  * each folio from those prepared for readahead.  It may fail to read a
0087  * folio by:
0088  *
0089  * * not calling readahead_folio() sufficiently many times, effectively
0090  *   ignoring some folios, as might be appropriate if the path to
0091  *   storage is congested.
0092  *
0093  * * failing to actually submit a read request for a given folio,
0094  *   possibly due to insufficient resources, or
0095  *
0096  * * getting an error during subsequent processing of a request.
0097  *
0098  * In the last two cases, the folio should be unlocked by the filesystem
0099  * to indicate that the read attempt has failed.  In the first case the
0100  * folio will be unlocked by the VFS.
0101  *
0102  * Those folios not in the final ``async_size`` of the request should be
0103  * considered to be important and ->readahead() should not fail them due
0104  * to congestion or temporary resource unavailability, but should wait
0105  * for necessary resources (e.g.  memory or indexing information) to
0106  * become available.  Folios in the final ``async_size`` may be
0107  * considered less urgent and failure to read them is more acceptable.
0108  * In this case it is best to use filemap_remove_folio() to remove the
0109  * folios from the page cache as is automatically done for folios that
0110  * were not fetched with readahead_folio().  This will allow a
0111  * subsequent synchronous readahead request to try them again.  If they
0112  * are left in the page cache, then they will be read individually using
0113  * ->read_folio() which may be less efficient.
0114  */
0115 
0116 #include <linux/blkdev.h>
0117 #include <linux/kernel.h>
0118 #include <linux/dax.h>
0119 #include <linux/gfp.h>
0120 #include <linux/export.h>
0121 #include <linux/backing-dev.h>
0122 #include <linux/task_io_accounting_ops.h>
0123 #include <linux/pagevec.h>
0124 #include <linux/pagemap.h>
0125 #include <linux/syscalls.h>
0126 #include <linux/file.h>
0127 #include <linux/mm_inline.h>
0128 #include <linux/blk-cgroup.h>
0129 #include <linux/fadvise.h>
0130 #include <linux/sched/mm.h>
0131 
0132 #include "internal.h"
0133 
0134 /*
0135  * Initialise a struct file's readahead state.  Assumes that the caller has
0136  * memset *ra to zero.
0137  */
0138 void
0139 file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
0140 {
0141     ra->ra_pages = inode_to_bdi(mapping->host)->ra_pages;
0142     ra->prev_pos = -1;
0143 }
0144 EXPORT_SYMBOL_GPL(file_ra_state_init);
0145 
0146 static void read_pages(struct readahead_control *rac)
0147 {
0148     const struct address_space_operations *aops = rac->mapping->a_ops;
0149     struct folio *folio;
0150     struct blk_plug plug;
0151 
0152     if (!readahead_count(rac))
0153         return;
0154 
0155     blk_start_plug(&plug);
0156 
0157     if (aops->readahead) {
0158         aops->readahead(rac);
0159         /*
0160          * Clean up the remaining folios.  The sizes in ->ra
0161          * may be used to size the next readahead, so make sure
0162          * they accurately reflect what happened.
0163          */
0164         while ((folio = readahead_folio(rac)) != NULL) {
0165             unsigned long nr = folio_nr_pages(folio);
0166 
0167             folio_get(folio);
0168             rac->ra->size -= nr;
0169             if (rac->ra->async_size >= nr) {
0170                 rac->ra->async_size -= nr;
0171                 filemap_remove_folio(folio);
0172             }
0173             folio_unlock(folio);
0174             folio_put(folio);
0175         }
0176     } else {
0177         while ((folio = readahead_folio(rac)) != NULL)
0178             aops->read_folio(rac->file, folio);
0179     }
0180 
0181     blk_finish_plug(&plug);
0182 
0183     BUG_ON(readahead_count(rac));
0184 }
0185 
0186 /**
0187  * page_cache_ra_unbounded - Start unchecked readahead.
0188  * @ractl: Readahead control.
0189  * @nr_to_read: The number of pages to read.
0190  * @lookahead_size: Where to start the next readahead.
0191  *
0192  * This function is for filesystems to call when they want to start
0193  * readahead beyond a file's stated i_size.  This is almost certainly
0194  * not the function you want to call.  Use page_cache_async_readahead()
0195  * or page_cache_sync_readahead() instead.
0196  *
0197  * Context: File is referenced by caller.  Mutexes may be held by caller.
0198  * May sleep, but will not reenter filesystem to reclaim memory.
0199  */
0200 void page_cache_ra_unbounded(struct readahead_control *ractl,
0201         unsigned long nr_to_read, unsigned long lookahead_size)
0202 {
0203     struct address_space *mapping = ractl->mapping;
0204     unsigned long index = readahead_index(ractl);
0205     gfp_t gfp_mask = readahead_gfp_mask(mapping);
0206     unsigned long i;
0207 
0208     /*
0209      * Partway through the readahead operation, we will have added
0210      * locked pages to the page cache, but will not yet have submitted
0211      * them for I/O.  Adding another page may need to allocate memory,
0212      * which can trigger memory reclaim.  Telling the VM we're in
0213      * the middle of a filesystem operation will cause it to not
0214      * touch file-backed pages, preventing a deadlock.  Most (all?)
0215      * filesystems already specify __GFP_NOFS in their mapping's
0216      * gfp_mask, but let's be explicit here.
0217      */
0218     unsigned int nofs = memalloc_nofs_save();
0219 
0220     filemap_invalidate_lock_shared(mapping);
0221     /*
0222      * Preallocate as many pages as we will need.
0223      */
0224     for (i = 0; i < nr_to_read; i++) {
0225         struct folio *folio = xa_load(&mapping->i_pages, index + i);
0226 
0227         if (folio && !xa_is_value(folio)) {
0228             /*
0229              * Page already present?  Kick off the current batch
0230              * of contiguous pages before continuing with the
0231              * next batch.  This page may be the one we would
0232              * have intended to mark as Readahead, but we don't
0233              * have a stable reference to this page, and it's
0234              * not worth getting one just for that.
0235              */
0236             read_pages(ractl);
0237             ractl->_index++;
0238             i = ractl->_index + ractl->_nr_pages - index - 1;
0239             continue;
0240         }
0241 
0242         folio = filemap_alloc_folio(gfp_mask, 0);
0243         if (!folio)
0244             break;
0245         if (filemap_add_folio(mapping, folio, index + i,
0246                     gfp_mask) < 0) {
0247             folio_put(folio);
0248             read_pages(ractl);
0249             ractl->_index++;
0250             i = ractl->_index + ractl->_nr_pages - index - 1;
0251             continue;
0252         }
0253         if (i == nr_to_read - lookahead_size)
0254             folio_set_readahead(folio);
0255         ractl->_nr_pages++;
0256     }
0257 
0258     /*
0259      * Now start the IO.  We ignore I/O errors - if the folio is not
0260      * uptodate then the caller will launch read_folio again, and
0261      * will then handle the error.
0262      */
0263     read_pages(ractl);
0264     filemap_invalidate_unlock_shared(mapping);
0265     memalloc_nofs_restore(nofs);
0266 }
0267 EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
0268 
0269 /*
0270  * do_page_cache_ra() actually reads a chunk of disk.  It allocates
0271  * the pages first, then submits them for I/O. This avoids the very bad
0272  * behaviour which would occur if page allocations are causing VM writeback.
0273  * We really don't want to intermingle reads and writes like that.
0274  */
0275 static void do_page_cache_ra(struct readahead_control *ractl,
0276         unsigned long nr_to_read, unsigned long lookahead_size)
0277 {
0278     struct inode *inode = ractl->mapping->host;
0279     unsigned long index = readahead_index(ractl);
0280     loff_t isize = i_size_read(inode);
0281     pgoff_t end_index;  /* The last page we want to read */
0282 
0283     if (isize == 0)
0284         return;
0285 
0286     end_index = (isize - 1) >> PAGE_SHIFT;
0287     if (index > end_index)
0288         return;
0289     /* Don't read past the page containing the last byte of the file */
0290     if (nr_to_read > end_index - index)
0291         nr_to_read = end_index - index + 1;
0292 
0293     page_cache_ra_unbounded(ractl, nr_to_read, lookahead_size);
0294 }
0295 
0296 /*
0297  * Chunk the readahead into 2 megabyte units, so that we don't pin too much
0298  * memory at once.
0299  */
0300 void force_page_cache_ra(struct readahead_control *ractl,
0301         unsigned long nr_to_read)
0302 {
0303     struct address_space *mapping = ractl->mapping;
0304     struct file_ra_state *ra = ractl->ra;
0305     struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
0306     unsigned long max_pages, index;
0307 
0308     if (unlikely(!mapping->a_ops->read_folio && !mapping->a_ops->readahead))
0309         return;
0310 
0311     /*
0312      * If the request exceeds the readahead window, allow the read to
0313      * be up to the optimal hardware IO size
0314      */
0315     index = readahead_index(ractl);
0316     max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
0317     nr_to_read = min_t(unsigned long, nr_to_read, max_pages);
0318     while (nr_to_read) {
0319         unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
0320 
0321         if (this_chunk > nr_to_read)
0322             this_chunk = nr_to_read;
0323         ractl->_index = index;
0324         do_page_cache_ra(ractl, this_chunk, 0);
0325 
0326         index += this_chunk;
0327         nr_to_read -= this_chunk;
0328     }
0329 }
0330 
0331 /*
0332  * Set the initial window size, round to next power of 2 and square
0333  * for small size, x 4 for medium, and x 2 for large
0334  * for 128k (32 page) max ra
0335  * 1-2 page = 16k, 3-4 page 32k, 5-8 page = 64k, > 8 page = 128k initial
0336  */
0337 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
0338 {
0339     unsigned long newsize = roundup_pow_of_two(size);
0340 
0341     if (newsize <= max / 32)
0342         newsize = newsize * 4;
0343     else if (newsize <= max / 4)
0344         newsize = newsize * 2;
0345     else
0346         newsize = max;
0347 
0348     return newsize;
0349 }
0350 
0351 /*
0352  *  Get the previous window size, ramp it up, and
0353  *  return it as the new window size.
0354  */
0355 static unsigned long get_next_ra_size(struct file_ra_state *ra,
0356                       unsigned long max)
0357 {
0358     unsigned long cur = ra->size;
0359 
0360     if (cur < max / 16)
0361         return 4 * cur;
0362     if (cur <= max / 2)
0363         return 2 * cur;
0364     return max;
0365 }
0366 
0367 /*
0368  * On-demand readahead design.
0369  *
0370  * The fields in struct file_ra_state represent the most-recently-executed
0371  * readahead attempt:
0372  *
0373  *                        |<----- async_size ---------|
0374  *     |------------------- size -------------------->|
0375  *     |==================#===========================|
0376  *     ^start             ^page marked with PG_readahead
0377  *
0378  * To overlap application thinking time and disk I/O time, we do
0379  * `readahead pipelining': Do not wait until the application consumed all
0380  * readahead pages and stalled on the missing page at readahead_index;
0381  * Instead, submit an asynchronous readahead I/O as soon as there are
0382  * only async_size pages left in the readahead window. Normally async_size
0383  * will be equal to size, for maximum pipelining.
0384  *
0385  * In interleaved sequential reads, concurrent streams on the same fd can
0386  * be invalidating each other's readahead state. So we flag the new readahead
0387  * page at (start+size-async_size) with PG_readahead, and use it as readahead
0388  * indicator. The flag won't be set on already cached pages, to avoid the
0389  * readahead-for-nothing fuss, saving pointless page cache lookups.
0390  *
0391  * prev_pos tracks the last visited byte in the _previous_ read request.
0392  * It should be maintained by the caller, and will be used for detecting
0393  * small random reads. Note that the readahead algorithm checks loosely
0394  * for sequential patterns. Hence interleaved reads might be served as
0395  * sequential ones.
0396  *
0397  * There is a special-case: if the first page which the application tries to
0398  * read happens to be the first page of the file, it is assumed that a linear
0399  * read is about to happen and the window is immediately set to the initial size
0400  * based on I/O request size and the max_readahead.
0401  *
0402  * The code ramps up the readahead size aggressively at first, but slow down as
0403  * it approaches max_readhead.
0404  */
0405 
0406 /*
0407  * Count contiguously cached pages from @index-1 to @index-@max,
0408  * this count is a conservative estimation of
0409  *  - length of the sequential read sequence, or
0410  *  - thrashing threshold in memory tight systems
0411  */
0412 static pgoff_t count_history_pages(struct address_space *mapping,
0413                    pgoff_t index, unsigned long max)
0414 {
0415     pgoff_t head;
0416 
0417     rcu_read_lock();
0418     head = page_cache_prev_miss(mapping, index - 1, max);
0419     rcu_read_unlock();
0420 
0421     return index - 1 - head;
0422 }
0423 
0424 /*
0425  * page cache context based readahead
0426  */
0427 static int try_context_readahead(struct address_space *mapping,
0428                  struct file_ra_state *ra,
0429                  pgoff_t index,
0430                  unsigned long req_size,
0431                  unsigned long max)
0432 {
0433     pgoff_t size;
0434 
0435     size = count_history_pages(mapping, index, max);
0436 
0437     /*
0438      * not enough history pages:
0439      * it could be a random read
0440      */
0441     if (size <= req_size)
0442         return 0;
0443 
0444     /*
0445      * starts from beginning of file:
0446      * it is a strong indication of long-run stream (or whole-file-read)
0447      */
0448     if (size >= index)
0449         size *= 2;
0450 
0451     ra->start = index;
0452     ra->size = min(size + req_size, max);
0453     ra->async_size = 1;
0454 
0455     return 1;
0456 }
0457 
0458 /*
0459  * There are some parts of the kernel which assume that PMD entries
0460  * are exactly HPAGE_PMD_ORDER.  Those should be fixed, but until then,
0461  * limit the maximum allocation order to PMD size.  I'm not aware of any
0462  * assumptions about maximum order if THP are disabled, but 8 seems like
0463  * a good order (that's 1MB if you're using 4kB pages)
0464  */
0465 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
0466 #define MAX_PAGECACHE_ORDER HPAGE_PMD_ORDER
0467 #else
0468 #define MAX_PAGECACHE_ORDER 8
0469 #endif
0470 
0471 static inline int ra_alloc_folio(struct readahead_control *ractl, pgoff_t index,
0472         pgoff_t mark, unsigned int order, gfp_t gfp)
0473 {
0474     int err;
0475     struct folio *folio = filemap_alloc_folio(gfp, order);
0476 
0477     if (!folio)
0478         return -ENOMEM;
0479     mark = round_up(mark, 1UL << order);
0480     if (index == mark)
0481         folio_set_readahead(folio);
0482     err = filemap_add_folio(ractl->mapping, folio, index, gfp);
0483     if (err)
0484         folio_put(folio);
0485     else
0486         ractl->_nr_pages += 1UL << order;
0487     return err;
0488 }
0489 
0490 void page_cache_ra_order(struct readahead_control *ractl,
0491         struct file_ra_state *ra, unsigned int new_order)
0492 {
0493     struct address_space *mapping = ractl->mapping;
0494     pgoff_t index = readahead_index(ractl);
0495     pgoff_t limit = (i_size_read(mapping->host) - 1) >> PAGE_SHIFT;
0496     pgoff_t mark = index + ra->size - ra->async_size;
0497     int err = 0;
0498     gfp_t gfp = readahead_gfp_mask(mapping);
0499 
0500     if (!mapping_large_folio_support(mapping) || ra->size < 4)
0501         goto fallback;
0502 
0503     limit = min(limit, index + ra->size - 1);
0504 
0505     if (new_order < MAX_PAGECACHE_ORDER) {
0506         new_order += 2;
0507         if (new_order > MAX_PAGECACHE_ORDER)
0508             new_order = MAX_PAGECACHE_ORDER;
0509         while ((1 << new_order) > ra->size)
0510             new_order--;
0511     }
0512 
0513     filemap_invalidate_lock_shared(mapping);
0514     while (index <= limit) {
0515         unsigned int order = new_order;
0516 
0517         /* Align with smaller pages if needed */
0518         if (index & ((1UL << order) - 1)) {
0519             order = __ffs(index);
0520             if (order == 1)
0521                 order = 0;
0522         }
0523         /* Don't allocate pages past EOF */
0524         while (index + (1UL << order) - 1 > limit) {
0525             if (--order == 1)
0526                 order = 0;
0527         }
0528         err = ra_alloc_folio(ractl, index, mark, order, gfp);
0529         if (err)
0530             break;
0531         index += 1UL << order;
0532     }
0533 
0534     if (index > limit) {
0535         ra->size += index - limit - 1;
0536         ra->async_size += index - limit - 1;
0537     }
0538 
0539     read_pages(ractl);
0540     filemap_invalidate_unlock_shared(mapping);
0541 
0542     /*
0543      * If there were already pages in the page cache, then we may have
0544      * left some gaps.  Let the regular readahead code take care of this
0545      * situation.
0546      */
0547     if (!err)
0548         return;
0549 fallback:
0550     do_page_cache_ra(ractl, ra->size, ra->async_size);
0551 }
0552 
0553 /*
0554  * A minimal readahead algorithm for trivial sequential/random reads.
0555  */
0556 static void ondemand_readahead(struct readahead_control *ractl,
0557         struct folio *folio, unsigned long req_size)
0558 {
0559     struct backing_dev_info *bdi = inode_to_bdi(ractl->mapping->host);
0560     struct file_ra_state *ra = ractl->ra;
0561     unsigned long max_pages = ra->ra_pages;
0562     unsigned long add_pages;
0563     pgoff_t index = readahead_index(ractl);
0564     pgoff_t expected, prev_index;
0565     unsigned int order = folio ? folio_order(folio) : 0;
0566 
0567     /*
0568      * If the request exceeds the readahead window, allow the read to
0569      * be up to the optimal hardware IO size
0570      */
0571     if (req_size > max_pages && bdi->io_pages > max_pages)
0572         max_pages = min(req_size, bdi->io_pages);
0573 
0574     /*
0575      * start of file
0576      */
0577     if (!index)
0578         goto initial_readahead;
0579 
0580     /*
0581      * It's the expected callback index, assume sequential access.
0582      * Ramp up sizes, and push forward the readahead window.
0583      */
0584     expected = round_up(ra->start + ra->size - ra->async_size,
0585             1UL << order);
0586     if (index == expected || index == (ra->start + ra->size)) {
0587         ra->start += ra->size;
0588         ra->size = get_next_ra_size(ra, max_pages);
0589         ra->async_size = ra->size;
0590         goto readit;
0591     }
0592 
0593     /*
0594      * Hit a marked folio without valid readahead state.
0595      * E.g. interleaved reads.
0596      * Query the pagecache for async_size, which normally equals to
0597      * readahead size. Ramp it up and use it as the new readahead size.
0598      */
0599     if (folio) {
0600         pgoff_t start;
0601 
0602         rcu_read_lock();
0603         start = page_cache_next_miss(ractl->mapping, index + 1,
0604                 max_pages);
0605         rcu_read_unlock();
0606 
0607         if (!start || start - index > max_pages)
0608             return;
0609 
0610         ra->start = start;
0611         ra->size = start - index;   /* old async_size */
0612         ra->size += req_size;
0613         ra->size = get_next_ra_size(ra, max_pages);
0614         ra->async_size = ra->size;
0615         goto readit;
0616     }
0617 
0618     /*
0619      * oversize read
0620      */
0621     if (req_size > max_pages)
0622         goto initial_readahead;
0623 
0624     /*
0625      * sequential cache miss
0626      * trivial case: (index - prev_index) == 1
0627      * unaligned reads: (index - prev_index) == 0
0628      */
0629     prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
0630     if (index - prev_index <= 1UL)
0631         goto initial_readahead;
0632 
0633     /*
0634      * Query the page cache and look for the traces(cached history pages)
0635      * that a sequential stream would leave behind.
0636      */
0637     if (try_context_readahead(ractl->mapping, ra, index, req_size,
0638             max_pages))
0639         goto readit;
0640 
0641     /*
0642      * standalone, small random read
0643      * Read as is, and do not pollute the readahead state.
0644      */
0645     do_page_cache_ra(ractl, req_size, 0);
0646     return;
0647 
0648 initial_readahead:
0649     ra->start = index;
0650     ra->size = get_init_ra_size(req_size, max_pages);
0651     ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size;
0652 
0653 readit:
0654     /*
0655      * Will this read hit the readahead marker made by itself?
0656      * If so, trigger the readahead marker hit now, and merge
0657      * the resulted next readahead window into the current one.
0658      * Take care of maximum IO pages as above.
0659      */
0660     if (index == ra->start && ra->size == ra->async_size) {
0661         add_pages = get_next_ra_size(ra, max_pages);
0662         if (ra->size + add_pages <= max_pages) {
0663             ra->async_size = add_pages;
0664             ra->size += add_pages;
0665         } else {
0666             ra->size = max_pages;
0667             ra->async_size = max_pages >> 1;
0668         }
0669     }
0670 
0671     ractl->_index = ra->start;
0672     page_cache_ra_order(ractl, ra, order);
0673 }
0674 
0675 void page_cache_sync_ra(struct readahead_control *ractl,
0676         unsigned long req_count)
0677 {
0678     bool do_forced_ra = ractl->file && (ractl->file->f_mode & FMODE_RANDOM);
0679 
0680     /*
0681      * Even if readahead is disabled, issue this request as readahead
0682      * as we'll need it to satisfy the requested range. The forced
0683      * readahead will do the right thing and limit the read to just the
0684      * requested range, which we'll set to 1 page for this case.
0685      */
0686     if (!ractl->ra->ra_pages || blk_cgroup_congested()) {
0687         if (!ractl->file)
0688             return;
0689         req_count = 1;
0690         do_forced_ra = true;
0691     }
0692 
0693     /* be dumb */
0694     if (do_forced_ra) {
0695         force_page_cache_ra(ractl, req_count);
0696         return;
0697     }
0698 
0699     ondemand_readahead(ractl, NULL, req_count);
0700 }
0701 EXPORT_SYMBOL_GPL(page_cache_sync_ra);
0702 
0703 void page_cache_async_ra(struct readahead_control *ractl,
0704         struct folio *folio, unsigned long req_count)
0705 {
0706     /* no readahead */
0707     if (!ractl->ra->ra_pages)
0708         return;
0709 
0710     /*
0711      * Same bit is used for PG_readahead and PG_reclaim.
0712      */
0713     if (folio_test_writeback(folio))
0714         return;
0715 
0716     folio_clear_readahead(folio);
0717 
0718     if (blk_cgroup_congested())
0719         return;
0720 
0721     ondemand_readahead(ractl, folio, req_count);
0722 }
0723 EXPORT_SYMBOL_GPL(page_cache_async_ra);
0724 
0725 ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
0726 {
0727     ssize_t ret;
0728     struct fd f;
0729 
0730     ret = -EBADF;
0731     f = fdget(fd);
0732     if (!f.file || !(f.file->f_mode & FMODE_READ))
0733         goto out;
0734 
0735     /*
0736      * The readahead() syscall is intended to run only on files
0737      * that can execute readahead. If readahead is not possible
0738      * on this file, then we must return -EINVAL.
0739      */
0740     ret = -EINVAL;
0741     if (!f.file->f_mapping || !f.file->f_mapping->a_ops ||
0742         !S_ISREG(file_inode(f.file)->i_mode))
0743         goto out;
0744 
0745     ret = vfs_fadvise(f.file, offset, count, POSIX_FADV_WILLNEED);
0746 out:
0747     fdput(f);
0748     return ret;
0749 }
0750 
0751 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
0752 {
0753     return ksys_readahead(fd, offset, count);
0754 }
0755 
0756 #if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_READAHEAD)
0757 COMPAT_SYSCALL_DEFINE4(readahead, int, fd, compat_arg_u64_dual(offset), size_t, count)
0758 {
0759     return ksys_readahead(fd, compat_arg_u64_glue(offset), count);
0760 }
0761 #endif
0762 
0763 /**
0764  * readahead_expand - Expand a readahead request
0765  * @ractl: The request to be expanded
0766  * @new_start: The revised start
0767  * @new_len: The revised size of the request
0768  *
0769  * Attempt to expand a readahead request outwards from the current size to the
0770  * specified size by inserting locked pages before and after the current window
0771  * to increase the size to the new window.  This may involve the insertion of
0772  * THPs, in which case the window may get expanded even beyond what was
0773  * requested.
0774  *
0775  * The algorithm will stop if it encounters a conflicting page already in the
0776  * pagecache and leave a smaller expansion than requested.
0777  *
0778  * The caller must check for this by examining the revised @ractl object for a
0779  * different expansion than was requested.
0780  */
0781 void readahead_expand(struct readahead_control *ractl,
0782               loff_t new_start, size_t new_len)
0783 {
0784     struct address_space *mapping = ractl->mapping;
0785     struct file_ra_state *ra = ractl->ra;
0786     pgoff_t new_index, new_nr_pages;
0787     gfp_t gfp_mask = readahead_gfp_mask(mapping);
0788 
0789     new_index = new_start / PAGE_SIZE;
0790 
0791     /* Expand the leading edge downwards */
0792     while (ractl->_index > new_index) {
0793         unsigned long index = ractl->_index - 1;
0794         struct page *page = xa_load(&mapping->i_pages, index);
0795 
0796         if (page && !xa_is_value(page))
0797             return; /* Page apparently present */
0798 
0799         page = __page_cache_alloc(gfp_mask);
0800         if (!page)
0801             return;
0802         if (add_to_page_cache_lru(page, mapping, index, gfp_mask) < 0) {
0803             put_page(page);
0804             return;
0805         }
0806 
0807         ractl->_nr_pages++;
0808         ractl->_index = page->index;
0809     }
0810 
0811     new_len += new_start - readahead_pos(ractl);
0812     new_nr_pages = DIV_ROUND_UP(new_len, PAGE_SIZE);
0813 
0814     /* Expand the trailing edge upwards */
0815     while (ractl->_nr_pages < new_nr_pages) {
0816         unsigned long index = ractl->_index + ractl->_nr_pages;
0817         struct page *page = xa_load(&mapping->i_pages, index);
0818 
0819         if (page && !xa_is_value(page))
0820             return; /* Page apparently present */
0821 
0822         page = __page_cache_alloc(gfp_mask);
0823         if (!page)
0824             return;
0825         if (add_to_page_cache_lru(page, mapping, index, gfp_mask) < 0) {
0826             put_page(page);
0827             return;
0828         }
0829         ractl->_nr_pages++;
0830         if (ra) {
0831             ra->size++;
0832             ra->async_size++;
0833         }
0834     }
0835 }
0836 EXPORT_SYMBOL(readahead_expand);