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