OSDN Git Service

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