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