Merge git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6
[wrt350n-kernel.git] / mm / filemap.c
blobab88b2d21ad22c936bcbede600f0718a6411fb42
1 /*
2 * linux/mm/filemap.c
4 * Copyright (C) 1994-1999 Linus Torvalds
5 */
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)
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 <<<<<<< HEAD:mm/filemap.c
32 #include <linux/backing-dev.h>
33 =======
34 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/filemap.c
35 #include <linux/security.h>
36 #include <linux/syscalls.h>
37 #include <linux/cpuset.h>
38 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
39 #include <linux/memcontrol.h>
40 #include "internal.h"
43 * FIXME: remove all knowledge of the buffer layer from the core VM
45 #include <linux/buffer_head.h> /* for generic_osync_inode */
47 #include <asm/mman.h>
49 static ssize_t
50 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
51 loff_t offset, unsigned long nr_segs);
54 * Shared mappings implemented 30.11.1994. It's not fully working yet,
55 * though.
57 * Shared mappings now work. 15.8.1995 Bruno.
59 * finished 'unifying' the page and buffer cache and SMP-threaded the
60 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
62 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
66 * Lock ordering:
68 * ->i_mmap_lock (vmtruncate)
69 * ->private_lock (__free_pte->__set_page_dirty_buffers)
70 * ->swap_lock (exclusive_swap_page, others)
71 * ->mapping->tree_lock
73 * ->i_mutex
74 * ->i_mmap_lock (truncate->unmap_mapping_range)
76 * ->mmap_sem
77 * ->i_mmap_lock
78 * ->page_table_lock or pte_lock (various, mainly in memory.c)
79 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
81 * ->mmap_sem
82 * ->lock_page (access_process_vm)
84 * ->i_mutex (generic_file_buffered_write)
85 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
87 * ->i_mutex
88 * ->i_alloc_sem (various)
90 * ->inode_lock
91 * ->sb_lock (fs/fs-writeback.c)
92 * ->mapping->tree_lock (__sync_single_inode)
94 * ->i_mmap_lock
95 * ->anon_vma.lock (vma_adjust)
97 * ->anon_vma.lock
98 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
100 * ->page_table_lock or pte_lock
101 * ->swap_lock (try_to_unmap_one)
102 * ->private_lock (try_to_unmap_one)
103 * ->tree_lock (try_to_unmap_one)
104 * ->zone.lru_lock (follow_page->mark_page_accessed)
105 * ->zone.lru_lock (check_pte_range->isolate_lru_page)
106 * ->private_lock (page_remove_rmap->set_page_dirty)
107 * ->tree_lock (page_remove_rmap->set_page_dirty)
108 * ->inode_lock (page_remove_rmap->set_page_dirty)
109 * ->inode_lock (zap_pte_range->set_page_dirty)
110 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
112 * ->task->proc_lock
113 * ->dcache_lock (proc_pid_lookup)
117 * Remove a page from the page cache and free it. Caller has to make
118 * sure the page is locked and that nobody else uses it - or that usage
119 * is safe. The caller must hold a write_lock on the mapping's tree_lock.
121 void __remove_from_page_cache(struct page *page)
123 struct address_space *mapping = page->mapping;
125 mem_cgroup_uncharge_page(page);
126 radix_tree_delete(&mapping->page_tree, page->index);
127 page->mapping = NULL;
128 mapping->nrpages--;
129 __dec_zone_page_state(page, NR_FILE_PAGES);
130 BUG_ON(page_mapped(page));
133 * Some filesystems seem to re-dirty the page even after
134 * the VM has canceled the dirty bit (eg ext3 journaling).
136 * Fix it up by doing a final dirty accounting check after
137 * having removed the page entirely.
139 if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
140 dec_zone_page_state(page, NR_FILE_DIRTY);
141 dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
145 void remove_from_page_cache(struct page *page)
147 struct address_space *mapping = page->mapping;
149 BUG_ON(!PageLocked(page));
151 write_lock_irq(&mapping->tree_lock);
152 __remove_from_page_cache(page);
153 write_unlock_irq(&mapping->tree_lock);
156 static int sync_page(void *word)
158 struct address_space *mapping;
159 struct page *page;
161 page = container_of((unsigned long *)word, struct page, flags);
164 * page_mapping() is being called without PG_locked held.
165 * Some knowledge of the state and use of the page is used to
166 * reduce the requirements down to a memory barrier.
167 * The danger here is of a stale page_mapping() return value
168 * indicating a struct address_space different from the one it's
169 * associated with when it is associated with one.
170 * After smp_mb(), it's either the correct page_mapping() for
171 * the page, or an old page_mapping() and the page's own
172 * page_mapping() has gone NULL.
173 * The ->sync_page() address_space operation must tolerate
174 * page_mapping() going NULL. By an amazing coincidence,
175 * this comes about because none of the users of the page
176 * in the ->sync_page() methods make essential use of the
177 * page_mapping(), merely passing the page down to the backing
178 * device's unplug functions when it's non-NULL, which in turn
179 * ignore it for all cases but swap, where only page_private(page) is
180 * of interest. When page_mapping() does go NULL, the entire
181 * call stack gracefully ignores the page and returns.
182 * -- wli
184 smp_mb();
185 mapping = page_mapping(page);
186 if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
187 mapping->a_ops->sync_page(page);
188 io_schedule();
189 return 0;
192 static int sync_page_killable(void *word)
194 sync_page(word);
195 return fatal_signal_pending(current) ? -EINTR : 0;
199 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
200 * @mapping: address space structure to write
201 * @start: offset in bytes where the range starts
202 * @end: offset in bytes where the range ends (inclusive)
203 * @sync_mode: enable synchronous operation
205 * Start writeback against all of a mapping's dirty pages that lie
206 * within the byte offsets <start, end> inclusive.
208 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
209 * opposed to a regular memory cleansing writeback. The difference between
210 * these two operations is that if a dirty page/buffer is encountered, it must
211 * be waited upon, and not just skipped over.
213 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
214 loff_t end, int sync_mode)
216 int ret;
217 struct writeback_control wbc = {
218 .sync_mode = sync_mode,
219 .nr_to_write = mapping->nrpages * 2,
220 .range_start = start,
221 .range_end = end,
224 if (!mapping_cap_writeback_dirty(mapping))
225 return 0;
227 ret = do_writepages(mapping, &wbc);
228 return ret;
231 static inline int __filemap_fdatawrite(struct address_space *mapping,
232 int sync_mode)
234 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
237 int filemap_fdatawrite(struct address_space *mapping)
239 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
241 EXPORT_SYMBOL(filemap_fdatawrite);
243 static int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
244 loff_t end)
246 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
250 * filemap_flush - mostly a non-blocking flush
251 * @mapping: target address_space
253 * This is a mostly non-blocking flush. Not suitable for data-integrity
254 * purposes - I/O may not be started against all dirty pages.
256 int filemap_flush(struct address_space *mapping)
258 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
260 EXPORT_SYMBOL(filemap_flush);
263 * wait_on_page_writeback_range - wait for writeback to complete
264 * @mapping: target address_space
265 * @start: beginning page index
266 * @end: ending page index
268 * Wait for writeback to complete against pages indexed by start->end
269 * inclusive
271 int wait_on_page_writeback_range(struct address_space *mapping,
272 pgoff_t start, pgoff_t end)
274 struct pagevec pvec;
275 int nr_pages;
276 int ret = 0;
277 pgoff_t index;
279 if (end < start)
280 return 0;
282 pagevec_init(&pvec, 0);
283 index = start;
284 while ((index <= end) &&
285 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
286 PAGECACHE_TAG_WRITEBACK,
287 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
288 unsigned i;
290 for (i = 0; i < nr_pages; i++) {
291 struct page *page = pvec.pages[i];
293 /* until radix tree lookup accepts end_index */
294 if (page->index > end)
295 continue;
297 wait_on_page_writeback(page);
298 if (PageError(page))
299 ret = -EIO;
301 pagevec_release(&pvec);
302 cond_resched();
305 /* Check for outstanding write errors */
306 if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
307 ret = -ENOSPC;
308 if (test_and_clear_bit(AS_EIO, &mapping->flags))
309 ret = -EIO;
311 return ret;
315 * sync_page_range - write and wait on all pages in the passed range
316 * @inode: target inode
317 * @mapping: target address_space
318 * @pos: beginning offset in pages to write
319 * @count: number of bytes to write
321 * Write and wait upon all the pages in the passed range. This is a "data
322 * integrity" operation. It waits upon in-flight writeout before starting and
323 * waiting upon new writeout. If there was an IO error, return it.
325 * We need to re-take i_mutex during the generic_osync_inode list walk because
326 * it is otherwise livelockable.
328 int sync_page_range(struct inode *inode, struct address_space *mapping,
329 loff_t pos, loff_t count)
331 pgoff_t start = pos >> PAGE_CACHE_SHIFT;
332 pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
333 int ret;
335 if (!mapping_cap_writeback_dirty(mapping) || !count)
336 return 0;
337 ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
338 if (ret == 0) {
339 mutex_lock(&inode->i_mutex);
340 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
341 mutex_unlock(&inode->i_mutex);
343 if (ret == 0)
344 ret = wait_on_page_writeback_range(mapping, start, end);
345 return ret;
347 EXPORT_SYMBOL(sync_page_range);
350 * sync_page_range_nolock
351 * @inode: target inode
352 * @mapping: target address_space
353 * @pos: beginning offset in pages to write
354 * @count: number of bytes to write
356 * Note: Holding i_mutex across sync_page_range_nolock() is not a good idea
357 * as it forces O_SYNC writers to different parts of the same file
358 * to be serialised right until io completion.
360 int sync_page_range_nolock(struct inode *inode, struct address_space *mapping,
361 loff_t pos, loff_t count)
363 pgoff_t start = pos >> PAGE_CACHE_SHIFT;
364 pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
365 int ret;
367 if (!mapping_cap_writeback_dirty(mapping) || !count)
368 return 0;
369 ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
370 if (ret == 0)
371 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
372 if (ret == 0)
373 ret = wait_on_page_writeback_range(mapping, start, end);
374 return ret;
376 EXPORT_SYMBOL(sync_page_range_nolock);
379 * filemap_fdatawait - wait for all under-writeback pages to complete
380 * @mapping: address space structure to wait for
382 * Walk the list of under-writeback pages of the given address space
383 * and wait for all of them.
385 int filemap_fdatawait(struct address_space *mapping)
387 loff_t i_size = i_size_read(mapping->host);
389 if (i_size == 0)
390 return 0;
392 return wait_on_page_writeback_range(mapping, 0,
393 (i_size - 1) >> PAGE_CACHE_SHIFT);
395 EXPORT_SYMBOL(filemap_fdatawait);
397 int filemap_write_and_wait(struct address_space *mapping)
399 int err = 0;
401 if (mapping->nrpages) {
402 err = filemap_fdatawrite(mapping);
404 * Even if the above returned error, the pages may be
405 * written partially (e.g. -ENOSPC), so we wait for it.
406 * But the -EIO is special case, it may indicate the worst
407 * thing (e.g. bug) happened, so we avoid waiting for it.
409 if (err != -EIO) {
410 int err2 = filemap_fdatawait(mapping);
411 if (!err)
412 err = err2;
415 return err;
417 EXPORT_SYMBOL(filemap_write_and_wait);
420 * filemap_write_and_wait_range - write out & wait on a file range
421 * @mapping: the address_space for the pages
422 * @lstart: offset in bytes where the range starts
423 * @lend: offset in bytes where the range ends (inclusive)
425 * Write out and wait upon file offsets lstart->lend, inclusive.
427 * Note that `lend' is inclusive (describes the last byte to be written) so
428 * that this function can be used to write to the very end-of-file (end = -1).
430 int filemap_write_and_wait_range(struct address_space *mapping,
431 loff_t lstart, loff_t lend)
433 int err = 0;
435 if (mapping->nrpages) {
436 err = __filemap_fdatawrite_range(mapping, lstart, lend,
437 WB_SYNC_ALL);
438 /* See comment of filemap_write_and_wait() */
439 if (err != -EIO) {
440 int err2 = wait_on_page_writeback_range(mapping,
441 lstart >> PAGE_CACHE_SHIFT,
442 lend >> PAGE_CACHE_SHIFT);
443 if (!err)
444 err = err2;
447 return err;
451 * add_to_page_cache - add newly allocated pagecache pages
452 * @page: page to add
453 * @mapping: the page's address_space
454 * @offset: page index
455 * @gfp_mask: page allocation mode
457 * This function is used to add newly allocated pagecache pages;
458 * the page is new, so we can just run SetPageLocked() against it.
459 * The other page state flags were set by rmqueue().
461 * This function does not add the page to the LRU. The caller must do that.
463 int add_to_page_cache(struct page *page, struct address_space *mapping,
464 pgoff_t offset, gfp_t gfp_mask)
466 int error = mem_cgroup_cache_charge(page, current->mm,
467 gfp_mask & ~__GFP_HIGHMEM);
468 if (error)
469 goto out;
471 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
472 if (error == 0) {
473 write_lock_irq(&mapping->tree_lock);
474 error = radix_tree_insert(&mapping->page_tree, offset, page);
475 if (!error) {
476 page_cache_get(page);
477 SetPageLocked(page);
478 page->mapping = mapping;
479 page->index = offset;
480 mapping->nrpages++;
481 __inc_zone_page_state(page, NR_FILE_PAGES);
482 } else
483 mem_cgroup_uncharge_page(page);
485 write_unlock_irq(&mapping->tree_lock);
486 radix_tree_preload_end();
487 } else
488 mem_cgroup_uncharge_page(page);
489 out:
490 return error;
492 EXPORT_SYMBOL(add_to_page_cache);
494 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
495 pgoff_t offset, gfp_t gfp_mask)
497 int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
498 if (ret == 0)
499 lru_cache_add(page);
500 return ret;
503 #ifdef CONFIG_NUMA
504 struct page *__page_cache_alloc(gfp_t gfp)
506 if (cpuset_do_page_mem_spread()) {
507 int n = cpuset_mem_spread_node();
508 return alloc_pages_node(n, gfp, 0);
510 return alloc_pages(gfp, 0);
512 EXPORT_SYMBOL(__page_cache_alloc);
513 #endif
515 static int __sleep_on_page_lock(void *word)
517 io_schedule();
518 return 0;
522 * In order to wait for pages to become available there must be
523 * waitqueues associated with pages. By using a hash table of
524 * waitqueues where the bucket discipline is to maintain all
525 * waiters on the same queue and wake all when any of the pages
526 * become available, and for the woken contexts to check to be
527 * sure the appropriate page became available, this saves space
528 * at a cost of "thundering herd" phenomena during rare hash
529 * collisions.
531 static wait_queue_head_t *page_waitqueue(struct page *page)
533 const struct zone *zone = page_zone(page);
535 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
538 static inline void wake_up_page(struct page *page, int bit)
540 __wake_up_bit(page_waitqueue(page), &page->flags, bit);
543 void wait_on_page_bit(struct page *page, int bit_nr)
545 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
547 if (test_bit(bit_nr, &page->flags))
548 __wait_on_bit(page_waitqueue(page), &wait, sync_page,
549 TASK_UNINTERRUPTIBLE);
551 EXPORT_SYMBOL(wait_on_page_bit);
554 * unlock_page - unlock a locked page
555 * @page: the page
557 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
558 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
559 * mechananism between PageLocked pages and PageWriteback pages is shared.
560 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
562 * The first mb is necessary to safely close the critical section opened by the
563 * TestSetPageLocked(), the second mb is necessary to enforce ordering between
564 * the clear_bit and the read of the waitqueue (to avoid SMP races with a
565 * parallel wait_on_page_locked()).
567 void unlock_page(struct page *page)
569 smp_mb__before_clear_bit();
570 if (!TestClearPageLocked(page))
571 BUG();
572 smp_mb__after_clear_bit();
573 wake_up_page(page, PG_locked);
575 EXPORT_SYMBOL(unlock_page);
578 * end_page_writeback - end writeback against a page
579 * @page: the page
581 void end_page_writeback(struct page *page)
583 if (!TestClearPageReclaim(page) || rotate_reclaimable_page(page)) {
584 if (!test_clear_page_writeback(page))
585 BUG();
587 smp_mb__after_clear_bit();
588 wake_up_page(page, PG_writeback);
590 EXPORT_SYMBOL(end_page_writeback);
593 * __lock_page - get a lock on the page, assuming we need to sleep to get it
594 * @page: the page to lock
596 * Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary. If some
597 * random driver's requestfn sets TASK_RUNNING, we could busywait. However
598 * chances are that on the second loop, the block layer's plug list is empty,
599 * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
601 void __lock_page(struct page *page)
603 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
605 __wait_on_bit_lock(page_waitqueue(page), &wait, sync_page,
606 TASK_UNINTERRUPTIBLE);
608 EXPORT_SYMBOL(__lock_page);
610 int __lock_page_killable(struct page *page)
612 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
614 return __wait_on_bit_lock(page_waitqueue(page), &wait,
615 sync_page_killable, TASK_KILLABLE);
619 * Variant of lock_page that does not require the caller to hold a reference
620 * on the page's mapping.
622 void __lock_page_nosync(struct page *page)
624 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
625 __wait_on_bit_lock(page_waitqueue(page), &wait, __sleep_on_page_lock,
626 TASK_UNINTERRUPTIBLE);
630 * find_get_page - find and get a page reference
631 * @mapping: the address_space to search
632 * @offset: the page index
634 * Is there a pagecache struct page at the given (mapping, offset) tuple?
635 * If yes, increment its refcount and return it; if no, return NULL.
637 struct page * find_get_page(struct address_space *mapping, pgoff_t offset)
639 struct page *page;
641 read_lock_irq(&mapping->tree_lock);
642 page = radix_tree_lookup(&mapping->page_tree, offset);
643 if (page)
644 page_cache_get(page);
645 read_unlock_irq(&mapping->tree_lock);
646 return page;
648 EXPORT_SYMBOL(find_get_page);
651 * find_lock_page - locate, pin and lock a pagecache page
652 * @mapping: the address_space to search
653 * @offset: the page index
655 * Locates the desired pagecache page, locks it, increments its reference
656 * count and returns its address.
658 * Returns zero if the page was not present. find_lock_page() may sleep.
660 struct page *find_lock_page(struct address_space *mapping,
661 pgoff_t offset)
663 struct page *page;
665 repeat:
666 read_lock_irq(&mapping->tree_lock);
667 page = radix_tree_lookup(&mapping->page_tree, offset);
668 if (page) {
669 page_cache_get(page);
670 if (TestSetPageLocked(page)) {
671 read_unlock_irq(&mapping->tree_lock);
672 __lock_page(page);
674 /* Has the page been truncated while we slept? */
675 if (unlikely(page->mapping != mapping)) {
676 unlock_page(page);
677 page_cache_release(page);
678 goto repeat;
680 VM_BUG_ON(page->index != offset);
681 goto out;
684 read_unlock_irq(&mapping->tree_lock);
685 out:
686 return page;
688 EXPORT_SYMBOL(find_lock_page);
691 * find_or_create_page - locate or add a pagecache page
692 * @mapping: the page's address_space
693 * @index: the page's index into the mapping
694 * @gfp_mask: page allocation mode
696 * Locates a page in the pagecache. If the page is not present, a new page
697 * is allocated using @gfp_mask and is added to the pagecache and to the VM's
698 * LRU list. The returned page is locked and has its reference count
699 * incremented.
701 * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
702 * allocation!
704 * find_or_create_page() returns the desired page's address, or zero on
705 * memory exhaustion.
707 struct page *find_or_create_page(struct address_space *mapping,
708 pgoff_t index, gfp_t gfp_mask)
710 struct page *page;
711 int err;
712 repeat:
713 page = find_lock_page(mapping, index);
714 if (!page) {
715 page = __page_cache_alloc(gfp_mask);
716 if (!page)
717 return NULL;
718 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
719 if (unlikely(err)) {
720 page_cache_release(page);
721 page = NULL;
722 if (err == -EEXIST)
723 goto repeat;
726 return page;
728 EXPORT_SYMBOL(find_or_create_page);
731 * find_get_pages - gang pagecache lookup
732 * @mapping: The address_space to search
733 * @start: The starting page index
734 * @nr_pages: The maximum number of pages
735 * @pages: Where the resulting pages are placed
737 * find_get_pages() will search for and return a group of up to
738 * @nr_pages pages in the mapping. The pages are placed at @pages.
739 * find_get_pages() takes a reference against the returned pages.
741 * The search returns a group of mapping-contiguous pages with ascending
742 * indexes. There may be holes in the indices due to not-present pages.
744 * find_get_pages() returns the number of pages which were found.
746 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
747 unsigned int nr_pages, struct page **pages)
749 unsigned int i;
750 unsigned int ret;
752 read_lock_irq(&mapping->tree_lock);
753 ret = radix_tree_gang_lookup(&mapping->page_tree,
754 (void **)pages, start, nr_pages);
755 for (i = 0; i < ret; i++)
756 page_cache_get(pages[i]);
757 read_unlock_irq(&mapping->tree_lock);
758 return ret;
762 * find_get_pages_contig - gang contiguous pagecache lookup
763 * @mapping: The address_space to search
764 * @index: The starting page index
765 * @nr_pages: The maximum number of pages
766 * @pages: Where the resulting pages are placed
768 * find_get_pages_contig() works exactly like find_get_pages(), except
769 * that the returned number of pages are guaranteed to be contiguous.
771 * find_get_pages_contig() returns the number of pages which were found.
773 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
774 unsigned int nr_pages, struct page **pages)
776 unsigned int i;
777 unsigned int ret;
779 read_lock_irq(&mapping->tree_lock);
780 ret = radix_tree_gang_lookup(&mapping->page_tree,
781 (void **)pages, index, nr_pages);
782 for (i = 0; i < ret; i++) {
783 if (pages[i]->mapping == NULL || pages[i]->index != index)
784 break;
786 page_cache_get(pages[i]);
787 index++;
789 read_unlock_irq(&mapping->tree_lock);
790 return i;
792 EXPORT_SYMBOL(find_get_pages_contig);
795 * find_get_pages_tag - find and return pages that match @tag
796 * @mapping: the address_space to search
797 * @index: the starting page index
798 * @tag: the tag index
799 * @nr_pages: the maximum number of pages
800 * @pages: where the resulting pages are placed
802 * Like find_get_pages, except we only return pages which are tagged with
803 * @tag. We update @index to index the next page for the traversal.
805 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
806 int tag, unsigned int nr_pages, struct page **pages)
808 unsigned int i;
809 unsigned int ret;
811 read_lock_irq(&mapping->tree_lock);
812 ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
813 (void **)pages, *index, nr_pages, tag);
814 for (i = 0; i < ret; i++)
815 page_cache_get(pages[i]);
816 if (ret)
817 *index = pages[ret - 1]->index + 1;
818 read_unlock_irq(&mapping->tree_lock);
819 return ret;
821 EXPORT_SYMBOL(find_get_pages_tag);
824 * grab_cache_page_nowait - returns locked page at given index in given cache
825 * @mapping: target address_space
826 * @index: the page index
828 * Same as grab_cache_page(), but do not wait if the page is unavailable.
829 * This is intended for speculative data generators, where the data can
830 * be regenerated if the page couldn't be grabbed. This routine should
831 * be safe to call while holding the lock for another page.
833 * Clear __GFP_FS when allocating the page to avoid recursion into the fs
834 * and deadlock against the caller's locked page.
836 struct page *
837 grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
839 struct page *page = find_get_page(mapping, index);
841 if (page) {
842 if (!TestSetPageLocked(page))
843 return page;
844 page_cache_release(page);
845 return NULL;
847 page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
848 if (page && add_to_page_cache_lru(page, mapping, index, GFP_KERNEL)) {
849 page_cache_release(page);
850 page = NULL;
852 return page;
854 EXPORT_SYMBOL(grab_cache_page_nowait);
857 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
858 * a _large_ part of the i/o request. Imagine the worst scenario:
860 * ---R__________________________________________B__________
861 * ^ reading here ^ bad block(assume 4k)
863 * read(R) => miss => readahead(R...B) => media error => frustrating retries
864 * => failing the whole request => read(R) => read(R+1) =>
865 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
866 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
867 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
869 * It is going insane. Fix it by quickly scaling down the readahead size.
871 static void shrink_readahead_size_eio(struct file *filp,
872 struct file_ra_state *ra)
874 if (!ra->ra_pages)
875 return;
877 ra->ra_pages /= 4;
881 * do_generic_file_read - generic file read routine
882 * @filp: the file to read
883 * @ppos: current file position
884 * @desc: read_descriptor
885 * @actor: read method
887 * This is a generic file read routine, and uses the
888 * mapping->a_ops->readpage() function for the actual low-level stuff.
890 * This is really ugly. But the goto's actually try to clarify some
891 * of the logic when it comes to error handling etc.
893 static void do_generic_file_read(struct file *filp, loff_t *ppos,
894 read_descriptor_t *desc, read_actor_t actor)
896 struct address_space *mapping = filp->f_mapping;
897 struct inode *inode = mapping->host;
898 struct file_ra_state *ra = &filp->f_ra;
899 pgoff_t index;
900 pgoff_t last_index;
901 pgoff_t prev_index;
902 unsigned long offset; /* offset into pagecache page */
903 unsigned int prev_offset;
904 int error;
906 index = *ppos >> PAGE_CACHE_SHIFT;
907 prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
908 prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
909 last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
910 offset = *ppos & ~PAGE_CACHE_MASK;
912 for (;;) {
913 struct page *page;
914 pgoff_t end_index;
915 loff_t isize;
916 unsigned long nr, ret;
918 cond_resched();
919 find_page:
920 page = find_get_page(mapping, index);
921 if (!page) {
922 page_cache_sync_readahead(mapping,
923 ra, filp,
924 index, last_index - index);
925 page = find_get_page(mapping, index);
926 if (unlikely(page == NULL))
927 goto no_cached_page;
929 if (PageReadahead(page)) {
930 page_cache_async_readahead(mapping,
931 ra, filp, page,
932 index, last_index - index);
934 if (!PageUptodate(page))
935 goto page_not_up_to_date;
936 page_ok:
938 * i_size must be checked after we know the page is Uptodate.
940 * Checking i_size after the check allows us to calculate
941 * the correct value for "nr", which means the zero-filled
942 * part of the page is not copied back to userspace (unless
943 * another truncate extends the file - this is desired though).
946 isize = i_size_read(inode);
947 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
948 if (unlikely(!isize || index > end_index)) {
949 page_cache_release(page);
950 goto out;
953 /* nr is the maximum number of bytes to copy from this page */
954 nr = PAGE_CACHE_SIZE;
955 if (index == end_index) {
956 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
957 if (nr <= offset) {
958 page_cache_release(page);
959 goto out;
962 nr = nr - offset;
964 /* If users can be writing to this page using arbitrary
965 * virtual addresses, take care about potential aliasing
966 * before reading the page on the kernel side.
968 if (mapping_writably_mapped(mapping))
969 flush_dcache_page(page);
972 * When a sequential read accesses a page several times,
973 * only mark it as accessed the first time.
975 if (prev_index != index || offset != prev_offset)
976 mark_page_accessed(page);
977 prev_index = index;
980 * Ok, we have the page, and it's up-to-date, so
981 * now we can copy it to user space...
983 * The actor routine returns how many bytes were actually used..
984 * NOTE! This may not be the same as how much of a user buffer
985 * we filled up (we may be padding etc), so we can only update
986 * "pos" here (the actor routine has to update the user buffer
987 * pointers and the remaining count).
989 ret = actor(desc, page, offset, nr);
990 offset += ret;
991 index += offset >> PAGE_CACHE_SHIFT;
992 offset &= ~PAGE_CACHE_MASK;
993 prev_offset = offset;
995 page_cache_release(page);
996 if (ret == nr && desc->count)
997 continue;
998 goto out;
1000 page_not_up_to_date:
1001 /* Get exclusive access to the page ... */
1002 if (lock_page_killable(page))
1003 goto readpage_eio;
1005 /* Did it get truncated before we got the lock? */
1006 if (!page->mapping) {
1007 unlock_page(page);
1008 page_cache_release(page);
1009 continue;
1012 /* Did somebody else fill it already? */
1013 if (PageUptodate(page)) {
1014 unlock_page(page);
1015 goto page_ok;
1018 readpage:
1019 /* Start the actual read. The read will unlock the page. */
1020 error = mapping->a_ops->readpage(filp, page);
1022 if (unlikely(error)) {
1023 if (error == AOP_TRUNCATED_PAGE) {
1024 page_cache_release(page);
1025 goto find_page;
1027 goto readpage_error;
1030 if (!PageUptodate(page)) {
1031 if (lock_page_killable(page))
1032 goto readpage_eio;
1033 if (!PageUptodate(page)) {
1034 if (page->mapping == NULL) {
1036 * invalidate_inode_pages got it
1038 unlock_page(page);
1039 page_cache_release(page);
1040 goto find_page;
1042 unlock_page(page);
1043 shrink_readahead_size_eio(filp, ra);
1044 goto readpage_eio;
1046 unlock_page(page);
1049 goto page_ok;
1051 readpage_eio:
1052 error = -EIO;
1053 readpage_error:
1054 /* UHHUH! A synchronous read error occurred. Report it */
1055 desc->error = error;
1056 page_cache_release(page);
1057 goto out;
1059 no_cached_page:
1061 * Ok, it wasn't cached, so we need to create a new
1062 * page..
1064 page = page_cache_alloc_cold(mapping);
1065 if (!page) {
1066 desc->error = -ENOMEM;
1067 goto out;
1069 error = add_to_page_cache_lru(page, mapping,
1070 index, GFP_KERNEL);
1071 if (error) {
1072 page_cache_release(page);
1073 if (error == -EEXIST)
1074 goto find_page;
1075 desc->error = error;
1076 goto out;
1078 goto readpage;
1081 out:
1082 ra->prev_pos = prev_index;
1083 ra->prev_pos <<= PAGE_CACHE_SHIFT;
1084 ra->prev_pos |= prev_offset;
1086 *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1087 if (filp)
1088 file_accessed(filp);
1091 int file_read_actor(read_descriptor_t *desc, struct page *page,
1092 unsigned long offset, unsigned long size)
1094 char *kaddr;
1095 unsigned long left, count = desc->count;
1097 if (size > count)
1098 size = count;
1101 * Faults on the destination of a read are common, so do it before
1102 * taking the kmap.
1104 if (!fault_in_pages_writeable(desc->arg.buf, size)) {
1105 kaddr = kmap_atomic(page, KM_USER0);
1106 left = __copy_to_user_inatomic(desc->arg.buf,
1107 kaddr + offset, size);
1108 kunmap_atomic(kaddr, KM_USER0);
1109 if (left == 0)
1110 goto success;
1113 /* Do it the slow way */
1114 kaddr = kmap(page);
1115 left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
1116 kunmap(page);
1118 if (left) {
1119 size -= left;
1120 desc->error = -EFAULT;
1122 success:
1123 desc->count = count - size;
1124 desc->written += size;
1125 desc->arg.buf += size;
1126 return size;
1130 * Performs necessary checks before doing a write
1131 * @iov: io vector request
1132 * @nr_segs: number of segments in the iovec
1133 * @count: number of bytes to write
1134 * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1136 * Adjust number of segments and amount of bytes to write (nr_segs should be
1137 * properly initialized first). Returns appropriate error code that caller
1138 * should return or zero in case that write should be allowed.
1140 int generic_segment_checks(const struct iovec *iov,
1141 unsigned long *nr_segs, size_t *count, int access_flags)
1143 unsigned long seg;
1144 size_t cnt = 0;
1145 for (seg = 0; seg < *nr_segs; seg++) {
1146 const struct iovec *iv = &iov[seg];
1149 * If any segment has a negative length, or the cumulative
1150 * length ever wraps negative then return -EINVAL.
1152 cnt += iv->iov_len;
1153 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1154 return -EINVAL;
1155 if (access_ok(access_flags, iv->iov_base, iv->iov_len))
1156 continue;
1157 if (seg == 0)
1158 return -EFAULT;
1159 *nr_segs = seg;
1160 cnt -= iv->iov_len; /* This segment is no good */
1161 break;
1163 *count = cnt;
1164 return 0;
1166 EXPORT_SYMBOL(generic_segment_checks);
1169 * generic_file_aio_read - generic filesystem read routine
1170 * @iocb: kernel I/O control block
1171 * @iov: io vector request
1172 * @nr_segs: number of segments in the iovec
1173 * @pos: current file position
1175 * This is the "read()" routine for all filesystems
1176 * that can use the page cache directly.
1178 ssize_t
1179 generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1180 unsigned long nr_segs, loff_t pos)
1182 struct file *filp = iocb->ki_filp;
1183 ssize_t retval;
1184 unsigned long seg;
1185 size_t count;
1186 loff_t *ppos = &iocb->ki_pos;
1188 count = 0;
1189 retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
1190 if (retval)
1191 return retval;
1193 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1194 if (filp->f_flags & O_DIRECT) {
1195 loff_t size;
1196 struct address_space *mapping;
1197 struct inode *inode;
1199 mapping = filp->f_mapping;
1200 inode = mapping->host;
1201 retval = 0;
1202 if (!count)
1203 goto out; /* skip atime */
1204 size = i_size_read(inode);
1205 if (pos < size) {
1206 retval = generic_file_direct_IO(READ, iocb,
1207 iov, pos, nr_segs);
1208 if (retval > 0)
1209 *ppos = pos + retval;
1211 if (likely(retval != 0)) {
1212 file_accessed(filp);
1213 goto out;
1217 retval = 0;
1218 if (count) {
1219 for (seg = 0; seg < nr_segs; seg++) {
1220 read_descriptor_t desc;
1222 desc.written = 0;
1223 desc.arg.buf = iov[seg].iov_base;
1224 desc.count = iov[seg].iov_len;
1225 if (desc.count == 0)
1226 continue;
1227 desc.error = 0;
1228 do_generic_file_read(filp,ppos,&desc,file_read_actor);
1229 retval += desc.written;
1230 if (desc.error) {
1231 retval = retval ?: desc.error;
1232 break;
1234 if (desc.count > 0)
1235 break;
1238 out:
1239 return retval;
1241 EXPORT_SYMBOL(generic_file_aio_read);
1243 static ssize_t
1244 do_readahead(struct address_space *mapping, struct file *filp,
1245 pgoff_t index, unsigned long nr)
1247 if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1248 return -EINVAL;
1250 force_page_cache_readahead(mapping, filp, index,
1251 max_sane_readahead(nr));
1252 return 0;
1255 asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
1257 ssize_t ret;
1258 struct file *file;
1260 ret = -EBADF;
1261 file = fget(fd);
1262 if (file) {
1263 if (file->f_mode & FMODE_READ) {
1264 struct address_space *mapping = file->f_mapping;
1265 pgoff_t start = offset >> PAGE_CACHE_SHIFT;
1266 pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1267 unsigned long len = end - start + 1;
1268 ret = do_readahead(mapping, file, start, len);
1270 fput(file);
1272 return ret;
1275 #ifdef CONFIG_MMU
1277 * page_cache_read - adds requested page to the page cache if not already there
1278 * @file: file to read
1279 * @offset: page index
1281 * This adds the requested page to the page cache if it isn't already there,
1282 * and schedules an I/O to read in its contents from disk.
1284 static int page_cache_read(struct file *file, pgoff_t offset)
1286 struct address_space *mapping = file->f_mapping;
1287 struct page *page;
1288 int ret;
1290 do {
1291 page = page_cache_alloc_cold(mapping);
1292 if (!page)
1293 return -ENOMEM;
1295 ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1296 if (ret == 0)
1297 ret = mapping->a_ops->readpage(file, page);
1298 else if (ret == -EEXIST)
1299 ret = 0; /* losing race to add is OK */
1301 page_cache_release(page);
1303 } while (ret == AOP_TRUNCATED_PAGE);
1305 return ret;
1308 #define MMAP_LOTSAMISS (100)
1311 * filemap_fault - read in file data for page fault handling
1312 * @vma: vma in which the fault was taken
1313 * @vmf: struct vm_fault containing details of the fault
1315 * filemap_fault() is invoked via the vma operations vector for a
1316 * mapped memory region to read in file data during a page fault.
1318 * The goto's are kind of ugly, but this streamlines the normal case of having
1319 * it in the page cache, and handles the special cases reasonably without
1320 * having a lot of duplicated code.
1322 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1324 int error;
1325 struct file *file = vma->vm_file;
1326 struct address_space *mapping = file->f_mapping;
1327 struct file_ra_state *ra = &file->f_ra;
1328 struct inode *inode = mapping->host;
1329 struct page *page;
1330 pgoff_t size;
1331 int did_readaround = 0;
1332 int ret = 0;
1334 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1335 if (vmf->pgoff >= size)
1336 return VM_FAULT_SIGBUS;
1338 /* If we don't want any read-ahead, don't bother */
1339 if (VM_RandomReadHint(vma))
1340 goto no_cached_page;
1343 * Do we have something in the page cache already?
1345 retry_find:
1346 page = find_lock_page(mapping, vmf->pgoff);
1348 * For sequential accesses, we use the generic readahead logic.
1350 if (VM_SequentialReadHint(vma)) {
1351 if (!page) {
1352 page_cache_sync_readahead(mapping, ra, file,
1353 vmf->pgoff, 1);
1354 page = find_lock_page(mapping, vmf->pgoff);
1355 if (!page)
1356 goto no_cached_page;
1358 if (PageReadahead(page)) {
1359 page_cache_async_readahead(mapping, ra, file, page,
1360 vmf->pgoff, 1);
1364 if (!page) {
1365 unsigned long ra_pages;
1367 ra->mmap_miss++;
1370 * Do we miss much more than hit in this file? If so,
1371 * stop bothering with read-ahead. It will only hurt.
1373 if (ra->mmap_miss > MMAP_LOTSAMISS)
1374 goto no_cached_page;
1377 * To keep the pgmajfault counter straight, we need to
1378 * check did_readaround, as this is an inner loop.
1380 if (!did_readaround) {
1381 ret = VM_FAULT_MAJOR;
1382 count_vm_event(PGMAJFAULT);
1384 did_readaround = 1;
1385 ra_pages = max_sane_readahead(file->f_ra.ra_pages);
1386 if (ra_pages) {
1387 pgoff_t start = 0;
1389 if (vmf->pgoff > ra_pages / 2)
1390 start = vmf->pgoff - ra_pages / 2;
1391 do_page_cache_readahead(mapping, file, start, ra_pages);
1393 page = find_lock_page(mapping, vmf->pgoff);
1394 if (!page)
1395 goto no_cached_page;
1398 if (!did_readaround)
1399 ra->mmap_miss--;
1402 * We have a locked page in the page cache, now we need to check
1403 * that it's up-to-date. If not, it is going to be due to an error.
1405 if (unlikely(!PageUptodate(page)))
1406 goto page_not_uptodate;
1408 /* Must recheck i_size under page lock */
1409 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1410 if (unlikely(vmf->pgoff >= size)) {
1411 unlock_page(page);
1412 page_cache_release(page);
1413 return VM_FAULT_SIGBUS;
1417 * Found the page and have a reference on it.
1419 mark_page_accessed(page);
1420 ra->prev_pos = (loff_t)page->index << PAGE_CACHE_SHIFT;
1421 vmf->page = page;
1422 return ret | VM_FAULT_LOCKED;
1424 no_cached_page:
1426 * We're only likely to ever get here if MADV_RANDOM is in
1427 * effect.
1429 error = page_cache_read(file, vmf->pgoff);
1432 * The page we want has now been added to the page cache.
1433 * In the unlikely event that someone removed it in the
1434 * meantime, we'll just come back here and read it again.
1436 if (error >= 0)
1437 goto retry_find;
1440 * An error return from page_cache_read can result if the
1441 * system is low on memory, or a problem occurs while trying
1442 * to schedule I/O.
1444 if (error == -ENOMEM)
1445 return VM_FAULT_OOM;
1446 return VM_FAULT_SIGBUS;
1448 page_not_uptodate:
1449 /* IO error path */
1450 if (!did_readaround) {
1451 ret = VM_FAULT_MAJOR;
1452 count_vm_event(PGMAJFAULT);
1456 * Umm, take care of errors if the page isn't up-to-date.
1457 * Try to re-read it _once_. We do this synchronously,
1458 * because there really aren't any performance issues here
1459 * and we need to check for errors.
1461 ClearPageError(page);
1462 error = mapping->a_ops->readpage(file, page);
1463 page_cache_release(page);
1465 if (!error || error == AOP_TRUNCATED_PAGE)
1466 goto retry_find;
1468 /* Things didn't work out. Return zero to tell the mm layer so. */
1469 shrink_readahead_size_eio(file, ra);
1470 return VM_FAULT_SIGBUS;
1472 EXPORT_SYMBOL(filemap_fault);
1474 struct vm_operations_struct generic_file_vm_ops = {
1475 .fault = filemap_fault,
1478 /* This is used for a general mmap of a disk file */
1480 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1482 struct address_space *mapping = file->f_mapping;
1484 if (!mapping->a_ops->readpage)
1485 return -ENOEXEC;
1486 file_accessed(file);
1487 vma->vm_ops = &generic_file_vm_ops;
1488 vma->vm_flags |= VM_CAN_NONLINEAR;
1489 return 0;
1493 * This is for filesystems which do not implement ->writepage.
1495 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1497 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1498 return -EINVAL;
1499 return generic_file_mmap(file, vma);
1501 #else
1502 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1504 return -ENOSYS;
1506 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1508 return -ENOSYS;
1510 #endif /* CONFIG_MMU */
1512 EXPORT_SYMBOL(generic_file_mmap);
1513 EXPORT_SYMBOL(generic_file_readonly_mmap);
1515 static struct page *__read_cache_page(struct address_space *mapping,
1516 pgoff_t index,
1517 int (*filler)(void *,struct page*),
1518 void *data)
1520 struct page *page;
1521 int err;
1522 repeat:
1523 page = find_get_page(mapping, index);
1524 if (!page) {
1525 page = page_cache_alloc_cold(mapping);
1526 if (!page)
1527 return ERR_PTR(-ENOMEM);
1528 err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
1529 if (unlikely(err)) {
1530 page_cache_release(page);
1531 if (err == -EEXIST)
1532 goto repeat;
1533 /* Presumably ENOMEM for radix tree node */
1534 return ERR_PTR(err);
1536 err = filler(data, page);
1537 if (err < 0) {
1538 page_cache_release(page);
1539 page = ERR_PTR(err);
1542 return page;
1546 * Same as read_cache_page, but don't wait for page to become unlocked
1547 * after submitting it to the filler.
1549 struct page *read_cache_page_async(struct address_space *mapping,
1550 pgoff_t index,
1551 int (*filler)(void *,struct page*),
1552 void *data)
1554 struct page *page;
1555 int err;
1557 retry:
1558 page = __read_cache_page(mapping, index, filler, data);
1559 if (IS_ERR(page))
1560 return page;
1561 if (PageUptodate(page))
1562 goto out;
1564 lock_page(page);
1565 if (!page->mapping) {
1566 unlock_page(page);
1567 page_cache_release(page);
1568 goto retry;
1570 if (PageUptodate(page)) {
1571 unlock_page(page);
1572 goto out;
1574 err = filler(data, page);
1575 if (err < 0) {
1576 page_cache_release(page);
1577 return ERR_PTR(err);
1579 out:
1580 mark_page_accessed(page);
1581 return page;
1583 EXPORT_SYMBOL(read_cache_page_async);
1586 * read_cache_page - read into page cache, fill it if needed
1587 * @mapping: the page's address_space
1588 * @index: the page index
1589 * @filler: function to perform the read
1590 * @data: destination for read data
1592 * Read into the page cache. If a page already exists, and PageUptodate() is
1593 * not set, try to fill the page then wait for it to become unlocked.
1595 * If the page does not get brought uptodate, return -EIO.
1597 struct page *read_cache_page(struct address_space *mapping,
1598 pgoff_t index,
1599 int (*filler)(void *,struct page*),
1600 void *data)
1602 struct page *page;
1604 page = read_cache_page_async(mapping, index, filler, data);
1605 if (IS_ERR(page))
1606 goto out;
1607 wait_on_page_locked(page);
1608 if (!PageUptodate(page)) {
1609 page_cache_release(page);
1610 page = ERR_PTR(-EIO);
1612 out:
1613 return page;
1615 EXPORT_SYMBOL(read_cache_page);
1618 * The logic we want is
1620 * if suid or (sgid and xgrp)
1621 * remove privs
1623 int should_remove_suid(struct dentry *dentry)
1625 mode_t mode = dentry->d_inode->i_mode;
1626 int kill = 0;
1628 /* suid always must be killed */
1629 if (unlikely(mode & S_ISUID))
1630 kill = ATTR_KILL_SUID;
1633 * sgid without any exec bits is just a mandatory locking mark; leave
1634 * it alone. If some exec bits are set, it's a real sgid; kill it.
1636 if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1637 kill |= ATTR_KILL_SGID;
1639 if (unlikely(kill && !capable(CAP_FSETID)))
1640 return kill;
1642 return 0;
1644 EXPORT_SYMBOL(should_remove_suid);
1646 int __remove_suid(struct dentry *dentry, int kill)
1648 struct iattr newattrs;
1650 newattrs.ia_valid = ATTR_FORCE | kill;
1651 return notify_change(dentry, &newattrs);
1654 int remove_suid(struct dentry *dentry)
1656 int killsuid = should_remove_suid(dentry);
1657 int killpriv = security_inode_need_killpriv(dentry);
1658 int error = 0;
1660 if (killpriv < 0)
1661 return killpriv;
1662 if (killpriv)
1663 error = security_inode_killpriv(dentry);
1664 if (!error && killsuid)
1665 error = __remove_suid(dentry, killsuid);
1667 return error;
1669 EXPORT_SYMBOL(remove_suid);
1671 static size_t __iovec_copy_from_user_inatomic(char *vaddr,
1672 const struct iovec *iov, size_t base, size_t bytes)
1674 size_t copied = 0, left = 0;
1676 while (bytes) {
1677 char __user *buf = iov->iov_base + base;
1678 int copy = min(bytes, iov->iov_len - base);
1680 base = 0;
1681 left = __copy_from_user_inatomic_nocache(vaddr, buf, copy);
1682 copied += copy;
1683 bytes -= copy;
1684 vaddr += copy;
1685 iov++;
1687 if (unlikely(left))
1688 break;
1690 return copied - left;
1694 * Copy as much as we can into the page and return the number of bytes which
1695 * were sucessfully copied. If a fault is encountered then return the number of
1696 * bytes which were copied.
1698 size_t iov_iter_copy_from_user_atomic(struct page *page,
1699 struct iov_iter *i, unsigned long offset, size_t bytes)
1701 char *kaddr;
1702 size_t copied;
1704 BUG_ON(!in_atomic());
1705 kaddr = kmap_atomic(page, KM_USER0);
1706 if (likely(i->nr_segs == 1)) {
1707 int left;
1708 char __user *buf = i->iov->iov_base + i->iov_offset;
1709 left = __copy_from_user_inatomic_nocache(kaddr + offset,
1710 buf, bytes);
1711 copied = bytes - left;
1712 } else {
1713 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
1714 i->iov, i->iov_offset, bytes);
1716 kunmap_atomic(kaddr, KM_USER0);
1718 return copied;
1720 EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
1723 * This has the same sideeffects and return value as
1724 * iov_iter_copy_from_user_atomic().
1725 * The difference is that it attempts to resolve faults.
1726 * Page must not be locked.
1728 size_t iov_iter_copy_from_user(struct page *page,
1729 struct iov_iter *i, unsigned long offset, size_t bytes)
1731 char *kaddr;
1732 size_t copied;
1734 kaddr = kmap(page);
1735 if (likely(i->nr_segs == 1)) {
1736 int left;
1737 char __user *buf = i->iov->iov_base + i->iov_offset;
1738 left = __copy_from_user_nocache(kaddr + offset, buf, bytes);
1739 copied = bytes - left;
1740 } else {
1741 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
1742 i->iov, i->iov_offset, bytes);
1744 kunmap(page);
1745 return copied;
1747 EXPORT_SYMBOL(iov_iter_copy_from_user);
1749 <<<<<<< HEAD:mm/filemap.c
1750 static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes)
1751 =======
1752 void iov_iter_advance(struct iov_iter *i, size_t bytes)
1753 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/filemap.c
1755 <<<<<<< HEAD:mm/filemap.c
1756 =======
1757 BUG_ON(i->count < bytes);
1759 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/filemap.c
1760 if (likely(i->nr_segs == 1)) {
1761 i->iov_offset += bytes;
1762 <<<<<<< HEAD:mm/filemap.c
1763 =======
1764 i->count -= bytes;
1765 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/filemap.c
1766 } else {
1767 const struct iovec *iov = i->iov;
1768 size_t base = i->iov_offset;
1771 * The !iov->iov_len check ensures we skip over unlikely
1772 <<<<<<< HEAD:mm/filemap.c
1773 * zero-length segments.
1774 =======
1775 * zero-length segments (without overruning the iovec).
1776 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/filemap.c
1778 <<<<<<< HEAD:mm/filemap.c
1779 while (bytes || !iov->iov_len) {
1780 int copy = min(bytes, iov->iov_len - base);
1781 =======
1782 while (bytes || unlikely(!iov->iov_len && i->count)) {
1783 int copy;
1784 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/filemap.c
1786 <<<<<<< HEAD:mm/filemap.c
1787 =======
1788 copy = min(bytes, iov->iov_len - base);
1789 BUG_ON(!i->count || i->count < copy);
1790 i->count -= copy;
1791 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/filemap.c
1792 bytes -= copy;
1793 base += copy;
1794 if (iov->iov_len == base) {
1795 iov++;
1796 base = 0;
1799 i->iov = iov;
1800 i->iov_offset = base;
1803 <<<<<<< HEAD:mm/filemap.c
1805 void iov_iter_advance(struct iov_iter *i, size_t bytes)
1807 BUG_ON(i->count < bytes);
1809 __iov_iter_advance_iov(i, bytes);
1810 i->count -= bytes;
1812 =======
1813 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/filemap.c
1814 EXPORT_SYMBOL(iov_iter_advance);
1817 * Fault in the first iovec of the given iov_iter, to a maximum length
1818 * of bytes. Returns 0 on success, or non-zero if the memory could not be
1819 * accessed (ie. because it is an invalid address).
1821 * writev-intensive code may want this to prefault several iovecs -- that
1822 * would be possible (callers must not rely on the fact that _only_ the
1823 * first iovec will be faulted with the current implementation).
1825 int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
1827 char __user *buf = i->iov->iov_base + i->iov_offset;
1828 bytes = min(bytes, i->iov->iov_len - i->iov_offset);
1829 return fault_in_pages_readable(buf, bytes);
1831 EXPORT_SYMBOL(iov_iter_fault_in_readable);
1834 * Return the count of just the current iov_iter segment.
1836 size_t iov_iter_single_seg_count(struct iov_iter *i)
1838 const struct iovec *iov = i->iov;
1839 if (i->nr_segs == 1)
1840 return i->count;
1841 else
1842 return min(i->count, iov->iov_len - i->iov_offset);
1844 EXPORT_SYMBOL(iov_iter_single_seg_count);
1847 * Performs necessary checks before doing a write
1849 * Can adjust writing position or amount of bytes to write.
1850 * Returns appropriate error code that caller should return or
1851 * zero in case that write should be allowed.
1853 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
1855 struct inode *inode = file->f_mapping->host;
1856 unsigned long limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
1858 if (unlikely(*pos < 0))
1859 return -EINVAL;
1861 if (!isblk) {
1862 /* FIXME: this is for backwards compatibility with 2.4 */
1863 if (file->f_flags & O_APPEND)
1864 *pos = i_size_read(inode);
1866 if (limit != RLIM_INFINITY) {
1867 if (*pos >= limit) {
1868 send_sig(SIGXFSZ, current, 0);
1869 return -EFBIG;
1871 if (*count > limit - (typeof(limit))*pos) {
1872 *count = limit - (typeof(limit))*pos;
1878 * LFS rule
1880 if (unlikely(*pos + *count > MAX_NON_LFS &&
1881 !(file->f_flags & O_LARGEFILE))) {
1882 if (*pos >= MAX_NON_LFS) {
1883 return -EFBIG;
1885 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
1886 *count = MAX_NON_LFS - (unsigned long)*pos;
1891 * Are we about to exceed the fs block limit ?
1893 * If we have written data it becomes a short write. If we have
1894 * exceeded without writing data we send a signal and return EFBIG.
1895 * Linus frestrict idea will clean these up nicely..
1897 if (likely(!isblk)) {
1898 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
1899 if (*count || *pos > inode->i_sb->s_maxbytes) {
1900 return -EFBIG;
1902 /* zero-length writes at ->s_maxbytes are OK */
1905 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
1906 *count = inode->i_sb->s_maxbytes - *pos;
1907 } else {
1908 #ifdef CONFIG_BLOCK
1909 loff_t isize;
1910 if (bdev_read_only(I_BDEV(inode)))
1911 return -EPERM;
1912 isize = i_size_read(inode);
1913 if (*pos >= isize) {
1914 if (*count || *pos > isize)
1915 return -ENOSPC;
1918 if (*pos + *count > isize)
1919 *count = isize - *pos;
1920 #else
1921 return -EPERM;
1922 #endif
1924 return 0;
1926 EXPORT_SYMBOL(generic_write_checks);
1928 int pagecache_write_begin(struct file *file, struct address_space *mapping,
1929 loff_t pos, unsigned len, unsigned flags,
1930 struct page **pagep, void **fsdata)
1932 const struct address_space_operations *aops = mapping->a_ops;
1934 if (aops->write_begin) {
1935 return aops->write_begin(file, mapping, pos, len, flags,
1936 pagep, fsdata);
1937 } else {
1938 int ret;
1939 pgoff_t index = pos >> PAGE_CACHE_SHIFT;
1940 unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
1941 struct inode *inode = mapping->host;
1942 struct page *page;
1943 again:
1944 page = __grab_cache_page(mapping, index);
1945 *pagep = page;
1946 if (!page)
1947 return -ENOMEM;
1949 if (flags & AOP_FLAG_UNINTERRUPTIBLE && !PageUptodate(page)) {
1951 * There is no way to resolve a short write situation
1952 * for a !Uptodate page (except by double copying in
1953 * the caller done by generic_perform_write_2copy).
1955 * Instead, we have to bring it uptodate here.
1957 ret = aops->readpage(file, page);
1958 page_cache_release(page);
1959 if (ret) {
1960 if (ret == AOP_TRUNCATED_PAGE)
1961 goto again;
1962 return ret;
1964 goto again;
1967 ret = aops->prepare_write(file, page, offset, offset+len);
1968 if (ret) {
1969 unlock_page(page);
1970 page_cache_release(page);
1971 if (pos + len > inode->i_size)
1972 vmtruncate(inode, inode->i_size);
1974 return ret;
1977 EXPORT_SYMBOL(pagecache_write_begin);
1979 int pagecache_write_end(struct file *file, struct address_space *mapping,
1980 loff_t pos, unsigned len, unsigned copied,
1981 struct page *page, void *fsdata)
1983 const struct address_space_operations *aops = mapping->a_ops;
1984 int ret;
1986 if (aops->write_end) {
1987 mark_page_accessed(page);
1988 ret = aops->write_end(file, mapping, pos, len, copied,
1989 page, fsdata);
1990 } else {
1991 unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
1992 struct inode *inode = mapping->host;
1994 flush_dcache_page(page);
1995 ret = aops->commit_write(file, page, offset, offset+len);
1996 unlock_page(page);
1997 mark_page_accessed(page);
1998 page_cache_release(page);
2000 if (ret < 0) {
2001 if (pos + len > inode->i_size)
2002 vmtruncate(inode, inode->i_size);
2003 } else if (ret > 0)
2004 ret = min_t(size_t, copied, ret);
2005 else
2006 ret = copied;
2009 return ret;
2011 EXPORT_SYMBOL(pagecache_write_end);
2013 ssize_t
2014 generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
2015 unsigned long *nr_segs, loff_t pos, loff_t *ppos,
2016 size_t count, size_t ocount)
2018 struct file *file = iocb->ki_filp;
2019 struct address_space *mapping = file->f_mapping;
2020 struct inode *inode = mapping->host;
2021 ssize_t written;
2023 if (count != ocount)
2024 *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
2026 written = generic_file_direct_IO(WRITE, iocb, iov, pos, *nr_segs);
2027 if (written > 0) {
2028 loff_t end = pos + written;
2029 if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2030 i_size_write(inode, end);
2031 mark_inode_dirty(inode);
2033 *ppos = end;
2037 * Sync the fs metadata but not the minor inode changes and
2038 * of course not the data as we did direct DMA for the IO.
2039 * i_mutex is held, which protects generic_osync_inode() from
2040 * livelocking. AIO O_DIRECT ops attempt to sync metadata here.
2042 if ((written >= 0 || written == -EIOCBQUEUED) &&
2043 ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2044 int err = generic_osync_inode(inode, mapping, OSYNC_METADATA);
2045 if (err < 0)
2046 written = err;
2048 return written;
2050 EXPORT_SYMBOL(generic_file_direct_write);
2053 * Find or create a page at the given pagecache position. Return the locked
2054 * page. This function is specifically for buffered writes.
2056 struct page *__grab_cache_page(struct address_space *mapping, pgoff_t index)
2058 int status;
2059 struct page *page;
2060 repeat:
2061 page = find_lock_page(mapping, index);
2062 if (likely(page))
2063 return page;
2065 page = page_cache_alloc(mapping);
2066 if (!page)
2067 return NULL;
2068 status = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
2069 if (unlikely(status)) {
2070 page_cache_release(page);
2071 if (status == -EEXIST)
2072 goto repeat;
2073 return NULL;
2075 return page;
2077 EXPORT_SYMBOL(__grab_cache_page);
2079 static ssize_t generic_perform_write_2copy(struct file *file,
2080 struct iov_iter *i, loff_t pos)
2082 struct address_space *mapping = file->f_mapping;
2083 const struct address_space_operations *a_ops = mapping->a_ops;
2084 struct inode *inode = mapping->host;
2085 long status = 0;
2086 ssize_t written = 0;
2088 do {
2089 struct page *src_page;
2090 struct page *page;
2091 pgoff_t index; /* Pagecache index for current page */
2092 unsigned long offset; /* Offset into pagecache page */
2093 unsigned long bytes; /* Bytes to write to page */
2094 size_t copied; /* Bytes copied from user */
2096 offset = (pos & (PAGE_CACHE_SIZE - 1));
2097 index = pos >> PAGE_CACHE_SHIFT;
2098 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2099 iov_iter_count(i));
2102 * a non-NULL src_page indicates that we're doing the
2103 * copy via get_user_pages and kmap.
2105 src_page = NULL;
2108 * Bring in the user page that we will copy from _first_.
2109 * Otherwise there's a nasty deadlock on copying from the
2110 * same page as we're writing to, without it being marked
2111 * up-to-date.
2113 * Not only is this an optimisation, but it is also required
2114 * to check that the address is actually valid, when atomic
2115 * usercopies are used, below.
2117 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2118 status = -EFAULT;
2119 break;
2122 page = __grab_cache_page(mapping, index);
2123 if (!page) {
2124 status = -ENOMEM;
2125 break;
2129 * non-uptodate pages cannot cope with short copies, and we
2130 * cannot take a pagefault with the destination page locked.
2131 * So pin the source page to copy it.
2133 if (!PageUptodate(page) && !segment_eq(get_fs(), KERNEL_DS)) {
2134 unlock_page(page);
2136 src_page = alloc_page(GFP_KERNEL);
2137 if (!src_page) {
2138 page_cache_release(page);
2139 status = -ENOMEM;
2140 break;
2144 * Cannot get_user_pages with a page locked for the
2145 * same reason as we can't take a page fault with a
2146 * page locked (as explained below).
2148 copied = iov_iter_copy_from_user(src_page, i,
2149 offset, bytes);
2150 if (unlikely(copied == 0)) {
2151 status = -EFAULT;
2152 page_cache_release(page);
2153 page_cache_release(src_page);
2154 break;
2156 bytes = copied;
2158 lock_page(page);
2160 * Can't handle the page going uptodate here, because
2161 * that means we would use non-atomic usercopies, which
2162 * zero out the tail of the page, which can cause
2163 * zeroes to become transiently visible. We could just
2164 * use a non-zeroing copy, but the APIs aren't too
2165 * consistent.
2167 if (unlikely(!page->mapping || PageUptodate(page))) {
2168 unlock_page(page);
2169 page_cache_release(page);
2170 page_cache_release(src_page);
2171 continue;
2175 status = a_ops->prepare_write(file, page, offset, offset+bytes);
2176 if (unlikely(status))
2177 goto fs_write_aop_error;
2179 if (!src_page) {
2181 * Must not enter the pagefault handler here, because
2182 * we hold the page lock, so we might recursively
2183 * deadlock on the same lock, or get an ABBA deadlock
2184 * against a different lock, or against the mmap_sem
2185 * (which nests outside the page lock). So increment
2186 * preempt count, and use _atomic usercopies.
2188 * The page is uptodate so we are OK to encounter a
2189 * short copy: if unmodified parts of the page are
2190 * marked dirty and written out to disk, it doesn't
2191 * really matter.
2193 pagefault_disable();
2194 copied = iov_iter_copy_from_user_atomic(page, i,
2195 offset, bytes);
2196 pagefault_enable();
2197 } else {
2198 void *src, *dst;
2199 src = kmap_atomic(src_page, KM_USER0);
2200 dst = kmap_atomic(page, KM_USER1);
2201 memcpy(dst + offset, src + offset, bytes);
2202 kunmap_atomic(dst, KM_USER1);
2203 kunmap_atomic(src, KM_USER0);
2204 copied = bytes;
2206 flush_dcache_page(page);
2208 status = a_ops->commit_write(file, page, offset, offset+bytes);
2209 if (unlikely(status < 0))
2210 goto fs_write_aop_error;
2211 if (unlikely(status > 0)) /* filesystem did partial write */
2212 copied = min_t(size_t, copied, status);
2214 unlock_page(page);
2215 mark_page_accessed(page);
2216 page_cache_release(page);
2217 if (src_page)
2218 page_cache_release(src_page);
2220 iov_iter_advance(i, copied);
2221 pos += copied;
2222 written += copied;
2224 balance_dirty_pages_ratelimited(mapping);
2225 cond_resched();
2226 continue;
2228 fs_write_aop_error:
2229 unlock_page(page);
2230 page_cache_release(page);
2231 if (src_page)
2232 page_cache_release(src_page);
2235 * prepare_write() may have instantiated a few blocks
2236 * outside i_size. Trim these off again. Don't need
2237 * i_size_read because we hold i_mutex.
2239 if (pos + bytes > inode->i_size)
2240 vmtruncate(inode, inode->i_size);
2241 break;
2242 } while (iov_iter_count(i));
2244 return written ? written : status;
2247 static ssize_t generic_perform_write(struct file *file,
2248 struct iov_iter *i, loff_t pos)
2250 struct address_space *mapping = file->f_mapping;
2251 const struct address_space_operations *a_ops = mapping->a_ops;
2252 long status = 0;
2253 ssize_t written = 0;
2254 unsigned int flags = 0;
2257 * Copies from kernel address space cannot fail (NFSD is a big user).
2259 if (segment_eq(get_fs(), KERNEL_DS))
2260 flags |= AOP_FLAG_UNINTERRUPTIBLE;
2262 do {
2263 struct page *page;
2264 pgoff_t index; /* Pagecache index for current page */
2265 unsigned long offset; /* Offset into pagecache page */
2266 unsigned long bytes; /* Bytes to write to page */
2267 size_t copied; /* Bytes copied from user */
2268 void *fsdata;
2270 offset = (pos & (PAGE_CACHE_SIZE - 1));
2271 index = pos >> PAGE_CACHE_SHIFT;
2272 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2273 iov_iter_count(i));
2275 again:
2278 * Bring in the user page that we will copy from _first_.
2279 * Otherwise there's a nasty deadlock on copying from the
2280 * same page as we're writing to, without it being marked
2281 * up-to-date.
2283 * Not only is this an optimisation, but it is also required
2284 * to check that the address is actually valid, when atomic
2285 * usercopies are used, below.
2287 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2288 status = -EFAULT;
2289 break;
2292 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
2293 &page, &fsdata);
2294 if (unlikely(status))
2295 break;
2297 pagefault_disable();
2298 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2299 pagefault_enable();
2300 flush_dcache_page(page);
2302 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2303 page, fsdata);
2304 if (unlikely(status < 0))
2305 break;
2306 copied = status;
2308 cond_resched();
2310 iov_iter_advance(i, copied);
2311 if (unlikely(copied == 0)) {
2313 * If we were unable to copy any data at all, we must
2314 * fall back to a single segment length write.
2316 * If we didn't fallback here, we could livelock
2317 * because not all segments in the iov can be copied at
2318 * once without a pagefault.
2320 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2321 iov_iter_single_seg_count(i));
2322 goto again;
2324 pos += copied;
2325 written += copied;
2327 balance_dirty_pages_ratelimited(mapping);
2329 } while (iov_iter_count(i));
2331 return written ? written : status;
2334 ssize_t
2335 generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
2336 unsigned long nr_segs, loff_t pos, loff_t *ppos,
2337 size_t count, ssize_t written)
2339 struct file *file = iocb->ki_filp;
2340 struct address_space *mapping = file->f_mapping;
2341 const struct address_space_operations *a_ops = mapping->a_ops;
2342 struct inode *inode = mapping->host;
2343 ssize_t status;
2344 struct iov_iter i;
2346 iov_iter_init(&i, iov, nr_segs, count, written);
2347 if (a_ops->write_begin)
2348 status = generic_perform_write(file, &i, pos);
2349 else
2350 status = generic_perform_write_2copy(file, &i, pos);
2352 if (likely(status >= 0)) {
2353 written += status;
2354 *ppos = pos + status;
2357 * For now, when the user asks for O_SYNC, we'll actually give
2358 * O_DSYNC
2360 if (unlikely((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2361 if (!a_ops->writepage || !is_sync_kiocb(iocb))
2362 status = generic_osync_inode(inode, mapping,
2363 OSYNC_METADATA|OSYNC_DATA);
2368 * If we get here for O_DIRECT writes then we must have fallen through
2369 * to buffered writes (block instantiation inside i_size). So we sync
2370 * the file data here, to try to honour O_DIRECT expectations.
2372 if (unlikely(file->f_flags & O_DIRECT) && written)
2373 status = filemap_write_and_wait(mapping);
2375 return written ? written : status;
2377 EXPORT_SYMBOL(generic_file_buffered_write);
2379 static ssize_t
2380 __generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
2381 unsigned long nr_segs, loff_t *ppos)
2383 struct file *file = iocb->ki_filp;
2384 struct address_space * mapping = file->f_mapping;
2385 size_t ocount; /* original count */
2386 size_t count; /* after file limit checks */
2387 struct inode *inode = mapping->host;
2388 loff_t pos;
2389 ssize_t written;
2390 ssize_t err;
2392 ocount = 0;
2393 err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
2394 if (err)
2395 return err;
2397 count = ocount;
2398 pos = *ppos;
2400 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2402 /* We can write back this queue in page reclaim */
2403 current->backing_dev_info = mapping->backing_dev_info;
2404 written = 0;
2406 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2407 if (err)
2408 goto out;
2410 if (count == 0)
2411 goto out;
2413 err = remove_suid(file->f_path.dentry);
2414 if (err)
2415 goto out;
2417 file_update_time(file);
2419 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2420 if (unlikely(file->f_flags & O_DIRECT)) {
2421 loff_t endbyte;
2422 ssize_t written_buffered;
2424 written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
2425 ppos, count, ocount);
2426 if (written < 0 || written == count)
2427 goto out;
2429 * direct-io write to a hole: fall through to buffered I/O
2430 * for completing the rest of the request.
2432 pos += written;
2433 count -= written;
2434 written_buffered = generic_file_buffered_write(iocb, iov,
2435 nr_segs, pos, ppos, count,
2436 written);
2438 * If generic_file_buffered_write() retuned a synchronous error
2439 * then we want to return the number of bytes which were
2440 * direct-written, or the error code if that was zero. Note
2441 * that this differs from normal direct-io semantics, which
2442 * will return -EFOO even if some bytes were written.
2444 if (written_buffered < 0) {
2445 err = written_buffered;
2446 goto out;
2450 * We need to ensure that the page cache pages are written to
2451 * disk and invalidated to preserve the expected O_DIRECT
2452 * semantics.
2454 endbyte = pos + written_buffered - written - 1;
2455 err = do_sync_mapping_range(file->f_mapping, pos, endbyte,
2456 SYNC_FILE_RANGE_WAIT_BEFORE|
2457 SYNC_FILE_RANGE_WRITE|
2458 SYNC_FILE_RANGE_WAIT_AFTER);
2459 if (err == 0) {
2460 written = written_buffered;
2461 invalidate_mapping_pages(mapping,
2462 pos >> PAGE_CACHE_SHIFT,
2463 endbyte >> PAGE_CACHE_SHIFT);
2464 } else {
2466 * We don't know how much we wrote, so just return
2467 * the number of bytes which were direct-written
2470 } else {
2471 written = generic_file_buffered_write(iocb, iov, nr_segs,
2472 pos, ppos, count, written);
2474 out:
2475 current->backing_dev_info = NULL;
2476 return written ? written : err;
2479 ssize_t generic_file_aio_write_nolock(struct kiocb *iocb,
2480 const struct iovec *iov, unsigned long nr_segs, loff_t pos)
2482 struct file *file = iocb->ki_filp;
2483 struct address_space *mapping = file->f_mapping;
2484 struct inode *inode = mapping->host;
2485 ssize_t ret;
2487 BUG_ON(iocb->ki_pos != pos);
2489 ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
2490 &iocb->ki_pos);
2492 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2493 ssize_t err;
2495 err = sync_page_range_nolock(inode, mapping, pos, ret);
2496 if (err < 0)
2497 ret = err;
2499 return ret;
2501 EXPORT_SYMBOL(generic_file_aio_write_nolock);
2503 ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2504 unsigned long nr_segs, loff_t pos)
2506 struct file *file = iocb->ki_filp;
2507 struct address_space *mapping = file->f_mapping;
2508 struct inode *inode = mapping->host;
2509 ssize_t ret;
2511 BUG_ON(iocb->ki_pos != pos);
2513 mutex_lock(&inode->i_mutex);
2514 ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
2515 &iocb->ki_pos);
2516 mutex_unlock(&inode->i_mutex);
2518 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2519 ssize_t err;
2521 err = sync_page_range(inode, mapping, pos, ret);
2522 if (err < 0)
2523 ret = err;
2525 return ret;
2527 EXPORT_SYMBOL(generic_file_aio_write);
2530 * Called under i_mutex for writes to S_ISREG files. Returns -EIO if something
2531 * went wrong during pagecache shootdown.
2533 static ssize_t
2534 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2535 loff_t offset, unsigned long nr_segs)
2537 struct file *file = iocb->ki_filp;
2538 struct address_space *mapping = file->f_mapping;
2539 ssize_t retval;
2540 size_t write_len;
2541 pgoff_t end = 0; /* silence gcc */
2544 * If it's a write, unmap all mmappings of the file up-front. This
2545 * will cause any pte dirty bits to be propagated into the pageframes
2546 * for the subsequent filemap_write_and_wait().
2548 if (rw == WRITE) {
2549 write_len = iov_length(iov, nr_segs);
2550 end = (offset + write_len - 1) >> PAGE_CACHE_SHIFT;
2551 if (mapping_mapped(mapping))
2552 unmap_mapping_range(mapping, offset, write_len, 0);
2555 retval = filemap_write_and_wait(mapping);
2556 if (retval)
2557 goto out;
2560 * After a write we want buffered reads to be sure to go to disk to get
2561 * the new data. We invalidate clean cached page from the region we're
2562 * about to write. We do this *before* the write so that we can return
2563 * -EIO without clobbering -EIOCBQUEUED from ->direct_IO().
2565 if (rw == WRITE && mapping->nrpages) {
2566 retval = invalidate_inode_pages2_range(mapping,
2567 offset >> PAGE_CACHE_SHIFT, end);
2568 if (retval)
2569 goto out;
2572 retval = mapping->a_ops->direct_IO(rw, iocb, iov, offset, nr_segs);
2575 * Finally, try again to invalidate clean pages which might have been
2576 * cached by non-direct readahead, or faulted in by get_user_pages()
2577 * if the source of the write was an mmap'ed region of the file
2578 * we're writing. Either one is a pretty crazy thing to do,
2579 * so we don't support it 100%. If this invalidation
2580 * fails, tough, the write still worked...
2582 if (rw == WRITE && mapping->nrpages) {
2583 invalidate_inode_pages2_range(mapping, offset >> PAGE_CACHE_SHIFT, end);
2585 out:
2586 return retval;
2590 * try_to_release_page() - release old fs-specific metadata on a page
2592 * @page: the page which the kernel is trying to free
2593 * @gfp_mask: memory allocation flags (and I/O mode)
2595 * The address_space is to try to release any data against the page
2596 * (presumably at page->private). If the release was successful, return `1'.
2597 * Otherwise return zero.
2599 * The @gfp_mask argument specifies whether I/O may be performed to release
2600 * this page (__GFP_IO), and whether the call may block (__GFP_WAIT).
2602 * NOTE: @gfp_mask may go away, and this function may become non-blocking.
2604 int try_to_release_page(struct page *page, gfp_t gfp_mask)
2606 struct address_space * const mapping = page->mapping;
2608 BUG_ON(!PageLocked(page));
2609 if (PageWriteback(page))
2610 return 0;
2612 if (mapping && mapping->a_ops->releasepage)
2613 return mapping->a_ops->releasepage(page, gfp_mask);
2614 return try_to_free_buffers(page);
2617 EXPORT_SYMBOL(try_to_release_page);