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