Merge branch 'master'
[linux-2.6.git] / mm / filemap.c
1 /*
2  *      linux/mm/filemap.c
3  *
4  * Copyright (C) 1994-1999  Linus Torvalds
5  */
6
7 /*
8  * This file handles the generic file mmap semantics used by
9  * most "normal" filesystems (but you don't /have/ to use this:
10  * the NFS filesystem used to do this differently, for example)
11  */
12 #include <linux/module.h>
13 #include <linux/slab.h>
14 #include <linux/compiler.h>
15 #include <linux/fs.h>
16 #include <linux/uaccess.h>
17 #include <linux/aio.h>
18 #include <linux/capability.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/mm.h>
21 #include <linux/swap.h>
22 #include <linux/mman.h>
23 #include <linux/pagemap.h>
24 #include <linux/file.h>
25 #include <linux/uio.h>
26 #include <linux/hash.h>
27 #include <linux/writeback.h>
28 #include <linux/pagevec.h>
29 #include <linux/blkdev.h>
30 #include <linux/security.h>
31 #include <linux/syscalls.h>
32 #include <linux/cpuset.h>
33 #include "filemap.h"
34 #include "internal.h"
35
36 /*
37  * FIXME: remove all knowledge of the buffer layer from the core VM
38  */
39 #include <linux/buffer_head.h> /* for generic_osync_inode */
40
41 #include <asm/mman.h>
42
43 static ssize_t
44 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
45         loff_t offset, unsigned long nr_segs);
46
47 /*
48  * Shared mappings implemented 30.11.1994. It's not fully working yet,
49  * though.
50  *
51  * Shared mappings now work. 15.8.1995  Bruno.
52  *
53  * finished 'unifying' the page and buffer cache and SMP-threaded the
54  * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
55  *
56  * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
57  */
58
59 /*
60  * Lock ordering:
61  *
62  *  ->i_mmap_lock               (vmtruncate)
63  *    ->private_lock            (__free_pte->__set_page_dirty_buffers)
64  *      ->swap_lock             (exclusive_swap_page, others)
65  *        ->mapping->tree_lock
66  *
67  *  ->i_mutex
68  *    ->i_mmap_lock             (truncate->unmap_mapping_range)
69  *
70  *  ->mmap_sem
71  *    ->i_mmap_lock
72  *      ->page_table_lock or pte_lock   (various, mainly in memory.c)
73  *        ->mapping->tree_lock  (arch-dependent flush_dcache_mmap_lock)
74  *
75  *  ->mmap_sem
76  *    ->lock_page               (access_process_vm)
77  *
78  *  ->mmap_sem
79  *    ->i_mutex                 (msync)
80  *
81  *  ->i_mutex
82  *    ->i_alloc_sem             (various)
83  *
84  *  ->inode_lock
85  *    ->sb_lock                 (fs/fs-writeback.c)
86  *    ->mapping->tree_lock      (__sync_single_inode)
87  *
88  *  ->i_mmap_lock
89  *    ->anon_vma.lock           (vma_adjust)
90  *
91  *  ->anon_vma.lock
92  *    ->page_table_lock or pte_lock     (anon_vma_prepare and various)
93  *
94  *  ->page_table_lock or pte_lock
95  *    ->swap_lock               (try_to_unmap_one)
96  *    ->private_lock            (try_to_unmap_one)
97  *    ->tree_lock               (try_to_unmap_one)
98  *    ->zone.lru_lock           (follow_page->mark_page_accessed)
99  *    ->zone.lru_lock           (check_pte_range->isolate_lru_page)
100  *    ->private_lock            (page_remove_rmap->set_page_dirty)
101  *    ->tree_lock               (page_remove_rmap->set_page_dirty)
102  *    ->inode_lock              (page_remove_rmap->set_page_dirty)
103  *    ->inode_lock              (zap_pte_range->set_page_dirty)
104  *    ->private_lock            (zap_pte_range->__set_page_dirty_buffers)
105  *
106  *  ->task->proc_lock
107  *    ->dcache_lock             (proc_pid_lookup)
108  */
109
110 /*
111  * Remove a page from the page cache and free it. Caller has to make
112  * sure the page is locked and that nobody else uses it - or that usage
113  * is safe.  The caller must hold a write_lock on the mapping's tree_lock.
114  */
115 void __remove_from_page_cache(struct page *page)
116 {
117         struct address_space *mapping = page->mapping;
118
119         radix_tree_delete(&mapping->page_tree, page->index);
120         page->mapping = NULL;
121         mapping->nrpages--;
122         __dec_zone_page_state(page, NR_FILE_PAGES);
123 }
124
125 void remove_from_page_cache(struct page *page)
126 {
127         struct address_space *mapping = page->mapping;
128
129         BUG_ON(!PageLocked(page));
130
131         write_lock_irq(&mapping->tree_lock);
132         __remove_from_page_cache(page);
133         write_unlock_irq(&mapping->tree_lock);
134 }
135
136 static int sync_page(void *word)
137 {
138         struct address_space *mapping;
139         struct page *page;
140
141         page = container_of((unsigned long *)word, struct page, flags);
142
143         /*
144          * page_mapping() is being called without PG_locked held.
145          * Some knowledge of the state and use of the page is used to
146          * reduce the requirements down to a memory barrier.
147          * The danger here is of a stale page_mapping() return value
148          * indicating a struct address_space different from the one it's
149          * associated with when it is associated with one.
150          * After smp_mb(), it's either the correct page_mapping() for
151          * the page, or an old page_mapping() and the page's own
152          * page_mapping() has gone NULL.
153          * The ->sync_page() address_space operation must tolerate
154          * page_mapping() going NULL. By an amazing coincidence,
155          * this comes about because none of the users of the page
156          * in the ->sync_page() methods make essential use of the
157          * page_mapping(), merely passing the page down to the backing
158          * device's unplug functions when it's non-NULL, which in turn
159          * ignore it for all cases but swap, where only page_private(page) is
160          * of interest. When page_mapping() does go NULL, the entire
161          * call stack gracefully ignores the page and returns.
162          * -- wli
163          */
164         smp_mb();
165         mapping = page_mapping(page);
166         if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
167                 mapping->a_ops->sync_page(page);
168         io_schedule();
169         return 0;
170 }
171
172 /**
173  * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
174  * @mapping:    address space structure to write
175  * @start:      offset in bytes where the range starts
176  * @end:        offset in bytes where the range ends (inclusive)
177  * @sync_mode:  enable synchronous operation
178  *
179  * Start writeback against all of a mapping's dirty pages that lie
180  * within the byte offsets <start, end> inclusive.
181  *
182  * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
183  * opposed to a regular memory cleansing writeback.  The difference between
184  * these two operations is that if a dirty page/buffer is encountered, it must
185  * be waited upon, and not just skipped over.
186  */
187 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
188                                 loff_t end, int sync_mode)
189 {
190         int ret;
191         struct writeback_control wbc = {
192                 .sync_mode = sync_mode,
193                 .nr_to_write = mapping->nrpages * 2,
194                 .range_start = start,
195                 .range_end = end,
196         };
197
198         if (!mapping_cap_writeback_dirty(mapping))
199                 return 0;
200
201         ret = do_writepages(mapping, &wbc);
202         return ret;
203 }
204
205 static inline int __filemap_fdatawrite(struct address_space *mapping,
206         int sync_mode)
207 {
208         return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
209 }
210
211 int filemap_fdatawrite(struct address_space *mapping)
212 {
213         return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
214 }
215 EXPORT_SYMBOL(filemap_fdatawrite);
216
217 static int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
218                                 loff_t end)
219 {
220         return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
221 }
222
223 /**
224  * filemap_flush - mostly a non-blocking flush
225  * @mapping:    target address_space
226  *
227  * This is a mostly non-blocking flush.  Not suitable for data-integrity
228  * purposes - I/O may not be started against all dirty pages.
229  */
230 int filemap_flush(struct address_space *mapping)
231 {
232         return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
233 }
234 EXPORT_SYMBOL(filemap_flush);
235
236 /**
237  * wait_on_page_writeback_range - wait for writeback to complete
238  * @mapping:    target address_space
239  * @start:      beginning page index
240  * @end:        ending page index
241  *
242  * Wait for writeback to complete against pages indexed by start->end
243  * inclusive
244  */
245 int wait_on_page_writeback_range(struct address_space *mapping,
246                                 pgoff_t start, pgoff_t end)
247 {
248         struct pagevec pvec;
249         int nr_pages;
250         int ret = 0;
251         pgoff_t index;
252
253         if (end < start)
254                 return 0;
255
256         pagevec_init(&pvec, 0);
257         index = start;
258         while ((index <= end) &&
259                         (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
260                         PAGECACHE_TAG_WRITEBACK,
261                         min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
262                 unsigned i;
263
264                 for (i = 0; i < nr_pages; i++) {
265                         struct page *page = pvec.pages[i];
266
267                         /* until radix tree lookup accepts end_index */
268                         if (page->index > end)
269                                 continue;
270
271                         wait_on_page_writeback(page);
272                         if (PageError(page))
273                                 ret = -EIO;
274                 }
275                 pagevec_release(&pvec);
276                 cond_resched();
277         }
278
279         /* Check for outstanding write errors */
280         if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
281                 ret = -ENOSPC;
282         if (test_and_clear_bit(AS_EIO, &mapping->flags))
283                 ret = -EIO;
284
285         return ret;
286 }
287
288 /**
289  * sync_page_range - write and wait on all pages in the passed range
290  * @inode:      target inode
291  * @mapping:    target address_space
292  * @pos:        beginning offset in pages to write
293  * @count:      number of bytes to write
294  *
295  * Write and wait upon all the pages in the passed range.  This is a "data
296  * integrity" operation.  It waits upon in-flight writeout before starting and
297  * waiting upon new writeout.  If there was an IO error, return it.
298  *
299  * We need to re-take i_mutex during the generic_osync_inode list walk because
300  * it is otherwise livelockable.
301  */
302 int sync_page_range(struct inode *inode, struct address_space *mapping,
303                         loff_t pos, loff_t count)
304 {
305         pgoff_t start = pos >> PAGE_CACHE_SHIFT;
306         pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
307         int ret;
308
309         if (!mapping_cap_writeback_dirty(mapping) || !count)
310                 return 0;
311         ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
312         if (ret == 0) {
313                 mutex_lock(&inode->i_mutex);
314                 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
315                 mutex_unlock(&inode->i_mutex);
316         }
317         if (ret == 0)
318                 ret = wait_on_page_writeback_range(mapping, start, end);
319         return ret;
320 }
321 EXPORT_SYMBOL(sync_page_range);
322
323 /**
324  * sync_page_range_nolock
325  * @inode:      target inode
326  * @mapping:    target address_space
327  * @pos:        beginning offset in pages to write
328  * @count:      number of bytes to write
329  *
330  * Note: Holding i_mutex across sync_page_range_nolock is not a good idea
331  * as it forces O_SYNC writers to different parts of the same file
332  * to be serialised right until io completion.
333  */
334 int sync_page_range_nolock(struct inode *inode, struct address_space *mapping,
335                            loff_t pos, loff_t count)
336 {
337         pgoff_t start = pos >> PAGE_CACHE_SHIFT;
338         pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
339         int ret;
340
341         if (!mapping_cap_writeback_dirty(mapping) || !count)
342                 return 0;
343         ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
344         if (ret == 0)
345                 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
346         if (ret == 0)
347                 ret = wait_on_page_writeback_range(mapping, start, end);
348         return ret;
349 }
350 EXPORT_SYMBOL(sync_page_range_nolock);
351
352 /**
353  * filemap_fdatawait - wait for all under-writeback pages to complete
354  * @mapping: address space structure to wait for
355  *
356  * Walk the list of under-writeback pages of the given address space
357  * and wait for all of them.
358  */
359 int filemap_fdatawait(struct address_space *mapping)
360 {
361         loff_t i_size = i_size_read(mapping->host);
362
363         if (i_size == 0)
364                 return 0;
365
366         return wait_on_page_writeback_range(mapping, 0,
367                                 (i_size - 1) >> PAGE_CACHE_SHIFT);
368 }
369 EXPORT_SYMBOL(filemap_fdatawait);
370
371 int filemap_write_and_wait(struct address_space *mapping)
372 {
373         int err = 0;
374
375         if (mapping->nrpages) {
376                 err = filemap_fdatawrite(mapping);
377                 /*
378                  * Even if the above returned error, the pages may be
379                  * written partially (e.g. -ENOSPC), so we wait for it.
380                  * But the -EIO is special case, it may indicate the worst
381                  * thing (e.g. bug) happened, so we avoid waiting for it.
382                  */
383                 if (err != -EIO) {
384                         int err2 = filemap_fdatawait(mapping);
385                         if (!err)
386                                 err = err2;
387                 }
388         }
389         return err;
390 }
391 EXPORT_SYMBOL(filemap_write_and_wait);
392
393 /**
394  * filemap_write_and_wait_range - write out & wait on a file range
395  * @mapping:    the address_space for the pages
396  * @lstart:     offset in bytes where the range starts
397  * @lend:       offset in bytes where the range ends (inclusive)
398  *
399  * Write out and wait upon file offsets lstart->lend, inclusive.
400  *
401  * Note that `lend' is inclusive (describes the last byte to be written) so
402  * that this function can be used to write to the very end-of-file (end = -1).
403  */
404 int filemap_write_and_wait_range(struct address_space *mapping,
405                                  loff_t lstart, loff_t lend)
406 {
407         int err = 0;
408
409         if (mapping->nrpages) {
410                 err = __filemap_fdatawrite_range(mapping, lstart, lend,
411                                                  WB_SYNC_ALL);
412                 /* See comment of filemap_write_and_wait() */
413                 if (err != -EIO) {
414                         int err2 = wait_on_page_writeback_range(mapping,
415                                                 lstart >> PAGE_CACHE_SHIFT,
416                                                 lend >> PAGE_CACHE_SHIFT);
417                         if (!err)
418                                 err = err2;
419                 }
420         }
421         return err;
422 }
423
424 /**
425  * add_to_page_cache - add newly allocated pagecache pages
426  * @page:       page to add
427  * @mapping:    the page's address_space
428  * @offset:     page index
429  * @gfp_mask:   page allocation mode
430  *
431  * This function is used to add newly allocated pagecache pages;
432  * the page is new, so we can just run SetPageLocked() against it.
433  * The other page state flags were set by rmqueue().
434  *
435  * This function does not add the page to the LRU.  The caller must do that.
436  */
437 int add_to_page_cache(struct page *page, struct address_space *mapping,
438                 pgoff_t offset, gfp_t gfp_mask)
439 {
440         int error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
441
442         if (error == 0) {
443                 write_lock_irq(&mapping->tree_lock);
444                 error = radix_tree_insert(&mapping->page_tree, offset, page);
445                 if (!error) {
446                         page_cache_get(page);
447                         SetPageLocked(page);
448                         page->mapping = mapping;
449                         page->index = offset;
450                         mapping->nrpages++;
451                         __inc_zone_page_state(page, NR_FILE_PAGES);
452                 }
453                 write_unlock_irq(&mapping->tree_lock);
454                 radix_tree_preload_end();
455         }
456         return error;
457 }
458 EXPORT_SYMBOL(add_to_page_cache);
459
460 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
461                                 pgoff_t offset, gfp_t gfp_mask)
462 {
463         int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
464         if (ret == 0)
465                 lru_cache_add(page);
466         return ret;
467 }
468
469 #ifdef CONFIG_NUMA
470 struct page *page_cache_alloc(struct address_space *x)
471 {
472         if (cpuset_do_page_mem_spread()) {
473                 int n = cpuset_mem_spread_node();
474                 return alloc_pages_node(n, mapping_gfp_mask(x), 0);
475         }
476         return alloc_pages(mapping_gfp_mask(x), 0);
477 }
478 EXPORT_SYMBOL(page_cache_alloc);
479
480 struct page *page_cache_alloc_cold(struct address_space *x)
481 {
482         if (cpuset_do_page_mem_spread()) {
483                 int n = cpuset_mem_spread_node();
484                 return alloc_pages_node(n, mapping_gfp_mask(x)|__GFP_COLD, 0);
485         }
486         return alloc_pages(mapping_gfp_mask(x)|__GFP_COLD, 0);
487 }
488 EXPORT_SYMBOL(page_cache_alloc_cold);
489 #endif
490
491 /*
492  * In order to wait for pages to become available there must be
493  * waitqueues associated with pages. By using a hash table of
494  * waitqueues where the bucket discipline is to maintain all
495  * waiters on the same queue and wake all when any of the pages
496  * become available, and for the woken contexts to check to be
497  * sure the appropriate page became available, this saves space
498  * at a cost of "thundering herd" phenomena during rare hash
499  * collisions.
500  */
501 static wait_queue_head_t *page_waitqueue(struct page *page)
502 {
503         const struct zone *zone = page_zone(page);
504
505         return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
506 }
507
508 static inline void wake_up_page(struct page *page, int bit)
509 {
510         __wake_up_bit(page_waitqueue(page), &page->flags, bit);
511 }
512
513 void fastcall wait_on_page_bit(struct page *page, int bit_nr)
514 {
515         DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
516
517         if (test_bit(bit_nr, &page->flags))
518                 __wait_on_bit(page_waitqueue(page), &wait, sync_page,
519                                                         TASK_UNINTERRUPTIBLE);
520 }
521 EXPORT_SYMBOL(wait_on_page_bit);
522
523 /**
524  * unlock_page - unlock a locked page
525  * @page: the page
526  *
527  * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
528  * Also wakes sleepers in wait_on_page_writeback() because the wakeup
529  * mechananism between PageLocked pages and PageWriteback pages is shared.
530  * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
531  *
532  * The first mb is necessary to safely close the critical section opened by the
533  * TestSetPageLocked(), the second mb is necessary to enforce ordering between
534  * the clear_bit and the read of the waitqueue (to avoid SMP races with a
535  * parallel wait_on_page_locked()).
536  */
537 void fastcall unlock_page(struct page *page)
538 {
539         smp_mb__before_clear_bit();
540         if (!TestClearPageLocked(page))
541                 BUG();
542         smp_mb__after_clear_bit(); 
543         wake_up_page(page, PG_locked);
544 }
545 EXPORT_SYMBOL(unlock_page);
546
547 /**
548  * end_page_writeback - end writeback against a page
549  * @page: the page
550  */
551 void end_page_writeback(struct page *page)
552 {
553         if (!TestClearPageReclaim(page) || rotate_reclaimable_page(page)) {
554                 if (!test_clear_page_writeback(page))
555                         BUG();
556         }
557         smp_mb__after_clear_bit();
558         wake_up_page(page, PG_writeback);
559 }
560 EXPORT_SYMBOL(end_page_writeback);
561
562 /**
563  * __lock_page - get a lock on the page, assuming we need to sleep to get it
564  * @page: the page to lock
565  *
566  * Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary.  If some
567  * random driver's requestfn sets TASK_RUNNING, we could busywait.  However
568  * chances are that on the second loop, the block layer's plug list is empty,
569  * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
570  */
571 void fastcall __lock_page(struct page *page)
572 {
573         DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
574
575         __wait_on_bit_lock(page_waitqueue(page), &wait, sync_page,
576                                                         TASK_UNINTERRUPTIBLE);
577 }
578 EXPORT_SYMBOL(__lock_page);
579
580 /**
581  * find_get_page - find and get a page reference
582  * @mapping: the address_space to search
583  * @offset: the page index
584  *
585  * A rather lightweight function, finding and getting a reference to a
586  * hashed page atomically.
587  */
588 struct page * find_get_page(struct address_space *mapping, unsigned long offset)
589 {
590         struct page *page;
591
592         read_lock_irq(&mapping->tree_lock);
593         page = radix_tree_lookup(&mapping->page_tree, offset);
594         if (page)
595                 page_cache_get(page);
596         read_unlock_irq(&mapping->tree_lock);
597         return page;
598 }
599 EXPORT_SYMBOL(find_get_page);
600
601 /**
602  * find_trylock_page - find and lock a page
603  * @mapping: the address_space to search
604  * @offset: the page index
605  *
606  * Same as find_get_page(), but trylock it instead of incrementing the count.
607  */
608 struct page *find_trylock_page(struct address_space *mapping, unsigned long offset)
609 {
610         struct page *page;
611
612         read_lock_irq(&mapping->tree_lock);
613         page = radix_tree_lookup(&mapping->page_tree, offset);
614         if (page && TestSetPageLocked(page))
615                 page = NULL;
616         read_unlock_irq(&mapping->tree_lock);
617         return page;
618 }
619 EXPORT_SYMBOL(find_trylock_page);
620
621 /**
622  * find_lock_page - locate, pin and lock a pagecache page
623  * @mapping: the address_space to search
624  * @offset: the page index
625  *
626  * Locates the desired pagecache page, locks it, increments its reference
627  * count and returns its address.
628  *
629  * Returns zero if the page was not present. find_lock_page() may sleep.
630  */
631 struct page *find_lock_page(struct address_space *mapping,
632                                 unsigned long offset)
633 {
634         struct page *page;
635
636         read_lock_irq(&mapping->tree_lock);
637 repeat:
638         page = radix_tree_lookup(&mapping->page_tree, offset);
639         if (page) {
640                 page_cache_get(page);
641                 if (TestSetPageLocked(page)) {
642                         read_unlock_irq(&mapping->tree_lock);
643                         __lock_page(page);
644                         read_lock_irq(&mapping->tree_lock);
645
646                         /* Has the page been truncated while we slept? */
647                         if (unlikely(page->mapping != mapping ||
648                                      page->index != offset)) {
649                                 unlock_page(page);
650                                 page_cache_release(page);
651                                 goto repeat;
652                         }
653                 }
654         }
655         read_unlock_irq(&mapping->tree_lock);
656         return page;
657 }
658 EXPORT_SYMBOL(find_lock_page);
659
660 /**
661  * find_or_create_page - locate or add a pagecache page
662  * @mapping: the page's address_space
663  * @index: the page's index into the mapping
664  * @gfp_mask: page allocation mode
665  *
666  * Locates a page in the pagecache.  If the page is not present, a new page
667  * is allocated using @gfp_mask and is added to the pagecache and to the VM's
668  * LRU list.  The returned page is locked and has its reference count
669  * incremented.
670  *
671  * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
672  * allocation!
673  *
674  * find_or_create_page() returns the desired page's address, or zero on
675  * memory exhaustion.
676  */
677 struct page *find_or_create_page(struct address_space *mapping,
678                 unsigned long index, gfp_t gfp_mask)
679 {
680         struct page *page, *cached_page = NULL;
681         int err;
682 repeat:
683         page = find_lock_page(mapping, index);
684         if (!page) {
685                 if (!cached_page) {
686                         cached_page = alloc_page(gfp_mask);
687                         if (!cached_page)
688                                 return NULL;
689                 }
690                 err = add_to_page_cache_lru(cached_page, mapping,
691                                         index, gfp_mask);
692                 if (!err) {
693                         page = cached_page;
694                         cached_page = NULL;
695                 } else if (err == -EEXIST)
696                         goto repeat;
697         }
698         if (cached_page)
699                 page_cache_release(cached_page);
700         return page;
701 }
702 EXPORT_SYMBOL(find_or_create_page);
703
704 /**
705  * find_get_pages - gang pagecache lookup
706  * @mapping:    The address_space to search
707  * @start:      The starting page index
708  * @nr_pages:   The maximum number of pages
709  * @pages:      Where the resulting pages are placed
710  *
711  * find_get_pages() will search for and return a group of up to
712  * @nr_pages pages in the mapping.  The pages are placed at @pages.
713  * find_get_pages() takes a reference against the returned pages.
714  *
715  * The search returns a group of mapping-contiguous pages with ascending
716  * indexes.  There may be holes in the indices due to not-present pages.
717  *
718  * find_get_pages() returns the number of pages which were found.
719  */
720 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
721                             unsigned int nr_pages, struct page **pages)
722 {
723         unsigned int i;
724         unsigned int ret;
725
726         read_lock_irq(&mapping->tree_lock);
727         ret = radix_tree_gang_lookup(&mapping->page_tree,
728                                 (void **)pages, start, nr_pages);
729         for (i = 0; i < ret; i++)
730                 page_cache_get(pages[i]);
731         read_unlock_irq(&mapping->tree_lock);
732         return ret;
733 }
734
735 /**
736  * find_get_pages_contig - gang contiguous pagecache lookup
737  * @mapping:    The address_space to search
738  * @index:      The starting page index
739  * @nr_pages:   The maximum number of pages
740  * @pages:      Where the resulting pages are placed
741  *
742  * find_get_pages_contig() works exactly like find_get_pages(), except
743  * that the returned number of pages are guaranteed to be contiguous.
744  *
745  * find_get_pages_contig() returns the number of pages which were found.
746  */
747 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
748                                unsigned int nr_pages, struct page **pages)
749 {
750         unsigned int i;
751         unsigned int ret;
752
753         read_lock_irq(&mapping->tree_lock);
754         ret = radix_tree_gang_lookup(&mapping->page_tree,
755                                 (void **)pages, index, nr_pages);
756         for (i = 0; i < ret; i++) {
757                 if (pages[i]->mapping == NULL || pages[i]->index != index)
758                         break;
759
760                 page_cache_get(pages[i]);
761                 index++;
762         }
763         read_unlock_irq(&mapping->tree_lock);
764         return i;
765 }
766
767 /**
768  * find_get_pages_tag - find and return pages that match @tag
769  * @mapping:    the address_space to search
770  * @index:      the starting page index
771  * @tag:        the tag index
772  * @nr_pages:   the maximum number of pages
773  * @pages:      where the resulting pages are placed
774  *
775  * Like find_get_pages, except we only return pages which are tagged with
776  * @tag.   We update @index to index the next page for the traversal.
777  */
778 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
779                         int tag, unsigned int nr_pages, struct page **pages)
780 {
781         unsigned int i;
782         unsigned int ret;
783
784         read_lock_irq(&mapping->tree_lock);
785         ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
786                                 (void **)pages, *index, nr_pages, tag);
787         for (i = 0; i < ret; i++)
788                 page_cache_get(pages[i]);
789         if (ret)
790                 *index = pages[ret - 1]->index + 1;
791         read_unlock_irq(&mapping->tree_lock);
792         return ret;
793 }
794
795 /**
796  * grab_cache_page_nowait - returns locked page at given index in given cache
797  * @mapping: target address_space
798  * @index: the page index
799  *
800  * Same as grab_cache_page, but do not wait if the page is unavailable.
801  * This is intended for speculative data generators, where the data can
802  * be regenerated if the page couldn't be grabbed.  This routine should
803  * be safe to call while holding the lock for another page.
804  *
805  * Clear __GFP_FS when allocating the page to avoid recursion into the fs
806  * and deadlock against the caller's locked page.
807  */
808 struct page *
809 grab_cache_page_nowait(struct address_space *mapping, unsigned long index)
810 {
811         struct page *page = find_get_page(mapping, index);
812         gfp_t gfp_mask;
813
814         if (page) {
815                 if (!TestSetPageLocked(page))
816                         return page;
817                 page_cache_release(page);
818                 return NULL;
819         }
820         gfp_mask = mapping_gfp_mask(mapping) & ~__GFP_FS;
821         page = alloc_pages(gfp_mask, 0);
822         if (page && add_to_page_cache_lru(page, mapping, index, gfp_mask)) {
823                 page_cache_release(page);
824                 page = NULL;
825         }
826         return page;
827 }
828 EXPORT_SYMBOL(grab_cache_page_nowait);
829
830 /*
831  * CD/DVDs are error prone. When a medium error occurs, the driver may fail
832  * a _large_ part of the i/o request. Imagine the worst scenario:
833  *
834  *      ---R__________________________________________B__________
835  *         ^ reading here                             ^ bad block(assume 4k)
836  *
837  * read(R) => miss => readahead(R...B) => media error => frustrating retries
838  * => failing the whole request => read(R) => read(R+1) =>
839  * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
840  * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
841  * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
842  *
843  * It is going insane. Fix it by quickly scaling down the readahead size.
844  */
845 static void shrink_readahead_size_eio(struct file *filp,
846                                         struct file_ra_state *ra)
847 {
848         if (!ra->ra_pages)
849                 return;
850
851         ra->ra_pages /= 4;
852 }
853
854 /**
855  * do_generic_mapping_read - generic file read routine
856  * @mapping:    address_space to be read
857  * @_ra:        file's readahead state
858  * @filp:       the file to read
859  * @ppos:       current file position
860  * @desc:       read_descriptor
861  * @actor:      read method
862  *
863  * This is a generic file read routine, and uses the
864  * mapping->a_ops->readpage() function for the actual low-level stuff.
865  *
866  * This is really ugly. But the goto's actually try to clarify some
867  * of the logic when it comes to error handling etc.
868  *
869  * Note the struct file* is only passed for the use of readpage.
870  * It may be NULL.
871  */
872 void do_generic_mapping_read(struct address_space *mapping,
873                              struct file_ra_state *_ra,
874                              struct file *filp,
875                              loff_t *ppos,
876                              read_descriptor_t *desc,
877                              read_actor_t actor)
878 {
879         struct inode *inode = mapping->host;
880         unsigned long index;
881         unsigned long end_index;
882         unsigned long offset;
883         unsigned long last_index;
884         unsigned long next_index;
885         unsigned long prev_index;
886         loff_t isize;
887         struct page *cached_page;
888         int error;
889         struct file_ra_state ra = *_ra;
890
891         cached_page = NULL;
892         index = *ppos >> PAGE_CACHE_SHIFT;
893         next_index = index;
894         prev_index = ra.prev_page;
895         last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
896         offset = *ppos & ~PAGE_CACHE_MASK;
897
898         isize = i_size_read(inode);
899         if (!isize)
900                 goto out;
901
902         end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
903         for (;;) {
904                 struct page *page;
905                 unsigned long nr, ret;
906
907                 /* nr is the maximum number of bytes to copy from this page */
908                 nr = PAGE_CACHE_SIZE;
909                 if (index >= end_index) {
910                         if (index > end_index)
911                                 goto out;
912                         nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
913                         if (nr <= offset) {
914                                 goto out;
915                         }
916                 }
917                 nr = nr - offset;
918
919                 cond_resched();
920                 if (index == next_index)
921                         next_index = page_cache_readahead(mapping, &ra, filp,
922                                         index, last_index - index);
923
924 find_page:
925                 page = find_get_page(mapping, index);
926                 if (unlikely(page == NULL)) {
927                         handle_ra_miss(mapping, &ra, index);
928                         goto no_cached_page;
929                 }
930                 if (!PageUptodate(page))
931                         goto page_not_up_to_date;
932 page_ok:
933
934                 /* If users can be writing to this page using arbitrary
935                  * virtual addresses, take care about potential aliasing
936                  * before reading the page on the kernel side.
937                  */
938                 if (mapping_writably_mapped(mapping))
939                         flush_dcache_page(page);
940
941                 /*
942                  * When (part of) the same page is read multiple times
943                  * in succession, only mark it as accessed the first time.
944                  */
945                 if (prev_index != index)
946                         mark_page_accessed(page);
947                 prev_index = index;
948
949                 /*
950                  * Ok, we have the page, and it's up-to-date, so
951                  * now we can copy it to user space...
952                  *
953                  * The actor routine returns how many bytes were actually used..
954                  * NOTE! This may not be the same as how much of a user buffer
955                  * we filled up (we may be padding etc), so we can only update
956                  * "pos" here (the actor routine has to update the user buffer
957                  * pointers and the remaining count).
958                  */
959                 ret = actor(desc, page, offset, nr);
960                 offset += ret;
961                 index += offset >> PAGE_CACHE_SHIFT;
962                 offset &= ~PAGE_CACHE_MASK;
963
964                 page_cache_release(page);
965                 if (ret == nr && desc->count)
966                         continue;
967                 goto out;
968
969 page_not_up_to_date:
970                 /* Get exclusive access to the page ... */
971                 lock_page(page);
972
973                 /* Did it get unhashed before we got the lock? */
974                 if (!page->mapping) {
975                         unlock_page(page);
976                         page_cache_release(page);
977                         continue;
978                 }
979
980                 /* Did somebody else fill it already? */
981                 if (PageUptodate(page)) {
982                         unlock_page(page);
983                         goto page_ok;
984                 }
985
986 readpage:
987                 /* Start the actual read. The read will unlock the page. */
988                 error = mapping->a_ops->readpage(filp, page);
989
990                 if (unlikely(error)) {
991                         if (error == AOP_TRUNCATED_PAGE) {
992                                 page_cache_release(page);
993                                 goto find_page;
994                         }
995                         goto readpage_error;
996                 }
997
998                 if (!PageUptodate(page)) {
999                         lock_page(page);
1000                         if (!PageUptodate(page)) {
1001                                 if (page->mapping == NULL) {
1002                                         /*
1003                                          * invalidate_inode_pages got it
1004                                          */
1005                                         unlock_page(page);
1006                                         page_cache_release(page);
1007                                         goto find_page;
1008                                 }
1009                                 unlock_page(page);
1010                                 error = -EIO;
1011                                 shrink_readahead_size_eio(filp, &ra);
1012                                 goto readpage_error;
1013                         }
1014                         unlock_page(page);
1015                 }
1016
1017                 /*
1018                  * i_size must be checked after we have done ->readpage.
1019                  *
1020                  * Checking i_size after the readpage allows us to calculate
1021                  * the correct value for "nr", which means the zero-filled
1022                  * part of the page is not copied back to userspace (unless
1023                  * another truncate extends the file - this is desired though).
1024                  */
1025                 isize = i_size_read(inode);
1026                 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1027                 if (unlikely(!isize || index > end_index)) {
1028                         page_cache_release(page);
1029                         goto out;
1030                 }
1031
1032                 /* nr is the maximum number of bytes to copy from this page */
1033                 nr = PAGE_CACHE_SIZE;
1034                 if (index == end_index) {
1035                         nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
1036                         if (nr <= offset) {
1037                                 page_cache_release(page);
1038                                 goto out;
1039                         }
1040                 }
1041                 nr = nr - offset;
1042                 goto page_ok;
1043
1044 readpage_error:
1045                 /* UHHUH! A synchronous read error occurred. Report it */
1046                 desc->error = error;
1047                 page_cache_release(page);
1048                 goto out;
1049
1050 no_cached_page:
1051                 /*
1052                  * Ok, it wasn't cached, so we need to create a new
1053                  * page..
1054                  */
1055                 if (!cached_page) {
1056                         cached_page = page_cache_alloc_cold(mapping);
1057                         if (!cached_page) {
1058                                 desc->error = -ENOMEM;
1059                                 goto out;
1060                         }
1061                 }
1062                 error = add_to_page_cache_lru(cached_page, mapping,
1063                                                 index, GFP_KERNEL);
1064                 if (error) {
1065                         if (error == -EEXIST)
1066                                 goto find_page;
1067                         desc->error = error;
1068                         goto out;
1069                 }
1070                 page = cached_page;
1071                 cached_page = NULL;
1072                 goto readpage;
1073         }
1074
1075 out:
1076         *_ra = ra;
1077
1078         *ppos = ((loff_t) index << PAGE_CACHE_SHIFT) + offset;
1079         if (cached_page)
1080                 page_cache_release(cached_page);
1081         if (filp)
1082                 file_accessed(filp);
1083 }
1084 EXPORT_SYMBOL(do_generic_mapping_read);
1085
1086 int file_read_actor(read_descriptor_t *desc, struct page *page,
1087                         unsigned long offset, unsigned long size)
1088 {
1089         char *kaddr;
1090         unsigned long left, count = desc->count;
1091
1092         if (size > count)
1093                 size = count;
1094
1095         /*
1096          * Faults on the destination of a read are common, so do it before
1097          * taking the kmap.
1098          */
1099         if (!fault_in_pages_writeable(desc->arg.buf, size)) {
1100                 kaddr = kmap_atomic(page, KM_USER0);
1101                 left = __copy_to_user_inatomic(desc->arg.buf,
1102                                                 kaddr + offset, size);
1103                 kunmap_atomic(kaddr, KM_USER0);
1104                 if (left == 0)
1105                         goto success;
1106         }
1107
1108         /* Do it the slow way */
1109         kaddr = kmap(page);
1110         left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
1111         kunmap(page);
1112
1113         if (left) {
1114                 size -= left;
1115                 desc->error = -EFAULT;
1116         }
1117 success:
1118         desc->count = count - size;
1119         desc->written += size;
1120         desc->arg.buf += size;
1121         return size;
1122 }
1123
1124 /**
1125  * __generic_file_aio_read - generic filesystem read routine
1126  * @iocb:       kernel I/O control block
1127  * @iov:        io vector request
1128  * @nr_segs:    number of segments in the iovec
1129  * @ppos:       current file position
1130  *
1131  * This is the "read()" routine for all filesystems
1132  * that can use the page cache directly.
1133  */
1134 ssize_t
1135 __generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1136                 unsigned long nr_segs, loff_t *ppos)
1137 {
1138         struct file *filp = iocb->ki_filp;
1139         ssize_t retval;
1140         unsigned long seg;
1141         size_t count;
1142
1143         count = 0;
1144         for (seg = 0; seg < nr_segs; seg++) {
1145                 const struct iovec *iv = &iov[seg];
1146
1147                 /*
1148                  * If any segment has a negative length, or the cumulative
1149                  * length ever wraps negative then return -EINVAL.
1150                  */
1151                 count += iv->iov_len;
1152                 if (unlikely((ssize_t)(count|iv->iov_len) < 0))
1153                         return -EINVAL;
1154                 if (access_ok(VERIFY_WRITE, iv->iov_base, iv->iov_len))
1155                         continue;
1156                 if (seg == 0)
1157                         return -EFAULT;
1158                 nr_segs = seg;
1159                 count -= iv->iov_len;   /* This segment is no good */
1160                 break;
1161         }
1162
1163         /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1164         if (filp->f_flags & O_DIRECT) {
1165                 loff_t pos = *ppos, size;
1166                 struct address_space *mapping;
1167                 struct inode *inode;
1168
1169                 mapping = filp->f_mapping;
1170                 inode = mapping->host;
1171                 retval = 0;
1172                 if (!count)
1173                         goto out; /* skip atime */
1174                 size = i_size_read(inode);
1175                 if (pos < size) {
1176                         retval = generic_file_direct_IO(READ, iocb,
1177                                                 iov, pos, nr_segs);
1178                         if (retval > 0 && !is_sync_kiocb(iocb))
1179                                 retval = -EIOCBQUEUED;
1180                         if (retval > 0)
1181                                 *ppos = pos + retval;
1182                 }
1183                 file_accessed(filp);
1184                 if (retval != 0)
1185                         goto out;
1186         }
1187
1188         retval = 0;
1189         if (count) {
1190                 for (seg = 0; seg < nr_segs; seg++) {
1191                         read_descriptor_t desc;
1192
1193                         desc.written = 0;
1194                         desc.arg.buf = iov[seg].iov_base;
1195                         desc.count = iov[seg].iov_len;
1196                         if (desc.count == 0)
1197                                 continue;
1198                         desc.error = 0;
1199                         do_generic_file_read(filp,ppos,&desc,file_read_actor);
1200                         retval += desc.written;
1201                         if (desc.error) {
1202                                 retval = retval ?: desc.error;
1203                                 break;
1204                         }
1205                 }
1206         }
1207 out:
1208         return retval;
1209 }
1210 EXPORT_SYMBOL(__generic_file_aio_read);
1211
1212 ssize_t
1213 generic_file_aio_read(struct kiocb *iocb, char __user *buf, size_t count, loff_t pos)
1214 {
1215         struct iovec local_iov = { .iov_base = buf, .iov_len = count };
1216
1217         BUG_ON(iocb->ki_pos != pos);
1218         return __generic_file_aio_read(iocb, &local_iov, 1, &iocb->ki_pos);
1219 }
1220 EXPORT_SYMBOL(generic_file_aio_read);
1221
1222 ssize_t
1223 generic_file_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
1224 {
1225         struct iovec local_iov = { .iov_base = buf, .iov_len = count };
1226         struct kiocb kiocb;
1227         ssize_t ret;
1228
1229         init_sync_kiocb(&kiocb, filp);
1230         ret = __generic_file_aio_read(&kiocb, &local_iov, 1, ppos);
1231         if (-EIOCBQUEUED == ret)
1232                 ret = wait_on_sync_kiocb(&kiocb);
1233         return ret;
1234 }
1235 EXPORT_SYMBOL(generic_file_read);
1236
1237 int file_send_actor(read_descriptor_t * desc, struct page *page, unsigned long offset, unsigned long size)
1238 {
1239         ssize_t written;
1240         unsigned long count = desc->count;
1241         struct file *file = desc->arg.data;
1242
1243         if (size > count)
1244                 size = count;
1245
1246         written = file->f_op->sendpage(file, page, offset,
1247                                        size, &file->f_pos, size<count);
1248         if (written < 0) {
1249                 desc->error = written;
1250                 written = 0;
1251         }
1252         desc->count = count - written;
1253         desc->written += written;
1254         return written;
1255 }
1256
1257 ssize_t generic_file_sendfile(struct file *in_file, loff_t *ppos,
1258                          size_t count, read_actor_t actor, void *target)
1259 {
1260         read_descriptor_t desc;
1261
1262         if (!count)
1263                 return 0;
1264
1265         desc.written = 0;
1266         desc.count = count;
1267         desc.arg.data = target;
1268         desc.error = 0;
1269
1270         do_generic_file_read(in_file, ppos, &desc, actor);
1271         if (desc.written)
1272                 return desc.written;
1273         return desc.error;
1274 }
1275 EXPORT_SYMBOL(generic_file_sendfile);
1276
1277 static ssize_t
1278 do_readahead(struct address_space *mapping, struct file *filp,
1279              unsigned long index, unsigned long nr)
1280 {
1281         if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1282                 return -EINVAL;
1283
1284         force_page_cache_readahead(mapping, filp, index,
1285                                         max_sane_readahead(nr));
1286         return 0;
1287 }
1288
1289 asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
1290 {
1291         ssize_t ret;
1292         struct file *file;
1293
1294         ret = -EBADF;
1295         file = fget(fd);
1296         if (file) {
1297                 if (file->f_mode & FMODE_READ) {
1298                         struct address_space *mapping = file->f_mapping;
1299                         unsigned long start = offset >> PAGE_CACHE_SHIFT;
1300                         unsigned long end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1301                         unsigned long len = end - start + 1;
1302                         ret = do_readahead(mapping, file, start, len);
1303                 }
1304                 fput(file);
1305         }
1306         return ret;
1307 }
1308
1309 #ifdef CONFIG_MMU
1310 static int FASTCALL(page_cache_read(struct file * file, unsigned long offset));
1311 /**
1312  * page_cache_read - adds requested page to the page cache if not already there
1313  * @file:       file to read
1314  * @offset:     page index
1315  *
1316  * This adds the requested page to the page cache if it isn't already there,
1317  * and schedules an I/O to read in its contents from disk.
1318  */
1319 static int fastcall page_cache_read(struct file * file, unsigned long offset)
1320 {
1321         struct address_space *mapping = file->f_mapping;
1322         struct page *page; 
1323         int ret;
1324
1325         do {
1326                 page = page_cache_alloc_cold(mapping);
1327                 if (!page)
1328                         return -ENOMEM;
1329
1330                 ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1331                 if (ret == 0)
1332                         ret = mapping->a_ops->readpage(file, page);
1333                 else if (ret == -EEXIST)
1334                         ret = 0; /* losing race to add is OK */
1335
1336                 page_cache_release(page);
1337
1338         } while (ret == AOP_TRUNCATED_PAGE);
1339                 
1340         return ret;
1341 }
1342
1343 #define MMAP_LOTSAMISS  (100)
1344
1345 /**
1346  * filemap_nopage - read in file data for page fault handling
1347  * @area:       the applicable vm_area
1348  * @address:    target address to read in
1349  * @type:       returned with VM_FAULT_{MINOR,MAJOR} if not %NULL
1350  *
1351  * filemap_nopage() is invoked via the vma operations vector for a
1352  * mapped memory region to read in file data during a page fault.
1353  *
1354  * The goto's are kind of ugly, but this streamlines the normal case of having
1355  * it in the page cache, and handles the special cases reasonably without
1356  * having a lot of duplicated code.
1357  */
1358 struct page *filemap_nopage(struct vm_area_struct *area,
1359                                 unsigned long address, int *type)
1360 {
1361         int error;
1362         struct file *file = area->vm_file;
1363         struct address_space *mapping = file->f_mapping;
1364         struct file_ra_state *ra = &file->f_ra;
1365         struct inode *inode = mapping->host;
1366         struct page *page;
1367         unsigned long size, pgoff;
1368         int did_readaround = 0, majmin = VM_FAULT_MINOR;
1369
1370         pgoff = ((address-area->vm_start) >> PAGE_CACHE_SHIFT) + area->vm_pgoff;
1371
1372 retry_all:
1373         size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1374         if (pgoff >= size)
1375                 goto outside_data_content;
1376
1377         /* If we don't want any read-ahead, don't bother */
1378         if (VM_RandomReadHint(area))
1379                 goto no_cached_page;
1380
1381         /*
1382          * The readahead code wants to be told about each and every page
1383          * so it can build and shrink its windows appropriately
1384          *
1385          * For sequential accesses, we use the generic readahead logic.
1386          */
1387         if (VM_SequentialReadHint(area))
1388                 page_cache_readahead(mapping, ra, file, pgoff, 1);
1389
1390         /*
1391          * Do we have something in the page cache already?
1392          */
1393 retry_find:
1394         page = find_get_page(mapping, pgoff);
1395         if (!page) {
1396                 unsigned long ra_pages;
1397
1398                 if (VM_SequentialReadHint(area)) {
1399                         handle_ra_miss(mapping, ra, pgoff);
1400                         goto no_cached_page;
1401                 }
1402                 ra->mmap_miss++;
1403
1404                 /*
1405                  * Do we miss much more than hit in this file? If so,
1406                  * stop bothering with read-ahead. It will only hurt.
1407                  */
1408                 if (ra->mmap_miss > ra->mmap_hit + MMAP_LOTSAMISS)
1409                         goto no_cached_page;
1410
1411                 /*
1412                  * To keep the pgmajfault counter straight, we need to
1413                  * check did_readaround, as this is an inner loop.
1414                  */
1415                 if (!did_readaround) {
1416                         majmin = VM_FAULT_MAJOR;
1417                         count_vm_event(PGMAJFAULT);
1418                 }
1419                 did_readaround = 1;
1420                 ra_pages = max_sane_readahead(file->f_ra.ra_pages);
1421                 if (ra_pages) {
1422                         pgoff_t start = 0;
1423
1424                         if (pgoff > ra_pages / 2)
1425                                 start = pgoff - ra_pages / 2;
1426                         do_page_cache_readahead(mapping, file, start, ra_pages);
1427                 }
1428                 page = find_get_page(mapping, pgoff);
1429                 if (!page)
1430                         goto no_cached_page;
1431         }
1432
1433         if (!did_readaround)
1434                 ra->mmap_hit++;
1435
1436         /*
1437          * Ok, found a page in the page cache, now we need to check
1438          * that it's up-to-date.
1439          */
1440         if (!PageUptodate(page))
1441                 goto page_not_uptodate;
1442
1443 success:
1444         /*
1445          * Found the page and have a reference on it.
1446          */
1447         mark_page_accessed(page);
1448         if (type)
1449                 *type = majmin;
1450         return page;
1451
1452 outside_data_content:
1453         /*
1454          * An external ptracer can access pages that normally aren't
1455          * accessible..
1456          */
1457         if (area->vm_mm == current->mm)
1458                 return NULL;
1459         /* Fall through to the non-read-ahead case */
1460 no_cached_page:
1461         /*
1462          * We're only likely to ever get here if MADV_RANDOM is in
1463          * effect.
1464          */
1465         error = page_cache_read(file, pgoff);
1466         grab_swap_token();
1467
1468         /*
1469          * The page we want has now been added to the page cache.
1470          * In the unlikely event that someone removed it in the
1471          * meantime, we'll just come back here and read it again.
1472          */
1473         if (error >= 0)
1474                 goto retry_find;
1475
1476         /*
1477          * An error return from page_cache_read can result if the
1478          * system is low on memory, or a problem occurs while trying
1479          * to schedule I/O.
1480          */
1481         if (error == -ENOMEM)
1482                 return NOPAGE_OOM;
1483         return NULL;
1484
1485 page_not_uptodate:
1486         if (!did_readaround) {
1487                 majmin = VM_FAULT_MAJOR;
1488                 count_vm_event(PGMAJFAULT);
1489         }
1490         lock_page(page);
1491
1492         /* Did it get unhashed while we waited for it? */
1493         if (!page->mapping) {
1494                 unlock_page(page);
1495                 page_cache_release(page);
1496                 goto retry_all;
1497         }
1498
1499         /* Did somebody else get it up-to-date? */
1500         if (PageUptodate(page)) {
1501                 unlock_page(page);
1502                 goto success;
1503         }
1504
1505         error = mapping->a_ops->readpage(file, page);
1506         if (!error) {
1507                 wait_on_page_locked(page);
1508                 if (PageUptodate(page))
1509                         goto success;
1510         } else if (error == AOP_TRUNCATED_PAGE) {
1511                 page_cache_release(page);
1512                 goto retry_find;
1513         }
1514
1515         /*
1516          * Umm, take care of errors if the page isn't up-to-date.
1517          * Try to re-read it _once_. We do this synchronously,
1518          * because there really aren't any performance issues here
1519          * and we need to check for errors.
1520          */
1521         lock_page(page);
1522
1523         /* Somebody truncated the page on us? */
1524         if (!page->mapping) {
1525                 unlock_page(page);
1526                 page_cache_release(page);
1527                 goto retry_all;
1528         }
1529
1530         /* Somebody else successfully read it in? */
1531         if (PageUptodate(page)) {
1532                 unlock_page(page);
1533                 goto success;
1534         }
1535         ClearPageError(page);
1536         error = mapping->a_ops->readpage(file, page);
1537         if (!error) {
1538                 wait_on_page_locked(page);
1539                 if (PageUptodate(page))
1540                         goto success;
1541         } else if (error == AOP_TRUNCATED_PAGE) {
1542                 page_cache_release(page);
1543                 goto retry_find;
1544         }
1545
1546         /*
1547          * Things didn't work out. Return zero to tell the
1548          * mm layer so, possibly freeing the page cache page first.
1549          */
1550         shrink_readahead_size_eio(file, ra);
1551         page_cache_release(page);
1552         return NULL;
1553 }
1554 EXPORT_SYMBOL(filemap_nopage);
1555
1556 static struct page * filemap_getpage(struct file *file, unsigned long pgoff,
1557                                         int nonblock)
1558 {
1559         struct address_space *mapping = file->f_mapping;
1560         struct page *page;
1561         int error;
1562
1563         /*
1564          * Do we have something in the page cache already?
1565          */
1566 retry_find:
1567         page = find_get_page(mapping, pgoff);
1568         if (!page) {
1569                 if (nonblock)
1570                         return NULL;
1571                 goto no_cached_page;
1572         }
1573
1574         /*
1575          * Ok, found a page in the page cache, now we need to check
1576          * that it's up-to-date.
1577          */
1578         if (!PageUptodate(page)) {
1579                 if (nonblock) {
1580                         page_cache_release(page);
1581                         return NULL;
1582                 }
1583                 goto page_not_uptodate;
1584         }
1585
1586 success:
1587         /*
1588          * Found the page and have a reference on it.
1589          */
1590         mark_page_accessed(page);
1591         return page;
1592
1593 no_cached_page:
1594         error = page_cache_read(file, pgoff);
1595
1596         /*
1597          * The page we want has now been added to the page cache.
1598          * In the unlikely event that someone removed it in the
1599          * meantime, we'll just come back here and read it again.
1600          */
1601         if (error >= 0)
1602                 goto retry_find;
1603
1604         /*
1605          * An error return from page_cache_read can result if the
1606          * system is low on memory, or a problem occurs while trying
1607          * to schedule I/O.
1608          */
1609         return NULL;
1610
1611 page_not_uptodate:
1612         lock_page(page);
1613
1614         /* Did it get unhashed while we waited for it? */
1615         if (!page->mapping) {
1616                 unlock_page(page);
1617                 goto err;
1618         }
1619
1620         /* Did somebody else get it up-to-date? */
1621         if (PageUptodate(page)) {
1622                 unlock_page(page);
1623                 goto success;
1624         }
1625
1626         error = mapping->a_ops->readpage(file, page);
1627         if (!error) {
1628                 wait_on_page_locked(page);
1629                 if (PageUptodate(page))
1630                         goto success;
1631         } else if (error == AOP_TRUNCATED_PAGE) {
1632                 page_cache_release(page);
1633                 goto retry_find;
1634         }
1635
1636         /*
1637          * Umm, take care of errors if the page isn't up-to-date.
1638          * Try to re-read it _once_. We do this synchronously,
1639          * because there really aren't any performance issues here
1640          * and we need to check for errors.
1641          */
1642         lock_page(page);
1643
1644         /* Somebody truncated the page on us? */
1645         if (!page->mapping) {
1646                 unlock_page(page);
1647                 goto err;
1648         }
1649         /* Somebody else successfully read it in? */
1650         if (PageUptodate(page)) {
1651                 unlock_page(page);
1652                 goto success;
1653         }
1654
1655         ClearPageError(page);
1656         error = mapping->a_ops->readpage(file, page);
1657         if (!error) {
1658                 wait_on_page_locked(page);
1659                 if (PageUptodate(page))
1660                         goto success;
1661         } else if (error == AOP_TRUNCATED_PAGE) {
1662                 page_cache_release(page);
1663                 goto retry_find;
1664         }
1665
1666         /*
1667          * Things didn't work out. Return zero to tell the
1668          * mm layer so, possibly freeing the page cache page first.
1669          */
1670 err:
1671         page_cache_release(page);
1672
1673         return NULL;
1674 }
1675
1676 int filemap_populate(struct vm_area_struct *vma, unsigned long addr,
1677                 unsigned long len, pgprot_t prot, unsigned long pgoff,
1678                 int nonblock)
1679 {
1680         struct file *file = vma->vm_file;
1681         struct address_space *mapping = file->f_mapping;
1682         struct inode *inode = mapping->host;
1683         unsigned long size;
1684         struct mm_struct *mm = vma->vm_mm;
1685         struct page *page;
1686         int err;
1687
1688         if (!nonblock)
1689                 force_page_cache_readahead(mapping, vma->vm_file,
1690                                         pgoff, len >> PAGE_CACHE_SHIFT);
1691
1692 repeat:
1693         size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1694         if (pgoff + (len >> PAGE_CACHE_SHIFT) > size)
1695                 return -EINVAL;
1696
1697         page = filemap_getpage(file, pgoff, nonblock);
1698
1699         /* XXX: This is wrong, a filesystem I/O error may have happened. Fix that as
1700          * done in shmem_populate calling shmem_getpage */
1701         if (!page && !nonblock)
1702                 return -ENOMEM;
1703
1704         if (page) {
1705                 err = install_page(mm, vma, addr, page, prot);
1706                 if (err) {
1707                         page_cache_release(page);
1708                         return err;
1709                 }
1710         } else if (vma->vm_flags & VM_NONLINEAR) {
1711                 /* No page was found just because we can't read it in now (being
1712                  * here implies nonblock != 0), but the page may exist, so set
1713                  * the PTE to fault it in later. */
1714                 err = install_file_pte(mm, vma, addr, pgoff, prot);
1715                 if (err)
1716                         return err;
1717         }
1718
1719         len -= PAGE_SIZE;
1720         addr += PAGE_SIZE;
1721         pgoff++;
1722         if (len)
1723                 goto repeat;
1724
1725         return 0;
1726 }
1727 EXPORT_SYMBOL(filemap_populate);
1728
1729 struct vm_operations_struct generic_file_vm_ops = {
1730         .nopage         = filemap_nopage,
1731         .populate       = filemap_populate,
1732 };
1733
1734 /* This is used for a general mmap of a disk file */
1735
1736 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1737 {
1738         struct address_space *mapping = file->f_mapping;
1739
1740         if (!mapping->a_ops->readpage)
1741                 return -ENOEXEC;
1742         file_accessed(file);
1743         vma->vm_ops = &generic_file_vm_ops;
1744         return 0;
1745 }
1746
1747 /*
1748  * This is for filesystems which do not implement ->writepage.
1749  */
1750 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1751 {
1752         if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1753                 return -EINVAL;
1754         return generic_file_mmap(file, vma);
1755 }
1756 #else
1757 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1758 {
1759         return -ENOSYS;
1760 }
1761 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1762 {
1763         return -ENOSYS;
1764 }
1765 #endif /* CONFIG_MMU */
1766
1767 EXPORT_SYMBOL(generic_file_mmap);
1768 EXPORT_SYMBOL(generic_file_readonly_mmap);
1769
1770 static inline struct page *__read_cache_page(struct address_space *mapping,
1771                                 unsigned long index,
1772                                 int (*filler)(void *,struct page*),
1773                                 void *data)
1774 {
1775         struct page *page, *cached_page = NULL;
1776         int err;
1777 repeat:
1778         page = find_get_page(mapping, index);
1779         if (!page) {
1780                 if (!cached_page) {
1781                         cached_page = page_cache_alloc_cold(mapping);
1782                         if (!cached_page)
1783                                 return ERR_PTR(-ENOMEM);
1784                 }
1785                 err = add_to_page_cache_lru(cached_page, mapping,
1786                                         index, GFP_KERNEL);
1787                 if (err == -EEXIST)
1788                         goto repeat;
1789                 if (err < 0) {
1790                         /* Presumably ENOMEM for radix tree node */
1791                         page_cache_release(cached_page);
1792                         return ERR_PTR(err);
1793                 }
1794                 page = cached_page;
1795                 cached_page = NULL;
1796                 err = filler(data, page);
1797                 if (err < 0) {
1798                         page_cache_release(page);
1799                         page = ERR_PTR(err);
1800                 }
1801         }
1802         if (cached_page)
1803                 page_cache_release(cached_page);
1804         return page;
1805 }
1806
1807 /**
1808  * read_cache_page - read into page cache, fill it if needed
1809  * @mapping:    the page's address_space
1810  * @index:      the page index
1811  * @filler:     function to perform the read
1812  * @data:       destination for read data
1813  *
1814  * Read into the page cache. If a page already exists,
1815  * and PageUptodate() is not set, try to fill the page.
1816  */
1817 struct page *read_cache_page(struct address_space *mapping,
1818                                 unsigned long index,
1819                                 int (*filler)(void *,struct page*),
1820                                 void *data)
1821 {
1822         struct page *page;
1823         int err;
1824
1825 retry:
1826         page = __read_cache_page(mapping, index, filler, data);
1827         if (IS_ERR(page))
1828                 goto out;
1829         mark_page_accessed(page);
1830         if (PageUptodate(page))
1831                 goto out;
1832
1833         lock_page(page);
1834         if (!page->mapping) {
1835                 unlock_page(page);
1836                 page_cache_release(page);
1837                 goto retry;
1838         }
1839         if (PageUptodate(page)) {
1840                 unlock_page(page);
1841                 goto out;
1842         }
1843         err = filler(data, page);
1844         if (err < 0) {
1845                 page_cache_release(page);
1846                 page = ERR_PTR(err);
1847         }
1848  out:
1849         return page;
1850 }
1851 EXPORT_SYMBOL(read_cache_page);
1852
1853 /*
1854  * If the page was newly created, increment its refcount and add it to the
1855  * caller's lru-buffering pagevec.  This function is specifically for
1856  * generic_file_write().
1857  */
1858 static inline struct page *
1859 __grab_cache_page(struct address_space *mapping, unsigned long index,
1860                         struct page **cached_page, struct pagevec *lru_pvec)
1861 {
1862         int err;
1863         struct page *page;
1864 repeat:
1865         page = find_lock_page(mapping, index);
1866         if (!page) {
1867                 if (!*cached_page) {
1868                         *cached_page = page_cache_alloc(mapping);
1869                         if (!*cached_page)
1870                                 return NULL;
1871                 }
1872                 err = add_to_page_cache(*cached_page, mapping,
1873                                         index, GFP_KERNEL);
1874                 if (err == -EEXIST)
1875                         goto repeat;
1876                 if (err == 0) {
1877                         page = *cached_page;
1878                         page_cache_get(page);
1879                         if (!pagevec_add(lru_pvec, page))
1880                                 __pagevec_lru_add(lru_pvec);
1881                         *cached_page = NULL;
1882                 }
1883         }
1884         return page;
1885 }
1886
1887 /*
1888  * The logic we want is
1889  *
1890  *      if suid or (sgid and xgrp)
1891  *              remove privs
1892  */
1893 int remove_suid(struct dentry *dentry)
1894 {
1895         mode_t mode = dentry->d_inode->i_mode;
1896         int kill = 0;
1897         int result = 0;
1898
1899         /* suid always must be killed */
1900         if (unlikely(mode & S_ISUID))
1901                 kill = ATTR_KILL_SUID;
1902
1903         /*
1904          * sgid without any exec bits is just a mandatory locking mark; leave
1905          * it alone.  If some exec bits are set, it's a real sgid; kill it.
1906          */
1907         if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1908                 kill |= ATTR_KILL_SGID;
1909
1910         if (unlikely(kill && !capable(CAP_FSETID))) {
1911                 struct iattr newattrs;
1912
1913                 newattrs.ia_valid = ATTR_FORCE | kill;
1914                 result = notify_change(dentry, &newattrs);
1915         }
1916         return result;
1917 }
1918 EXPORT_SYMBOL(remove_suid);
1919
1920 size_t
1921 __filemap_copy_from_user_iovec_inatomic(char *vaddr,
1922                         const struct iovec *iov, size_t base, size_t bytes)
1923 {
1924         size_t copied = 0, left = 0;
1925
1926         while (bytes) {
1927                 char __user *buf = iov->iov_base + base;
1928                 int copy = min(bytes, iov->iov_len - base);
1929
1930                 base = 0;
1931                 left = __copy_from_user_inatomic_nocache(vaddr, buf, copy);
1932                 copied += copy;
1933                 bytes -= copy;
1934                 vaddr += copy;
1935                 iov++;
1936
1937                 if (unlikely(left))
1938                         break;
1939         }
1940         return copied - left;
1941 }
1942
1943 /*
1944  * Performs necessary checks before doing a write
1945  *
1946  * Can adjust writing position or amount of bytes to write.
1947  * Returns appropriate error code that caller should return or
1948  * zero in case that write should be allowed.
1949  */
1950 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
1951 {
1952         struct inode *inode = file->f_mapping->host;
1953         unsigned long limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
1954
1955         if (unlikely(*pos < 0))
1956                 return -EINVAL;
1957
1958         if (!isblk) {
1959                 /* FIXME: this is for backwards compatibility with 2.4 */
1960                 if (file->f_flags & O_APPEND)
1961                         *pos = i_size_read(inode);
1962
1963                 if (limit != RLIM_INFINITY) {
1964                         if (*pos >= limit) {
1965                                 send_sig(SIGXFSZ, current, 0);
1966                                 return -EFBIG;
1967                         }
1968                         if (*count > limit - (typeof(limit))*pos) {
1969                                 *count = limit - (typeof(limit))*pos;
1970                         }
1971                 }
1972         }
1973
1974         /*
1975          * LFS rule
1976          */
1977         if (unlikely(*pos + *count > MAX_NON_LFS &&
1978                                 !(file->f_flags & O_LARGEFILE))) {
1979                 if (*pos >= MAX_NON_LFS) {
1980                         send_sig(SIGXFSZ, current, 0);
1981                         return -EFBIG;
1982                 }
1983                 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
1984                         *count = MAX_NON_LFS - (unsigned long)*pos;
1985                 }
1986         }
1987
1988         /*
1989          * Are we about to exceed the fs block limit ?
1990          *
1991          * If we have written data it becomes a short write.  If we have
1992          * exceeded without writing data we send a signal and return EFBIG.
1993          * Linus frestrict idea will clean these up nicely..
1994          */
1995         if (likely(!isblk)) {
1996                 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
1997                         if (*count || *pos > inode->i_sb->s_maxbytes) {
1998                                 send_sig(SIGXFSZ, current, 0);
1999                                 return -EFBIG;
2000                         }
2001                         /* zero-length writes at ->s_maxbytes are OK */
2002                 }
2003
2004                 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
2005                         *count = inode->i_sb->s_maxbytes - *pos;
2006         } else {
2007                 loff_t isize;
2008                 if (bdev_read_only(I_BDEV(inode)))
2009                         return -EPERM;
2010                 isize = i_size_read(inode);
2011                 if (*pos >= isize) {
2012                         if (*count || *pos > isize)
2013                                 return -ENOSPC;
2014                 }
2015
2016                 if (*pos + *count > isize)
2017                         *count = isize - *pos;
2018         }
2019         return 0;
2020 }
2021 EXPORT_SYMBOL(generic_write_checks);
2022
2023 ssize_t
2024 generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
2025                 unsigned long *nr_segs, loff_t pos, loff_t *ppos,
2026                 size_t count, size_t ocount)
2027 {
2028         struct file     *file = iocb->ki_filp;
2029         struct address_space *mapping = file->f_mapping;
2030         struct inode    *inode = mapping->host;
2031         ssize_t         written;
2032
2033         if (count != ocount)
2034                 *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
2035
2036         written = generic_file_direct_IO(WRITE, iocb, iov, pos, *nr_segs);
2037         if (written > 0) {
2038                 loff_t end = pos + written;
2039                 if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2040                         i_size_write(inode,  end);
2041                         mark_inode_dirty(inode);
2042                 }
2043                 *ppos = end;
2044         }
2045
2046         /*
2047          * Sync the fs metadata but not the minor inode changes and
2048          * of course not the data as we did direct DMA for the IO.
2049          * i_mutex is held, which protects generic_osync_inode() from
2050          * livelocking.
2051          */
2052         if (written >= 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2053                 int err = generic_osync_inode(inode, mapping, OSYNC_METADATA);
2054                 if (err < 0)
2055                         written = err;
2056         }
2057         if (written == count && !is_sync_kiocb(iocb))
2058                 written = -EIOCBQUEUED;
2059         return written;
2060 }
2061 EXPORT_SYMBOL(generic_file_direct_write);
2062
2063 ssize_t
2064 generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
2065                 unsigned long nr_segs, loff_t pos, loff_t *ppos,
2066                 size_t count, ssize_t written)
2067 {
2068         struct file *file = iocb->ki_filp;
2069         struct address_space * mapping = file->f_mapping;
2070         const struct address_space_operations *a_ops = mapping->a_ops;
2071         struct inode    *inode = mapping->host;
2072         long            status = 0;
2073         struct page     *page;
2074         struct page     *cached_page = NULL;
2075         size_t          bytes;
2076         struct pagevec  lru_pvec;
2077         const struct iovec *cur_iov = iov; /* current iovec */
2078         size_t          iov_base = 0;      /* offset in the current iovec */
2079         char __user     *buf;
2080
2081         pagevec_init(&lru_pvec, 0);
2082
2083         /*
2084          * handle partial DIO write.  Adjust cur_iov if needed.
2085          */
2086         if (likely(nr_segs == 1))
2087                 buf = iov->iov_base + written;
2088         else {
2089                 filemap_set_next_iovec(&cur_iov, &iov_base, written);
2090                 buf = cur_iov->iov_base + iov_base;
2091         }
2092
2093         do {
2094                 unsigned long index;
2095                 unsigned long offset;
2096                 size_t copied;
2097
2098                 offset = (pos & (PAGE_CACHE_SIZE -1)); /* Within page */
2099                 index = pos >> PAGE_CACHE_SHIFT;
2100                 bytes = PAGE_CACHE_SIZE - offset;
2101
2102                 /* Limit the size of the copy to the caller's write size */
2103                 bytes = min(bytes, count);
2104
2105                 /*
2106                  * Limit the size of the copy to that of the current segment,
2107                  * because fault_in_pages_readable() doesn't know how to walk
2108                  * segments.
2109                  */
2110                 bytes = min(bytes, cur_iov->iov_len - iov_base);
2111
2112                 /*
2113                  * Bring in the user page that we will copy from _first_.
2114                  * Otherwise there's a nasty deadlock on copying from the
2115                  * same page as we're writing to, without it being marked
2116                  * up-to-date.
2117                  */
2118                 fault_in_pages_readable(buf, bytes);
2119
2120                 page = __grab_cache_page(mapping,index,&cached_page,&lru_pvec);
2121                 if (!page) {
2122                         status = -ENOMEM;
2123                         break;
2124                 }
2125
2126                 if (unlikely(bytes == 0)) {
2127                         status = 0;
2128                         copied = 0;
2129                         goto zero_length_segment;
2130                 }
2131
2132                 status = a_ops->prepare_write(file, page, offset, offset+bytes);
2133                 if (unlikely(status)) {
2134                         loff_t isize = i_size_read(inode);
2135
2136                         if (status != AOP_TRUNCATED_PAGE)
2137                                 unlock_page(page);
2138                         page_cache_release(page);
2139                         if (status == AOP_TRUNCATED_PAGE)
2140                                 continue;
2141                         /*
2142                          * prepare_write() may have instantiated a few blocks
2143                          * outside i_size.  Trim these off again.
2144                          */
2145                         if (pos + bytes > isize)
2146                                 vmtruncate(inode, isize);
2147                         break;
2148                 }
2149                 if (likely(nr_segs == 1))
2150                         copied = filemap_copy_from_user(page, offset,
2151                                                         buf, bytes);
2152                 else
2153                         copied = filemap_copy_from_user_iovec(page, offset,
2154                                                 cur_iov, iov_base, bytes);
2155                 flush_dcache_page(page);
2156                 status = a_ops->commit_write(file, page, offset, offset+bytes);
2157                 if (status == AOP_TRUNCATED_PAGE) {
2158                         page_cache_release(page);
2159                         continue;
2160                 }
2161 zero_length_segment:
2162                 if (likely(copied >= 0)) {
2163                         if (!status)
2164                                 status = copied;
2165
2166                         if (status >= 0) {
2167                                 written += status;
2168                                 count -= status;
2169                                 pos += status;
2170                                 buf += status;
2171                                 if (unlikely(nr_segs > 1)) {
2172                                         filemap_set_next_iovec(&cur_iov,
2173                                                         &iov_base, status);
2174                                         if (count)
2175                                                 buf = cur_iov->iov_base +
2176                                                         iov_base;
2177                                 } else {
2178                                         iov_base += status;
2179                                 }
2180                         }
2181                 }
2182                 if (unlikely(copied != bytes))
2183                         if (status >= 0)
2184                                 status = -EFAULT;
2185                 unlock_page(page);
2186                 mark_page_accessed(page);
2187                 page_cache_release(page);
2188                 if (status < 0)
2189                         break;
2190                 balance_dirty_pages_ratelimited(mapping);
2191                 cond_resched();
2192         } while (count);
2193         *ppos = pos;
2194
2195         if (cached_page)
2196                 page_cache_release(cached_page);
2197
2198         /*
2199          * For now, when the user asks for O_SYNC, we'll actually give O_DSYNC
2200          */
2201         if (likely(status >= 0)) {
2202                 if (unlikely((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2203                         if (!a_ops->writepage || !is_sync_kiocb(iocb))
2204                                 status = generic_osync_inode(inode, mapping,
2205                                                 OSYNC_METADATA|OSYNC_DATA);
2206                 }
2207         }
2208         
2209         /*
2210          * If we get here for O_DIRECT writes then we must have fallen through
2211          * to buffered writes (block instantiation inside i_size).  So we sync
2212          * the file data here, to try to honour O_DIRECT expectations.
2213          */
2214         if (unlikely(file->f_flags & O_DIRECT) && written)
2215                 status = filemap_write_and_wait(mapping);
2216
2217         pagevec_lru_add(&lru_pvec);
2218         return written ? written : status;
2219 }
2220 EXPORT_SYMBOL(generic_file_buffered_write);
2221
2222 static ssize_t
2223 __generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
2224                                 unsigned long nr_segs, loff_t *ppos)
2225 {
2226         struct file *file = iocb->ki_filp;
2227         const struct address_space * mapping = file->f_mapping;
2228         size_t ocount;          /* original count */
2229         size_t count;           /* after file limit checks */
2230         struct inode    *inode = mapping->host;
2231         unsigned long   seg;
2232         loff_t          pos;
2233         ssize_t         written;
2234         ssize_t         err;
2235
2236         ocount = 0;
2237         for (seg = 0; seg < nr_segs; seg++) {
2238                 const struct iovec *iv = &iov[seg];
2239
2240                 /*
2241                  * If any segment has a negative length, or the cumulative
2242                  * length ever wraps negative then return -EINVAL.
2243                  */
2244                 ocount += iv->iov_len;
2245                 if (unlikely((ssize_t)(ocount|iv->iov_len) < 0))
2246                         return -EINVAL;
2247                 if (access_ok(VERIFY_READ, iv->iov_base, iv->iov_len))
2248                         continue;
2249                 if (seg == 0)
2250                         return -EFAULT;
2251                 nr_segs = seg;
2252                 ocount -= iv->iov_len;  /* This segment is no good */
2253                 break;
2254         }
2255
2256         count = ocount;
2257         pos = *ppos;
2258
2259         vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2260
2261         /* We can write back this queue in page reclaim */
2262         current->backing_dev_info = mapping->backing_dev_info;
2263         written = 0;
2264
2265         err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2266         if (err)
2267                 goto out;
2268
2269         if (count == 0)
2270                 goto out;
2271
2272         err = remove_suid(file->f_dentry);
2273         if (err)
2274                 goto out;
2275
2276         file_update_time(file);
2277
2278         /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2279         if (unlikely(file->f_flags & O_DIRECT)) {
2280                 written = generic_file_direct_write(iocb, iov,
2281                                 &nr_segs, pos, ppos, count, ocount);
2282                 if (written < 0 || written == count)
2283                         goto out;
2284                 /*
2285                  * direct-io write to a hole: fall through to buffered I/O
2286                  * for completing the rest of the request.
2287                  */
2288                 pos += written;
2289                 count -= written;
2290         }
2291
2292         written = generic_file_buffered_write(iocb, iov, nr_segs,
2293                         pos, ppos, count, written);
2294 out:
2295         current->backing_dev_info = NULL;
2296         return written ? written : err;
2297 }
2298 EXPORT_SYMBOL(generic_file_aio_write_nolock);
2299
2300 ssize_t
2301 generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
2302                                 unsigned long nr_segs, loff_t *ppos)
2303 {
2304         struct file *file = iocb->ki_filp;
2305         struct address_space *mapping = file->f_mapping;
2306         struct inode *inode = mapping->host;
2307         ssize_t ret;
2308         loff_t pos = *ppos;
2309
2310         ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs, ppos);
2311
2312         if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2313                 int err;
2314
2315                 err = sync_page_range_nolock(inode, mapping, pos, ret);
2316                 if (err < 0)
2317                         ret = err;
2318         }
2319         return ret;
2320 }
2321
2322 static ssize_t
2323 __generic_file_write_nolock(struct file *file, const struct iovec *iov,
2324                                 unsigned long nr_segs, loff_t *ppos)
2325 {
2326         struct kiocb kiocb;
2327         ssize_t ret;
2328
2329         init_sync_kiocb(&kiocb, file);
2330         ret = __generic_file_aio_write_nolock(&kiocb, iov, nr_segs, ppos);
2331         if (ret == -EIOCBQUEUED)
2332                 ret = wait_on_sync_kiocb(&kiocb);
2333         return ret;
2334 }
2335
2336 ssize_t
2337 generic_file_write_nolock(struct file *file, const struct iovec *iov,
2338                                 unsigned long nr_segs, loff_t *ppos)
2339 {
2340         struct kiocb kiocb;
2341         ssize_t ret;
2342
2343         init_sync_kiocb(&kiocb, file);
2344         ret = generic_file_aio_write_nolock(&kiocb, iov, nr_segs, ppos);
2345         if (-EIOCBQUEUED == ret)
2346                 ret = wait_on_sync_kiocb(&kiocb);
2347         return ret;
2348 }
2349 EXPORT_SYMBOL(generic_file_write_nolock);
2350
2351 ssize_t generic_file_aio_write(struct kiocb *iocb, const char __user *buf,
2352                                size_t count, loff_t pos)
2353 {
2354         struct file *file = iocb->ki_filp;
2355         struct address_space *mapping = file->f_mapping;
2356         struct inode *inode = mapping->host;
2357         ssize_t ret;
2358         struct iovec local_iov = { .iov_base = (void __user *)buf,
2359                                         .iov_len = count };
2360
2361         BUG_ON(iocb->ki_pos != pos);
2362
2363         mutex_lock(&inode->i_mutex);
2364         ret = __generic_file_aio_write_nolock(iocb, &local_iov, 1,
2365                                                 &iocb->ki_pos);
2366         mutex_unlock(&inode->i_mutex);
2367
2368         if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2369                 ssize_t err;
2370
2371                 err = sync_page_range(inode, mapping, pos, ret);
2372                 if (err < 0)
2373                         ret = err;
2374         }
2375         return ret;
2376 }
2377 EXPORT_SYMBOL(generic_file_aio_write);
2378
2379 ssize_t generic_file_write(struct file *file, const char __user *buf,
2380                            size_t count, loff_t *ppos)
2381 {
2382         struct address_space *mapping = file->f_mapping;
2383         struct inode *inode = mapping->host;
2384         ssize_t ret;
2385         struct iovec local_iov = { .iov_base = (void __user *)buf,
2386                                         .iov_len = count };
2387
2388         mutex_lock(&inode->i_mutex);
2389         ret = __generic_file_write_nolock(file, &local_iov, 1, ppos);
2390         mutex_unlock(&inode->i_mutex);
2391
2392         if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2393                 ssize_t err;
2394
2395                 err = sync_page_range(inode, mapping, *ppos - ret, ret);
2396                 if (err < 0)
2397                         ret = err;
2398         }
2399         return ret;
2400 }
2401 EXPORT_SYMBOL(generic_file_write);
2402
2403 ssize_t generic_file_readv(struct file *filp, const struct iovec *iov,
2404                         unsigned long nr_segs, loff_t *ppos)
2405 {
2406         struct kiocb kiocb;
2407         ssize_t ret;
2408
2409         init_sync_kiocb(&kiocb, filp);
2410         ret = __generic_file_aio_read(&kiocb, iov, nr_segs, ppos);
2411         if (-EIOCBQUEUED == ret)
2412                 ret = wait_on_sync_kiocb(&kiocb);
2413         return ret;
2414 }
2415 EXPORT_SYMBOL(generic_file_readv);
2416
2417 ssize_t generic_file_writev(struct file *file, const struct iovec *iov,
2418                         unsigned long nr_segs, loff_t *ppos)
2419 {
2420         struct address_space *mapping = file->f_mapping;
2421         struct inode *inode = mapping->host;
2422         ssize_t ret;
2423
2424         mutex_lock(&inode->i_mutex);
2425         ret = __generic_file_write_nolock(file, iov, nr_segs, ppos);
2426         mutex_unlock(&inode->i_mutex);
2427
2428         if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2429                 int err;
2430
2431                 err = sync_page_range(inode, mapping, *ppos - ret, ret);
2432                 if (err < 0)
2433                         ret = err;
2434         }
2435         return ret;
2436 }
2437 EXPORT_SYMBOL(generic_file_writev);
2438
2439 /*
2440  * Called under i_mutex for writes to S_ISREG files.   Returns -EIO if something
2441  * went wrong during pagecache shootdown.
2442  */
2443 static ssize_t
2444 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2445         loff_t offset, unsigned long nr_segs)
2446 {
2447         struct file *file = iocb->ki_filp;
2448         struct address_space *mapping = file->f_mapping;
2449         ssize_t retval;
2450         size_t write_len = 0;
2451
2452         /*
2453          * If it's a write, unmap all mmappings of the file up-front.  This
2454          * will cause any pte dirty bits to be propagated into the pageframes
2455          * for the subsequent filemap_write_and_wait().
2456          */
2457         if (rw == WRITE) {
2458                 write_len = iov_length(iov, nr_segs);
2459                 if (mapping_mapped(mapping))
2460                         unmap_mapping_range(mapping, offset, write_len, 0);
2461         }
2462
2463         retval = filemap_write_and_wait(mapping);
2464         if (retval == 0) {
2465                 retval = mapping->a_ops->direct_IO(rw, iocb, iov,
2466                                                 offset, nr_segs);
2467                 if (rw == WRITE && mapping->nrpages) {
2468                         pgoff_t end = (offset + write_len - 1)
2469                                                 >> PAGE_CACHE_SHIFT;
2470                         int err = invalidate_inode_pages2_range(mapping,
2471                                         offset >> PAGE_CACHE_SHIFT, end);
2472                         if (err)
2473                                 retval = err;
2474                 }
2475         }
2476         return retval;
2477 }