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