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