xref: /linux/mm/readahead.c (revision d8327c784b51b57dac2c26cfad87dce0d68dfd98)
1 /*
2  * mm/readahead.c - address_space-level file readahead.
3  *
4  * Copyright (C) 2002, Linus Torvalds
5  *
6  * 09Apr2002	akpm@zip.com.au
7  *		Initial version.
8  */
9 
10 #include <linux/kernel.h>
11 #include <linux/fs.h>
12 #include <linux/mm.h>
13 #include <linux/module.h>
14 #include <linux/blkdev.h>
15 #include <linux/backing-dev.h>
16 #include <linux/pagevec.h>
17 
18 void default_unplug_io_fn(struct backing_dev_info *bdi, struct page *page)
19 {
20 }
21 EXPORT_SYMBOL(default_unplug_io_fn);
22 
23 struct backing_dev_info default_backing_dev_info = {
24 	.ra_pages	= (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE,
25 	.state		= 0,
26 	.capabilities	= BDI_CAP_MAP_COPY,
27 	.unplug_io_fn	= default_unplug_io_fn,
28 };
29 EXPORT_SYMBOL_GPL(default_backing_dev_info);
30 
31 /*
32  * Initialise a struct file's readahead state.  Assumes that the caller has
33  * memset *ra to zero.
34  */
35 void
36 file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping)
37 {
38 	ra->ra_pages = mapping->backing_dev_info->ra_pages;
39 	ra->prev_page = -1;
40 }
41 
42 /*
43  * Return max readahead size for this inode in number-of-pages.
44  */
45 static inline unsigned long get_max_readahead(struct file_ra_state *ra)
46 {
47 	return ra->ra_pages;
48 }
49 
50 static inline unsigned long get_min_readahead(struct file_ra_state *ra)
51 {
52 	return (VM_MIN_READAHEAD * 1024) / PAGE_CACHE_SIZE;
53 }
54 
55 static inline void ra_off(struct file_ra_state *ra)
56 {
57 	ra->start = 0;
58 	ra->flags = 0;
59 	ra->size = 0;
60 	ra->ahead_start = 0;
61 	ra->ahead_size = 0;
62 	return;
63 }
64 
65 /*
66  * Set the initial window size, round to next power of 2 and square
67  * for small size, x 4 for medium, and x 2 for large
68  * for 128k (32 page) max ra
69  * 1-8 page = 32k initial, > 8 page = 128k initial
70  */
71 static unsigned long get_init_ra_size(unsigned long size, unsigned long max)
72 {
73 	unsigned long newsize = roundup_pow_of_two(size);
74 
75 	if (newsize <= max / 64)
76 		newsize = newsize * newsize;
77 	else if (newsize <= max / 4)
78 		newsize = max / 4;
79 	else
80 		newsize = max;
81 	return newsize;
82 }
83 
84 /*
85  * Set the new window size, this is called only when I/O is to be submitted,
86  * not for each call to readahead.  If a cache miss occured, reduce next I/O
87  * size, else increase depending on how close to max we are.
88  */
89 static inline unsigned long get_next_ra_size(struct file_ra_state *ra)
90 {
91 	unsigned long max = get_max_readahead(ra);
92 	unsigned long min = get_min_readahead(ra);
93 	unsigned long cur = ra->size;
94 	unsigned long newsize;
95 
96 	if (ra->flags & RA_FLAG_MISS) {
97 		ra->flags &= ~RA_FLAG_MISS;
98 		newsize = max((cur - 2), min);
99 	} else if (cur < max / 16) {
100 		newsize = 4 * cur;
101 	} else {
102 		newsize = 2 * cur;
103 	}
104 	return min(newsize, max);
105 }
106 
107 #define list_to_page(head) (list_entry((head)->prev, struct page, lru))
108 
109 /**
110  * read_cache_pages - populate an address space with some pages, and
111  * 			start reads against them.
112  * @mapping: the address_space
113  * @pages: The address of a list_head which contains the target pages.  These
114  *   pages have their ->index populated and are otherwise uninitialised.
115  * @filler: callback routine for filling a single page.
116  * @data: private data for the callback routine.
117  *
118  * Hides the details of the LRU cache etc from the filesystems.
119  */
120 int read_cache_pages(struct address_space *mapping, struct list_head *pages,
121 			int (*filler)(void *, struct page *), void *data)
122 {
123 	struct page *page;
124 	struct pagevec lru_pvec;
125 	int ret = 0;
126 
127 	pagevec_init(&lru_pvec, 0);
128 
129 	while (!list_empty(pages)) {
130 		page = list_to_page(pages);
131 		list_del(&page->lru);
132 		if (add_to_page_cache(page, mapping, page->index, GFP_KERNEL)) {
133 			page_cache_release(page);
134 			continue;
135 		}
136 		ret = filler(data, page);
137 		if (!pagevec_add(&lru_pvec, page))
138 			__pagevec_lru_add(&lru_pvec);
139 		if (ret) {
140 			while (!list_empty(pages)) {
141 				struct page *victim;
142 
143 				victim = list_to_page(pages);
144 				list_del(&victim->lru);
145 				page_cache_release(victim);
146 			}
147 			break;
148 		}
149 	}
150 	pagevec_lru_add(&lru_pvec);
151 	return ret;
152 }
153 
154 EXPORT_SYMBOL(read_cache_pages);
155 
156 static int read_pages(struct address_space *mapping, struct file *filp,
157 		struct list_head *pages, unsigned nr_pages)
158 {
159 	unsigned page_idx;
160 	struct pagevec lru_pvec;
161 	int ret;
162 
163 	if (mapping->a_ops->readpages) {
164 		ret = mapping->a_ops->readpages(filp, mapping, pages, nr_pages);
165 		goto out;
166 	}
167 
168 	pagevec_init(&lru_pvec, 0);
169 	for (page_idx = 0; page_idx < nr_pages; page_idx++) {
170 		struct page *page = list_to_page(pages);
171 		list_del(&page->lru);
172 		if (!add_to_page_cache(page, mapping,
173 					page->index, GFP_KERNEL)) {
174 			ret = mapping->a_ops->readpage(filp, page);
175 			if (ret != AOP_TRUNCATED_PAGE) {
176 				if (!pagevec_add(&lru_pvec, page))
177 					__pagevec_lru_add(&lru_pvec);
178 				continue;
179 			} /* else fall through to release */
180 		}
181 		page_cache_release(page);
182 	}
183 	pagevec_lru_add(&lru_pvec);
184 	ret = 0;
185 out:
186 	return ret;
187 }
188 
189 /*
190  * Readahead design.
191  *
192  * The fields in struct file_ra_state represent the most-recently-executed
193  * readahead attempt:
194  *
195  * start:	Page index at which we started the readahead
196  * size:	Number of pages in that read
197  *              Together, these form the "current window".
198  *              Together, start and size represent the `readahead window'.
199  * prev_page:   The page which the readahead algorithm most-recently inspected.
200  *              It is mainly used to detect sequential file reading.
201  *              If page_cache_readahead sees that it is again being called for
202  *              a page which it just looked at, it can return immediately without
203  *              making any state changes.
204  * ahead_start,
205  * ahead_size:  Together, these form the "ahead window".
206  * ra_pages:	The externally controlled max readahead for this fd.
207  *
208  * When readahead is in the off state (size == 0), readahead is disabled.
209  * In this state, prev_page is used to detect the resumption of sequential I/O.
210  *
211  * The readahead code manages two windows - the "current" and the "ahead"
212  * windows.  The intent is that while the application is walking the pages
213  * in the current window, I/O is underway on the ahead window.  When the
214  * current window is fully traversed, it is replaced by the ahead window
215  * and the ahead window is invalidated.  When this copying happens, the
216  * new current window's pages are probably still locked.  So
217  * we submit a new batch of I/O immediately, creating a new ahead window.
218  *
219  * So:
220  *
221  *   ----|----------------|----------------|-----
222  *       ^start           ^start+size
223  *                        ^ahead_start     ^ahead_start+ahead_size
224  *
225  *         ^ When this page is read, we submit I/O for the
226  *           ahead window.
227  *
228  * A `readahead hit' occurs when a read request is made against a page which is
229  * the next sequential page. Ahead window calculations are done only when it
230  * is time to submit a new IO.  The code ramps up the size agressively at first,
231  * but slow down as it approaches max_readhead.
232  *
233  * Any seek/ramdom IO will result in readahead being turned off.  It will resume
234  * at the first sequential access.
235  *
236  * There is a special-case: if the first page which the application tries to
237  * read happens to be the first page of the file, it is assumed that a linear
238  * read is about to happen and the window is immediately set to the initial size
239  * based on I/O request size and the max_readahead.
240  *
241  * This function is to be called for every read request, rather than when
242  * it is time to perform readahead.  It is called only once for the entire I/O
243  * regardless of size unless readahead is unable to start enough I/O to satisfy
244  * the request (I/O request > max_readahead).
245  */
246 
247 /*
248  * do_page_cache_readahead actually reads a chunk of disk.  It allocates all
249  * the pages first, then submits them all for I/O. This avoids the very bad
250  * behaviour which would occur if page allocations are causing VM writeback.
251  * We really don't want to intermingle reads and writes like that.
252  *
253  * Returns the number of pages requested, or the maximum amount of I/O allowed.
254  *
255  * do_page_cache_readahead() returns -1 if it encountered request queue
256  * congestion.
257  */
258 static int
259 __do_page_cache_readahead(struct address_space *mapping, struct file *filp,
260 			pgoff_t offset, unsigned long nr_to_read)
261 {
262 	struct inode *inode = mapping->host;
263 	struct page *page;
264 	unsigned long end_index;	/* The last page we want to read */
265 	LIST_HEAD(page_pool);
266 	int page_idx;
267 	int ret = 0;
268 	loff_t isize = i_size_read(inode);
269 
270 	if (isize == 0)
271 		goto out;
272 
273  	end_index = ((isize - 1) >> PAGE_CACHE_SHIFT);
274 
275 	/*
276 	 * Preallocate as many pages as we will need.
277 	 */
278 	read_lock_irq(&mapping->tree_lock);
279 	for (page_idx = 0; page_idx < nr_to_read; page_idx++) {
280 		pgoff_t page_offset = offset + page_idx;
281 
282 		if (page_offset > end_index)
283 			break;
284 
285 		page = radix_tree_lookup(&mapping->page_tree, page_offset);
286 		if (page)
287 			continue;
288 
289 		read_unlock_irq(&mapping->tree_lock);
290 		page = page_cache_alloc_cold(mapping);
291 		read_lock_irq(&mapping->tree_lock);
292 		if (!page)
293 			break;
294 		page->index = page_offset;
295 		list_add(&page->lru, &page_pool);
296 		ret++;
297 	}
298 	read_unlock_irq(&mapping->tree_lock);
299 
300 	/*
301 	 * Now start the IO.  We ignore I/O errors - if the page is not
302 	 * uptodate then the caller will launch readpage again, and
303 	 * will then handle the error.
304 	 */
305 	if (ret)
306 		read_pages(mapping, filp, &page_pool, ret);
307 	BUG_ON(!list_empty(&page_pool));
308 out:
309 	return ret;
310 }
311 
312 /*
313  * Chunk the readahead into 2 megabyte units, so that we don't pin too much
314  * memory at once.
315  */
316 int force_page_cache_readahead(struct address_space *mapping, struct file *filp,
317 		pgoff_t offset, unsigned long nr_to_read)
318 {
319 	int ret = 0;
320 
321 	if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages))
322 		return -EINVAL;
323 
324 	while (nr_to_read) {
325 		int err;
326 
327 		unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_CACHE_SIZE;
328 
329 		if (this_chunk > nr_to_read)
330 			this_chunk = nr_to_read;
331 		err = __do_page_cache_readahead(mapping, filp,
332 						offset, this_chunk);
333 		if (err < 0) {
334 			ret = err;
335 			break;
336 		}
337 		ret += err;
338 		offset += this_chunk;
339 		nr_to_read -= this_chunk;
340 	}
341 	return ret;
342 }
343 
344 /*
345  * Check how effective readahead is being.  If the amount of started IO is
346  * less than expected then the file is partly or fully in pagecache and
347  * readahead isn't helping.
348  *
349  */
350 static inline int check_ra_success(struct file_ra_state *ra,
351 			unsigned long nr_to_read, unsigned long actual)
352 {
353 	if (actual == 0) {
354 		ra->cache_hit += nr_to_read;
355 		if (ra->cache_hit >= VM_MAX_CACHE_HIT) {
356 			ra_off(ra);
357 			ra->flags |= RA_FLAG_INCACHE;
358 			return 0;
359 		}
360 	} else {
361 		ra->cache_hit=0;
362 	}
363 	return 1;
364 }
365 
366 /*
367  * This version skips the IO if the queue is read-congested, and will tell the
368  * block layer to abandon the readahead if request allocation would block.
369  *
370  * force_page_cache_readahead() will ignore queue congestion and will block on
371  * request queues.
372  */
373 int do_page_cache_readahead(struct address_space *mapping, struct file *filp,
374 			pgoff_t offset, unsigned long nr_to_read)
375 {
376 	if (bdi_read_congested(mapping->backing_dev_info))
377 		return -1;
378 
379 	return __do_page_cache_readahead(mapping, filp, offset, nr_to_read);
380 }
381 
382 /*
383  * Read 'nr_to_read' pages starting at page 'offset'. If the flag 'block'
384  * is set wait till the read completes.  Otherwise attempt to read without
385  * blocking.
386  * Returns 1 meaning 'success' if read is succesfull without switching off
387  * readhaead mode. Otherwise return failure.
388  */
389 static int
390 blockable_page_cache_readahead(struct address_space *mapping, struct file *filp,
391 			pgoff_t offset, unsigned long nr_to_read,
392 			struct file_ra_state *ra, int block)
393 {
394 	int actual;
395 
396 	if (!block && bdi_read_congested(mapping->backing_dev_info))
397 		return 0;
398 
399 	actual = __do_page_cache_readahead(mapping, filp, offset, nr_to_read);
400 
401 	return check_ra_success(ra, nr_to_read, actual);
402 }
403 
404 static int make_ahead_window(struct address_space *mapping, struct file *filp,
405 				struct file_ra_state *ra, int force)
406 {
407 	int block, ret;
408 
409 	ra->ahead_size = get_next_ra_size(ra);
410 	ra->ahead_start = ra->start + ra->size;
411 
412 	block = force || (ra->prev_page >= ra->ahead_start);
413 	ret = blockable_page_cache_readahead(mapping, filp,
414 			ra->ahead_start, ra->ahead_size, ra, block);
415 
416 	if (!ret && !force) {
417 		/* A read failure in blocking mode, implies pages are
418 		 * all cached. So we can safely assume we have taken
419 		 * care of all the pages requested in this call.
420 		 * A read failure in non-blocking mode, implies we are
421 		 * reading more pages than requested in this call.  So
422 		 * we safely assume we have taken care of all the pages
423 		 * requested in this call.
424 		 *
425 		 * Just reset the ahead window in case we failed due to
426 		 * congestion.  The ahead window will any way be closed
427 		 * in case we failed due to excessive page cache hits.
428 		 */
429 		ra->ahead_start = 0;
430 		ra->ahead_size = 0;
431 	}
432 
433 	return ret;
434 }
435 
436 /**
437  * page_cache_readahead - generic adaptive readahead
438  * @mapping: address_space which holds the pagecache and I/O vectors
439  * @ra: file_ra_state which holds the readahead state
440  * @filp: passed on to ->readpage() and ->readpages()
441  * @offset: start offset into @mapping, in PAGE_CACHE_SIZE units
442  * @req_size: hint: total size of the read which the caller is performing in
443  *            PAGE_CACHE_SIZE units
444  *
445  * page_cache_readahead() is the main function.  If performs the adaptive
446  * readahead window size management and submits the readahead I/O.
447  *
448  * Note that @filp is purely used for passing on to the ->readpage[s]()
449  * handler: it may refer to a different file from @mapping (so we may not use
450  * @filp->f_mapping or @filp->f_dentry->d_inode here).
451  * Also, @ra may not be equal to &@filp->f_ra.
452  *
453  */
454 unsigned long
455 page_cache_readahead(struct address_space *mapping, struct file_ra_state *ra,
456 		     struct file *filp, pgoff_t offset, unsigned long req_size)
457 {
458 	unsigned long max, newsize;
459 	int sequential;
460 
461 	/*
462 	 * We avoid doing extra work and bogusly perturbing the readahead
463 	 * window expansion logic.
464 	 */
465 	if (offset == ra->prev_page && --req_size)
466 		++offset;
467 
468 	/* Note that prev_page == -1 if it is a first read */
469 	sequential = (offset == ra->prev_page + 1);
470 	ra->prev_page = offset;
471 
472 	max = get_max_readahead(ra);
473 	newsize = min(req_size, max);
474 
475 	/* No readahead or sub-page sized read or file already in cache */
476 	if (newsize == 0 || (ra->flags & RA_FLAG_INCACHE))
477 		goto out;
478 
479 	ra->prev_page += newsize - 1;
480 
481 	/*
482 	 * Special case - first read at start of file. We'll assume it's
483 	 * a whole-file read and grow the window fast.  Or detect first
484 	 * sequential access
485 	 */
486 	if (sequential && ra->size == 0) {
487 		ra->size = get_init_ra_size(newsize, max);
488 		ra->start = offset;
489 		if (!blockable_page_cache_readahead(mapping, filp, offset,
490 							 ra->size, ra, 1))
491 			goto out;
492 
493 		/*
494 		 * If the request size is larger than our max readahead, we
495 		 * at least want to be sure that we get 2 IOs in flight and
496 		 * we know that we will definitly need the new I/O.
497 		 * once we do this, subsequent calls should be able to overlap
498 		 * IOs,* thus preventing stalls. so issue the ahead window
499 		 * immediately.
500 		 */
501 		if (req_size >= max)
502 			make_ahead_window(mapping, filp, ra, 1);
503 
504 		goto out;
505 	}
506 
507 	/*
508 	 * Now handle the random case:
509 	 * partial page reads and first access were handled above,
510 	 * so this must be the next page otherwise it is random
511 	 */
512 	if (!sequential) {
513 		ra_off(ra);
514 		blockable_page_cache_readahead(mapping, filp, offset,
515 				 newsize, ra, 1);
516 		goto out;
517 	}
518 
519 	/*
520 	 * If we get here we are doing sequential IO and this was not the first
521 	 * occurence (ie we have an existing window)
522 	 */
523 
524 	if (ra->ahead_start == 0) {	 /* no ahead window yet */
525 		if (!make_ahead_window(mapping, filp, ra, 0))
526 			goto out;
527 	}
528 	/*
529 	 * Already have an ahead window, check if we crossed into it.
530 	 * If so, shift windows and issue a new ahead window.
531 	 * Only return the #pages that are in the current window, so that
532 	 * we get called back on the first page of the ahead window which
533 	 * will allow us to submit more IO.
534 	 */
535 	if (ra->prev_page >= ra->ahead_start) {
536 		ra->start = ra->ahead_start;
537 		ra->size = ra->ahead_size;
538 		make_ahead_window(mapping, filp, ra, 0);
539 	}
540 
541 out:
542 	return ra->prev_page + 1;
543 }
544 
545 /*
546  * handle_ra_miss() is called when it is known that a page which should have
547  * been present in the pagecache (we just did some readahead there) was in fact
548  * not found.  This will happen if it was evicted by the VM (readahead
549  * thrashing)
550  *
551  * Turn on the cache miss flag in the RA struct, this will cause the RA code
552  * to reduce the RA size on the next read.
553  */
554 void handle_ra_miss(struct address_space *mapping,
555 		struct file_ra_state *ra, pgoff_t offset)
556 {
557 	ra->flags |= RA_FLAG_MISS;
558 	ra->flags &= ~RA_FLAG_INCACHE;
559 	ra->cache_hit = 0;
560 }
561 
562 /*
563  * Given a desired number of PAGE_CACHE_SIZE readahead pages, return a
564  * sensible upper limit.
565  */
566 unsigned long max_sane_readahead(unsigned long nr)
567 {
568 	unsigned long active;
569 	unsigned long inactive;
570 	unsigned long free;
571 
572 	__get_zone_counts(&active, &inactive, &free, NODE_DATA(numa_node_id()));
573 	return min(nr, (inactive + free) / 2);
574 }
575