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