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