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