Back to home page

LXR

 
 

    


0001 /*
0002  * mm/readahead.c - address_space-level file readahead.
0003  *
0004  * Copyright (C) 2002, Linus Torvalds
0005  *
0006  * 09Apr2002    Andrew Morton
0007  *      Initial version.
0008  */
0009 
0010 #include <linux/kernel.h>
0011 #include <linux/dax.h>
0012 #include <linux/gfp.h>
0013 #include <linux/export.h>
0014 #include <linux/blkdev.h>
0015 #include <linux/backing-dev.h>
0016 #include <linux/task_io_accounting_ops.h>
0017 #include <linux/pagevec.h>
0018 #include <linux/pagemap.h>
0019 #include <linux/syscalls.h>
0020 #include <linux/file.h>
0021 #include <linux/mm_inline.h>
0022 
0023 #include "internal.h"
0024 
0025 /*
0026  * Initialise a struct file's readahead state.  Assumes that the caller has
0027  * memset *ra to zero.
0028  */
0029 void
0030 file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
0031 {
0032     ra->ra_pages = inode_to_bdi(mapping->host)->ra_pages;
0033     ra->prev_pos = -1;
0034 }
0035 EXPORT_SYMBOL_GPL(file_ra_state_init);
0036 
0037 /*
0038  * see if a page needs releasing upon read_cache_pages() failure
0039  * - the caller of read_cache_pages() may have set PG_private or PG_fscache
0040  *   before calling, such as the NFS fs marking pages that are cached locally
0041  *   on disk, thus we need to give the fs a chance to clean up in the event of
0042  *   an error
0043  */
0044 static void read_cache_pages_invalidate_page(struct address_space *mapping,
0045                          struct page *page)
0046 {
0047     if (page_has_private(page)) {
0048         if (!trylock_page(page))
0049             BUG();
0050         page->mapping = mapping;
0051         do_invalidatepage(page, 0, PAGE_SIZE);
0052         page->mapping = NULL;
0053         unlock_page(page);
0054     }
0055     put_page(page);
0056 }
0057 
0058 /*
0059  * release a list of pages, invalidating them first if need be
0060  */
0061 static void read_cache_pages_invalidate_pages(struct address_space *mapping,
0062                           struct list_head *pages)
0063 {
0064     struct page *victim;
0065 
0066     while (!list_empty(pages)) {
0067         victim = lru_to_page(pages);
0068         list_del(&victim->lru);
0069         read_cache_pages_invalidate_page(mapping, victim);
0070     }
0071 }
0072 
0073 /**
0074  * read_cache_pages - populate an address space with some pages & start reads against them
0075  * @mapping: the address_space
0076  * @pages: The address of a list_head which contains the target pages.  These
0077  *   pages have their ->index populated and are otherwise uninitialised.
0078  * @filler: callback routine for filling a single page.
0079  * @data: private data for the callback routine.
0080  *
0081  * Hides the details of the LRU cache etc from the filesystems.
0082  */
0083 int read_cache_pages(struct address_space *mapping, struct list_head *pages,
0084             int (*filler)(void *, struct page *), void *data)
0085 {
0086     struct page *page;
0087     int ret = 0;
0088 
0089     while (!list_empty(pages)) {
0090         page = lru_to_page(pages);
0091         list_del(&page->lru);
0092         if (add_to_page_cache_lru(page, mapping, page->index,
0093                 readahead_gfp_mask(mapping))) {
0094             read_cache_pages_invalidate_page(mapping, page);
0095             continue;
0096         }
0097         put_page(page);
0098 
0099         ret = filler(data, page);
0100         if (unlikely(ret)) {
0101             read_cache_pages_invalidate_pages(mapping, pages);
0102             break;
0103         }
0104         task_io_account_read(PAGE_SIZE);
0105     }
0106     return ret;
0107 }
0108 
0109 EXPORT_SYMBOL(read_cache_pages);
0110 
0111 static int read_pages(struct address_space *mapping, struct file *filp,
0112         struct list_head *pages, unsigned int nr_pages, gfp_t gfp)
0113 {
0114     struct blk_plug plug;
0115     unsigned page_idx;
0116     int ret;
0117 
0118     blk_start_plug(&plug);
0119 
0120     if (mapping->a_ops->readpages) {
0121         ret = mapping->a_ops->readpages(filp, mapping, pages, nr_pages);
0122         /* Clean up the remaining pages */
0123         put_pages_list(pages);
0124         goto out;
0125     }
0126 
0127     for (page_idx = 0; page_idx < nr_pages; page_idx++) {
0128         struct page *page = lru_to_page(pages);
0129         list_del(&page->lru);
0130         if (!add_to_page_cache_lru(page, mapping, page->index, gfp))
0131             mapping->a_ops->readpage(filp, page);
0132         put_page(page);
0133     }
0134     ret = 0;
0135 
0136 out:
0137     blk_finish_plug(&plug);
0138 
0139     return ret;
0140 }
0141 
0142 /*
0143  * __do_page_cache_readahead() actually reads a chunk of disk.  It allocates all
0144  * the pages first, then submits them all for I/O. This avoids the very bad
0145  * behaviour which would occur if page allocations are causing VM writeback.
0146  * We really don't want to intermingle reads and writes like that.
0147  *
0148  * Returns the number of pages requested, or the maximum amount of I/O allowed.
0149  */
0150 int __do_page_cache_readahead(struct address_space *mapping, struct file *filp,
0151             pgoff_t offset, unsigned long nr_to_read,
0152             unsigned long lookahead_size)
0153 {
0154     struct inode *inode = mapping->host;
0155     struct page *page;
0156     unsigned long end_index;    /* The last page we want to read */
0157     LIST_HEAD(page_pool);
0158     int page_idx;
0159     int ret = 0;
0160     loff_t isize = i_size_read(inode);
0161     gfp_t gfp_mask = readahead_gfp_mask(mapping);
0162 
0163     if (isize == 0)
0164         goto out;
0165 
0166     end_index = ((isize - 1) >> PAGE_SHIFT);
0167 
0168     /*
0169      * Preallocate as many pages as we will need.
0170      */
0171     for (page_idx = 0; page_idx < nr_to_read; page_idx++) {
0172         pgoff_t page_offset = offset + page_idx;
0173 
0174         if (page_offset > end_index)
0175             break;
0176 
0177         rcu_read_lock();
0178         page = radix_tree_lookup(&mapping->page_tree, page_offset);
0179         rcu_read_unlock();
0180         if (page && !radix_tree_exceptional_entry(page))
0181             continue;
0182 
0183         page = __page_cache_alloc(gfp_mask);
0184         if (!page)
0185             break;
0186         page->index = page_offset;
0187         list_add(&page->lru, &page_pool);
0188         if (page_idx == nr_to_read - lookahead_size)
0189             SetPageReadahead(page);
0190         ret++;
0191     }
0192 
0193     /*
0194      * Now start the IO.  We ignore I/O errors - if the page is not
0195      * uptodate then the caller will launch readpage again, and
0196      * will then handle the error.
0197      */
0198     if (ret)
0199         read_pages(mapping, filp, &page_pool, ret, gfp_mask);
0200     BUG_ON(!list_empty(&page_pool));
0201 out:
0202     return ret;
0203 }
0204 
0205 /*
0206  * Chunk the readahead into 2 megabyte units, so that we don't pin too much
0207  * memory at once.
0208  */
0209 int force_page_cache_readahead(struct address_space *mapping, struct file *filp,
0210                    pgoff_t offset, unsigned long nr_to_read)
0211 {
0212     struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
0213     struct file_ra_state *ra = &filp->f_ra;
0214     unsigned long max_pages;
0215 
0216     if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages))
0217         return -EINVAL;
0218 
0219     /*
0220      * If the request exceeds the readahead window, allow the read to
0221      * be up to the optimal hardware IO size
0222      */
0223     max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
0224     nr_to_read = min(nr_to_read, max_pages);
0225     while (nr_to_read) {
0226         int err;
0227 
0228         unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
0229 
0230         if (this_chunk > nr_to_read)
0231             this_chunk = nr_to_read;
0232         err = __do_page_cache_readahead(mapping, filp,
0233                         offset, this_chunk, 0);
0234         if (err < 0)
0235             return err;
0236 
0237         offset += this_chunk;
0238         nr_to_read -= this_chunk;
0239     }
0240     return 0;
0241 }
0242 
0243 /*
0244  * Set the initial window size, round to next power of 2 and square
0245  * for small size, x 4 for medium, and x 2 for large
0246  * for 128k (32 page) max ra
0247  * 1-8 page = 32k initial, > 8 page = 128k initial
0248  */
0249 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
0250 {
0251     unsigned long newsize = roundup_pow_of_two(size);
0252 
0253     if (newsize <= max / 32)
0254         newsize = newsize * 4;
0255     else if (newsize <= max / 4)
0256         newsize = newsize * 2;
0257     else
0258         newsize = max;
0259 
0260     return newsize;
0261 }
0262 
0263 /*
0264  *  Get the previous window size, ramp it up, and
0265  *  return it as the new window size.
0266  */
0267 static unsigned long get_next_ra_size(struct file_ra_state *ra,
0268                         unsigned long max)
0269 {
0270     unsigned long cur = ra->size;
0271     unsigned long newsize;
0272 
0273     if (cur < max / 16)
0274         newsize = 4 * cur;
0275     else
0276         newsize = 2 * cur;
0277 
0278     return min(newsize, max);
0279 }
0280 
0281 /*
0282  * On-demand readahead design.
0283  *
0284  * The fields in struct file_ra_state represent the most-recently-executed
0285  * readahead attempt:
0286  *
0287  *                        |<----- async_size ---------|
0288  *     |------------------- size -------------------->|
0289  *     |==================#===========================|
0290  *     ^start             ^page marked with PG_readahead
0291  *
0292  * To overlap application thinking time and disk I/O time, we do
0293  * `readahead pipelining': Do not wait until the application consumed all
0294  * readahead pages and stalled on the missing page at readahead_index;
0295  * Instead, submit an asynchronous readahead I/O as soon as there are
0296  * only async_size pages left in the readahead window. Normally async_size
0297  * will be equal to size, for maximum pipelining.
0298  *
0299  * In interleaved sequential reads, concurrent streams on the same fd can
0300  * be invalidating each other's readahead state. So we flag the new readahead
0301  * page at (start+size-async_size) with PG_readahead, and use it as readahead
0302  * indicator. The flag won't be set on already cached pages, to avoid the
0303  * readahead-for-nothing fuss, saving pointless page cache lookups.
0304  *
0305  * prev_pos tracks the last visited byte in the _previous_ read request.
0306  * It should be maintained by the caller, and will be used for detecting
0307  * small random reads. Note that the readahead algorithm checks loosely
0308  * for sequential patterns. Hence interleaved reads might be served as
0309  * sequential ones.
0310  *
0311  * There is a special-case: if the first page which the application tries to
0312  * read happens to be the first page of the file, it is assumed that a linear
0313  * read is about to happen and the window is immediately set to the initial size
0314  * based on I/O request size and the max_readahead.
0315  *
0316  * The code ramps up the readahead size aggressively at first, but slow down as
0317  * it approaches max_readhead.
0318  */
0319 
0320 /*
0321  * Count contiguously cached pages from @offset-1 to @offset-@max,
0322  * this count is a conservative estimation of
0323  *  - length of the sequential read sequence, or
0324  *  - thrashing threshold in memory tight systems
0325  */
0326 static pgoff_t count_history_pages(struct address_space *mapping,
0327                    pgoff_t offset, unsigned long max)
0328 {
0329     pgoff_t head;
0330 
0331     rcu_read_lock();
0332     head = page_cache_prev_hole(mapping, offset - 1, max);
0333     rcu_read_unlock();
0334 
0335     return offset - 1 - head;
0336 }
0337 
0338 /*
0339  * page cache context based read-ahead
0340  */
0341 static int try_context_readahead(struct address_space *mapping,
0342                  struct file_ra_state *ra,
0343                  pgoff_t offset,
0344                  unsigned long req_size,
0345                  unsigned long max)
0346 {
0347     pgoff_t size;
0348 
0349     size = count_history_pages(mapping, offset, max);
0350 
0351     /*
0352      * not enough history pages:
0353      * it could be a random read
0354      */
0355     if (size <= req_size)
0356         return 0;
0357 
0358     /*
0359      * starts from beginning of file:
0360      * it is a strong indication of long-run stream (or whole-file-read)
0361      */
0362     if (size >= offset)
0363         size *= 2;
0364 
0365     ra->start = offset;
0366     ra->size = min(size + req_size, max);
0367     ra->async_size = 1;
0368 
0369     return 1;
0370 }
0371 
0372 /*
0373  * A minimal readahead algorithm for trivial sequential/random reads.
0374  */
0375 static unsigned long
0376 ondemand_readahead(struct address_space *mapping,
0377            struct file_ra_state *ra, struct file *filp,
0378            bool hit_readahead_marker, pgoff_t offset,
0379            unsigned long req_size)
0380 {
0381     struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
0382     unsigned long max_pages = ra->ra_pages;
0383     pgoff_t prev_offset;
0384 
0385     /*
0386      * If the request exceeds the readahead window, allow the read to
0387      * be up to the optimal hardware IO size
0388      */
0389     if (req_size > max_pages && bdi->io_pages > max_pages)
0390         max_pages = min(req_size, bdi->io_pages);
0391 
0392     /*
0393      * start of file
0394      */
0395     if (!offset)
0396         goto initial_readahead;
0397 
0398     /*
0399      * It's the expected callback offset, assume sequential access.
0400      * Ramp up sizes, and push forward the readahead window.
0401      */
0402     if ((offset == (ra->start + ra->size - ra->async_size) ||
0403          offset == (ra->start + ra->size))) {
0404         ra->start += ra->size;
0405         ra->size = get_next_ra_size(ra, max_pages);
0406         ra->async_size = ra->size;
0407         goto readit;
0408     }
0409 
0410     /*
0411      * Hit a marked page without valid readahead state.
0412      * E.g. interleaved reads.
0413      * Query the pagecache for async_size, which normally equals to
0414      * readahead size. Ramp it up and use it as the new readahead size.
0415      */
0416     if (hit_readahead_marker) {
0417         pgoff_t start;
0418 
0419         rcu_read_lock();
0420         start = page_cache_next_hole(mapping, offset + 1, max_pages);
0421         rcu_read_unlock();
0422 
0423         if (!start || start - offset > max_pages)
0424             return 0;
0425 
0426         ra->start = start;
0427         ra->size = start - offset;  /* old async_size */
0428         ra->size += req_size;
0429         ra->size = get_next_ra_size(ra, max_pages);
0430         ra->async_size = ra->size;
0431         goto readit;
0432     }
0433 
0434     /*
0435      * oversize read
0436      */
0437     if (req_size > max_pages)
0438         goto initial_readahead;
0439 
0440     /*
0441      * sequential cache miss
0442      * trivial case: (offset - prev_offset) == 1
0443      * unaligned reads: (offset - prev_offset) == 0
0444      */
0445     prev_offset = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
0446     if (offset - prev_offset <= 1UL)
0447         goto initial_readahead;
0448 
0449     /*
0450      * Query the page cache and look for the traces(cached history pages)
0451      * that a sequential stream would leave behind.
0452      */
0453     if (try_context_readahead(mapping, ra, offset, req_size, max_pages))
0454         goto readit;
0455 
0456     /*
0457      * standalone, small random read
0458      * Read as is, and do not pollute the readahead state.
0459      */
0460     return __do_page_cache_readahead(mapping, filp, offset, req_size, 0);
0461 
0462 initial_readahead:
0463     ra->start = offset;
0464     ra->size = get_init_ra_size(req_size, max_pages);
0465     ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size;
0466 
0467 readit:
0468     /*
0469      * Will this read hit the readahead marker made by itself?
0470      * If so, trigger the readahead marker hit now, and merge
0471      * the resulted next readahead window into the current one.
0472      */
0473     if (offset == ra->start && ra->size == ra->async_size) {
0474         ra->async_size = get_next_ra_size(ra, max_pages);
0475         ra->size += ra->async_size;
0476     }
0477 
0478     return ra_submit(ra, mapping, filp);
0479 }
0480 
0481 /**
0482  * page_cache_sync_readahead - generic file readahead
0483  * @mapping: address_space which holds the pagecache and I/O vectors
0484  * @ra: file_ra_state which holds the readahead state
0485  * @filp: passed on to ->readpage() and ->readpages()
0486  * @offset: start offset into @mapping, in pagecache page-sized units
0487  * @req_size: hint: total size of the read which the caller is performing in
0488  *            pagecache pages
0489  *
0490  * page_cache_sync_readahead() should be called when a cache miss happened:
0491  * it will submit the read.  The readahead logic may decide to piggyback more
0492  * pages onto the read request if access patterns suggest it will improve
0493  * performance.
0494  */
0495 void page_cache_sync_readahead(struct address_space *mapping,
0496                    struct file_ra_state *ra, struct file *filp,
0497                    pgoff_t offset, unsigned long req_size)
0498 {
0499     /* no read-ahead */
0500     if (!ra->ra_pages)
0501         return;
0502 
0503     /* be dumb */
0504     if (filp && (filp->f_mode & FMODE_RANDOM)) {
0505         force_page_cache_readahead(mapping, filp, offset, req_size);
0506         return;
0507     }
0508 
0509     /* do read-ahead */
0510     ondemand_readahead(mapping, ra, filp, false, offset, req_size);
0511 }
0512 EXPORT_SYMBOL_GPL(page_cache_sync_readahead);
0513 
0514 /**
0515  * page_cache_async_readahead - file readahead for marked pages
0516  * @mapping: address_space which holds the pagecache and I/O vectors
0517  * @ra: file_ra_state which holds the readahead state
0518  * @filp: passed on to ->readpage() and ->readpages()
0519  * @page: the page at @offset which has the PG_readahead flag set
0520  * @offset: start offset into @mapping, in pagecache page-sized units
0521  * @req_size: hint: total size of the read which the caller is performing in
0522  *            pagecache pages
0523  *
0524  * page_cache_async_readahead() should be called when a page is used which
0525  * has the PG_readahead flag; this is a marker to suggest that the application
0526  * has used up enough of the readahead window that we should start pulling in
0527  * more pages.
0528  */
0529 void
0530 page_cache_async_readahead(struct address_space *mapping,
0531                struct file_ra_state *ra, struct file *filp,
0532                struct page *page, pgoff_t offset,
0533                unsigned long req_size)
0534 {
0535     /* no read-ahead */
0536     if (!ra->ra_pages)
0537         return;
0538 
0539     /*
0540      * Same bit is used for PG_readahead and PG_reclaim.
0541      */
0542     if (PageWriteback(page))
0543         return;
0544 
0545     ClearPageReadahead(page);
0546 
0547     /*
0548      * Defer asynchronous read-ahead on IO congestion.
0549      */
0550     if (inode_read_congested(mapping->host))
0551         return;
0552 
0553     /* do read-ahead */
0554     ondemand_readahead(mapping, ra, filp, true, offset, req_size);
0555 }
0556 EXPORT_SYMBOL_GPL(page_cache_async_readahead);
0557 
0558 static ssize_t
0559 do_readahead(struct address_space *mapping, struct file *filp,
0560          pgoff_t index, unsigned long nr)
0561 {
0562     if (!mapping || !mapping->a_ops)
0563         return -EINVAL;
0564 
0565     /*
0566      * Readahead doesn't make sense for DAX inodes, but we don't want it
0567      * to report a failure either.  Instead, we just return success and
0568      * don't do any work.
0569      */
0570     if (dax_mapping(mapping))
0571         return 0;
0572 
0573     return force_page_cache_readahead(mapping, filp, index, nr);
0574 }
0575 
0576 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
0577 {
0578     ssize_t ret;
0579     struct fd f;
0580 
0581     ret = -EBADF;
0582     f = fdget(fd);
0583     if (f.file) {
0584         if (f.file->f_mode & FMODE_READ) {
0585             struct address_space *mapping = f.file->f_mapping;
0586             pgoff_t start = offset >> PAGE_SHIFT;
0587             pgoff_t end = (offset + count - 1) >> PAGE_SHIFT;
0588             unsigned long len = end - start + 1;
0589             ret = do_readahead(mapping, f.file, start, len);
0590         }
0591         fdput(f);
0592     }
0593     return ret;
0594 }