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