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/export.h>
13 #include <linux/compiler.h>
15 #include <linux/uaccess.h>
16 #include <linux/capability.h>
17 #include <linux/kernel_stat.h>
18 #include <linux/gfp.h>
20 #include <linux/swap.h>
21 #include <linux/mman.h>
22 #include <linux/pagemap.h>
23 #include <linux/file.h>
24 #include <linux/uio.h>
25 #include <linux/hash.h>
26 #include <linux/writeback.h>
27 #include <linux/backing-dev.h>
28 #include <linux/pagevec.h>
29 #include <linux/blkdev.h>
30 #include <linux/security.h>
31 #include <linux/cpuset.h>
32 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
33 #include <linux/hugetlb.h>
34 #include <linux/memcontrol.h>
35 #include <linux/cleancache.h>
36 #include <linux/rmap.h>
39 #define CREATE_TRACE_POINTS
40 #include <trace/events/filemap.h>
43 * FIXME: remove all knowledge of the buffer layer from the core VM
45 #include <linux/buffer_head.h> /* for try_to_free_buffers */
50 * Shared mappings implemented 30.11.1994. It's not fully working yet,
53 * Shared mappings now work. 15.8.1995 Bruno.
55 * finished 'unifying' the page and buffer cache and SMP-threaded the
56 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
58 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
64 * ->i_mmap_rwsem (truncate_pagecache)
65 * ->private_lock (__free_pte->__set_page_dirty_buffers)
66 * ->swap_lock (exclusive_swap_page, others)
67 * ->mapping->tree_lock
70 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
74 * ->page_table_lock or pte_lock (various, mainly in memory.c)
75 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
78 * ->lock_page (access_process_vm)
80 * ->i_mutex (generic_perform_write)
81 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
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 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
102 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
103 * ->memcg->move_lock (page_remove_rmap->mem_cgroup_begin_page_stat)
104 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
105 * ->inode->i_lock (zap_pte_range->set_page_dirty)
106 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
109 * ->tasklist_lock (memory_failure, collect_procs_ao)
112 static int page_cache_tree_insert(struct address_space *mapping,
113 struct page *page, void **shadowp)
115 struct radix_tree_node *node;
119 error = __radix_tree_create(&mapping->page_tree, page->index,
126 p = radix_tree_deref_slot_protected(slot, &mapping->tree_lock);
127 if (!radix_tree_exceptional_entry(p))
131 mapping->nrshadows--;
133 workingset_node_shadows_dec(node);
135 radix_tree_replace_slot(slot, page);
138 workingset_node_pages_inc(node);
140 * Don't track node that contains actual pages.
142 * Avoid acquiring the list_lru lock if already
143 * untracked. The list_empty() test is safe as
144 * node->private_list is protected by
145 * mapping->tree_lock.
147 if (!list_empty(&node->private_list)) {
148 local_lock(workingset_shadow_lock);
149 list_lru_del(&__workingset_shadow_nodes,
150 &node->private_list);
151 local_unlock(workingset_shadow_lock);
157 static void page_cache_tree_delete(struct address_space *mapping,
158 struct page *page, void *shadow)
160 struct radix_tree_node *node;
166 VM_BUG_ON(!PageLocked(page));
168 __radix_tree_lookup(&mapping->page_tree, page->index, &node, &slot);
172 * We need a node to properly account shadow
173 * entries. Don't plant any without. XXX
179 mapping->nrshadows++;
181 * Make sure the nrshadows update is committed before
182 * the nrpages update so that final truncate racing
183 * with reclaim does not see both counters 0 at the
184 * same time and miss a shadow entry.
191 /* Clear direct pointer tags in root node */
192 mapping->page_tree.gfp_mask &= __GFP_BITS_MASK;
193 radix_tree_replace_slot(slot, shadow);
197 /* Clear tree tags for the removed page */
199 offset = index & RADIX_TREE_MAP_MASK;
200 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
201 if (test_bit(offset, node->tags[tag]))
202 radix_tree_tag_clear(&mapping->page_tree, index, tag);
205 /* Delete page, swap shadow entry */
206 radix_tree_replace_slot(slot, shadow);
207 workingset_node_pages_dec(node);
209 workingset_node_shadows_inc(node);
211 if (__radix_tree_delete_node(&mapping->page_tree, node))
215 * Track node that only contains shadow entries.
217 * Avoid acquiring the list_lru lock if already tracked. The
218 * list_empty() test is safe as node->private_list is
219 * protected by mapping->tree_lock.
221 if (!workingset_node_pages(node) &&
222 list_empty(&node->private_list)) {
223 node->private_data = mapping;
224 local_lock(workingset_shadow_lock);
225 list_lru_add(&__workingset_shadow_nodes, &node->private_list);
226 local_unlock(workingset_shadow_lock);
231 * Delete a page from the page cache and free it. Caller has to make
232 * sure the page is locked and that nobody else uses it - or that usage
233 * is safe. The caller must hold the mapping's tree_lock and
234 * mem_cgroup_begin_page_stat().
236 void __delete_from_page_cache(struct page *page, void *shadow,
237 struct mem_cgroup *memcg)
239 struct address_space *mapping = page->mapping;
241 trace_mm_filemap_delete_from_page_cache(page);
243 * if we're uptodate, flush out into the cleancache, otherwise
244 * invalidate any existing cleancache entries. We can't leave
245 * stale data around in the cleancache once our page is gone
247 if (PageUptodate(page) && PageMappedToDisk(page))
248 cleancache_put_page(page);
250 cleancache_invalidate_page(mapping, page);
252 page_cache_tree_delete(mapping, page, shadow);
254 page->mapping = NULL;
255 /* Leave page->index set: truncation lookup relies upon it */
257 /* hugetlb pages do not participate in page cache accounting. */
259 __dec_zone_page_state(page, NR_FILE_PAGES);
260 if (PageSwapBacked(page))
261 __dec_zone_page_state(page, NR_SHMEM);
262 BUG_ON(page_mapped(page));
265 * At this point page must be either written or cleaned by truncate.
266 * Dirty page here signals a bug and loss of unwritten data.
268 * This fixes dirty accounting after removing the page entirely but
269 * leaves PageDirty set: it has no effect for truncated page and
270 * anyway will be cleared before returning page into buddy allocator.
272 if (WARN_ON_ONCE(PageDirty(page)))
273 account_page_cleaned(page, mapping, memcg,
274 inode_to_wb(mapping->host));
278 * delete_from_page_cache - delete page from page cache
279 * @page: the page which the kernel is trying to remove from page cache
281 * This must be called only on pages that have been verified to be in the page
282 * cache and locked. It will never put the page into the free list, the caller
283 * has a reference on the page.
285 void delete_from_page_cache(struct page *page)
287 struct address_space *mapping = page->mapping;
288 struct mem_cgroup *memcg;
291 void (*freepage)(struct page *);
293 BUG_ON(!PageLocked(page));
295 freepage = mapping->a_ops->freepage;
297 memcg = mem_cgroup_begin_page_stat(page);
298 spin_lock_irqsave(&mapping->tree_lock, flags);
299 __delete_from_page_cache(page, NULL, memcg);
300 spin_unlock_irqrestore(&mapping->tree_lock, flags);
301 mem_cgroup_end_page_stat(memcg);
305 page_cache_release(page);
307 EXPORT_SYMBOL(delete_from_page_cache);
309 static int filemap_check_errors(struct address_space *mapping)
312 /* Check for outstanding write errors */
313 if (test_bit(AS_ENOSPC, &mapping->flags) &&
314 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
316 if (test_bit(AS_EIO, &mapping->flags) &&
317 test_and_clear_bit(AS_EIO, &mapping->flags))
323 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
324 * @mapping: address space structure to write
325 * @start: offset in bytes where the range starts
326 * @end: offset in bytes where the range ends (inclusive)
327 * @sync_mode: enable synchronous operation
329 * Start writeback against all of a mapping's dirty pages that lie
330 * within the byte offsets <start, end> inclusive.
332 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
333 * opposed to a regular memory cleansing writeback. The difference between
334 * these two operations is that if a dirty page/buffer is encountered, it must
335 * be waited upon, and not just skipped over.
337 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
338 loff_t end, int sync_mode)
341 struct writeback_control wbc = {
342 .sync_mode = sync_mode,
343 .nr_to_write = LONG_MAX,
344 .range_start = start,
348 if (!mapping_cap_writeback_dirty(mapping))
351 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
352 ret = do_writepages(mapping, &wbc);
353 wbc_detach_inode(&wbc);
357 static inline int __filemap_fdatawrite(struct address_space *mapping,
360 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
363 int filemap_fdatawrite(struct address_space *mapping)
365 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
367 EXPORT_SYMBOL(filemap_fdatawrite);
369 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
372 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
374 EXPORT_SYMBOL(filemap_fdatawrite_range);
377 * filemap_flush - mostly a non-blocking flush
378 * @mapping: target address_space
380 * This is a mostly non-blocking flush. Not suitable for data-integrity
381 * purposes - I/O may not be started against all dirty pages.
383 int filemap_flush(struct address_space *mapping)
385 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
387 EXPORT_SYMBOL(filemap_flush);
389 static int __filemap_fdatawait_range(struct address_space *mapping,
390 loff_t start_byte, loff_t end_byte)
392 pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;
393 pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;
398 if (end_byte < start_byte)
401 pagevec_init(&pvec, 0);
402 while ((index <= end) &&
403 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
404 PAGECACHE_TAG_WRITEBACK,
405 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
408 for (i = 0; i < nr_pages; i++) {
409 struct page *page = pvec.pages[i];
411 /* until radix tree lookup accepts end_index */
412 if (page->index > end)
415 wait_on_page_writeback(page);
416 if (TestClearPageError(page))
419 pagevec_release(&pvec);
427 * filemap_fdatawait_range - wait for writeback to complete
428 * @mapping: address space structure to wait for
429 * @start_byte: offset in bytes where the range starts
430 * @end_byte: offset in bytes where the range ends (inclusive)
432 * Walk the list of under-writeback pages of the given address space
433 * in the given range and wait for all of them. Check error status of
434 * the address space and return it.
436 * Since the error status of the address space is cleared by this function,
437 * callers are responsible for checking the return value and handling and/or
438 * reporting the error.
440 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
445 ret = __filemap_fdatawait_range(mapping, start_byte, end_byte);
446 ret2 = filemap_check_errors(mapping);
452 EXPORT_SYMBOL(filemap_fdatawait_range);
455 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
456 * @mapping: address space structure to wait for
458 * Walk the list of under-writeback pages of the given address space
459 * and wait for all of them. Unlike filemap_fdatawait(), this function
460 * does not clear error status of the address space.
462 * Use this function if callers don't handle errors themselves. Expected
463 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
466 void filemap_fdatawait_keep_errors(struct address_space *mapping)
468 loff_t i_size = i_size_read(mapping->host);
473 __filemap_fdatawait_range(mapping, 0, i_size - 1);
477 * filemap_fdatawait - wait for all under-writeback pages to complete
478 * @mapping: address space structure to wait for
480 * Walk the list of under-writeback pages of the given address space
481 * and wait for all of them. Check error status of the address space
484 * Since the error status of the address space is cleared by this function,
485 * callers are responsible for checking the return value and handling and/or
486 * reporting the error.
488 int filemap_fdatawait(struct address_space *mapping)
490 loff_t i_size = i_size_read(mapping->host);
495 return filemap_fdatawait_range(mapping, 0, i_size - 1);
497 EXPORT_SYMBOL(filemap_fdatawait);
499 int filemap_write_and_wait(struct address_space *mapping)
503 if (mapping->nrpages) {
504 err = filemap_fdatawrite(mapping);
506 * Even if the above returned error, the pages may be
507 * written partially (e.g. -ENOSPC), so we wait for it.
508 * But the -EIO is special case, it may indicate the worst
509 * thing (e.g. bug) happened, so we avoid waiting for it.
512 int err2 = filemap_fdatawait(mapping);
517 err = filemap_check_errors(mapping);
521 EXPORT_SYMBOL(filemap_write_and_wait);
524 * filemap_write_and_wait_range - write out & wait on a file range
525 * @mapping: the address_space for the pages
526 * @lstart: offset in bytes where the range starts
527 * @lend: offset in bytes where the range ends (inclusive)
529 * Write out and wait upon file offsets lstart->lend, inclusive.
531 * Note that `lend' is inclusive (describes the last byte to be written) so
532 * that this function can be used to write to the very end-of-file (end = -1).
534 int filemap_write_and_wait_range(struct address_space *mapping,
535 loff_t lstart, loff_t lend)
539 if (mapping->nrpages) {
540 err = __filemap_fdatawrite_range(mapping, lstart, lend,
542 /* See comment of filemap_write_and_wait() */
544 int err2 = filemap_fdatawait_range(mapping,
550 err = filemap_check_errors(mapping);
554 EXPORT_SYMBOL(filemap_write_and_wait_range);
557 * replace_page_cache_page - replace a pagecache page with a new one
558 * @old: page to be replaced
559 * @new: page to replace with
560 * @gfp_mask: allocation mode
562 * This function replaces a page in the pagecache with a new one. On
563 * success it acquires the pagecache reference for the new page and
564 * drops it for the old page. Both the old and new pages must be
565 * locked. This function does not add the new page to the LRU, the
566 * caller must do that.
568 * The remove + add is atomic. The only way this function can fail is
569 * memory allocation failure.
571 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
575 VM_BUG_ON_PAGE(!PageLocked(old), old);
576 VM_BUG_ON_PAGE(!PageLocked(new), new);
577 VM_BUG_ON_PAGE(new->mapping, new);
579 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
581 struct address_space *mapping = old->mapping;
582 void (*freepage)(struct page *);
583 struct mem_cgroup *memcg;
586 pgoff_t offset = old->index;
587 freepage = mapping->a_ops->freepage;
590 new->mapping = mapping;
593 memcg = mem_cgroup_begin_page_stat(old);
594 spin_lock_irqsave(&mapping->tree_lock, flags);
595 __delete_from_page_cache(old, NULL, memcg);
596 error = page_cache_tree_insert(mapping, new, NULL);
600 * hugetlb pages do not participate in page cache accounting.
603 __inc_zone_page_state(new, NR_FILE_PAGES);
604 if (PageSwapBacked(new))
605 __inc_zone_page_state(new, NR_SHMEM);
606 spin_unlock_irqrestore(&mapping->tree_lock, flags);
607 mem_cgroup_end_page_stat(memcg);
608 mem_cgroup_replace_page(old, new);
609 radix_tree_preload_end();
612 page_cache_release(old);
617 EXPORT_SYMBOL_GPL(replace_page_cache_page);
619 static int __add_to_page_cache_locked(struct page *page,
620 struct address_space *mapping,
621 pgoff_t offset, gfp_t gfp_mask,
624 int huge = PageHuge(page);
625 struct mem_cgroup *memcg;
628 VM_BUG_ON_PAGE(!PageLocked(page), page);
629 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
632 error = mem_cgroup_try_charge(page, current->mm,
638 error = radix_tree_maybe_preload(gfp_mask & ~__GFP_HIGHMEM);
641 mem_cgroup_cancel_charge(page, memcg);
645 page_cache_get(page);
646 page->mapping = mapping;
647 page->index = offset;
649 spin_lock_irq(&mapping->tree_lock);
650 error = page_cache_tree_insert(mapping, page, shadowp);
651 radix_tree_preload_end();
655 /* hugetlb pages do not participate in page cache accounting. */
657 __inc_zone_page_state(page, NR_FILE_PAGES);
658 spin_unlock_irq(&mapping->tree_lock);
660 mem_cgroup_commit_charge(page, memcg, false);
661 trace_mm_filemap_add_to_page_cache(page);
664 page->mapping = NULL;
665 /* Leave page->index set: truncation relies upon it */
666 spin_unlock_irq(&mapping->tree_lock);
668 mem_cgroup_cancel_charge(page, memcg);
669 page_cache_release(page);
674 * add_to_page_cache_locked - add a locked page to the pagecache
676 * @mapping: the page's address_space
677 * @offset: page index
678 * @gfp_mask: page allocation mode
680 * This function is used to add a page to the pagecache. It must be locked.
681 * This function does not add the page to the LRU. The caller must do that.
683 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
684 pgoff_t offset, gfp_t gfp_mask)
686 return __add_to_page_cache_locked(page, mapping, offset,
689 EXPORT_SYMBOL(add_to_page_cache_locked);
691 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
692 pgoff_t offset, gfp_t gfp_mask)
697 __set_page_locked(page);
698 ret = __add_to_page_cache_locked(page, mapping, offset,
701 __clear_page_locked(page);
704 * The page might have been evicted from cache only
705 * recently, in which case it should be activated like
706 * any other repeatedly accessed page.
708 if (shadow && workingset_refault(shadow)) {
710 workingset_activation(page);
712 ClearPageActive(page);
717 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
720 struct page *__page_cache_alloc(gfp_t gfp)
725 if (cpuset_do_page_mem_spread()) {
726 unsigned int cpuset_mems_cookie;
728 cpuset_mems_cookie = read_mems_allowed_begin();
729 n = cpuset_mem_spread_node();
730 page = __alloc_pages_node(n, gfp, 0);
731 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
735 return alloc_pages(gfp, 0);
737 EXPORT_SYMBOL(__page_cache_alloc);
741 * In order to wait for pages to become available there must be
742 * waitqueues associated with pages. By using a hash table of
743 * waitqueues where the bucket discipline is to maintain all
744 * waiters on the same queue and wake all when any of the pages
745 * become available, and for the woken contexts to check to be
746 * sure the appropriate page became available, this saves space
747 * at a cost of "thundering herd" phenomena during rare hash
750 wait_queue_head_t *page_waitqueue(struct page *page)
752 const struct zone *zone = page_zone(page);
754 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
756 EXPORT_SYMBOL(page_waitqueue);
758 void wait_on_page_bit(struct page *page, int bit_nr)
760 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
762 if (test_bit(bit_nr, &page->flags))
763 __wait_on_bit(page_waitqueue(page), &wait, bit_wait_io,
764 TASK_UNINTERRUPTIBLE);
766 EXPORT_SYMBOL(wait_on_page_bit);
768 int wait_on_page_bit_killable(struct page *page, int bit_nr)
770 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
772 if (!test_bit(bit_nr, &page->flags))
775 return __wait_on_bit(page_waitqueue(page), &wait,
776 bit_wait_io, TASK_KILLABLE);
779 int wait_on_page_bit_killable_timeout(struct page *page,
780 int bit_nr, unsigned long timeout)
782 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
784 wait.key.timeout = jiffies + timeout;
785 if (!test_bit(bit_nr, &page->flags))
787 return __wait_on_bit(page_waitqueue(page), &wait,
788 bit_wait_io_timeout, TASK_KILLABLE);
790 EXPORT_SYMBOL_GPL(wait_on_page_bit_killable_timeout);
793 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
794 * @page: Page defining the wait queue of interest
795 * @waiter: Waiter to add to the queue
797 * Add an arbitrary @waiter to the wait queue for the nominated @page.
799 void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
801 wait_queue_head_t *q = page_waitqueue(page);
804 spin_lock_irqsave(&q->lock, flags);
805 __add_wait_queue(q, waiter);
806 spin_unlock_irqrestore(&q->lock, flags);
808 EXPORT_SYMBOL_GPL(add_page_wait_queue);
811 * unlock_page - unlock a locked page
814 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
815 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
816 * mechanism between PageLocked pages and PageWriteback pages is shared.
817 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
819 * The mb is necessary to enforce ordering between the clear_bit and the read
820 * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
822 void unlock_page(struct page *page)
824 VM_BUG_ON_PAGE(!PageLocked(page), page);
825 clear_bit_unlock(PG_locked, &page->flags);
826 smp_mb__after_atomic();
827 wake_up_page(page, PG_locked);
829 EXPORT_SYMBOL(unlock_page);
832 * end_page_writeback - end writeback against a page
835 void end_page_writeback(struct page *page)
838 * TestClearPageReclaim could be used here but it is an atomic
839 * operation and overkill in this particular case. Failing to
840 * shuffle a page marked for immediate reclaim is too mild to
841 * justify taking an atomic operation penalty at the end of
842 * ever page writeback.
844 if (PageReclaim(page)) {
845 ClearPageReclaim(page);
846 rotate_reclaimable_page(page);
849 if (!test_clear_page_writeback(page))
852 smp_mb__after_atomic();
853 wake_up_page(page, PG_writeback);
855 EXPORT_SYMBOL(end_page_writeback);
858 * After completing I/O on a page, call this routine to update the page
859 * flags appropriately
861 void page_endio(struct page *page, int rw, int err)
865 SetPageUptodate(page);
867 ClearPageUptodate(page);
871 } else { /* rw == WRITE */
875 mapping_set_error(page->mapping, err);
877 end_page_writeback(page);
880 EXPORT_SYMBOL_GPL(page_endio);
883 * __lock_page - get a lock on the page, assuming we need to sleep to get it
884 * @page: the page to lock
886 void __lock_page(struct page *page)
888 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
890 __wait_on_bit_lock(page_waitqueue(page), &wait, bit_wait_io,
891 TASK_UNINTERRUPTIBLE);
893 EXPORT_SYMBOL(__lock_page);
895 int __lock_page_killable(struct page *page)
897 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
899 return __wait_on_bit_lock(page_waitqueue(page), &wait,
900 bit_wait_io, TASK_KILLABLE);
902 EXPORT_SYMBOL_GPL(__lock_page_killable);
906 * 1 - page is locked; mmap_sem is still held.
907 * 0 - page is not locked.
908 * mmap_sem has been released (up_read()), unless flags had both
909 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
910 * which case mmap_sem is still held.
912 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
913 * with the page locked and the mmap_sem unperturbed.
915 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
918 if (flags & FAULT_FLAG_ALLOW_RETRY) {
920 * CAUTION! In this case, mmap_sem is not released
921 * even though return 0.
923 if (flags & FAULT_FLAG_RETRY_NOWAIT)
926 up_read(&mm->mmap_sem);
927 if (flags & FAULT_FLAG_KILLABLE)
928 wait_on_page_locked_killable(page);
930 wait_on_page_locked(page);
933 if (flags & FAULT_FLAG_KILLABLE) {
936 ret = __lock_page_killable(page);
938 up_read(&mm->mmap_sem);
948 * page_cache_next_hole - find the next hole (not-present entry)
951 * @max_scan: maximum range to search
953 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
954 * lowest indexed hole.
956 * Returns: the index of the hole if found, otherwise returns an index
957 * outside of the set specified (in which case 'return - index >=
958 * max_scan' will be true). In rare cases of index wrap-around, 0 will
961 * page_cache_next_hole may be called under rcu_read_lock. However,
962 * like radix_tree_gang_lookup, this will not atomically search a
963 * snapshot of the tree at a single point in time. For example, if a
964 * hole is created at index 5, then subsequently a hole is created at
965 * index 10, page_cache_next_hole covering both indexes may return 10
966 * if called under rcu_read_lock.
968 pgoff_t page_cache_next_hole(struct address_space *mapping,
969 pgoff_t index, unsigned long max_scan)
973 for (i = 0; i < max_scan; i++) {
976 page = radix_tree_lookup(&mapping->page_tree, index);
977 if (!page || radix_tree_exceptional_entry(page))
986 EXPORT_SYMBOL(page_cache_next_hole);
989 * page_cache_prev_hole - find the prev hole (not-present entry)
992 * @max_scan: maximum range to search
994 * Search backwards in the range [max(index-max_scan+1, 0), index] for
997 * Returns: the index of the hole if found, otherwise returns an index
998 * outside of the set specified (in which case 'index - return >=
999 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
1002 * page_cache_prev_hole may be called under rcu_read_lock. However,
1003 * like radix_tree_gang_lookup, this will not atomically search a
1004 * snapshot of the tree at a single point in time. For example, if a
1005 * hole is created at index 10, then subsequently a hole is created at
1006 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1007 * called under rcu_read_lock.
1009 pgoff_t page_cache_prev_hole(struct address_space *mapping,
1010 pgoff_t index, unsigned long max_scan)
1014 for (i = 0; i < max_scan; i++) {
1017 page = radix_tree_lookup(&mapping->page_tree, index);
1018 if (!page || radix_tree_exceptional_entry(page))
1021 if (index == ULONG_MAX)
1027 EXPORT_SYMBOL(page_cache_prev_hole);
1030 * find_get_entry - find and get a page cache entry
1031 * @mapping: the address_space to search
1032 * @offset: the page cache index
1034 * Looks up the page cache slot at @mapping & @offset. If there is a
1035 * page cache page, it is returned with an increased refcount.
1037 * If the slot holds a shadow entry of a previously evicted page, or a
1038 * swap entry from shmem/tmpfs, it is returned.
1040 * Otherwise, %NULL is returned.
1042 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1050 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
1052 page = radix_tree_deref_slot(pagep);
1053 if (unlikely(!page))
1055 if (radix_tree_exception(page)) {
1056 if (radix_tree_deref_retry(page))
1059 * A shadow entry of a recently evicted page,
1060 * or a swap entry from shmem/tmpfs. Return
1061 * it without attempting to raise page count.
1065 if (!page_cache_get_speculative(page))
1069 * Has the page moved?
1070 * This is part of the lockless pagecache protocol. See
1071 * include/linux/pagemap.h for details.
1073 if (unlikely(page != *pagep)) {
1074 page_cache_release(page);
1083 EXPORT_SYMBOL(find_get_entry);
1086 * find_lock_entry - locate, pin and lock a page cache entry
1087 * @mapping: the address_space to search
1088 * @offset: the page cache index
1090 * Looks up the page cache slot at @mapping & @offset. If there is a
1091 * page cache page, it is returned locked and with an increased
1094 * If the slot holds a shadow entry of a previously evicted page, or a
1095 * swap entry from shmem/tmpfs, it is returned.
1097 * Otherwise, %NULL is returned.
1099 * find_lock_entry() may sleep.
1101 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1106 page = find_get_entry(mapping, offset);
1107 if (page && !radix_tree_exception(page)) {
1109 /* Has the page been truncated? */
1110 if (unlikely(page->mapping != mapping)) {
1112 page_cache_release(page);
1115 VM_BUG_ON_PAGE(page->index != offset, page);
1119 EXPORT_SYMBOL(find_lock_entry);
1122 * pagecache_get_page - find and get a page reference
1123 * @mapping: the address_space to search
1124 * @offset: the page index
1125 * @fgp_flags: PCG flags
1126 * @gfp_mask: gfp mask to use for the page cache data page allocation
1128 * Looks up the page cache slot at @mapping & @offset.
1130 * PCG flags modify how the page is returned.
1132 * FGP_ACCESSED: the page will be marked accessed
1133 * FGP_LOCK: Page is return locked
1134 * FGP_CREAT: If page is not present then a new page is allocated using
1135 * @gfp_mask and added to the page cache and the VM's LRU
1136 * list. The page is returned locked and with an increased
1137 * refcount. Otherwise, %NULL is returned.
1139 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1140 * if the GFP flags specified for FGP_CREAT are atomic.
1142 * If there is a page cache page, it is returned with an increased refcount.
1144 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1145 int fgp_flags, gfp_t gfp_mask)
1150 page = find_get_entry(mapping, offset);
1151 if (radix_tree_exceptional_entry(page))
1156 if (fgp_flags & FGP_LOCK) {
1157 if (fgp_flags & FGP_NOWAIT) {
1158 if (!trylock_page(page)) {
1159 page_cache_release(page);
1166 /* Has the page been truncated? */
1167 if (unlikely(page->mapping != mapping)) {
1169 page_cache_release(page);
1172 VM_BUG_ON_PAGE(page->index != offset, page);
1175 if (page && (fgp_flags & FGP_ACCESSED))
1176 mark_page_accessed(page);
1179 if (!page && (fgp_flags & FGP_CREAT)) {
1181 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1182 gfp_mask |= __GFP_WRITE;
1183 if (fgp_flags & FGP_NOFS)
1184 gfp_mask &= ~__GFP_FS;
1186 page = __page_cache_alloc(gfp_mask);
1190 if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
1191 fgp_flags |= FGP_LOCK;
1193 /* Init accessed so avoid atomic mark_page_accessed later */
1194 if (fgp_flags & FGP_ACCESSED)
1195 __SetPageReferenced(page);
1197 err = add_to_page_cache_lru(page, mapping, offset,
1198 gfp_mask & GFP_RECLAIM_MASK);
1199 if (unlikely(err)) {
1200 page_cache_release(page);
1209 EXPORT_SYMBOL(pagecache_get_page);
1212 * find_get_entries - gang pagecache lookup
1213 * @mapping: The address_space to search
1214 * @start: The starting page cache index
1215 * @nr_entries: The maximum number of entries
1216 * @entries: Where the resulting entries are placed
1217 * @indices: The cache indices corresponding to the entries in @entries
1219 * find_get_entries() will search for and return a group of up to
1220 * @nr_entries entries in the mapping. The entries are placed at
1221 * @entries. find_get_entries() takes a reference against any actual
1224 * The search returns a group of mapping-contiguous page cache entries
1225 * with ascending indexes. There may be holes in the indices due to
1226 * not-present pages.
1228 * Any shadow entries of evicted pages, or swap entries from
1229 * shmem/tmpfs, are included in the returned array.
1231 * find_get_entries() returns the number of pages and shadow entries
1234 unsigned find_get_entries(struct address_space *mapping,
1235 pgoff_t start, unsigned int nr_entries,
1236 struct page **entries, pgoff_t *indices)
1239 unsigned int ret = 0;
1240 struct radix_tree_iter iter;
1247 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1250 page = radix_tree_deref_slot(slot);
1251 if (unlikely(!page))
1253 if (radix_tree_exception(page)) {
1254 if (radix_tree_deref_retry(page))
1257 * A shadow entry of a recently evicted page,
1258 * or a swap entry from shmem/tmpfs. Return
1259 * it without attempting to raise page count.
1263 if (!page_cache_get_speculative(page))
1266 /* Has the page moved? */
1267 if (unlikely(page != *slot)) {
1268 page_cache_release(page);
1272 indices[ret] = iter.index;
1273 entries[ret] = page;
1274 if (++ret == nr_entries)
1282 * find_get_pages - gang pagecache lookup
1283 * @mapping: The address_space to search
1284 * @start: The starting page index
1285 * @nr_pages: The maximum number of pages
1286 * @pages: Where the resulting pages are placed
1288 * find_get_pages() will search for and return a group of up to
1289 * @nr_pages pages in the mapping. The pages are placed at @pages.
1290 * find_get_pages() takes a reference against the returned pages.
1292 * The search returns a group of mapping-contiguous pages with ascending
1293 * indexes. There may be holes in the indices due to not-present pages.
1295 * find_get_pages() returns the number of pages which were found.
1297 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
1298 unsigned int nr_pages, struct page **pages)
1300 struct radix_tree_iter iter;
1304 if (unlikely(!nr_pages))
1309 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1312 page = radix_tree_deref_slot(slot);
1313 if (unlikely(!page))
1316 if (radix_tree_exception(page)) {
1317 if (radix_tree_deref_retry(page)) {
1319 * Transient condition which can only trigger
1320 * when entry at index 0 moves out of or back
1321 * to root: none yet gotten, safe to restart.
1323 WARN_ON(iter.index);
1327 * A shadow entry of a recently evicted page,
1328 * or a swap entry from shmem/tmpfs. Skip
1334 if (!page_cache_get_speculative(page))
1337 /* Has the page moved? */
1338 if (unlikely(page != *slot)) {
1339 page_cache_release(page);
1344 if (++ret == nr_pages)
1353 * find_get_pages_contig - gang contiguous pagecache lookup
1354 * @mapping: The address_space to search
1355 * @index: The starting page index
1356 * @nr_pages: The maximum number of pages
1357 * @pages: Where the resulting pages are placed
1359 * find_get_pages_contig() works exactly like find_get_pages(), except
1360 * that the returned number of pages are guaranteed to be contiguous.
1362 * find_get_pages_contig() returns the number of pages which were found.
1364 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1365 unsigned int nr_pages, struct page **pages)
1367 struct radix_tree_iter iter;
1369 unsigned int ret = 0;
1371 if (unlikely(!nr_pages))
1376 radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
1379 page = radix_tree_deref_slot(slot);
1380 /* The hole, there no reason to continue */
1381 if (unlikely(!page))
1384 if (radix_tree_exception(page)) {
1385 if (radix_tree_deref_retry(page)) {
1387 * Transient condition which can only trigger
1388 * when entry at index 0 moves out of or back
1389 * to root: none yet gotten, safe to restart.
1394 * A shadow entry of a recently evicted page,
1395 * or a swap entry from shmem/tmpfs. Stop
1396 * looking for contiguous pages.
1401 if (!page_cache_get_speculative(page))
1404 /* Has the page moved? */
1405 if (unlikely(page != *slot)) {
1406 page_cache_release(page);
1411 * must check mapping and index after taking the ref.
1412 * otherwise we can get both false positives and false
1413 * negatives, which is just confusing to the caller.
1415 if (page->mapping == NULL || page->index != iter.index) {
1416 page_cache_release(page);
1421 if (++ret == nr_pages)
1427 EXPORT_SYMBOL(find_get_pages_contig);
1430 * find_get_pages_tag - find and return pages that match @tag
1431 * @mapping: the address_space to search
1432 * @index: the starting page index
1433 * @tag: the tag index
1434 * @nr_pages: the maximum number of pages
1435 * @pages: where the resulting pages are placed
1437 * Like find_get_pages, except we only return pages which are tagged with
1438 * @tag. We update @index to index the next page for the traversal.
1440 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
1441 int tag, unsigned int nr_pages, struct page **pages)
1443 struct radix_tree_iter iter;
1447 if (unlikely(!nr_pages))
1452 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1453 &iter, *index, tag) {
1456 page = radix_tree_deref_slot(slot);
1457 if (unlikely(!page))
1460 if (radix_tree_exception(page)) {
1461 if (radix_tree_deref_retry(page)) {
1463 * Transient condition which can only trigger
1464 * when entry at index 0 moves out of or back
1465 * to root: none yet gotten, safe to restart.
1470 * A shadow entry of a recently evicted page.
1472 * Those entries should never be tagged, but
1473 * this tree walk is lockless and the tags are
1474 * looked up in bulk, one radix tree node at a
1475 * time, so there is a sizable window for page
1476 * reclaim to evict a page we saw tagged.
1483 if (!page_cache_get_speculative(page))
1486 /* Has the page moved? */
1487 if (unlikely(page != *slot)) {
1488 page_cache_release(page);
1493 if (++ret == nr_pages)
1500 *index = pages[ret - 1]->index + 1;
1504 EXPORT_SYMBOL(find_get_pages_tag);
1507 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1508 * a _large_ part of the i/o request. Imagine the worst scenario:
1510 * ---R__________________________________________B__________
1511 * ^ reading here ^ bad block(assume 4k)
1513 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1514 * => failing the whole request => read(R) => read(R+1) =>
1515 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1516 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1517 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1519 * It is going insane. Fix it by quickly scaling down the readahead size.
1521 static void shrink_readahead_size_eio(struct file *filp,
1522 struct file_ra_state *ra)
1528 * do_generic_file_read - generic file read routine
1529 * @filp: the file to read
1530 * @ppos: current file position
1531 * @iter: data destination
1532 * @written: already copied
1534 * This is a generic file read routine, and uses the
1535 * mapping->a_ops->readpage() function for the actual low-level stuff.
1537 * This is really ugly. But the goto's actually try to clarify some
1538 * of the logic when it comes to error handling etc.
1540 static ssize_t do_generic_file_read(struct file *filp, loff_t *ppos,
1541 struct iov_iter *iter, ssize_t written)
1543 struct address_space *mapping = filp->f_mapping;
1544 struct inode *inode = mapping->host;
1545 struct file_ra_state *ra = &filp->f_ra;
1549 unsigned long offset; /* offset into pagecache page */
1550 unsigned int prev_offset;
1553 index = *ppos >> PAGE_CACHE_SHIFT;
1554 prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
1555 prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
1556 last_index = (*ppos + iter->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
1557 offset = *ppos & ~PAGE_CACHE_MASK;
1563 unsigned long nr, ret;
1567 if (fatal_signal_pending(current)) {
1572 page = find_get_page(mapping, index);
1574 page_cache_sync_readahead(mapping,
1576 index, last_index - index);
1577 page = find_get_page(mapping, index);
1578 if (unlikely(page == NULL))
1579 goto no_cached_page;
1581 if (PageReadahead(page)) {
1582 page_cache_async_readahead(mapping,
1584 index, last_index - index);
1586 if (!PageUptodate(page)) {
1587 if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
1588 !mapping->a_ops->is_partially_uptodate)
1589 goto page_not_up_to_date;
1590 if (!trylock_page(page))
1591 goto page_not_up_to_date;
1592 /* Did it get truncated before we got the lock? */
1594 goto page_not_up_to_date_locked;
1595 if (!mapping->a_ops->is_partially_uptodate(page,
1596 offset, iter->count))
1597 goto page_not_up_to_date_locked;
1602 * i_size must be checked after we know the page is Uptodate.
1604 * Checking i_size after the check allows us to calculate
1605 * the correct value for "nr", which means the zero-filled
1606 * part of the page is not copied back to userspace (unless
1607 * another truncate extends the file - this is desired though).
1610 isize = i_size_read(inode);
1611 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1612 if (unlikely(!isize || index > end_index)) {
1613 page_cache_release(page);
1617 /* nr is the maximum number of bytes to copy from this page */
1618 nr = PAGE_CACHE_SIZE;
1619 if (index == end_index) {
1620 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
1622 page_cache_release(page);
1628 /* If users can be writing to this page using arbitrary
1629 * virtual addresses, take care about potential aliasing
1630 * before reading the page on the kernel side.
1632 if (mapping_writably_mapped(mapping))
1633 flush_dcache_page(page);
1636 * When a sequential read accesses a page several times,
1637 * only mark it as accessed the first time.
1639 if (prev_index != index || offset != prev_offset)
1640 mark_page_accessed(page);
1644 * Ok, we have the page, and it's up-to-date, so
1645 * now we can copy it to user space...
1648 ret = copy_page_to_iter(page, offset, nr, iter);
1650 index += offset >> PAGE_CACHE_SHIFT;
1651 offset &= ~PAGE_CACHE_MASK;
1652 prev_offset = offset;
1654 page_cache_release(page);
1656 if (!iov_iter_count(iter))
1664 page_not_up_to_date:
1665 /* Get exclusive access to the page ... */
1666 error = lock_page_killable(page);
1667 if (unlikely(error))
1668 goto readpage_error;
1670 page_not_up_to_date_locked:
1671 /* Did it get truncated before we got the lock? */
1672 if (!page->mapping) {
1674 page_cache_release(page);
1678 /* Did somebody else fill it already? */
1679 if (PageUptodate(page)) {
1686 * A previous I/O error may have been due to temporary
1687 * failures, eg. multipath errors.
1688 * PG_error will be set again if readpage fails.
1690 ClearPageError(page);
1691 /* Start the actual read. The read will unlock the page. */
1692 error = mapping->a_ops->readpage(filp, page);
1694 if (unlikely(error)) {
1695 if (error == AOP_TRUNCATED_PAGE) {
1696 page_cache_release(page);
1700 goto readpage_error;
1703 if (!PageUptodate(page)) {
1704 error = lock_page_killable(page);
1705 if (unlikely(error))
1706 goto readpage_error;
1707 if (!PageUptodate(page)) {
1708 if (page->mapping == NULL) {
1710 * invalidate_mapping_pages got it
1713 page_cache_release(page);
1717 shrink_readahead_size_eio(filp, ra);
1719 goto readpage_error;
1727 /* UHHUH! A synchronous read error occurred. Report it */
1728 page_cache_release(page);
1733 * Ok, it wasn't cached, so we need to create a new
1736 page = page_cache_alloc_cold(mapping);
1741 error = add_to_page_cache_lru(page, mapping, index,
1742 mapping_gfp_constraint(mapping, GFP_KERNEL));
1744 page_cache_release(page);
1745 if (error == -EEXIST) {
1755 ra->prev_pos = prev_index;
1756 ra->prev_pos <<= PAGE_CACHE_SHIFT;
1757 ra->prev_pos |= prev_offset;
1759 *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1760 file_accessed(filp);
1761 return written ? written : error;
1765 * generic_file_read_iter - generic filesystem read routine
1766 * @iocb: kernel I/O control block
1767 * @iter: destination for the data read
1769 * This is the "read_iter()" routine for all filesystems
1770 * that can use the page cache directly.
1773 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
1775 struct file *file = iocb->ki_filp;
1777 loff_t *ppos = &iocb->ki_pos;
1780 if (iocb->ki_flags & IOCB_DIRECT) {
1781 struct address_space *mapping = file->f_mapping;
1782 struct inode *inode = mapping->host;
1783 size_t count = iov_iter_count(iter);
1787 goto out; /* skip atime */
1788 size = i_size_read(inode);
1789 retval = filemap_write_and_wait_range(mapping, pos,
1792 struct iov_iter data = *iter;
1793 retval = mapping->a_ops->direct_IO(iocb, &data, pos);
1797 *ppos = pos + retval;
1798 iov_iter_advance(iter, retval);
1802 * Btrfs can have a short DIO read if we encounter
1803 * compressed extents, so if there was an error, or if
1804 * we've already read everything we wanted to, or if
1805 * there was a short read because we hit EOF, go ahead
1806 * and return. Otherwise fallthrough to buffered io for
1807 * the rest of the read. Buffered reads will not work for
1808 * DAX files, so don't bother trying.
1810 if (retval < 0 || !iov_iter_count(iter) || *ppos >= size ||
1812 file_accessed(file);
1817 retval = do_generic_file_read(file, ppos, iter, retval);
1821 EXPORT_SYMBOL(generic_file_read_iter);
1825 * page_cache_read - adds requested page to the page cache if not already there
1826 * @file: file to read
1827 * @offset: page index
1829 * This adds the requested page to the page cache if it isn't already there,
1830 * and schedules an I/O to read in its contents from disk.
1832 static int page_cache_read(struct file *file, pgoff_t offset)
1834 struct address_space *mapping = file->f_mapping;
1839 page = page_cache_alloc_cold(mapping);
1843 ret = add_to_page_cache_lru(page, mapping, offset,
1844 mapping_gfp_constraint(mapping, GFP_KERNEL));
1846 ret = mapping->a_ops->readpage(file, page);
1847 else if (ret == -EEXIST)
1848 ret = 0; /* losing race to add is OK */
1850 page_cache_release(page);
1852 } while (ret == AOP_TRUNCATED_PAGE);
1857 #define MMAP_LOTSAMISS (100)
1860 * Synchronous readahead happens when we don't even find
1861 * a page in the page cache at all.
1863 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
1864 struct file_ra_state *ra,
1868 struct address_space *mapping = file->f_mapping;
1870 /* If we don't want any read-ahead, don't bother */
1871 if (vma->vm_flags & VM_RAND_READ)
1876 if (vma->vm_flags & VM_SEQ_READ) {
1877 page_cache_sync_readahead(mapping, ra, file, offset,
1882 /* Avoid banging the cache line if not needed */
1883 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
1887 * Do we miss much more than hit in this file? If so,
1888 * stop bothering with read-ahead. It will only hurt.
1890 if (ra->mmap_miss > MMAP_LOTSAMISS)
1896 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
1897 ra->size = ra->ra_pages;
1898 ra->async_size = ra->ra_pages / 4;
1899 ra_submit(ra, mapping, file);
1903 * Asynchronous readahead happens when we find the page and PG_readahead,
1904 * so we want to possibly extend the readahead further..
1906 static void do_async_mmap_readahead(struct vm_area_struct *vma,
1907 struct file_ra_state *ra,
1912 struct address_space *mapping = file->f_mapping;
1914 /* If we don't want any read-ahead, don't bother */
1915 if (vma->vm_flags & VM_RAND_READ)
1917 if (ra->mmap_miss > 0)
1919 if (PageReadahead(page))
1920 page_cache_async_readahead(mapping, ra, file,
1921 page, offset, ra->ra_pages);
1925 * filemap_fault - read in file data for page fault handling
1926 * @vma: vma in which the fault was taken
1927 * @vmf: struct vm_fault containing details of the fault
1929 * filemap_fault() is invoked via the vma operations vector for a
1930 * mapped memory region to read in file data during a page fault.
1932 * The goto's are kind of ugly, but this streamlines the normal case of having
1933 * it in the page cache, and handles the special cases reasonably without
1934 * having a lot of duplicated code.
1936 * vma->vm_mm->mmap_sem must be held on entry.
1938 * If our return value has VM_FAULT_RETRY set, it's because
1939 * lock_page_or_retry() returned 0.
1940 * The mmap_sem has usually been released in this case.
1941 * See __lock_page_or_retry() for the exception.
1943 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
1944 * has not been released.
1946 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
1948 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1951 struct file *file = vma->vm_file;
1952 struct address_space *mapping = file->f_mapping;
1953 struct file_ra_state *ra = &file->f_ra;
1954 struct inode *inode = mapping->host;
1955 pgoff_t offset = vmf->pgoff;
1960 size = round_up(i_size_read(inode), PAGE_CACHE_SIZE);
1961 if (offset >= size >> PAGE_CACHE_SHIFT)
1962 return VM_FAULT_SIGBUS;
1965 * Do we have something in the page cache already?
1967 page = find_get_page(mapping, offset);
1968 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
1970 * We found the page, so try async readahead before
1971 * waiting for the lock.
1973 do_async_mmap_readahead(vma, ra, file, page, offset);
1975 /* No page in the page cache at all */
1976 do_sync_mmap_readahead(vma, ra, file, offset);
1977 count_vm_event(PGMAJFAULT);
1978 mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
1979 ret = VM_FAULT_MAJOR;
1981 page = find_get_page(mapping, offset);
1983 goto no_cached_page;
1986 if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {
1987 page_cache_release(page);
1988 return ret | VM_FAULT_RETRY;
1991 /* Did it get truncated? */
1992 if (unlikely(page->mapping != mapping)) {
1997 VM_BUG_ON_PAGE(page->index != offset, page);
2000 * We have a locked page in the page cache, now we need to check
2001 * that it's up-to-date. If not, it is going to be due to an error.
2003 if (unlikely(!PageUptodate(page)))
2004 goto page_not_uptodate;
2007 * Found the page and have a reference on it.
2008 * We must recheck i_size under page lock.
2010 size = round_up(i_size_read(inode), PAGE_CACHE_SIZE);
2011 if (unlikely(offset >= size >> PAGE_CACHE_SHIFT)) {
2013 page_cache_release(page);
2014 return VM_FAULT_SIGBUS;
2018 return ret | VM_FAULT_LOCKED;
2022 * We're only likely to ever get here if MADV_RANDOM is in
2025 error = page_cache_read(file, offset);
2028 * The page we want has now been added to the page cache.
2029 * In the unlikely event that someone removed it in the
2030 * meantime, we'll just come back here and read it again.
2036 * An error return from page_cache_read can result if the
2037 * system is low on memory, or a problem occurs while trying
2040 if (error == -ENOMEM)
2041 return VM_FAULT_OOM;
2042 return VM_FAULT_SIGBUS;
2046 * Umm, take care of errors if the page isn't up-to-date.
2047 * Try to re-read it _once_. We do this synchronously,
2048 * because there really aren't any performance issues here
2049 * and we need to check for errors.
2051 ClearPageError(page);
2052 error = mapping->a_ops->readpage(file, page);
2054 wait_on_page_locked(page);
2055 if (!PageUptodate(page))
2058 page_cache_release(page);
2060 if (!error || error == AOP_TRUNCATED_PAGE)
2063 /* Things didn't work out. Return zero to tell the mm layer so. */
2064 shrink_readahead_size_eio(file, ra);
2065 return VM_FAULT_SIGBUS;
2067 EXPORT_SYMBOL(filemap_fault);
2069 void filemap_map_pages(struct vm_area_struct *vma, struct vm_fault *vmf)
2071 struct radix_tree_iter iter;
2073 struct file *file = vma->vm_file;
2074 struct address_space *mapping = file->f_mapping;
2077 unsigned long address = (unsigned long) vmf->virtual_address;
2082 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, vmf->pgoff) {
2083 if (iter.index > vmf->max_pgoff)
2086 page = radix_tree_deref_slot(slot);
2087 if (unlikely(!page))
2089 if (radix_tree_exception(page)) {
2090 if (radix_tree_deref_retry(page))
2096 if (!page_cache_get_speculative(page))
2099 /* Has the page moved? */
2100 if (unlikely(page != *slot)) {
2101 page_cache_release(page);
2105 if (!PageUptodate(page) ||
2106 PageReadahead(page) ||
2109 if (!trylock_page(page))
2112 if (page->mapping != mapping || !PageUptodate(page))
2115 size = round_up(i_size_read(mapping->host), PAGE_CACHE_SIZE);
2116 if (page->index >= size >> PAGE_CACHE_SHIFT)
2119 pte = vmf->pte + page->index - vmf->pgoff;
2120 if (!pte_none(*pte))
2123 if (file->f_ra.mmap_miss > 0)
2124 file->f_ra.mmap_miss--;
2125 addr = address + (page->index - vmf->pgoff) * PAGE_SIZE;
2126 do_set_pte(vma, addr, page, pte, false, false);
2132 page_cache_release(page);
2134 if (iter.index == vmf->max_pgoff)
2139 EXPORT_SYMBOL(filemap_map_pages);
2141 int filemap_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
2143 struct page *page = vmf->page;
2144 struct inode *inode = file_inode(vma->vm_file);
2145 int ret = VM_FAULT_LOCKED;
2147 sb_start_pagefault(inode->i_sb);
2148 file_update_time(vma->vm_file);
2150 if (page->mapping != inode->i_mapping) {
2152 ret = VM_FAULT_NOPAGE;
2156 * We mark the page dirty already here so that when freeze is in
2157 * progress, we are guaranteed that writeback during freezing will
2158 * see the dirty page and writeprotect it again.
2160 set_page_dirty(page);
2161 wait_for_stable_page(page);
2163 sb_end_pagefault(inode->i_sb);
2166 EXPORT_SYMBOL(filemap_page_mkwrite);
2168 const struct vm_operations_struct generic_file_vm_ops = {
2169 .fault = filemap_fault,
2170 .map_pages = filemap_map_pages,
2171 .page_mkwrite = filemap_page_mkwrite,
2174 /* This is used for a general mmap of a disk file */
2176 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2178 struct address_space *mapping = file->f_mapping;
2180 if (!mapping->a_ops->readpage)
2182 file_accessed(file);
2183 vma->vm_ops = &generic_file_vm_ops;
2188 * This is for filesystems which do not implement ->writepage.
2190 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2192 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2194 return generic_file_mmap(file, vma);
2197 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2201 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2205 #endif /* CONFIG_MMU */
2207 EXPORT_SYMBOL(generic_file_mmap);
2208 EXPORT_SYMBOL(generic_file_readonly_mmap);
2210 static struct page *wait_on_page_read(struct page *page)
2212 if (!IS_ERR(page)) {
2213 wait_on_page_locked(page);
2214 if (!PageUptodate(page)) {
2215 page_cache_release(page);
2216 page = ERR_PTR(-EIO);
2222 static struct page *__read_cache_page(struct address_space *mapping,
2224 int (*filler)(void *, struct page *),
2231 page = find_get_page(mapping, index);
2233 page = __page_cache_alloc(gfp | __GFP_COLD);
2235 return ERR_PTR(-ENOMEM);
2236 err = add_to_page_cache_lru(page, mapping, index, gfp);
2237 if (unlikely(err)) {
2238 page_cache_release(page);
2241 /* Presumably ENOMEM for radix tree node */
2242 return ERR_PTR(err);
2244 err = filler(data, page);
2246 page_cache_release(page);
2247 page = ERR_PTR(err);
2249 page = wait_on_page_read(page);
2255 static struct page *do_read_cache_page(struct address_space *mapping,
2257 int (*filler)(void *, struct page *),
2266 page = __read_cache_page(mapping, index, filler, data, gfp);
2269 if (PageUptodate(page))
2273 if (!page->mapping) {
2275 page_cache_release(page);
2278 if (PageUptodate(page)) {
2282 err = filler(data, page);
2284 page_cache_release(page);
2285 return ERR_PTR(err);
2287 page = wait_on_page_read(page);
2292 mark_page_accessed(page);
2297 * read_cache_page - read into page cache, fill it if needed
2298 * @mapping: the page's address_space
2299 * @index: the page index
2300 * @filler: function to perform the read
2301 * @data: first arg to filler(data, page) function, often left as NULL
2303 * Read into the page cache. If a page already exists, and PageUptodate() is
2304 * not set, try to fill the page and wait for it to become unlocked.
2306 * If the page does not get brought uptodate, return -EIO.
2308 struct page *read_cache_page(struct address_space *mapping,
2310 int (*filler)(void *, struct page *),
2313 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2315 EXPORT_SYMBOL(read_cache_page);
2318 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2319 * @mapping: the page's address_space
2320 * @index: the page index
2321 * @gfp: the page allocator flags to use if allocating
2323 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2324 * any new page allocations done using the specified allocation flags.
2326 * If the page does not get brought uptodate, return -EIO.
2328 struct page *read_cache_page_gfp(struct address_space *mapping,
2332 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2334 return do_read_cache_page(mapping, index, filler, NULL, gfp);
2336 EXPORT_SYMBOL(read_cache_page_gfp);
2339 * Performs necessary checks before doing a write
2341 * Can adjust writing position or amount of bytes to write.
2342 * Returns appropriate error code that caller should return or
2343 * zero in case that write should be allowed.
2345 inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
2347 struct file *file = iocb->ki_filp;
2348 struct inode *inode = file->f_mapping->host;
2349 unsigned long limit = rlimit(RLIMIT_FSIZE);
2352 if (!iov_iter_count(from))
2355 /* FIXME: this is for backwards compatibility with 2.4 */
2356 if (iocb->ki_flags & IOCB_APPEND)
2357 iocb->ki_pos = i_size_read(inode);
2361 if (limit != RLIM_INFINITY) {
2362 if (iocb->ki_pos >= limit) {
2363 send_sig(SIGXFSZ, current, 0);
2366 iov_iter_truncate(from, limit - (unsigned long)pos);
2372 if (unlikely(pos + iov_iter_count(from) > MAX_NON_LFS &&
2373 !(file->f_flags & O_LARGEFILE))) {
2374 if (pos >= MAX_NON_LFS)
2376 iov_iter_truncate(from, MAX_NON_LFS - (unsigned long)pos);
2380 * Are we about to exceed the fs block limit ?
2382 * If we have written data it becomes a short write. If we have
2383 * exceeded without writing data we send a signal and return EFBIG.
2384 * Linus frestrict idea will clean these up nicely..
2386 if (unlikely(pos >= inode->i_sb->s_maxbytes))
2389 iov_iter_truncate(from, inode->i_sb->s_maxbytes - pos);
2390 return iov_iter_count(from);
2392 EXPORT_SYMBOL(generic_write_checks);
2394 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2395 loff_t pos, unsigned len, unsigned flags,
2396 struct page **pagep, void **fsdata)
2398 const struct address_space_operations *aops = mapping->a_ops;
2400 return aops->write_begin(file, mapping, pos, len, flags,
2403 EXPORT_SYMBOL(pagecache_write_begin);
2405 int pagecache_write_end(struct file *file, struct address_space *mapping,
2406 loff_t pos, unsigned len, unsigned copied,
2407 struct page *page, void *fsdata)
2409 const struct address_space_operations *aops = mapping->a_ops;
2411 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2413 EXPORT_SYMBOL(pagecache_write_end);
2416 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from, loff_t pos)
2418 struct file *file = iocb->ki_filp;
2419 struct address_space *mapping = file->f_mapping;
2420 struct inode *inode = mapping->host;
2424 struct iov_iter data;
2426 write_len = iov_iter_count(from);
2427 end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
2429 written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
2434 * After a write we want buffered reads to be sure to go to disk to get
2435 * the new data. We invalidate clean cached page from the region we're
2436 * about to write. We do this *before* the write so that we can return
2437 * without clobbering -EIOCBQUEUED from ->direct_IO().
2439 if (mapping->nrpages) {
2440 written = invalidate_inode_pages2_range(mapping,
2441 pos >> PAGE_CACHE_SHIFT, end);
2443 * If a page can not be invalidated, return 0 to fall back
2444 * to buffered write.
2447 if (written == -EBUSY)
2454 written = mapping->a_ops->direct_IO(iocb, &data, pos);
2457 * Finally, try again to invalidate clean pages which might have been
2458 * cached by non-direct readahead, or faulted in by get_user_pages()
2459 * if the source of the write was an mmap'ed region of the file
2460 * we're writing. Either one is a pretty crazy thing to do,
2461 * so we don't support it 100%. If this invalidation
2462 * fails, tough, the write still worked...
2464 if (mapping->nrpages) {
2465 invalidate_inode_pages2_range(mapping,
2466 pos >> PAGE_CACHE_SHIFT, end);
2471 iov_iter_advance(from, written);
2472 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2473 i_size_write(inode, pos);
2474 mark_inode_dirty(inode);
2481 EXPORT_SYMBOL(generic_file_direct_write);
2484 * Find or create a page at the given pagecache position. Return the locked
2485 * page. This function is specifically for buffered writes.
2487 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2488 pgoff_t index, unsigned flags)
2491 int fgp_flags = FGP_LOCK|FGP_ACCESSED|FGP_WRITE|FGP_CREAT;
2493 if (flags & AOP_FLAG_NOFS)
2494 fgp_flags |= FGP_NOFS;
2496 page = pagecache_get_page(mapping, index, fgp_flags,
2497 mapping_gfp_mask(mapping));
2499 wait_for_stable_page(page);
2503 EXPORT_SYMBOL(grab_cache_page_write_begin);
2505 ssize_t generic_perform_write(struct file *file,
2506 struct iov_iter *i, loff_t pos)
2508 struct address_space *mapping = file->f_mapping;
2509 const struct address_space_operations *a_ops = mapping->a_ops;
2511 ssize_t written = 0;
2512 unsigned int flags = 0;
2515 * Copies from kernel address space cannot fail (NFSD is a big user).
2517 if (!iter_is_iovec(i))
2518 flags |= AOP_FLAG_UNINTERRUPTIBLE;
2522 unsigned long offset; /* Offset into pagecache page */
2523 unsigned long bytes; /* Bytes to write to page */
2524 size_t copied; /* Bytes copied from user */
2527 offset = (pos & (PAGE_CACHE_SIZE - 1));
2528 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2533 * Bring in the user page that we will copy from _first_.
2534 * Otherwise there's a nasty deadlock on copying from the
2535 * same page as we're writing to, without it being marked
2538 * Not only is this an optimisation, but it is also required
2539 * to check that the address is actually valid, when atomic
2540 * usercopies are used, below.
2542 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2547 if (fatal_signal_pending(current)) {
2552 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
2554 if (unlikely(status < 0))
2557 if (mapping_writably_mapped(mapping))
2558 flush_dcache_page(page);
2560 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2561 flush_dcache_page(page);
2563 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2565 if (unlikely(status < 0))
2571 iov_iter_advance(i, copied);
2572 if (unlikely(copied == 0)) {
2574 * If we were unable to copy any data at all, we must
2575 * fall back to a single segment length write.
2577 * If we didn't fallback here, we could livelock
2578 * because not all segments in the iov can be copied at
2579 * once without a pagefault.
2581 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2582 iov_iter_single_seg_count(i));
2588 balance_dirty_pages_ratelimited(mapping);
2589 } while (iov_iter_count(i));
2591 return written ? written : status;
2593 EXPORT_SYMBOL(generic_perform_write);
2596 * __generic_file_write_iter - write data to a file
2597 * @iocb: IO state structure (file, offset, etc.)
2598 * @from: iov_iter with data to write
2600 * This function does all the work needed for actually writing data to a
2601 * file. It does all basic checks, removes SUID from the file, updates
2602 * modification times and calls proper subroutines depending on whether we
2603 * do direct IO or a standard buffered write.
2605 * It expects i_mutex to be grabbed unless we work on a block device or similar
2606 * object which does not need locking at all.
2608 * This function does *not* take care of syncing data in case of O_SYNC write.
2609 * A caller has to handle it. This is mainly due to the fact that we want to
2610 * avoid syncing under i_mutex.
2612 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2614 struct file *file = iocb->ki_filp;
2615 struct address_space * mapping = file->f_mapping;
2616 struct inode *inode = mapping->host;
2617 ssize_t written = 0;
2621 /* We can write back this queue in page reclaim */
2622 current->backing_dev_info = inode_to_bdi(inode);
2623 err = file_remove_privs(file);
2627 err = file_update_time(file);
2631 if (iocb->ki_flags & IOCB_DIRECT) {
2632 loff_t pos, endbyte;
2634 written = generic_file_direct_write(iocb, from, iocb->ki_pos);
2636 * If the write stopped short of completing, fall back to
2637 * buffered writes. Some filesystems do this for writes to
2638 * holes, for example. For DAX files, a buffered write will
2639 * not succeed (even if it did, DAX does not handle dirty
2640 * page-cache pages correctly).
2642 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
2645 status = generic_perform_write(file, from, pos = iocb->ki_pos);
2647 * If generic_perform_write() returned a synchronous error
2648 * then we want to return the number of bytes which were
2649 * direct-written, or the error code if that was zero. Note
2650 * that this differs from normal direct-io semantics, which
2651 * will return -EFOO even if some bytes were written.
2653 if (unlikely(status < 0)) {
2658 * We need to ensure that the page cache pages are written to
2659 * disk and invalidated to preserve the expected O_DIRECT
2662 endbyte = pos + status - 1;
2663 err = filemap_write_and_wait_range(mapping, pos, endbyte);
2665 iocb->ki_pos = endbyte + 1;
2667 invalidate_mapping_pages(mapping,
2668 pos >> PAGE_CACHE_SHIFT,
2669 endbyte >> PAGE_CACHE_SHIFT);
2672 * We don't know how much we wrote, so just return
2673 * the number of bytes which were direct-written
2677 written = generic_perform_write(file, from, iocb->ki_pos);
2678 if (likely(written > 0))
2679 iocb->ki_pos += written;
2682 current->backing_dev_info = NULL;
2683 return written ? written : err;
2685 EXPORT_SYMBOL(__generic_file_write_iter);
2688 * generic_file_write_iter - write data to a file
2689 * @iocb: IO state structure
2690 * @from: iov_iter with data to write
2692 * This is a wrapper around __generic_file_write_iter() to be used by most
2693 * filesystems. It takes care of syncing the file in case of O_SYNC file
2694 * and acquires i_mutex as needed.
2696 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2698 struct file *file = iocb->ki_filp;
2699 struct inode *inode = file->f_mapping->host;
2702 mutex_lock(&inode->i_mutex);
2703 ret = generic_write_checks(iocb, from);
2705 ret = __generic_file_write_iter(iocb, from);
2706 mutex_unlock(&inode->i_mutex);
2711 err = generic_write_sync(file, iocb->ki_pos - ret, ret);
2717 EXPORT_SYMBOL(generic_file_write_iter);
2720 * try_to_release_page() - release old fs-specific metadata on a page
2722 * @page: the page which the kernel is trying to free
2723 * @gfp_mask: memory allocation flags (and I/O mode)
2725 * The address_space is to try to release any data against the page
2726 * (presumably at page->private). If the release was successful, return `1'.
2727 * Otherwise return zero.
2729 * This may also be called if PG_fscache is set on a page, indicating that the
2730 * page is known to the local caching routines.
2732 * The @gfp_mask argument specifies whether I/O may be performed to release
2733 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
2736 int try_to_release_page(struct page *page, gfp_t gfp_mask)
2738 struct address_space * const mapping = page->mapping;
2740 BUG_ON(!PageLocked(page));
2741 if (PageWriteback(page))
2744 if (mapping && mapping->a_ops->releasepage)
2745 return mapping->a_ops->releasepage(page, gfp_mask);
2746 return try_to_free_buffers(page);
2749 EXPORT_SYMBOL(try_to_release_page);