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