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