mm/readahead: make page_cache_ra_unbounded take a readahead_control
[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 #include <linux/kernel.h>
12 #include <linux/dax.h>
13 #include <linux/gfp.h>
14 #include <linux/export.h>
15 #include <linux/blkdev.h>
16 #include <linux/backing-dev.h>
17 #include <linux/task_io_accounting_ops.h>
18 #include <linux/pagevec.h>
19 #include <linux/pagemap.h>
20 #include <linux/syscalls.h>
21 #include <linux/file.h>
22 #include <linux/mm_inline.h>
23 #include <linux/blk-cgroup.h>
24 #include <linux/fadvise.h>
25 #include <linux/sched/mm.h>
26
27 #include "internal.h"
28
29 /*
30  * Initialise a struct file's readahead state.  Assumes that the caller has
31  * memset *ra to zero.
32  */
33 void
34 file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
35 {
36         ra->ra_pages = inode_to_bdi(mapping->host)->ra_pages;
37         ra->prev_pos = -1;
38 }
39 EXPORT_SYMBOL_GPL(file_ra_state_init);
40
41 /*
42  * see if a page needs releasing upon read_cache_pages() failure
43  * - the caller of read_cache_pages() may have set PG_private or PG_fscache
44  *   before calling, such as the NFS fs marking pages that are cached locally
45  *   on disk, thus we need to give the fs a chance to clean up in the event of
46  *   an error
47  */
48 static void read_cache_pages_invalidate_page(struct address_space *mapping,
49                                              struct page *page)
50 {
51         if (page_has_private(page)) {
52                 if (!trylock_page(page))
53                         BUG();
54                 page->mapping = mapping;
55                 do_invalidatepage(page, 0, PAGE_SIZE);
56                 page->mapping = NULL;
57                 unlock_page(page);
58         }
59         put_page(page);
60 }
61
62 /*
63  * release a list of pages, invalidating them first if need be
64  */
65 static void read_cache_pages_invalidate_pages(struct address_space *mapping,
66                                               struct list_head *pages)
67 {
68         struct page *victim;
69
70         while (!list_empty(pages)) {
71                 victim = lru_to_page(pages);
72                 list_del(&victim->lru);
73                 read_cache_pages_invalidate_page(mapping, victim);
74         }
75 }
76
77 /**
78  * read_cache_pages - populate an address space with some pages & start reads against them
79  * @mapping: the address_space
80  * @pages: The address of a list_head which contains the target pages.  These
81  *   pages have their ->index populated and are otherwise uninitialised.
82  * @filler: callback routine for filling a single page.
83  * @data: private data for the callback routine.
84  *
85  * Hides the details of the LRU cache etc from the filesystems.
86  *
87  * Returns: %0 on success, error return by @filler otherwise
88  */
89 int read_cache_pages(struct address_space *mapping, struct list_head *pages,
90                         int (*filler)(void *, struct page *), void *data)
91 {
92         struct page *page;
93         int ret = 0;
94
95         while (!list_empty(pages)) {
96                 page = lru_to_page(pages);
97                 list_del(&page->lru);
98                 if (add_to_page_cache_lru(page, mapping, page->index,
99                                 readahead_gfp_mask(mapping))) {
100                         read_cache_pages_invalidate_page(mapping, page);
101                         continue;
102                 }
103                 put_page(page);
104
105                 ret = filler(data, page);
106                 if (unlikely(ret)) {
107                         read_cache_pages_invalidate_pages(mapping, pages);
108                         break;
109                 }
110                 task_io_account_read(PAGE_SIZE);
111         }
112         return ret;
113 }
114
115 EXPORT_SYMBOL(read_cache_pages);
116
117 static void read_pages(struct readahead_control *rac, struct list_head *pages,
118                 bool skip_page)
119 {
120         const struct address_space_operations *aops = rac->mapping->a_ops;
121         struct page *page;
122         struct blk_plug plug;
123
124         if (!readahead_count(rac))
125                 goto out;
126
127         blk_start_plug(&plug);
128
129         if (aops->readahead) {
130                 aops->readahead(rac);
131                 /* Clean up the remaining pages */
132                 while ((page = readahead_page(rac))) {
133                         unlock_page(page);
134                         put_page(page);
135                 }
136         } else if (aops->readpages) {
137                 aops->readpages(rac->file, rac->mapping, pages,
138                                 readahead_count(rac));
139                 /* Clean up the remaining pages */
140                 put_pages_list(pages);
141                 rac->_index += rac->_nr_pages;
142                 rac->_nr_pages = 0;
143         } else {
144                 while ((page = readahead_page(rac))) {
145                         aops->readpage(rac->file, page);
146                         put_page(page);
147                 }
148         }
149
150         blk_finish_plug(&plug);
151
152         BUG_ON(!list_empty(pages));
153         BUG_ON(readahead_count(rac));
154
155 out:
156         if (skip_page)
157                 rac->_index++;
158 }
159
160 /**
161  * page_cache_ra_unbounded - Start unchecked readahead.
162  * @ractl: Readahead control.
163  * @nr_to_read: The number of pages to read.
164  * @lookahead_size: Where to start the next readahead.
165  *
166  * This function is for filesystems to call when they want to start
167  * readahead beyond a file's stated i_size.  This is almost certainly
168  * not the function you want to call.  Use page_cache_async_readahead()
169  * or page_cache_sync_readahead() instead.
170  *
171  * Context: File is referenced by caller.  Mutexes may be held by caller.
172  * May sleep, but will not reenter filesystem to reclaim memory.
173  */
174 void page_cache_ra_unbounded(struct readahead_control *ractl,
175                 unsigned long nr_to_read, unsigned long lookahead_size)
176 {
177         struct address_space *mapping = ractl->mapping;
178         unsigned long index = readahead_index(ractl);
179         LIST_HEAD(page_pool);
180         gfp_t gfp_mask = readahead_gfp_mask(mapping);
181         unsigned long i;
182
183         /*
184          * Partway through the readahead operation, we will have added
185          * locked pages to the page cache, but will not yet have submitted
186          * them for I/O.  Adding another page may need to allocate memory,
187          * which can trigger memory reclaim.  Telling the VM we're in
188          * the middle of a filesystem operation will cause it to not
189          * touch file-backed pages, preventing a deadlock.  Most (all?)
190          * filesystems already specify __GFP_NOFS in their mapping's
191          * gfp_mask, but let's be explicit here.
192          */
193         unsigned int nofs = memalloc_nofs_save();
194
195         /*
196          * Preallocate as many pages as we will need.
197          */
198         for (i = 0; i < nr_to_read; i++) {
199                 struct page *page = xa_load(&mapping->i_pages, index + i);
200
201                 BUG_ON(index + i != ractl->_index + ractl->_nr_pages);
202
203                 if (page && !xa_is_value(page)) {
204                         /*
205                          * Page already present?  Kick off the current batch
206                          * of contiguous pages before continuing with the
207                          * next batch.  This page may be the one we would
208                          * have intended to mark as Readahead, but we don't
209                          * have a stable reference to this page, and it's
210                          * not worth getting one just for that.
211                          */
212                         read_pages(ractl, &page_pool, true);
213                         continue;
214                 }
215
216                 page = __page_cache_alloc(gfp_mask);
217                 if (!page)
218                         break;
219                 if (mapping->a_ops->readpages) {
220                         page->index = index + i;
221                         list_add(&page->lru, &page_pool);
222                 } else if (add_to_page_cache_lru(page, mapping, index + i,
223                                         gfp_mask) < 0) {
224                         put_page(page);
225                         read_pages(ractl, &page_pool, true);
226                         continue;
227                 }
228                 if (i == nr_to_read - lookahead_size)
229                         SetPageReadahead(page);
230                 ractl->_nr_pages++;
231         }
232
233         /*
234          * Now start the IO.  We ignore I/O errors - if the page is not
235          * uptodate then the caller will launch readpage again, and
236          * will then handle the error.
237          */
238         read_pages(ractl, &page_pool, false);
239         memalloc_nofs_restore(nofs);
240 }
241 EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
242
243 /*
244  * __do_page_cache_readahead() actually reads a chunk of disk.  It allocates
245  * the pages first, then submits them for I/O. This avoids the very bad
246  * behaviour which would occur if page allocations are causing VM writeback.
247  * We really don't want to intermingle reads and writes like that.
248  */
249 void __do_page_cache_readahead(struct address_space *mapping,
250                 struct file *file, pgoff_t index, unsigned long nr_to_read,
251                 unsigned long lookahead_size)
252 {
253         DEFINE_READAHEAD(ractl, file, mapping, index);
254         struct inode *inode = mapping->host;
255         loff_t isize = i_size_read(inode);
256         pgoff_t end_index;      /* The last page we want to read */
257
258         if (isize == 0)
259                 return;
260
261         end_index = (isize - 1) >> PAGE_SHIFT;
262         if (index > end_index)
263                 return;
264         /* Don't read past the page containing the last byte of the file */
265         if (nr_to_read > end_index - index)
266                 nr_to_read = end_index - index + 1;
267
268         page_cache_ra_unbounded(&ractl, nr_to_read, lookahead_size);
269 }
270
271 /*
272  * Chunk the readahead into 2 megabyte units, so that we don't pin too much
273  * memory at once.
274  */
275 void force_page_cache_readahead(struct address_space *mapping,
276                 struct file *filp, pgoff_t index, unsigned long nr_to_read)
277 {
278         struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
279         struct file_ra_state *ra = &filp->f_ra;
280         unsigned long max_pages;
281
282         if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages &&
283                         !mapping->a_ops->readahead))
284                 return;
285
286         /*
287          * If the request exceeds the readahead window, allow the read to
288          * be up to the optimal hardware IO size
289          */
290         max_pages = max_t(unsigned long, bdi->io_pages, ra->ra_pages);
291         nr_to_read = min(nr_to_read, max_pages);
292         while (nr_to_read) {
293                 unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_SIZE;
294
295                 if (this_chunk > nr_to_read)
296                         this_chunk = nr_to_read;
297                 __do_page_cache_readahead(mapping, filp, index, this_chunk, 0);
298
299                 index += this_chunk;
300                 nr_to_read -= this_chunk;
301         }
302 }
303
304 /*
305  * Set the initial window size, round to next power of 2 and square
306  * for small size, x 4 for medium, and x 2 for large
307  * for 128k (32 page) max ra
308  * 1-8 page = 32k initial, > 8 page = 128k initial
309  */
310 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
311 {
312         unsigned long newsize = roundup_pow_of_two(size);
313
314         if (newsize <= max / 32)
315                 newsize = newsize * 4;
316         else if (newsize <= max / 4)
317                 newsize = newsize * 2;
318         else
319                 newsize = max;
320
321         return newsize;
322 }
323
324 /*
325  *  Get the previous window size, ramp it up, and
326  *  return it as the new window size.
327  */
328 static unsigned long get_next_ra_size(struct file_ra_state *ra,
329                                       unsigned long max)
330 {
331         unsigned long cur = ra->size;
332
333         if (cur < max / 16)
334                 return 4 * cur;
335         if (cur <= max / 2)
336                 return 2 * cur;
337         return max;
338 }
339
340 /*
341  * On-demand readahead design.
342  *
343  * The fields in struct file_ra_state represent the most-recently-executed
344  * readahead attempt:
345  *
346  *                        |<----- async_size ---------|
347  *     |------------------- size -------------------->|
348  *     |==================#===========================|
349  *     ^start             ^page marked with PG_readahead
350  *
351  * To overlap application thinking time and disk I/O time, we do
352  * `readahead pipelining': Do not wait until the application consumed all
353  * readahead pages and stalled on the missing page at readahead_index;
354  * Instead, submit an asynchronous readahead I/O as soon as there are
355  * only async_size pages left in the readahead window. Normally async_size
356  * will be equal to size, for maximum pipelining.
357  *
358  * In interleaved sequential reads, concurrent streams on the same fd can
359  * be invalidating each other's readahead state. So we flag the new readahead
360  * page at (start+size-async_size) with PG_readahead, and use it as readahead
361  * indicator. The flag won't be set on already cached pages, to avoid the
362  * readahead-for-nothing fuss, saving pointless page cache lookups.
363  *
364  * prev_pos tracks the last visited byte in the _previous_ read request.
365  * It should be maintained by the caller, and will be used for detecting
366  * small random reads. Note that the readahead algorithm checks loosely
367  * for sequential patterns. Hence interleaved reads might be served as
368  * sequential ones.
369  *
370  * There is a special-case: if the first page which the application tries to
371  * read happens to be the first page of the file, it is assumed that a linear
372  * read is about to happen and the window is immediately set to the initial size
373  * based on I/O request size and the max_readahead.
374  *
375  * The code ramps up the readahead size aggressively at first, but slow down as
376  * it approaches max_readhead.
377  */
378
379 /*
380  * Count contiguously cached pages from @index-1 to @index-@max,
381  * this count is a conservative estimation of
382  *      - length of the sequential read sequence, or
383  *      - thrashing threshold in memory tight systems
384  */
385 static pgoff_t count_history_pages(struct address_space *mapping,
386                                    pgoff_t index, unsigned long max)
387 {
388         pgoff_t head;
389
390         rcu_read_lock();
391         head = page_cache_prev_miss(mapping, index - 1, max);
392         rcu_read_unlock();
393
394         return index - 1 - head;
395 }
396
397 /*
398  * page cache context based read-ahead
399  */
400 static int try_context_readahead(struct address_space *mapping,
401                                  struct file_ra_state *ra,
402                                  pgoff_t index,
403                                  unsigned long req_size,
404                                  unsigned long max)
405 {
406         pgoff_t size;
407
408         size = count_history_pages(mapping, index, max);
409
410         /*
411          * not enough history pages:
412          * it could be a random read
413          */
414         if (size <= req_size)
415                 return 0;
416
417         /*
418          * starts from beginning of file:
419          * it is a strong indication of long-run stream (or whole-file-read)
420          */
421         if (size >= index)
422                 size *= 2;
423
424         ra->start = index;
425         ra->size = min(size + req_size, max);
426         ra->async_size = 1;
427
428         return 1;
429 }
430
431 /*
432  * A minimal readahead algorithm for trivial sequential/random reads.
433  */
434 static void ondemand_readahead(struct address_space *mapping,
435                 struct file_ra_state *ra, struct file *filp,
436                 bool hit_readahead_marker, pgoff_t index,
437                 unsigned long req_size)
438 {
439         struct backing_dev_info *bdi = inode_to_bdi(mapping->host);
440         unsigned long max_pages = ra->ra_pages;
441         unsigned long add_pages;
442         pgoff_t prev_index;
443
444         /*
445          * If the request exceeds the readahead window, allow the read to
446          * be up to the optimal hardware IO size
447          */
448         if (req_size > max_pages && bdi->io_pages > max_pages)
449                 max_pages = min(req_size, bdi->io_pages);
450
451         /*
452          * start of file
453          */
454         if (!index)
455                 goto initial_readahead;
456
457         /*
458          * It's the expected callback index, assume sequential access.
459          * Ramp up sizes, and push forward the readahead window.
460          */
461         if ((index == (ra->start + ra->size - ra->async_size) ||
462              index == (ra->start + ra->size))) {
463                 ra->start += ra->size;
464                 ra->size = get_next_ra_size(ra, max_pages);
465                 ra->async_size = ra->size;
466                 goto readit;
467         }
468
469         /*
470          * Hit a marked page without valid readahead state.
471          * E.g. interleaved reads.
472          * Query the pagecache for async_size, which normally equals to
473          * readahead size. Ramp it up and use it as the new readahead size.
474          */
475         if (hit_readahead_marker) {
476                 pgoff_t start;
477
478                 rcu_read_lock();
479                 start = page_cache_next_miss(mapping, index + 1, max_pages);
480                 rcu_read_unlock();
481
482                 if (!start || start - index > max_pages)
483                         return;
484
485                 ra->start = start;
486                 ra->size = start - index;       /* old async_size */
487                 ra->size += req_size;
488                 ra->size = get_next_ra_size(ra, max_pages);
489                 ra->async_size = ra->size;
490                 goto readit;
491         }
492
493         /*
494          * oversize read
495          */
496         if (req_size > max_pages)
497                 goto initial_readahead;
498
499         /*
500          * sequential cache miss
501          * trivial case: (index - prev_index) == 1
502          * unaligned reads: (index - prev_index) == 0
503          */
504         prev_index = (unsigned long long)ra->prev_pos >> PAGE_SHIFT;
505         if (index - prev_index <= 1UL)
506                 goto initial_readahead;
507
508         /*
509          * Query the page cache and look for the traces(cached history pages)
510          * that a sequential stream would leave behind.
511          */
512         if (try_context_readahead(mapping, ra, index, req_size, max_pages))
513                 goto readit;
514
515         /*
516          * standalone, small random read
517          * Read as is, and do not pollute the readahead state.
518          */
519         __do_page_cache_readahead(mapping, filp, index, req_size, 0);
520         return;
521
522 initial_readahead:
523         ra->start = index;
524         ra->size = get_init_ra_size(req_size, max_pages);
525         ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size;
526
527 readit:
528         /*
529          * Will this read hit the readahead marker made by itself?
530          * If so, trigger the readahead marker hit now, and merge
531          * the resulted next readahead window into the current one.
532          * Take care of maximum IO pages as above.
533          */
534         if (index == ra->start && ra->size == ra->async_size) {
535                 add_pages = get_next_ra_size(ra, max_pages);
536                 if (ra->size + add_pages <= max_pages) {
537                         ra->async_size = add_pages;
538                         ra->size += add_pages;
539                 } else {
540                         ra->size = max_pages;
541                         ra->async_size = max_pages >> 1;
542                 }
543         }
544
545         ra_submit(ra, mapping, filp);
546 }
547
548 /**
549  * page_cache_sync_readahead - generic file readahead
550  * @mapping: address_space which holds the pagecache and I/O vectors
551  * @ra: file_ra_state which holds the readahead state
552  * @filp: passed on to ->readpage() and ->readpages()
553  * @index: Index of first page to be read.
554  * @req_count: Total number of pages being read by the caller.
555  *
556  * page_cache_sync_readahead() should be called when a cache miss happened:
557  * it will submit the read.  The readahead logic may decide to piggyback more
558  * pages onto the read request if access patterns suggest it will improve
559  * performance.
560  */
561 void page_cache_sync_readahead(struct address_space *mapping,
562                                struct file_ra_state *ra, struct file *filp,
563                                pgoff_t index, unsigned long req_count)
564 {
565         /* no read-ahead */
566         if (!ra->ra_pages)
567                 return;
568
569         if (blk_cgroup_congested())
570                 return;
571
572         /* be dumb */
573         if (filp && (filp->f_mode & FMODE_RANDOM)) {
574                 force_page_cache_readahead(mapping, filp, index, req_count);
575                 return;
576         }
577
578         /* do read-ahead */
579         ondemand_readahead(mapping, ra, filp, false, index, req_count);
580 }
581 EXPORT_SYMBOL_GPL(page_cache_sync_readahead);
582
583 /**
584  * page_cache_async_readahead - file readahead for marked pages
585  * @mapping: address_space which holds the pagecache and I/O vectors
586  * @ra: file_ra_state which holds the readahead state
587  * @filp: passed on to ->readpage() and ->readpages()
588  * @page: The page at @index which triggered the readahead call.
589  * @index: Index of first page to be read.
590  * @req_count: Total number of pages being read by the caller.
591  *
592  * page_cache_async_readahead() should be called when a page is used which
593  * is marked as PageReadahead; this is a marker to suggest that the application
594  * has used up enough of the readahead window that we should start pulling in
595  * more pages.
596  */
597 void
598 page_cache_async_readahead(struct address_space *mapping,
599                            struct file_ra_state *ra, struct file *filp,
600                            struct page *page, pgoff_t index,
601                            unsigned long req_count)
602 {
603         /* no read-ahead */
604         if (!ra->ra_pages)
605                 return;
606
607         /*
608          * Same bit is used for PG_readahead and PG_reclaim.
609          */
610         if (PageWriteback(page))
611                 return;
612
613         ClearPageReadahead(page);
614
615         /*
616          * Defer asynchronous read-ahead on IO congestion.
617          */
618         if (inode_read_congested(mapping->host))
619                 return;
620
621         if (blk_cgroup_congested())
622                 return;
623
624         /* do read-ahead */
625         ondemand_readahead(mapping, ra, filp, true, index, req_count);
626 }
627 EXPORT_SYMBOL_GPL(page_cache_async_readahead);
628
629 ssize_t ksys_readahead(int fd, loff_t offset, size_t count)
630 {
631         ssize_t ret;
632         struct fd f;
633
634         ret = -EBADF;
635         f = fdget(fd);
636         if (!f.file || !(f.file->f_mode & FMODE_READ))
637                 goto out;
638
639         /*
640          * The readahead() syscall is intended to run only on files
641          * that can execute readahead. If readahead is not possible
642          * on this file, then we must return -EINVAL.
643          */
644         ret = -EINVAL;
645         if (!f.file->f_mapping || !f.file->f_mapping->a_ops ||
646             !S_ISREG(file_inode(f.file)->i_mode))
647                 goto out;
648
649         ret = vfs_fadvise(f.file, offset, count, POSIX_FADV_WILLNEED);
650 out:
651         fdput(f);
652         return ret;
653 }
654
655 SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count)
656 {
657         return ksys_readahead(fd, offset, count);
658 }