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