4 * Copyright (C) 1994-1999 Linus Torvalds
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/compiler.h>
15 #include <linux/uaccess.h>
16 #include <linux/aio.h>
17 #include <linux/capability.h>
18 #include <linux/kernel_stat.h>
19 #include <linux/gfp.h>
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() */
40 * FIXME: remove all knowledge of the buffer layer from the core VM
42 #include <linux/buffer_head.h> /* for try_to_free_buffers */
47 * Shared mappings implemented 30.11.1994. It's not fully working yet,
50 * Shared mappings now work. 15.8.1995 Bruno.
52 * finished 'unifying' the page and buffer cache and SMP-threaded the
53 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
55 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
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
67 * ->i_mmap_lock (truncate->unmap_mapping_range)
71 * ->page_table_lock or pte_lock (various, mainly in memory.c)
72 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
75 * ->lock_page (access_process_vm)
77 * ->i_mutex (generic_file_buffered_write)
78 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
81 * ->i_alloc_sem (various)
84 * ->sb_lock (fs/fs-writeback.c)
85 * ->mapping->tree_lock (__sync_single_inode)
88 * ->anon_vma.lock (vma_adjust)
91 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
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)
105 * (code doesn't rely on that order, so you could switch it around)
106 * ->tasklist_lock (memory_failure, collect_procs_ao)
111 * Delete a page from the page cache and free it. Caller has to make
112 * sure the page is locked and that nobody else uses it - or that usage
113 * is safe. The caller must hold the mapping's tree_lock.
115 void __delete_from_page_cache(struct page *page)
117 struct address_space *mapping = page->mapping;
119 radix_tree_delete(&mapping->page_tree, page->index);
120 page->mapping = NULL;
122 __dec_zone_page_state(page, NR_FILE_PAGES);
123 if (PageSwapBacked(page))
124 __dec_zone_page_state(page, NR_SHMEM);
125 BUG_ON(page_mapped(page));
128 * Some filesystems seem to re-dirty the page even after
129 * the VM has canceled the dirty bit (eg ext3 journaling).
131 * Fix it up by doing a final dirty accounting check after
132 * having removed the page entirely.
134 if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
135 dec_zone_page_state(page, NR_FILE_DIRTY);
136 dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
141 * delete_from_page_cache - delete page from page cache
142 * @page: the page which the kernel is trying to remove from page cache
144 * This must be called only on pages that have been verified to be in the page
145 * cache and locked. It will never put the page into the free list, the caller
146 * has a reference on the page.
148 void delete_from_page_cache(struct page *page)
150 struct address_space *mapping = page->mapping;
151 void (*freepage)(struct page *);
153 BUG_ON(!PageLocked(page));
155 freepage = mapping->a_ops->freepage;
156 spin_lock_irq(&mapping->tree_lock);
157 __delete_from_page_cache(page);
158 spin_unlock_irq(&mapping->tree_lock);
159 mem_cgroup_uncharge_cache_page(page);
163 page_cache_release(page);
165 EXPORT_SYMBOL(delete_from_page_cache);
167 static int sleep_on_page(void *word)
173 static int sleep_on_page_killable(void *word)
176 return fatal_signal_pending(current) ? -EINTR : 0;
180 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
181 * @mapping: address space structure to write
182 * @start: offset in bytes where the range starts
183 * @end: offset in bytes where the range ends (inclusive)
184 * @sync_mode: enable synchronous operation
186 * Start writeback against all of a mapping's dirty pages that lie
187 * within the byte offsets <start, end> inclusive.
189 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
190 * opposed to a regular memory cleansing writeback. The difference between
191 * these two operations is that if a dirty page/buffer is encountered, it must
192 * be waited upon, and not just skipped over.
194 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
195 loff_t end, int sync_mode)
198 struct writeback_control wbc = {
199 .sync_mode = sync_mode,
200 .nr_to_write = LONG_MAX,
201 .range_start = start,
205 if (!mapping_cap_writeback_dirty(mapping))
208 ret = do_writepages(mapping, &wbc);
212 static inline int __filemap_fdatawrite(struct address_space *mapping,
215 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
218 int filemap_fdatawrite(struct address_space *mapping)
220 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
222 EXPORT_SYMBOL(filemap_fdatawrite);
224 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
227 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
229 EXPORT_SYMBOL(filemap_fdatawrite_range);
232 * filemap_flush - mostly a non-blocking flush
233 * @mapping: target address_space
235 * This is a mostly non-blocking flush. Not suitable for data-integrity
236 * purposes - I/O may not be started against all dirty pages.
238 int filemap_flush(struct address_space *mapping)
240 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
242 EXPORT_SYMBOL(filemap_flush);
245 * filemap_fdatawait_range - wait for writeback to complete
246 * @mapping: address space structure to wait for
247 * @start_byte: offset in bytes where the range starts
248 * @end_byte: offset in bytes where the range ends (inclusive)
250 * Walk the list of under-writeback pages of the given address space
251 * in the given range and wait for all of them.
253 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
256 pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;
257 pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;
262 if (end_byte < start_byte)
265 pagevec_init(&pvec, 0);
266 while ((index <= end) &&
267 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
268 PAGECACHE_TAG_WRITEBACK,
269 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
272 for (i = 0; i < nr_pages; i++) {
273 struct page *page = pvec.pages[i];
275 /* until radix tree lookup accepts end_index */
276 if (page->index > end)
279 wait_on_page_writeback(page);
280 if (TestClearPageError(page))
283 pagevec_release(&pvec);
287 /* Check for outstanding write errors */
288 if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
290 if (test_and_clear_bit(AS_EIO, &mapping->flags))
295 EXPORT_SYMBOL(filemap_fdatawait_range);
298 * filemap_fdatawait - wait for all under-writeback pages to complete
299 * @mapping: address space structure to wait for
301 * Walk the list of under-writeback pages of the given address space
302 * and wait for all of them.
304 int filemap_fdatawait(struct address_space *mapping)
306 loff_t i_size = i_size_read(mapping->host);
311 return filemap_fdatawait_range(mapping, 0, i_size - 1);
313 EXPORT_SYMBOL(filemap_fdatawait);
315 int filemap_write_and_wait(struct address_space *mapping)
319 if (mapping->nrpages) {
320 err = filemap_fdatawrite(mapping);
322 * Even if the above returned error, the pages may be
323 * written partially (e.g. -ENOSPC), so we wait for it.
324 * But the -EIO is special case, it may indicate the worst
325 * thing (e.g. bug) happened, so we avoid waiting for it.
328 int err2 = filemap_fdatawait(mapping);
335 EXPORT_SYMBOL(filemap_write_and_wait);
338 * filemap_write_and_wait_range - write out & wait on a file range
339 * @mapping: the address_space for the pages
340 * @lstart: offset in bytes where the range starts
341 * @lend: offset in bytes where the range ends (inclusive)
343 * Write out and wait upon file offsets lstart->lend, inclusive.
345 * Note that `lend' is inclusive (describes the last byte to be written) so
346 * that this function can be used to write to the very end-of-file (end = -1).
348 int filemap_write_and_wait_range(struct address_space *mapping,
349 loff_t lstart, loff_t lend)
353 if (mapping->nrpages) {
354 err = __filemap_fdatawrite_range(mapping, lstart, lend,
356 /* See comment of filemap_write_and_wait() */
358 int err2 = filemap_fdatawait_range(mapping,
366 EXPORT_SYMBOL(filemap_write_and_wait_range);
369 * replace_page_cache_page - replace a pagecache page with a new one
370 * @old: page to be replaced
371 * @new: page to replace with
372 * @gfp_mask: allocation mode
374 * This function replaces a page in the pagecache with a new one. On
375 * success it acquires the pagecache reference for the new page and
376 * drops it for the old page. Both the old and new pages must be
377 * locked. This function does not add the new page to the LRU, the
378 * caller must do that.
380 * The remove + add is atomic. The only way this function can fail is
381 * memory allocation failure.
383 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
386 struct mem_cgroup *memcg = NULL;
388 VM_BUG_ON(!PageLocked(old));
389 VM_BUG_ON(!PageLocked(new));
390 VM_BUG_ON(new->mapping);
393 * This is not page migration, but prepare_migration and
394 * end_migration does enough work for charge replacement.
396 * In the longer term we probably want a specialized function
397 * for moving the charge from old to new in a more efficient
400 error = mem_cgroup_prepare_migration(old, new, &memcg, gfp_mask);
404 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
406 struct address_space *mapping = old->mapping;
407 void (*freepage)(struct page *);
409 pgoff_t offset = old->index;
410 freepage = mapping->a_ops->freepage;
413 new->mapping = mapping;
416 spin_lock_irq(&mapping->tree_lock);
417 __delete_from_page_cache(old);
418 error = radix_tree_insert(&mapping->page_tree, offset, new);
421 __inc_zone_page_state(new, NR_FILE_PAGES);
422 if (PageSwapBacked(new))
423 __inc_zone_page_state(new, NR_SHMEM);
424 spin_unlock_irq(&mapping->tree_lock);
425 radix_tree_preload_end();
428 page_cache_release(old);
429 mem_cgroup_end_migration(memcg, old, new, true);
431 mem_cgroup_end_migration(memcg, old, new, false);
436 EXPORT_SYMBOL_GPL(replace_page_cache_page);
439 * add_to_page_cache_locked - add a locked page to the pagecache
441 * @mapping: the page's address_space
442 * @offset: page index
443 * @gfp_mask: page allocation mode
445 * This function is used to add a page to the pagecache. It must be locked.
446 * This function does not add the page to the LRU. The caller must do that.
448 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
449 pgoff_t offset, gfp_t gfp_mask)
453 VM_BUG_ON(!PageLocked(page));
455 error = mem_cgroup_cache_charge(page, current->mm,
456 gfp_mask & GFP_RECLAIM_MASK);
460 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
462 page_cache_get(page);
463 page->mapping = mapping;
464 page->index = offset;
466 spin_lock_irq(&mapping->tree_lock);
467 error = radix_tree_insert(&mapping->page_tree, offset, page);
468 if (likely(!error)) {
470 __inc_zone_page_state(page, NR_FILE_PAGES);
471 if (PageSwapBacked(page))
472 __inc_zone_page_state(page, NR_SHMEM);
473 spin_unlock_irq(&mapping->tree_lock);
475 page->mapping = NULL;
476 spin_unlock_irq(&mapping->tree_lock);
477 mem_cgroup_uncharge_cache_page(page);
478 page_cache_release(page);
480 radix_tree_preload_end();
482 mem_cgroup_uncharge_cache_page(page);
486 EXPORT_SYMBOL(add_to_page_cache_locked);
488 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
489 pgoff_t offset, gfp_t gfp_mask)
494 * Splice_read and readahead add shmem/tmpfs pages into the page cache
495 * before shmem_readpage has a chance to mark them as SwapBacked: they
496 * need to go on the anon lru below, and mem_cgroup_cache_charge
497 * (called in add_to_page_cache) needs to know where they're going too.
499 if (mapping_cap_swap_backed(mapping))
500 SetPageSwapBacked(page);
502 ret = add_to_page_cache(page, mapping, offset, gfp_mask);
504 if (page_is_file_cache(page))
505 lru_cache_add_file(page);
507 lru_cache_add_anon(page);
511 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
514 struct page *__page_cache_alloc(gfp_t gfp)
519 if (cpuset_do_page_mem_spread()) {
521 n = cpuset_mem_spread_node();
522 page = alloc_pages_exact_node(n, gfp, 0);
526 return alloc_pages(gfp, 0);
528 EXPORT_SYMBOL(__page_cache_alloc);
532 * In order to wait for pages to become available there must be
533 * waitqueues associated with pages. By using a hash table of
534 * waitqueues where the bucket discipline is to maintain all
535 * waiters on the same queue and wake all when any of the pages
536 * become available, and for the woken contexts to check to be
537 * sure the appropriate page became available, this saves space
538 * at a cost of "thundering herd" phenomena during rare hash
541 static wait_queue_head_t *page_waitqueue(struct page *page)
543 const struct zone *zone = page_zone(page);
545 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
548 static inline void wake_up_page(struct page *page, int bit)
550 __wake_up_bit(page_waitqueue(page), &page->flags, bit);
553 void wait_on_page_bit(struct page *page, int bit_nr)
555 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
557 if (test_bit(bit_nr, &page->flags))
558 __wait_on_bit(page_waitqueue(page), &wait, sleep_on_page,
559 TASK_UNINTERRUPTIBLE);
561 EXPORT_SYMBOL(wait_on_page_bit);
564 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
565 * @page: Page defining the wait queue of interest
566 * @waiter: Waiter to add to the queue
568 * Add an arbitrary @waiter to the wait queue for the nominated @page.
570 void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
572 wait_queue_head_t *q = page_waitqueue(page);
575 spin_lock_irqsave(&q->lock, flags);
576 __add_wait_queue(q, waiter);
577 spin_unlock_irqrestore(&q->lock, flags);
579 EXPORT_SYMBOL_GPL(add_page_wait_queue);
582 * unlock_page - unlock a locked page
585 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
586 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
587 * mechananism between PageLocked pages and PageWriteback pages is shared.
588 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
590 * The mb is necessary to enforce ordering between the clear_bit and the read
591 * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
593 void unlock_page(struct page *page)
595 VM_BUG_ON(!PageLocked(page));
596 clear_bit_unlock(PG_locked, &page->flags);
597 smp_mb__after_clear_bit();
598 wake_up_page(page, PG_locked);
600 EXPORT_SYMBOL(unlock_page);
603 * end_page_writeback - end writeback against a page
606 void end_page_writeback(struct page *page)
608 if (TestClearPageReclaim(page))
609 rotate_reclaimable_page(page);
611 if (!test_clear_page_writeback(page))
614 smp_mb__after_clear_bit();
615 wake_up_page(page, PG_writeback);
617 EXPORT_SYMBOL(end_page_writeback);
620 * __lock_page - get a lock on the page, assuming we need to sleep to get it
621 * @page: the page to lock
623 void __lock_page(struct page *page)
625 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
627 __wait_on_bit_lock(page_waitqueue(page), &wait, sleep_on_page,
628 TASK_UNINTERRUPTIBLE);
630 EXPORT_SYMBOL(__lock_page);
632 int __lock_page_killable(struct page *page)
634 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
636 return __wait_on_bit_lock(page_waitqueue(page), &wait,
637 sleep_on_page_killable, TASK_KILLABLE);
639 EXPORT_SYMBOL_GPL(__lock_page_killable);
641 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
644 if (!(flags & FAULT_FLAG_ALLOW_RETRY)) {
648 if (!(flags & FAULT_FLAG_RETRY_NOWAIT)) {
649 up_read(&mm->mmap_sem);
650 wait_on_page_locked(page);
657 * find_get_page - find and get a page reference
658 * @mapping: the address_space to search
659 * @offset: the page index
661 * Is there a pagecache struct page at the given (mapping, offset) tuple?
662 * If yes, increment its refcount and return it; if no, return NULL.
664 struct page *find_get_page(struct address_space *mapping, pgoff_t offset)
672 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
674 page = radix_tree_deref_slot(pagep);
677 if (radix_tree_deref_retry(page))
680 if (!page_cache_get_speculative(page))
684 * Has the page moved?
685 * This is part of the lockless pagecache protocol. See
686 * include/linux/pagemap.h for details.
688 if (unlikely(page != *pagep)) {
689 page_cache_release(page);
698 EXPORT_SYMBOL(find_get_page);
701 * find_lock_page - locate, pin and lock a pagecache page
702 * @mapping: the address_space to search
703 * @offset: the page index
705 * Locates the desired pagecache page, locks it, increments its reference
706 * count and returns its address.
708 * Returns zero if the page was not present. find_lock_page() may sleep.
710 struct page *find_lock_page(struct address_space *mapping, pgoff_t offset)
715 page = find_get_page(mapping, offset);
718 /* Has the page been truncated? */
719 if (unlikely(page->mapping != mapping)) {
721 page_cache_release(page);
724 VM_BUG_ON(page->index != offset);
728 EXPORT_SYMBOL(find_lock_page);
731 * find_or_create_page - locate or add a pagecache page
732 * @mapping: the page's address_space
733 * @index: the page's index into the mapping
734 * @gfp_mask: page allocation mode
736 * Locates a page in the pagecache. If the page is not present, a new page
737 * is allocated using @gfp_mask and is added to the pagecache and to the VM's
738 * LRU list. The returned page is locked and has its reference count
741 * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
744 * find_or_create_page() returns the desired page's address, or zero on
747 struct page *find_or_create_page(struct address_space *mapping,
748 pgoff_t index, gfp_t gfp_mask)
753 page = find_lock_page(mapping, index);
755 page = __page_cache_alloc(gfp_mask);
759 * We want a regular kernel memory (not highmem or DMA etc)
760 * allocation for the radix tree nodes, but we need to honour
761 * the context-specific requirements the caller has asked for.
762 * GFP_RECLAIM_MASK collects those requirements.
764 err = add_to_page_cache_lru(page, mapping, index,
765 (gfp_mask & GFP_RECLAIM_MASK));
767 page_cache_release(page);
775 EXPORT_SYMBOL(find_or_create_page);
778 * find_get_pages - gang pagecache lookup
779 * @mapping: The address_space to search
780 * @start: The starting page index
781 * @nr_pages: The maximum number of pages
782 * @pages: Where the resulting pages are placed
784 * find_get_pages() will search for and return a group of up to
785 * @nr_pages pages in the mapping. The pages are placed at @pages.
786 * find_get_pages() takes a reference against the returned pages.
788 * The search returns a group of mapping-contiguous pages with ascending
789 * indexes. There may be holes in the indices due to not-present pages.
791 * find_get_pages() returns the number of pages which were found.
793 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
794 unsigned int nr_pages, struct page **pages)
798 unsigned int nr_found;
802 nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
803 (void ***)pages, start, nr_pages);
805 for (i = 0; i < nr_found; i++) {
808 page = radix_tree_deref_slot((void **)pages[i]);
813 * This can only trigger when the entry at index 0 moves out
814 * of or back to the root: none yet gotten, safe to restart.
816 if (radix_tree_deref_retry(page)) {
821 if (!page_cache_get_speculative(page))
824 /* Has the page moved? */
825 if (unlikely(page != *((void **)pages[i]))) {
826 page_cache_release(page);
835 * If all entries were removed before we could secure them,
836 * try again, because callers stop trying once 0 is returned.
838 if (unlikely(!ret && nr_found))
845 * find_get_pages_contig - gang contiguous pagecache lookup
846 * @mapping: The address_space to search
847 * @index: The starting page index
848 * @nr_pages: The maximum number of pages
849 * @pages: Where the resulting pages are placed
851 * find_get_pages_contig() works exactly like find_get_pages(), except
852 * that the returned number of pages are guaranteed to be contiguous.
854 * find_get_pages_contig() returns the number of pages which were found.
856 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
857 unsigned int nr_pages, struct page **pages)
861 unsigned int nr_found;
865 nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
866 (void ***)pages, index, nr_pages);
868 for (i = 0; i < nr_found; i++) {
871 page = radix_tree_deref_slot((void **)pages[i]);
876 * This can only trigger when the entry at index 0 moves out
877 * of or back to the root: none yet gotten, safe to restart.
879 if (radix_tree_deref_retry(page))
882 if (!page_cache_get_speculative(page))
885 /* Has the page moved? */
886 if (unlikely(page != *((void **)pages[i]))) {
887 page_cache_release(page);
892 * must check mapping and index after taking the ref.
893 * otherwise we can get both false positives and false
894 * negatives, which is just confusing to the caller.
896 if (page->mapping == NULL || page->index != index) {
897 page_cache_release(page);
908 EXPORT_SYMBOL(find_get_pages_contig);
911 * find_get_pages_tag - find and return pages that match @tag
912 * @mapping: the address_space to search
913 * @index: the starting page index
914 * @tag: the tag index
915 * @nr_pages: the maximum number of pages
916 * @pages: where the resulting pages are placed
918 * Like find_get_pages, except we only return pages which are tagged with
919 * @tag. We update @index to index the next page for the traversal.
921 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
922 int tag, unsigned int nr_pages, struct page **pages)
926 unsigned int nr_found;
930 nr_found = radix_tree_gang_lookup_tag_slot(&mapping->page_tree,
931 (void ***)pages, *index, nr_pages, tag);
933 for (i = 0; i < nr_found; i++) {
936 page = radix_tree_deref_slot((void **)pages[i]);
941 * This can only trigger when the entry at index 0 moves out
942 * of or back to the root: none yet gotten, safe to restart.
944 if (radix_tree_deref_retry(page))
947 if (!page_cache_get_speculative(page))
950 /* Has the page moved? */
951 if (unlikely(page != *((void **)pages[i]))) {
952 page_cache_release(page);
961 * If all entries were removed before we could secure them,
962 * try again, because callers stop trying once 0 is returned.
964 if (unlikely(!ret && nr_found))
969 *index = pages[ret - 1]->index + 1;
973 EXPORT_SYMBOL(find_get_pages_tag);
976 * grab_cache_page_nowait - returns locked page at given index in given cache
977 * @mapping: target address_space
978 * @index: the page index
980 * Same as grab_cache_page(), but do not wait if the page is unavailable.
981 * This is intended for speculative data generators, where the data can
982 * be regenerated if the page couldn't be grabbed. This routine should
983 * be safe to call while holding the lock for another page.
985 * Clear __GFP_FS when allocating the page to avoid recursion into the fs
986 * and deadlock against the caller's locked page.
989 grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
991 struct page *page = find_get_page(mapping, index);
994 if (trylock_page(page))
996 page_cache_release(page);
999 page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
1000 if (page && add_to_page_cache_lru(page, mapping, index, GFP_NOFS)) {
1001 page_cache_release(page);
1006 EXPORT_SYMBOL(grab_cache_page_nowait);
1009 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1010 * a _large_ part of the i/o request. Imagine the worst scenario:
1012 * ---R__________________________________________B__________
1013 * ^ reading here ^ bad block(assume 4k)
1015 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1016 * => failing the whole request => read(R) => read(R+1) =>
1017 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1018 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1019 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1021 * It is going insane. Fix it by quickly scaling down the readahead size.
1023 static void shrink_readahead_size_eio(struct file *filp,
1024 struct file_ra_state *ra)
1030 * do_generic_file_read - generic file read routine
1031 * @filp: the file to read
1032 * @ppos: current file position
1033 * @desc: read_descriptor
1034 * @actor: read method
1036 * This is a generic file read routine, and uses the
1037 * mapping->a_ops->readpage() function for the actual low-level stuff.
1039 * This is really ugly. But the goto's actually try to clarify some
1040 * of the logic when it comes to error handling etc.
1042 static void do_generic_file_read(struct file *filp, loff_t *ppos,
1043 read_descriptor_t *desc, read_actor_t actor)
1045 struct address_space *mapping = filp->f_mapping;
1046 struct inode *inode = mapping->host;
1047 struct file_ra_state *ra = &filp->f_ra;
1051 unsigned long offset; /* offset into pagecache page */
1052 unsigned int prev_offset;
1055 index = *ppos >> PAGE_CACHE_SHIFT;
1056 prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
1057 prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
1058 last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
1059 offset = *ppos & ~PAGE_CACHE_MASK;
1065 unsigned long nr, ret;
1069 page = find_get_page(mapping, index);
1071 page_cache_sync_readahead(mapping,
1073 index, last_index - index);
1074 page = find_get_page(mapping, index);
1075 if (unlikely(page == NULL))
1076 goto no_cached_page;
1078 if (PageReadahead(page)) {
1079 page_cache_async_readahead(mapping,
1081 index, last_index - index);
1083 if (!PageUptodate(page)) {
1084 if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
1085 !mapping->a_ops->is_partially_uptodate)
1086 goto page_not_up_to_date;
1087 if (!trylock_page(page))
1088 goto page_not_up_to_date;
1089 /* Did it get truncated before we got the lock? */
1091 goto page_not_up_to_date_locked;
1092 if (!mapping->a_ops->is_partially_uptodate(page,
1094 goto page_not_up_to_date_locked;
1099 * i_size must be checked after we know the page is Uptodate.
1101 * Checking i_size after the check allows us to calculate
1102 * the correct value for "nr", which means the zero-filled
1103 * part of the page is not copied back to userspace (unless
1104 * another truncate extends the file - this is desired though).
1107 isize = i_size_read(inode);
1108 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1109 if (unlikely(!isize || index > end_index)) {
1110 page_cache_release(page);
1114 /* nr is the maximum number of bytes to copy from this page */
1115 nr = PAGE_CACHE_SIZE;
1116 if (index == end_index) {
1117 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
1119 page_cache_release(page);
1125 /* If users can be writing to this page using arbitrary
1126 * virtual addresses, take care about potential aliasing
1127 * before reading the page on the kernel side.
1129 if (mapping_writably_mapped(mapping))
1130 flush_dcache_page(page);
1133 * When a sequential read accesses a page several times,
1134 * only mark it as accessed the first time.
1136 if (prev_index != index || offset != prev_offset)
1137 mark_page_accessed(page);
1141 * Ok, we have the page, and it's up-to-date, so
1142 * now we can copy it to user space...
1144 * The actor routine returns how many bytes were actually used..
1145 * NOTE! This may not be the same as how much of a user buffer
1146 * we filled up (we may be padding etc), so we can only update
1147 * "pos" here (the actor routine has to update the user buffer
1148 * pointers and the remaining count).
1150 ret = actor(desc, page, offset, nr);
1152 index += offset >> PAGE_CACHE_SHIFT;
1153 offset &= ~PAGE_CACHE_MASK;
1154 prev_offset = offset;
1156 page_cache_release(page);
1157 if (ret == nr && desc->count)
1161 page_not_up_to_date:
1162 /* Get exclusive access to the page ... */
1163 error = lock_page_killable(page);
1164 if (unlikely(error))
1165 goto readpage_error;
1167 page_not_up_to_date_locked:
1168 /* Did it get truncated before we got the lock? */
1169 if (!page->mapping) {
1171 page_cache_release(page);
1175 /* Did somebody else fill it already? */
1176 if (PageUptodate(page)) {
1183 * A previous I/O error may have been due to temporary
1184 * failures, eg. multipath errors.
1185 * PG_error will be set again if readpage fails.
1187 ClearPageError(page);
1188 /* Start the actual read. The read will unlock the page. */
1189 error = mapping->a_ops->readpage(filp, page);
1191 if (unlikely(error)) {
1192 if (error == AOP_TRUNCATED_PAGE) {
1193 page_cache_release(page);
1196 goto readpage_error;
1199 if (!PageUptodate(page)) {
1200 error = lock_page_killable(page);
1201 if (unlikely(error))
1202 goto readpage_error;
1203 if (!PageUptodate(page)) {
1204 if (page->mapping == NULL) {
1206 * invalidate_mapping_pages got it
1209 page_cache_release(page);
1213 shrink_readahead_size_eio(filp, ra);
1215 goto readpage_error;
1223 /* UHHUH! A synchronous read error occurred. Report it */
1224 desc->error = error;
1225 page_cache_release(page);
1230 * Ok, it wasn't cached, so we need to create a new
1233 page = page_cache_alloc_cold(mapping);
1235 desc->error = -ENOMEM;
1238 error = add_to_page_cache_lru(page, mapping,
1241 page_cache_release(page);
1242 if (error == -EEXIST)
1244 desc->error = error;
1251 ra->prev_pos = prev_index;
1252 ra->prev_pos <<= PAGE_CACHE_SHIFT;
1253 ra->prev_pos |= prev_offset;
1255 *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1256 file_accessed(filp);
1259 int file_read_actor(read_descriptor_t *desc, struct page *page,
1260 unsigned long offset, unsigned long size)
1263 unsigned long left, count = desc->count;
1269 * Faults on the destination of a read are common, so do it before
1272 if (!fault_in_pages_writeable(desc->arg.buf, size)) {
1273 kaddr = kmap_atomic(page, KM_USER0);
1274 left = __copy_to_user_inatomic(desc->arg.buf,
1275 kaddr + offset, size);
1276 kunmap_atomic(kaddr, KM_USER0);
1281 /* Do it the slow way */
1283 left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
1288 desc->error = -EFAULT;
1291 desc->count = count - size;
1292 desc->written += size;
1293 desc->arg.buf += size;
1298 * Performs necessary checks before doing a write
1299 * @iov: io vector request
1300 * @nr_segs: number of segments in the iovec
1301 * @count: number of bytes to write
1302 * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1304 * Adjust number of segments and amount of bytes to write (nr_segs should be
1305 * properly initialized first). Returns appropriate error code that caller
1306 * should return or zero in case that write should be allowed.
1308 int generic_segment_checks(const struct iovec *iov,
1309 unsigned long *nr_segs, size_t *count, int access_flags)
1313 for (seg = 0; seg < *nr_segs; seg++) {
1314 const struct iovec *iv = &iov[seg];
1317 * If any segment has a negative length, or the cumulative
1318 * length ever wraps negative then return -EINVAL.
1321 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1323 if (access_ok(access_flags, iv->iov_base, iv->iov_len))
1328 cnt -= iv->iov_len; /* This segment is no good */
1334 EXPORT_SYMBOL(generic_segment_checks);
1337 * generic_file_aio_read - generic filesystem read routine
1338 * @iocb: kernel I/O control block
1339 * @iov: io vector request
1340 * @nr_segs: number of segments in the iovec
1341 * @pos: current file position
1343 * This is the "read()" routine for all filesystems
1344 * that can use the page cache directly.
1347 generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1348 unsigned long nr_segs, loff_t pos)
1350 struct file *filp = iocb->ki_filp;
1352 unsigned long seg = 0;
1354 loff_t *ppos = &iocb->ki_pos;
1355 struct blk_plug plug;
1358 retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
1362 blk_start_plug(&plug);
1364 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1365 if (filp->f_flags & O_DIRECT) {
1367 struct address_space *mapping;
1368 struct inode *inode;
1370 mapping = filp->f_mapping;
1371 inode = mapping->host;
1373 goto out; /* skip atime */
1374 size = i_size_read(inode);
1376 retval = filemap_write_and_wait_range(mapping, pos,
1377 pos + iov_length(iov, nr_segs) - 1);
1379 retval = mapping->a_ops->direct_IO(READ, iocb,
1383 *ppos = pos + retval;
1388 * Btrfs can have a short DIO read if we encounter
1389 * compressed extents, so if there was an error, or if
1390 * we've already read everything we wanted to, or if
1391 * there was a short read because we hit EOF, go ahead
1392 * and return. Otherwise fallthrough to buffered io for
1393 * the rest of the read.
1395 if (retval < 0 || !count || *ppos >= size) {
1396 file_accessed(filp);
1403 for (seg = 0; seg < nr_segs; seg++) {
1404 read_descriptor_t desc;
1408 * If we did a short DIO read we need to skip the section of the
1409 * iov that we've already read data into.
1412 if (count > iov[seg].iov_len) {
1413 count -= iov[seg].iov_len;
1421 desc.arg.buf = iov[seg].iov_base + offset;
1422 desc.count = iov[seg].iov_len - offset;
1423 if (desc.count == 0)
1426 do_generic_file_read(filp, ppos, &desc, file_read_actor);
1427 retval += desc.written;
1429 retval = retval ?: desc.error;
1436 blk_finish_plug(&plug);
1439 EXPORT_SYMBOL(generic_file_aio_read);
1442 do_readahead(struct address_space *mapping, struct file *filp,
1443 pgoff_t index, unsigned long nr)
1445 if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1448 force_page_cache_readahead(mapping, filp, index, nr);
1452 SYSCALL_DEFINE(readahead)(int fd, loff_t offset, size_t count)
1460 if (file->f_mode & FMODE_READ) {
1461 struct address_space *mapping = file->f_mapping;
1462 pgoff_t start = offset >> PAGE_CACHE_SHIFT;
1463 pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1464 unsigned long len = end - start + 1;
1465 ret = do_readahead(mapping, file, start, len);
1471 #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
1472 asmlinkage long SyS_readahead(long fd, loff_t offset, long count)
1474 return SYSC_readahead((int) fd, offset, (size_t) count);
1476 SYSCALL_ALIAS(sys_readahead, SyS_readahead);
1481 * page_cache_read - adds requested page to the page cache if not already there
1482 * @file: file to read
1483 * @offset: page index
1485 * This adds the requested page to the page cache if it isn't already there,
1486 * and schedules an I/O to read in its contents from disk.
1488 static int page_cache_read(struct file *file, pgoff_t offset)
1490 struct address_space *mapping = file->f_mapping;
1495 page = page_cache_alloc_cold(mapping);
1499 ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1501 ret = mapping->a_ops->readpage(file, page);
1502 else if (ret == -EEXIST)
1503 ret = 0; /* losing race to add is OK */
1505 page_cache_release(page);
1507 } while (ret == AOP_TRUNCATED_PAGE);
1512 #define MMAP_LOTSAMISS (100)
1515 * Synchronous readahead happens when we don't even find
1516 * a page in the page cache at all.
1518 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
1519 struct file_ra_state *ra,
1523 unsigned long ra_pages;
1524 struct address_space *mapping = file->f_mapping;
1526 /* If we don't want any read-ahead, don't bother */
1527 if (VM_RandomReadHint(vma))
1530 if (VM_SequentialReadHint(vma) ||
1531 offset - 1 == (ra->prev_pos >> PAGE_CACHE_SHIFT)) {
1532 page_cache_sync_readahead(mapping, ra, file, offset,
1537 if (ra->mmap_miss < INT_MAX)
1541 * Do we miss much more than hit in this file? If so,
1542 * stop bothering with read-ahead. It will only hurt.
1544 if (ra->mmap_miss > MMAP_LOTSAMISS)
1550 ra_pages = max_sane_readahead(ra->ra_pages);
1552 ra->start = max_t(long, 0, offset - ra_pages/2);
1553 ra->size = ra_pages;
1555 ra_submit(ra, mapping, file);
1560 * Asynchronous readahead happens when we find the page and PG_readahead,
1561 * so we want to possibly extend the readahead further..
1563 static void do_async_mmap_readahead(struct vm_area_struct *vma,
1564 struct file_ra_state *ra,
1569 struct address_space *mapping = file->f_mapping;
1571 /* If we don't want any read-ahead, don't bother */
1572 if (VM_RandomReadHint(vma))
1574 if (ra->mmap_miss > 0)
1576 if (PageReadahead(page))
1577 page_cache_async_readahead(mapping, ra, file,
1578 page, offset, ra->ra_pages);
1582 * filemap_fault - read in file data for page fault handling
1583 * @vma: vma in which the fault was taken
1584 * @vmf: struct vm_fault containing details of the fault
1586 * filemap_fault() is invoked via the vma operations vector for a
1587 * mapped memory region to read in file data during a page fault.
1589 * The goto's are kind of ugly, but this streamlines the normal case of having
1590 * it in the page cache, and handles the special cases reasonably without
1591 * having a lot of duplicated code.
1593 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1596 struct file *file = vma->vm_file;
1597 struct address_space *mapping = file->f_mapping;
1598 struct file_ra_state *ra = &file->f_ra;
1599 struct inode *inode = mapping->host;
1600 pgoff_t offset = vmf->pgoff;
1605 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1607 return VM_FAULT_SIGBUS;
1610 * Do we have something in the page cache already?
1612 page = find_get_page(mapping, offset);
1615 * We found the page, so try async readahead before
1616 * waiting for the lock.
1618 do_async_mmap_readahead(vma, ra, file, page, offset);
1620 /* No page in the page cache at all */
1621 do_sync_mmap_readahead(vma, ra, file, offset);
1622 count_vm_event(PGMAJFAULT);
1623 ret = VM_FAULT_MAJOR;
1625 page = find_get_page(mapping, offset);
1627 goto no_cached_page;
1630 if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {
1631 page_cache_release(page);
1632 return ret | VM_FAULT_RETRY;
1635 /* Did it get truncated? */
1636 if (unlikely(page->mapping != mapping)) {
1641 VM_BUG_ON(page->index != offset);
1644 * We have a locked page in the page cache, now we need to check
1645 * that it's up-to-date. If not, it is going to be due to an error.
1647 if (unlikely(!PageUptodate(page)))
1648 goto page_not_uptodate;
1651 * Found the page and have a reference on it.
1652 * We must recheck i_size under page lock.
1654 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1655 if (unlikely(offset >= size)) {
1657 page_cache_release(page);
1658 return VM_FAULT_SIGBUS;
1661 ra->prev_pos = (loff_t)offset << PAGE_CACHE_SHIFT;
1663 return ret | VM_FAULT_LOCKED;
1667 * We're only likely to ever get here if MADV_RANDOM is in
1670 error = page_cache_read(file, offset);
1673 * The page we want has now been added to the page cache.
1674 * In the unlikely event that someone removed it in the
1675 * meantime, we'll just come back here and read it again.
1681 * An error return from page_cache_read can result if the
1682 * system is low on memory, or a problem occurs while trying
1685 if (error == -ENOMEM)
1686 return VM_FAULT_OOM;
1687 return VM_FAULT_SIGBUS;
1691 * Umm, take care of errors if the page isn't up-to-date.
1692 * Try to re-read it _once_. We do this synchronously,
1693 * because there really aren't any performance issues here
1694 * and we need to check for errors.
1696 ClearPageError(page);
1697 error = mapping->a_ops->readpage(file, page);
1699 wait_on_page_locked(page);
1700 if (!PageUptodate(page))
1703 page_cache_release(page);
1705 if (!error || error == AOP_TRUNCATED_PAGE)
1708 /* Things didn't work out. Return zero to tell the mm layer so. */
1709 shrink_readahead_size_eio(file, ra);
1710 return VM_FAULT_SIGBUS;
1712 EXPORT_SYMBOL(filemap_fault);
1714 const struct vm_operations_struct generic_file_vm_ops = {
1715 .fault = filemap_fault,
1718 /* This is used for a general mmap of a disk file */
1720 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1722 struct address_space *mapping = file->f_mapping;
1724 if (!mapping->a_ops->readpage)
1726 file_accessed(file);
1727 vma->vm_ops = &generic_file_vm_ops;
1728 vma->vm_flags |= VM_CAN_NONLINEAR;
1733 * This is for filesystems which do not implement ->writepage.
1735 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1737 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1739 return generic_file_mmap(file, vma);
1742 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1746 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1750 #endif /* CONFIG_MMU */
1752 EXPORT_SYMBOL(generic_file_mmap);
1753 EXPORT_SYMBOL(generic_file_readonly_mmap);
1755 static struct page *__read_cache_page(struct address_space *mapping,
1757 int (*filler)(void *,struct page*),
1764 page = find_get_page(mapping, index);
1766 page = __page_cache_alloc(gfp | __GFP_COLD);
1768 return ERR_PTR(-ENOMEM);
1769 err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
1770 if (unlikely(err)) {
1771 page_cache_release(page);
1774 /* Presumably ENOMEM for radix tree node */
1775 return ERR_PTR(err);
1777 err = filler(data, page);
1779 page_cache_release(page);
1780 page = ERR_PTR(err);
1786 static struct page *do_read_cache_page(struct address_space *mapping,
1788 int (*filler)(void *,struct page*),
1797 page = __read_cache_page(mapping, index, filler, data, gfp);
1800 if (PageUptodate(page))
1804 if (!page->mapping) {
1806 page_cache_release(page);
1809 if (PageUptodate(page)) {
1813 err = filler(data, page);
1815 page_cache_release(page);
1816 return ERR_PTR(err);
1819 mark_page_accessed(page);
1824 * read_cache_page_async - read into page cache, fill it if needed
1825 * @mapping: the page's address_space
1826 * @index: the page index
1827 * @filler: function to perform the read
1828 * @data: destination for read data
1830 * Same as read_cache_page, but don't wait for page to become unlocked
1831 * after submitting it to the filler.
1833 * Read into the page cache. If a page already exists, and PageUptodate() is
1834 * not set, try to fill the page but don't wait for it to become unlocked.
1836 * If the page does not get brought uptodate, return -EIO.
1838 struct page *read_cache_page_async(struct address_space *mapping,
1840 int (*filler)(void *,struct page*),
1843 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
1845 EXPORT_SYMBOL(read_cache_page_async);
1847 static struct page *wait_on_page_read(struct page *page)
1849 if (!IS_ERR(page)) {
1850 wait_on_page_locked(page);
1851 if (!PageUptodate(page)) {
1852 page_cache_release(page);
1853 page = ERR_PTR(-EIO);
1860 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
1861 * @mapping: the page's address_space
1862 * @index: the page index
1863 * @gfp: the page allocator flags to use if allocating
1865 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
1866 * any new page allocations done using the specified allocation flags. Note
1867 * that the Radix tree operations will still use GFP_KERNEL, so you can't
1868 * expect to do this atomically or anything like that - but you can pass in
1869 * other page requirements.
1871 * If the page does not get brought uptodate, return -EIO.
1873 struct page *read_cache_page_gfp(struct address_space *mapping,
1877 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
1879 return wait_on_page_read(do_read_cache_page(mapping, index, filler, NULL, gfp));
1881 EXPORT_SYMBOL(read_cache_page_gfp);
1884 * read_cache_page - read into page cache, fill it if needed
1885 * @mapping: the page's address_space
1886 * @index: the page index
1887 * @filler: function to perform the read
1888 * @data: destination for read data
1890 * Read into the page cache. If a page already exists, and PageUptodate() is
1891 * not set, try to fill the page then wait for it to become unlocked.
1893 * If the page does not get brought uptodate, return -EIO.
1895 struct page *read_cache_page(struct address_space *mapping,
1897 int (*filler)(void *,struct page*),
1900 return wait_on_page_read(read_cache_page_async(mapping, index, filler, data));
1902 EXPORT_SYMBOL(read_cache_page);
1905 * The logic we want is
1907 * if suid or (sgid and xgrp)
1910 int should_remove_suid(struct dentry *dentry)
1912 mode_t mode = dentry->d_inode->i_mode;
1915 /* suid always must be killed */
1916 if (unlikely(mode & S_ISUID))
1917 kill = ATTR_KILL_SUID;
1920 * sgid without any exec bits is just a mandatory locking mark; leave
1921 * it alone. If some exec bits are set, it's a real sgid; kill it.
1923 if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1924 kill |= ATTR_KILL_SGID;
1926 if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))
1931 EXPORT_SYMBOL(should_remove_suid);
1933 static int __remove_suid(struct dentry *dentry, int kill)
1935 struct iattr newattrs;
1937 newattrs.ia_valid = ATTR_FORCE | kill;
1938 return notify_change(dentry, &newattrs);
1941 int file_remove_suid(struct file *file)
1943 struct dentry *dentry = file->f_path.dentry;
1944 int killsuid = should_remove_suid(dentry);
1945 int killpriv = security_inode_need_killpriv(dentry);
1951 error = security_inode_killpriv(dentry);
1952 if (!error && killsuid)
1953 error = __remove_suid(dentry, killsuid);
1957 EXPORT_SYMBOL(file_remove_suid);
1959 static size_t __iovec_copy_from_user_inatomic(char *vaddr,
1960 const struct iovec *iov, size_t base, size_t bytes)
1962 size_t copied = 0, left = 0;
1965 char __user *buf = iov->iov_base + base;
1966 int copy = min(bytes, iov->iov_len - base);
1969 left = __copy_from_user_inatomic(vaddr, buf, copy);
1978 return copied - left;
1982 * Copy as much as we can into the page and return the number of bytes which
1983 * were successfully copied. If a fault is encountered then return the number of
1984 * bytes which were copied.
1986 size_t iov_iter_copy_from_user_atomic(struct page *page,
1987 struct iov_iter *i, unsigned long offset, size_t bytes)
1992 BUG_ON(!in_atomic());
1993 kaddr = kmap_atomic(page, KM_USER0);
1994 if (likely(i->nr_segs == 1)) {
1996 char __user *buf = i->iov->iov_base + i->iov_offset;
1997 left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
1998 copied = bytes - left;
2000 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
2001 i->iov, i->iov_offset, bytes);
2003 kunmap_atomic(kaddr, KM_USER0);
2007 EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
2010 * This has the same sideeffects and return value as
2011 * iov_iter_copy_from_user_atomic().
2012 * The difference is that it attempts to resolve faults.
2013 * Page must not be locked.
2015 size_t iov_iter_copy_from_user(struct page *page,
2016 struct iov_iter *i, unsigned long offset, size_t bytes)
2022 if (likely(i->nr_segs == 1)) {
2024 char __user *buf = i->iov->iov_base + i->iov_offset;
2025 left = __copy_from_user(kaddr + offset, buf, bytes);
2026 copied = bytes - left;
2028 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
2029 i->iov, i->iov_offset, bytes);
2034 EXPORT_SYMBOL(iov_iter_copy_from_user);
2036 void iov_iter_advance(struct iov_iter *i, size_t bytes)
2038 BUG_ON(i->count < bytes);
2040 if (likely(i->nr_segs == 1)) {
2041 i->iov_offset += bytes;
2044 const struct iovec *iov = i->iov;
2045 size_t base = i->iov_offset;
2048 * The !iov->iov_len check ensures we skip over unlikely
2049 * zero-length segments (without overruning the iovec).
2051 while (bytes || unlikely(i->count && !iov->iov_len)) {
2054 copy = min(bytes, iov->iov_len - base);
2055 BUG_ON(!i->count || i->count < copy);
2059 if (iov->iov_len == base) {
2065 i->iov_offset = base;
2068 EXPORT_SYMBOL(iov_iter_advance);
2071 * Fault in the first iovec of the given iov_iter, to a maximum length
2072 * of bytes. Returns 0 on success, or non-zero if the memory could not be
2073 * accessed (ie. because it is an invalid address).
2075 * writev-intensive code may want this to prefault several iovecs -- that
2076 * would be possible (callers must not rely on the fact that _only_ the
2077 * first iovec will be faulted with the current implementation).
2079 int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
2081 char __user *buf = i->iov->iov_base + i->iov_offset;
2082 bytes = min(bytes, i->iov->iov_len - i->iov_offset);
2083 return fault_in_pages_readable(buf, bytes);
2085 EXPORT_SYMBOL(iov_iter_fault_in_readable);
2088 * Return the count of just the current iov_iter segment.
2090 size_t iov_iter_single_seg_count(struct iov_iter *i)
2092 const struct iovec *iov = i->iov;
2093 if (i->nr_segs == 1)
2096 return min(i->count, iov->iov_len - i->iov_offset);
2098 EXPORT_SYMBOL(iov_iter_single_seg_count);
2101 * Performs necessary checks before doing a write
2103 * Can adjust writing position or amount of bytes to write.
2104 * Returns appropriate error code that caller should return or
2105 * zero in case that write should be allowed.
2107 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
2109 struct inode *inode = file->f_mapping->host;
2110 unsigned long limit = rlimit(RLIMIT_FSIZE);
2112 if (unlikely(*pos < 0))
2116 /* FIXME: this is for backwards compatibility with 2.4 */
2117 if (file->f_flags & O_APPEND)
2118 *pos = i_size_read(inode);
2120 if (limit != RLIM_INFINITY) {
2121 if (*pos >= limit) {
2122 send_sig(SIGXFSZ, current, 0);
2125 if (*count > limit - (typeof(limit))*pos) {
2126 *count = limit - (typeof(limit))*pos;
2134 if (unlikely(*pos + *count > MAX_NON_LFS &&
2135 !(file->f_flags & O_LARGEFILE))) {
2136 if (*pos >= MAX_NON_LFS) {
2139 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
2140 *count = MAX_NON_LFS - (unsigned long)*pos;
2145 * Are we about to exceed the fs block limit ?
2147 * If we have written data it becomes a short write. If we have
2148 * exceeded without writing data we send a signal and return EFBIG.
2149 * Linus frestrict idea will clean these up nicely..
2151 if (likely(!isblk)) {
2152 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
2153 if (*count || *pos > inode->i_sb->s_maxbytes) {
2156 /* zero-length writes at ->s_maxbytes are OK */
2159 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
2160 *count = inode->i_sb->s_maxbytes - *pos;
2164 if (bdev_read_only(I_BDEV(inode)))
2166 isize = i_size_read(inode);
2167 if (*pos >= isize) {
2168 if (*count || *pos > isize)
2172 if (*pos + *count > isize)
2173 *count = isize - *pos;
2180 EXPORT_SYMBOL(generic_write_checks);
2182 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2183 loff_t pos, unsigned len, unsigned flags,
2184 struct page **pagep, void **fsdata)
2186 const struct address_space_operations *aops = mapping->a_ops;
2188 return aops->write_begin(file, mapping, pos, len, flags,
2191 EXPORT_SYMBOL(pagecache_write_begin);
2193 int pagecache_write_end(struct file *file, struct address_space *mapping,
2194 loff_t pos, unsigned len, unsigned copied,
2195 struct page *page, void *fsdata)
2197 const struct address_space_operations *aops = mapping->a_ops;
2199 mark_page_accessed(page);
2200 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2202 EXPORT_SYMBOL(pagecache_write_end);
2205 generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
2206 unsigned long *nr_segs, loff_t pos, loff_t *ppos,
2207 size_t count, size_t ocount)
2209 struct file *file = iocb->ki_filp;
2210 struct address_space *mapping = file->f_mapping;
2211 struct inode *inode = mapping->host;
2216 if (count != ocount)
2217 *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
2219 write_len = iov_length(iov, *nr_segs);
2220 end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
2222 written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
2227 * After a write we want buffered reads to be sure to go to disk to get
2228 * the new data. We invalidate clean cached page from the region we're
2229 * about to write. We do this *before* the write so that we can return
2230 * without clobbering -EIOCBQUEUED from ->direct_IO().
2232 if (mapping->nrpages) {
2233 written = invalidate_inode_pages2_range(mapping,
2234 pos >> PAGE_CACHE_SHIFT, end);
2236 * If a page can not be invalidated, return 0 to fall back
2237 * to buffered write.
2240 if (written == -EBUSY)
2246 written = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);
2249 * Finally, try again to invalidate clean pages which might have been
2250 * cached by non-direct readahead, or faulted in by get_user_pages()
2251 * if the source of the write was an mmap'ed region of the file
2252 * we're writing. Either one is a pretty crazy thing to do,
2253 * so we don't support it 100%. If this invalidation
2254 * fails, tough, the write still worked...
2256 if (mapping->nrpages) {
2257 invalidate_inode_pages2_range(mapping,
2258 pos >> PAGE_CACHE_SHIFT, end);
2263 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2264 i_size_write(inode, pos);
2265 mark_inode_dirty(inode);
2272 EXPORT_SYMBOL(generic_file_direct_write);
2275 * Find or create a page at the given pagecache position. Return the locked
2276 * page. This function is specifically for buffered writes.
2278 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2279 pgoff_t index, unsigned flags)
2283 gfp_t gfp_notmask = 0;
2284 if (flags & AOP_FLAG_NOFS)
2285 gfp_notmask = __GFP_FS;
2287 page = find_lock_page(mapping, index);
2291 page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~gfp_notmask);
2294 status = add_to_page_cache_lru(page, mapping, index,
2295 GFP_KERNEL & ~gfp_notmask);
2296 if (unlikely(status)) {
2297 page_cache_release(page);
2298 if (status == -EEXIST)
2304 EXPORT_SYMBOL(grab_cache_page_write_begin);
2306 static ssize_t generic_perform_write(struct file *file,
2307 struct iov_iter *i, loff_t pos)
2309 struct address_space *mapping = file->f_mapping;
2310 const struct address_space_operations *a_ops = mapping->a_ops;
2312 ssize_t written = 0;
2313 unsigned int flags = 0;
2316 * Copies from kernel address space cannot fail (NFSD is a big user).
2318 if (segment_eq(get_fs(), KERNEL_DS))
2319 flags |= AOP_FLAG_UNINTERRUPTIBLE;
2323 unsigned long offset; /* Offset into pagecache page */
2324 unsigned long bytes; /* Bytes to write to page */
2325 size_t copied; /* Bytes copied from user */
2328 offset = (pos & (PAGE_CACHE_SIZE - 1));
2329 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2335 * Bring in the user page that we will copy from _first_.
2336 * Otherwise there's a nasty deadlock on copying from the
2337 * same page as we're writing to, without it being marked
2340 * Not only is this an optimisation, but it is also required
2341 * to check that the address is actually valid, when atomic
2342 * usercopies are used, below.
2344 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2349 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
2351 if (unlikely(status))
2354 if (mapping_writably_mapped(mapping))
2355 flush_dcache_page(page);
2357 pagefault_disable();
2358 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2360 flush_dcache_page(page);
2362 mark_page_accessed(page);
2363 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2365 if (unlikely(status < 0))
2371 iov_iter_advance(i, copied);
2372 if (unlikely(copied == 0)) {
2374 * If we were unable to copy any data at all, we must
2375 * fall back to a single segment length write.
2377 * If we didn't fallback here, we could livelock
2378 * because not all segments in the iov can be copied at
2379 * once without a pagefault.
2381 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2382 iov_iter_single_seg_count(i));
2388 balance_dirty_pages_ratelimited(mapping);
2390 } while (iov_iter_count(i));
2392 return written ? written : status;
2396 generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
2397 unsigned long nr_segs, loff_t pos, loff_t *ppos,
2398 size_t count, ssize_t written)
2400 struct file *file = iocb->ki_filp;
2404 iov_iter_init(&i, iov, nr_segs, count, written);
2405 status = generic_perform_write(file, &i, pos);
2407 if (likely(status >= 0)) {
2409 *ppos = pos + status;
2412 return written ? written : status;
2414 EXPORT_SYMBOL(generic_file_buffered_write);
2417 * __generic_file_aio_write - write data to a file
2418 * @iocb: IO state structure (file, offset, etc.)
2419 * @iov: vector with data to write
2420 * @nr_segs: number of segments in the vector
2421 * @ppos: position where to write
2423 * This function does all the work needed for actually writing data to a
2424 * file. It does all basic checks, removes SUID from the file, updates
2425 * modification times and calls proper subroutines depending on whether we
2426 * do direct IO or a standard buffered write.
2428 * It expects i_mutex to be grabbed unless we work on a block device or similar
2429 * object which does not need locking at all.
2431 * This function does *not* take care of syncing data in case of O_SYNC write.
2432 * A caller has to handle it. This is mainly due to the fact that we want to
2433 * avoid syncing under i_mutex.
2435 ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2436 unsigned long nr_segs, loff_t *ppos)
2438 struct file *file = iocb->ki_filp;
2439 struct address_space * mapping = file->f_mapping;
2440 size_t ocount; /* original count */
2441 size_t count; /* after file limit checks */
2442 struct inode *inode = mapping->host;
2448 err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
2455 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2457 /* We can write back this queue in page reclaim */
2458 current->backing_dev_info = mapping->backing_dev_info;
2461 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2468 err = file_remove_suid(file);
2472 file_update_time(file);
2474 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2475 if (unlikely(file->f_flags & O_DIRECT)) {
2477 ssize_t written_buffered;
2479 written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
2480 ppos, count, ocount);
2481 if (written < 0 || written == count)
2484 * direct-io write to a hole: fall through to buffered I/O
2485 * for completing the rest of the request.
2489 written_buffered = generic_file_buffered_write(iocb, iov,
2490 nr_segs, pos, ppos, count,
2493 * If generic_file_buffered_write() retuned a synchronous error
2494 * then we want to return the number of bytes which were
2495 * direct-written, or the error code if that was zero. Note
2496 * that this differs from normal direct-io semantics, which
2497 * will return -EFOO even if some bytes were written.
2499 if (written_buffered < 0) {
2500 err = written_buffered;
2505 * We need to ensure that the page cache pages are written to
2506 * disk and invalidated to preserve the expected O_DIRECT
2509 endbyte = pos + written_buffered - written - 1;
2510 err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
2512 written = written_buffered;
2513 invalidate_mapping_pages(mapping,
2514 pos >> PAGE_CACHE_SHIFT,
2515 endbyte >> PAGE_CACHE_SHIFT);
2518 * We don't know how much we wrote, so just return
2519 * the number of bytes which were direct-written
2523 written = generic_file_buffered_write(iocb, iov, nr_segs,
2524 pos, ppos, count, written);
2527 current->backing_dev_info = NULL;
2528 return written ? written : err;
2530 EXPORT_SYMBOL(__generic_file_aio_write);
2533 * generic_file_aio_write - write data to a file
2534 * @iocb: IO state structure
2535 * @iov: vector with data to write
2536 * @nr_segs: number of segments in the vector
2537 * @pos: position in file where to write
2539 * This is a wrapper around __generic_file_aio_write() to be used by most
2540 * filesystems. It takes care of syncing the file in case of O_SYNC file
2541 * and acquires i_mutex as needed.
2543 ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2544 unsigned long nr_segs, loff_t pos)
2546 struct file *file = iocb->ki_filp;
2547 struct inode *inode = file->f_mapping->host;
2548 struct blk_plug plug;
2551 BUG_ON(iocb->ki_pos != pos);
2553 mutex_lock(&inode->i_mutex);
2554 blk_start_plug(&plug);
2555 ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
2556 mutex_unlock(&inode->i_mutex);
2558 if (ret > 0 || ret == -EIOCBQUEUED) {
2561 err = generic_write_sync(file, pos, ret);
2562 if (err < 0 && ret > 0)
2565 blk_finish_plug(&plug);
2568 EXPORT_SYMBOL(generic_file_aio_write);
2571 * try_to_release_page() - release old fs-specific metadata on a page
2573 * @page: the page which the kernel is trying to free
2574 * @gfp_mask: memory allocation flags (and I/O mode)
2576 * The address_space is to try to release any data against the page
2577 * (presumably at page->private). If the release was successful, return `1'.
2578 * Otherwise return zero.
2580 * This may also be called if PG_fscache is set on a page, indicating that the
2581 * page is known to the local caching routines.
2583 * The @gfp_mask argument specifies whether I/O may be performed to release
2584 * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
2587 int try_to_release_page(struct page *page, gfp_t gfp_mask)
2589 struct address_space * const mapping = page->mapping;
2591 BUG_ON(!PageLocked(page));
2592 if (PageWriteback(page))
2595 if (mapping && mapping->a_ops->releasepage)
2596 return mapping->a_ops->releasepage(page, gfp_mask);
2597 return try_to_free_buffers(page);
2600 EXPORT_SYMBOL(try_to_release_page);