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