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>
14 #include <linux/dax.h>
16 #include <linux/uaccess.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/cpuset.h>
33 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
34 #include <linux/hugetlb.h>
35 #include <linux/memcontrol.h>
36 #include <linux/cleancache.h>
37 #include <linux/rmap.h>
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/filemap.h>
44 * FIXME: remove all knowledge of the buffer layer from the core VM
46 #include <linux/buffer_head.h> /* for try_to_free_buffers */
51 * Shared mappings implemented 30.11.1994. It's not fully working yet,
54 * Shared mappings now work. 15.8.1995 Bruno.
56 * finished 'unifying' the page and buffer cache and SMP-threaded the
57 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
59 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
65 * ->i_mmap_rwsem (truncate_pagecache)
66 * ->private_lock (__free_pte->__set_page_dirty_buffers)
67 * ->swap_lock (exclusive_swap_page, others)
68 * ->mapping->tree_lock
71 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
75 * ->page_table_lock or pte_lock (various, mainly in memory.c)
76 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
79 * ->lock_page (access_process_vm)
81 * ->i_mutex (generic_perform_write)
82 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
85 * sb_lock (fs/fs-writeback.c)
86 * ->mapping->tree_lock (__sync_single_inode)
89 * ->anon_vma.lock (vma_adjust)
92 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
94 * ->page_table_lock or pte_lock
95 * ->swap_lock (try_to_unmap_one)
96 * ->private_lock (try_to_unmap_one)
97 * ->tree_lock (try_to_unmap_one)
98 * ->zone.lru_lock (follow_page->mark_page_accessed)
99 * ->zone.lru_lock (check_pte_range->isolate_lru_page)
100 * ->private_lock (page_remove_rmap->set_page_dirty)
101 * ->tree_lock (page_remove_rmap->set_page_dirty)
102 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
103 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
104 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
105 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
106 * ->inode->i_lock (zap_pte_range->set_page_dirty)
107 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
110 * ->tasklist_lock (memory_failure, collect_procs_ao)
113 static void page_cache_tree_delete(struct address_space
*mapping
,
114 struct page
*page
, void *shadow
)
116 struct radix_tree_node
*node
;
118 VM_BUG_ON(!PageLocked(page
));
120 node
= radix_tree_replace_clear_tags(&mapping
->page_tree
, page
->index
,
124 mapping
->nrexceptional
++;
126 * Make sure the nrexceptional update is committed before
127 * the nrpages update so that final truncate racing
128 * with reclaim does not see both counters 0 at the
129 * same time and miss a shadow entry.
138 workingset_node_pages_dec(node
);
140 workingset_node_shadows_inc(node
);
142 if (__radix_tree_delete_node(&mapping
->page_tree
, node
))
146 * Track node that only contains shadow entries. DAX mappings contain
147 * no shadow entries and may contain other exceptional entries so skip
150 * Avoid acquiring the list_lru lock if already tracked. The
151 * list_empty() test is safe as node->private_list is
152 * protected by mapping->tree_lock.
154 if (!dax_mapping(mapping
) && !workingset_node_pages(node
) &&
155 list_empty(&node
->private_list
)) {
156 node
->private_data
= mapping
;
157 list_lru_add(&workingset_shadow_nodes
, &node
->private_list
);
162 * Delete a page from the page cache and free it. Caller has to make
163 * sure the page is locked and that nobody else uses it - or that usage
164 * is safe. The caller must hold the mapping's tree_lock.
166 void __delete_from_page_cache(struct page
*page
, void *shadow
)
168 struct address_space
*mapping
= page
->mapping
;
170 trace_mm_filemap_delete_from_page_cache(page
);
172 * if we're uptodate, flush out into the cleancache, otherwise
173 * invalidate any existing cleancache entries. We can't leave
174 * stale data around in the cleancache once our page is gone
176 if (PageUptodate(page
) && PageMappedToDisk(page
))
177 cleancache_put_page(page
);
179 cleancache_invalidate_page(mapping
, page
);
181 VM_BUG_ON_PAGE(page_mapped(page
), page
);
182 if (!IS_ENABLED(CONFIG_DEBUG_VM
) && unlikely(page_mapped(page
))) {
185 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
186 current
->comm
, page_to_pfn(page
));
187 dump_page(page
, "still mapped when deleted");
189 add_taint(TAINT_BAD_PAGE
, LOCKDEP_NOW_UNRELIABLE
);
191 mapcount
= page_mapcount(page
);
192 if (mapping_exiting(mapping
) &&
193 page_count(page
) >= mapcount
+ 2) {
195 * All vmas have already been torn down, so it's
196 * a good bet that actually the page is unmapped,
197 * and we'd prefer not to leak it: if we're wrong,
198 * some other bad page check should catch it later.
200 page_mapcount_reset(page
);
201 page_ref_sub(page
, mapcount
);
205 page_cache_tree_delete(mapping
, page
, shadow
);
207 page
->mapping
= NULL
;
208 /* Leave page->index set: truncation lookup relies upon it */
210 /* hugetlb pages do not participate in page cache accounting. */
212 __dec_zone_page_state(page
, NR_FILE_PAGES
);
213 if (PageSwapBacked(page
))
214 __dec_zone_page_state(page
, NR_SHMEM
);
217 * At this point page must be either written or cleaned by truncate.
218 * Dirty page here signals a bug and loss of unwritten data.
220 * This fixes dirty accounting after removing the page entirely but
221 * leaves PageDirty set: it has no effect for truncated page and
222 * anyway will be cleared before returning page into buddy allocator.
224 if (WARN_ON_ONCE(PageDirty(page
)))
225 account_page_cleaned(page
, mapping
, inode_to_wb(mapping
->host
));
229 * delete_from_page_cache - delete page from page cache
230 * @page: the page which the kernel is trying to remove from page cache
232 * This must be called only on pages that have been verified to be in the page
233 * cache and locked. It will never put the page into the free list, the caller
234 * has a reference on the page.
236 void delete_from_page_cache(struct page
*page
)
238 struct address_space
*mapping
= page
->mapping
;
241 void (*freepage
)(struct page
*);
243 BUG_ON(!PageLocked(page
));
245 freepage
= mapping
->a_ops
->freepage
;
247 spin_lock_irqsave(&mapping
->tree_lock
, flags
);
248 __delete_from_page_cache(page
, NULL
);
249 spin_unlock_irqrestore(&mapping
->tree_lock
, flags
);
255 EXPORT_SYMBOL(delete_from_page_cache
);
257 static int filemap_check_errors(struct address_space
*mapping
)
260 /* Check for outstanding write errors */
261 if (test_bit(AS_ENOSPC
, &mapping
->flags
) &&
262 test_and_clear_bit(AS_ENOSPC
, &mapping
->flags
))
264 if (test_bit(AS_EIO
, &mapping
->flags
) &&
265 test_and_clear_bit(AS_EIO
, &mapping
->flags
))
271 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
272 * @mapping: address space structure to write
273 * @start: offset in bytes where the range starts
274 * @end: offset in bytes where the range ends (inclusive)
275 * @sync_mode: enable synchronous operation
277 * Start writeback against all of a mapping's dirty pages that lie
278 * within the byte offsets <start, end> inclusive.
280 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
281 * opposed to a regular memory cleansing writeback. The difference between
282 * these two operations is that if a dirty page/buffer is encountered, it must
283 * be waited upon, and not just skipped over.
285 int __filemap_fdatawrite_range(struct address_space
*mapping
, loff_t start
,
286 loff_t end
, int sync_mode
)
289 struct writeback_control wbc
= {
290 .sync_mode
= sync_mode
,
291 .nr_to_write
= LONG_MAX
,
292 .range_start
= start
,
296 if (!mapping_cap_writeback_dirty(mapping
))
299 wbc_attach_fdatawrite_inode(&wbc
, mapping
->host
);
300 ret
= do_writepages(mapping
, &wbc
);
301 wbc_detach_inode(&wbc
);
305 static inline int __filemap_fdatawrite(struct address_space
*mapping
,
308 return __filemap_fdatawrite_range(mapping
, 0, LLONG_MAX
, sync_mode
);
311 int filemap_fdatawrite(struct address_space
*mapping
)
313 return __filemap_fdatawrite(mapping
, WB_SYNC_ALL
);
315 EXPORT_SYMBOL(filemap_fdatawrite
);
317 int filemap_fdatawrite_range(struct address_space
*mapping
, loff_t start
,
320 return __filemap_fdatawrite_range(mapping
, start
, end
, WB_SYNC_ALL
);
322 EXPORT_SYMBOL(filemap_fdatawrite_range
);
325 * filemap_flush - mostly a non-blocking flush
326 * @mapping: target address_space
328 * This is a mostly non-blocking flush. Not suitable for data-integrity
329 * purposes - I/O may not be started against all dirty pages.
331 int filemap_flush(struct address_space
*mapping
)
333 return __filemap_fdatawrite(mapping
, WB_SYNC_NONE
);
335 EXPORT_SYMBOL(filemap_flush
);
337 static int __filemap_fdatawait_range(struct address_space
*mapping
,
338 loff_t start_byte
, loff_t end_byte
)
340 pgoff_t index
= start_byte
>> PAGE_SHIFT
;
341 pgoff_t end
= end_byte
>> PAGE_SHIFT
;
346 if (end_byte
< start_byte
)
349 pagevec_init(&pvec
, 0);
350 while ((index
<= end
) &&
351 (nr_pages
= pagevec_lookup_tag(&pvec
, mapping
, &index
,
352 PAGECACHE_TAG_WRITEBACK
,
353 min(end
- index
, (pgoff_t
)PAGEVEC_SIZE
-1) + 1)) != 0) {
356 for (i
= 0; i
< nr_pages
; i
++) {
357 struct page
*page
= pvec
.pages
[i
];
359 /* until radix tree lookup accepts end_index */
360 if (page
->index
> end
)
363 wait_on_page_writeback(page
);
364 if (TestClearPageError(page
))
367 pagevec_release(&pvec
);
375 * filemap_fdatawait_range - wait for writeback to complete
376 * @mapping: address space structure to wait for
377 * @start_byte: offset in bytes where the range starts
378 * @end_byte: offset in bytes where the range ends (inclusive)
380 * Walk the list of under-writeback pages of the given address space
381 * in the given range and wait for all of them. Check error status of
382 * the address space and return it.
384 * Since the error status of the address space is cleared by this function,
385 * callers are responsible for checking the return value and handling and/or
386 * reporting the error.
388 int filemap_fdatawait_range(struct address_space
*mapping
, loff_t start_byte
,
393 ret
= __filemap_fdatawait_range(mapping
, start_byte
, end_byte
);
394 ret2
= filemap_check_errors(mapping
);
400 EXPORT_SYMBOL(filemap_fdatawait_range
);
403 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
404 * @mapping: address space structure to wait for
406 * Walk the list of under-writeback pages of the given address space
407 * and wait for all of them. Unlike filemap_fdatawait(), this function
408 * does not clear error status of the address space.
410 * Use this function if callers don't handle errors themselves. Expected
411 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
414 void filemap_fdatawait_keep_errors(struct address_space
*mapping
)
416 loff_t i_size
= i_size_read(mapping
->host
);
421 __filemap_fdatawait_range(mapping
, 0, i_size
- 1);
425 * filemap_fdatawait - wait for all under-writeback pages to complete
426 * @mapping: address space structure to wait for
428 * Walk the list of under-writeback pages of the given address space
429 * and wait for all of them. Check error status of the address space
432 * Since the error status of the address space is cleared by this function,
433 * callers are responsible for checking the return value and handling and/or
434 * reporting the error.
436 int filemap_fdatawait(struct address_space
*mapping
)
438 loff_t i_size
= i_size_read(mapping
->host
);
443 return filemap_fdatawait_range(mapping
, 0, i_size
- 1);
445 EXPORT_SYMBOL(filemap_fdatawait
);
447 int filemap_write_and_wait(struct address_space
*mapping
)
451 if ((!dax_mapping(mapping
) && mapping
->nrpages
) ||
452 (dax_mapping(mapping
) && mapping
->nrexceptional
)) {
453 err
= filemap_fdatawrite(mapping
);
455 * Even if the above returned error, the pages may be
456 * written partially (e.g. -ENOSPC), so we wait for it.
457 * But the -EIO is special case, it may indicate the worst
458 * thing (e.g. bug) happened, so we avoid waiting for it.
461 int err2
= filemap_fdatawait(mapping
);
466 err
= filemap_check_errors(mapping
);
470 EXPORT_SYMBOL(filemap_write_and_wait
);
473 * filemap_write_and_wait_range - write out & wait on a file range
474 * @mapping: the address_space for the pages
475 * @lstart: offset in bytes where the range starts
476 * @lend: offset in bytes where the range ends (inclusive)
478 * Write out and wait upon file offsets lstart->lend, inclusive.
480 * Note that `lend' is inclusive (describes the last byte to be written) so
481 * that this function can be used to write to the very end-of-file (end = -1).
483 int filemap_write_and_wait_range(struct address_space
*mapping
,
484 loff_t lstart
, loff_t lend
)
488 if ((!dax_mapping(mapping
) && mapping
->nrpages
) ||
489 (dax_mapping(mapping
) && mapping
->nrexceptional
)) {
490 err
= __filemap_fdatawrite_range(mapping
, lstart
, lend
,
492 /* See comment of filemap_write_and_wait() */
494 int err2
= filemap_fdatawait_range(mapping
,
500 err
= filemap_check_errors(mapping
);
504 EXPORT_SYMBOL(filemap_write_and_wait_range
);
507 * replace_page_cache_page - replace a pagecache page with a new one
508 * @old: page to be replaced
509 * @new: page to replace with
510 * @gfp_mask: allocation mode
512 * This function replaces a page in the pagecache with a new one. On
513 * success it acquires the pagecache reference for the new page and
514 * drops it for the old page. Both the old and new pages must be
515 * locked. This function does not add the new page to the LRU, the
516 * caller must do that.
518 * The remove + add is atomic. The only way this function can fail is
519 * memory allocation failure.
521 int replace_page_cache_page(struct page
*old
, struct page
*new, gfp_t gfp_mask
)
525 VM_BUG_ON_PAGE(!PageLocked(old
), old
);
526 VM_BUG_ON_PAGE(!PageLocked(new), new);
527 VM_BUG_ON_PAGE(new->mapping
, new);
529 error
= radix_tree_preload(gfp_mask
& ~__GFP_HIGHMEM
);
531 struct address_space
*mapping
= old
->mapping
;
532 void (*freepage
)(struct page
*);
535 pgoff_t offset
= old
->index
;
536 freepage
= mapping
->a_ops
->freepage
;
539 new->mapping
= mapping
;
542 spin_lock_irqsave(&mapping
->tree_lock
, flags
);
543 __delete_from_page_cache(old
, NULL
);
544 error
= radix_tree_insert(&mapping
->page_tree
, offset
, new);
549 * hugetlb pages do not participate in page cache accounting.
552 __inc_zone_page_state(new, NR_FILE_PAGES
);
553 if (PageSwapBacked(new))
554 __inc_zone_page_state(new, NR_SHMEM
);
555 spin_unlock_irqrestore(&mapping
->tree_lock
, flags
);
556 mem_cgroup_migrate(old
, new);
557 radix_tree_preload_end();
565 EXPORT_SYMBOL_GPL(replace_page_cache_page
);
567 static int page_cache_tree_insert(struct address_space
*mapping
,
568 struct page
*page
, void **shadowp
)
570 struct radix_tree_node
*node
;
574 error
= __radix_tree_create(&mapping
->page_tree
, page
->index
, 0,
581 p
= radix_tree_deref_slot_protected(slot
, &mapping
->tree_lock
);
582 if (!radix_tree_exceptional_entry(p
))
585 mapping
->nrexceptional
--;
586 if (!dax_mapping(mapping
)) {
590 workingset_node_shadows_dec(node
);
592 /* DAX can replace empty locked entry with a hole */
594 (void *)(RADIX_TREE_EXCEPTIONAL_ENTRY
|
595 RADIX_DAX_ENTRY_LOCK
));
596 /* DAX accounts exceptional entries as normal pages */
598 workingset_node_pages_dec(node
);
599 /* Wakeup waiters for exceptional entry lock */
600 dax_wake_mapping_entry_waiter(mapping
, page
->index
,
604 radix_tree_replace_slot(slot
, page
);
607 workingset_node_pages_inc(node
);
609 * Don't track node that contains actual pages.
611 * Avoid acquiring the list_lru lock if already
612 * untracked. The list_empty() test is safe as
613 * node->private_list is protected by
614 * mapping->tree_lock.
616 if (!list_empty(&node
->private_list
))
617 list_lru_del(&workingset_shadow_nodes
,
618 &node
->private_list
);
623 static int __add_to_page_cache_locked(struct page
*page
,
624 struct address_space
*mapping
,
625 pgoff_t offset
, gfp_t gfp_mask
,
628 int huge
= PageHuge(page
);
629 struct mem_cgroup
*memcg
;
632 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
633 VM_BUG_ON_PAGE(PageSwapBacked(page
), page
);
636 error
= mem_cgroup_try_charge(page
, current
->mm
,
637 gfp_mask
, &memcg
, false);
642 error
= radix_tree_maybe_preload(gfp_mask
& ~__GFP_HIGHMEM
);
645 mem_cgroup_cancel_charge(page
, memcg
, false);
650 page
->mapping
= mapping
;
651 page
->index
= offset
;
653 spin_lock_irq(&mapping
->tree_lock
);
654 error
= page_cache_tree_insert(mapping
, page
, shadowp
);
655 radix_tree_preload_end();
659 /* hugetlb pages do not participate in page cache accounting. */
661 __inc_zone_page_state(page
, NR_FILE_PAGES
);
662 spin_unlock_irq(&mapping
->tree_lock
);
664 mem_cgroup_commit_charge(page
, memcg
, false, false);
665 trace_mm_filemap_add_to_page_cache(page
);
668 page
->mapping
= NULL
;
669 /* Leave page->index set: truncation relies upon it */
670 spin_unlock_irq(&mapping
->tree_lock
);
672 mem_cgroup_cancel_charge(page
, memcg
, false);
678 * add_to_page_cache_locked - add a locked page to the pagecache
680 * @mapping: the page's address_space
681 * @offset: page index
682 * @gfp_mask: page allocation mode
684 * This function is used to add a page to the pagecache. It must be locked.
685 * This function does not add the page to the LRU. The caller must do that.
687 int add_to_page_cache_locked(struct page
*page
, struct address_space
*mapping
,
688 pgoff_t offset
, gfp_t gfp_mask
)
690 return __add_to_page_cache_locked(page
, mapping
, offset
,
693 EXPORT_SYMBOL(add_to_page_cache_locked
);
695 int add_to_page_cache_lru(struct page
*page
, struct address_space
*mapping
,
696 pgoff_t offset
, gfp_t gfp_mask
)
701 __SetPageLocked(page
);
702 ret
= __add_to_page_cache_locked(page
, mapping
, offset
,
705 __ClearPageLocked(page
);
708 * The page might have been evicted from cache only
709 * recently, in which case it should be activated like
710 * any other repeatedly accessed page.
711 * The exception is pages getting rewritten; evicting other
712 * data from the working set, only to cache data that will
713 * get overwritten with something else, is a waste of memory.
715 if (!(gfp_mask
& __GFP_WRITE
) &&
716 shadow
&& workingset_refault(shadow
)) {
718 workingset_activation(page
);
720 ClearPageActive(page
);
725 EXPORT_SYMBOL_GPL(add_to_page_cache_lru
);
728 struct page
*__page_cache_alloc(gfp_t gfp
)
733 if (cpuset_do_page_mem_spread()) {
734 unsigned int cpuset_mems_cookie
;
736 cpuset_mems_cookie
= read_mems_allowed_begin();
737 n
= cpuset_mem_spread_node();
738 page
= __alloc_pages_node(n
, gfp
, 0);
739 } while (!page
&& read_mems_allowed_retry(cpuset_mems_cookie
));
743 return alloc_pages(gfp
, 0);
745 EXPORT_SYMBOL(__page_cache_alloc
);
749 * In order to wait for pages to become available there must be
750 * waitqueues associated with pages. By using a hash table of
751 * waitqueues where the bucket discipline is to maintain all
752 * waiters on the same queue and wake all when any of the pages
753 * become available, and for the woken contexts to check to be
754 * sure the appropriate page became available, this saves space
755 * at a cost of "thundering herd" phenomena during rare hash
758 wait_queue_head_t
*page_waitqueue(struct page
*page
)
760 const struct zone
*zone
= page_zone(page
);
762 return &zone
->wait_table
[hash_ptr(page
, zone
->wait_table_bits
)];
764 EXPORT_SYMBOL(page_waitqueue
);
766 void wait_on_page_bit(struct page
*page
, int bit_nr
)
768 DEFINE_WAIT_BIT(wait
, &page
->flags
, bit_nr
);
770 if (test_bit(bit_nr
, &page
->flags
))
771 __wait_on_bit(page_waitqueue(page
), &wait
, bit_wait_io
,
772 TASK_UNINTERRUPTIBLE
);
774 EXPORT_SYMBOL(wait_on_page_bit
);
776 int wait_on_page_bit_killable(struct page
*page
, int bit_nr
)
778 DEFINE_WAIT_BIT(wait
, &page
->flags
, bit_nr
);
780 if (!test_bit(bit_nr
, &page
->flags
))
783 return __wait_on_bit(page_waitqueue(page
), &wait
,
784 bit_wait_io
, TASK_KILLABLE
);
787 int wait_on_page_bit_killable_timeout(struct page
*page
,
788 int bit_nr
, unsigned long timeout
)
790 DEFINE_WAIT_BIT(wait
, &page
->flags
, bit_nr
);
792 wait
.key
.timeout
= jiffies
+ timeout
;
793 if (!test_bit(bit_nr
, &page
->flags
))
795 return __wait_on_bit(page_waitqueue(page
), &wait
,
796 bit_wait_io_timeout
, TASK_KILLABLE
);
798 EXPORT_SYMBOL_GPL(wait_on_page_bit_killable_timeout
);
801 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
802 * @page: Page defining the wait queue of interest
803 * @waiter: Waiter to add to the queue
805 * Add an arbitrary @waiter to the wait queue for the nominated @page.
807 void add_page_wait_queue(struct page
*page
, wait_queue_t
*waiter
)
809 wait_queue_head_t
*q
= page_waitqueue(page
);
812 spin_lock_irqsave(&q
->lock
, flags
);
813 __add_wait_queue(q
, waiter
);
814 spin_unlock_irqrestore(&q
->lock
, flags
);
816 EXPORT_SYMBOL_GPL(add_page_wait_queue
);
819 * unlock_page - unlock a locked page
822 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
823 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
824 * mechanism between PageLocked pages and PageWriteback pages is shared.
825 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
827 * The mb is necessary to enforce ordering between the clear_bit and the read
828 * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
830 void unlock_page(struct page
*page
)
832 page
= compound_head(page
);
833 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
834 clear_bit_unlock(PG_locked
, &page
->flags
);
835 smp_mb__after_atomic();
836 wake_up_page(page
, PG_locked
);
838 EXPORT_SYMBOL(unlock_page
);
841 * end_page_writeback - end writeback against a page
844 void end_page_writeback(struct page
*page
)
847 * TestClearPageReclaim could be used here but it is an atomic
848 * operation and overkill in this particular case. Failing to
849 * shuffle a page marked for immediate reclaim is too mild to
850 * justify taking an atomic operation penalty at the end of
851 * ever page writeback.
853 if (PageReclaim(page
)) {
854 ClearPageReclaim(page
);
855 rotate_reclaimable_page(page
);
858 if (!test_clear_page_writeback(page
))
861 smp_mb__after_atomic();
862 wake_up_page(page
, PG_writeback
);
864 EXPORT_SYMBOL(end_page_writeback
);
867 * After completing I/O on a page, call this routine to update the page
868 * flags appropriately
870 void page_endio(struct page
*page
, int rw
, int err
)
874 SetPageUptodate(page
);
876 ClearPageUptodate(page
);
880 } else { /* rw == WRITE */
884 mapping_set_error(page
->mapping
, err
);
886 end_page_writeback(page
);
889 EXPORT_SYMBOL_GPL(page_endio
);
892 * __lock_page - get a lock on the page, assuming we need to sleep to get it
893 * @page: the page to lock
895 void __lock_page(struct page
*page
)
897 struct page
*page_head
= compound_head(page
);
898 DEFINE_WAIT_BIT(wait
, &page_head
->flags
, PG_locked
);
900 __wait_on_bit_lock(page_waitqueue(page_head
), &wait
, bit_wait_io
,
901 TASK_UNINTERRUPTIBLE
);
903 EXPORT_SYMBOL(__lock_page
);
905 int __lock_page_killable(struct page
*page
)
907 struct page
*page_head
= compound_head(page
);
908 DEFINE_WAIT_BIT(wait
, &page_head
->flags
, PG_locked
);
910 return __wait_on_bit_lock(page_waitqueue(page_head
), &wait
,
911 bit_wait_io
, TASK_KILLABLE
);
913 EXPORT_SYMBOL_GPL(__lock_page_killable
);
917 * 1 - page is locked; mmap_sem is still held.
918 * 0 - page is not locked.
919 * mmap_sem has been released (up_read()), unless flags had both
920 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
921 * which case mmap_sem is still held.
923 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
924 * with the page locked and the mmap_sem unperturbed.
926 int __lock_page_or_retry(struct page
*page
, struct mm_struct
*mm
,
929 if (flags
& FAULT_FLAG_ALLOW_RETRY
) {
931 * CAUTION! In this case, mmap_sem is not released
932 * even though return 0.
934 if (flags
& FAULT_FLAG_RETRY_NOWAIT
)
937 up_read(&mm
->mmap_sem
);
938 if (flags
& FAULT_FLAG_KILLABLE
)
939 wait_on_page_locked_killable(page
);
941 wait_on_page_locked(page
);
944 if (flags
& FAULT_FLAG_KILLABLE
) {
947 ret
= __lock_page_killable(page
);
949 up_read(&mm
->mmap_sem
);
959 * page_cache_next_hole - find the next hole (not-present entry)
962 * @max_scan: maximum range to search
964 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
965 * lowest indexed hole.
967 * Returns: the index of the hole if found, otherwise returns an index
968 * outside of the set specified (in which case 'return - index >=
969 * max_scan' will be true). In rare cases of index wrap-around, 0 will
972 * page_cache_next_hole may be called under rcu_read_lock. However,
973 * like radix_tree_gang_lookup, this will not atomically search a
974 * snapshot of the tree at a single point in time. For example, if a
975 * hole is created at index 5, then subsequently a hole is created at
976 * index 10, page_cache_next_hole covering both indexes may return 10
977 * if called under rcu_read_lock.
979 pgoff_t
page_cache_next_hole(struct address_space
*mapping
,
980 pgoff_t index
, unsigned long max_scan
)
984 for (i
= 0; i
< max_scan
; i
++) {
987 page
= radix_tree_lookup(&mapping
->page_tree
, index
);
988 if (!page
|| radix_tree_exceptional_entry(page
))
997 EXPORT_SYMBOL(page_cache_next_hole
);
1000 * page_cache_prev_hole - find the prev hole (not-present entry)
1003 * @max_scan: maximum range to search
1005 * Search backwards in the range [max(index-max_scan+1, 0), index] for
1008 * Returns: the index of the hole if found, otherwise returns an index
1009 * outside of the set specified (in which case 'index - return >=
1010 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
1013 * page_cache_prev_hole may be called under rcu_read_lock. However,
1014 * like radix_tree_gang_lookup, this will not atomically search a
1015 * snapshot of the tree at a single point in time. For example, if a
1016 * hole is created at index 10, then subsequently a hole is created at
1017 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1018 * called under rcu_read_lock.
1020 pgoff_t
page_cache_prev_hole(struct address_space
*mapping
,
1021 pgoff_t index
, unsigned long max_scan
)
1025 for (i
= 0; i
< max_scan
; i
++) {
1028 page
= radix_tree_lookup(&mapping
->page_tree
, index
);
1029 if (!page
|| radix_tree_exceptional_entry(page
))
1032 if (index
== ULONG_MAX
)
1038 EXPORT_SYMBOL(page_cache_prev_hole
);
1041 * find_get_entry - find and get a page cache entry
1042 * @mapping: the address_space to search
1043 * @offset: the page cache index
1045 * Looks up the page cache slot at @mapping & @offset. If there is a
1046 * page cache page, it is returned with an increased refcount.
1048 * If the slot holds a shadow entry of a previously evicted page, or a
1049 * swap entry from shmem/tmpfs, it is returned.
1051 * Otherwise, %NULL is returned.
1053 struct page
*find_get_entry(struct address_space
*mapping
, pgoff_t offset
)
1061 pagep
= radix_tree_lookup_slot(&mapping
->page_tree
, offset
);
1063 page
= radix_tree_deref_slot(pagep
);
1064 if (unlikely(!page
))
1066 if (radix_tree_exception(page
)) {
1067 if (radix_tree_deref_retry(page
))
1070 * A shadow entry of a recently evicted page,
1071 * or a swap entry from shmem/tmpfs. Return
1072 * it without attempting to raise page count.
1076 if (!page_cache_get_speculative(page
))
1080 * Has the page moved?
1081 * This is part of the lockless pagecache protocol. See
1082 * include/linux/pagemap.h for details.
1084 if (unlikely(page
!= *pagep
)) {
1094 EXPORT_SYMBOL(find_get_entry
);
1097 * find_lock_entry - locate, pin and lock a page cache entry
1098 * @mapping: the address_space to search
1099 * @offset: the page cache index
1101 * Looks up the page cache slot at @mapping & @offset. If there is a
1102 * page cache page, it is returned locked and with an increased
1105 * If the slot holds a shadow entry of a previously evicted page, or a
1106 * swap entry from shmem/tmpfs, it is returned.
1108 * Otherwise, %NULL is returned.
1110 * find_lock_entry() may sleep.
1112 struct page
*find_lock_entry(struct address_space
*mapping
, pgoff_t offset
)
1117 page
= find_get_entry(mapping
, offset
);
1118 if (page
&& !radix_tree_exception(page
)) {
1120 /* Has the page been truncated? */
1121 if (unlikely(page
->mapping
!= mapping
)) {
1126 VM_BUG_ON_PAGE(page
->index
!= offset
, page
);
1130 EXPORT_SYMBOL(find_lock_entry
);
1133 * pagecache_get_page - find and get a page reference
1134 * @mapping: the address_space to search
1135 * @offset: the page index
1136 * @fgp_flags: PCG flags
1137 * @gfp_mask: gfp mask to use for the page cache data page allocation
1139 * Looks up the page cache slot at @mapping & @offset.
1141 * PCG flags modify how the page is returned.
1143 * FGP_ACCESSED: the page will be marked accessed
1144 * FGP_LOCK: Page is return locked
1145 * FGP_CREAT: If page is not present then a new page is allocated using
1146 * @gfp_mask and added to the page cache and the VM's LRU
1147 * list. The page is returned locked and with an increased
1148 * refcount. Otherwise, %NULL is returned.
1150 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1151 * if the GFP flags specified for FGP_CREAT are atomic.
1153 * If there is a page cache page, it is returned with an increased refcount.
1155 struct page
*pagecache_get_page(struct address_space
*mapping
, pgoff_t offset
,
1156 int fgp_flags
, gfp_t gfp_mask
)
1161 page
= find_get_entry(mapping
, offset
);
1162 if (radix_tree_exceptional_entry(page
))
1167 if (fgp_flags
& FGP_LOCK
) {
1168 if (fgp_flags
& FGP_NOWAIT
) {
1169 if (!trylock_page(page
)) {
1177 /* Has the page been truncated? */
1178 if (unlikely(page
->mapping
!= mapping
)) {
1183 VM_BUG_ON_PAGE(page
->index
!= offset
, page
);
1186 if (page
&& (fgp_flags
& FGP_ACCESSED
))
1187 mark_page_accessed(page
);
1190 if (!page
&& (fgp_flags
& FGP_CREAT
)) {
1192 if ((fgp_flags
& FGP_WRITE
) && mapping_cap_account_dirty(mapping
))
1193 gfp_mask
|= __GFP_WRITE
;
1194 if (fgp_flags
& FGP_NOFS
)
1195 gfp_mask
&= ~__GFP_FS
;
1197 page
= __page_cache_alloc(gfp_mask
);
1201 if (WARN_ON_ONCE(!(fgp_flags
& FGP_LOCK
)))
1202 fgp_flags
|= FGP_LOCK
;
1204 /* Init accessed so avoid atomic mark_page_accessed later */
1205 if (fgp_flags
& FGP_ACCESSED
)
1206 __SetPageReferenced(page
);
1208 err
= add_to_page_cache_lru(page
, mapping
, offset
,
1209 gfp_mask
& GFP_RECLAIM_MASK
);
1210 if (unlikely(err
)) {
1220 EXPORT_SYMBOL(pagecache_get_page
);
1223 * find_get_entries - gang pagecache lookup
1224 * @mapping: The address_space to search
1225 * @start: The starting page cache index
1226 * @nr_entries: The maximum number of entries
1227 * @entries: Where the resulting entries are placed
1228 * @indices: The cache indices corresponding to the entries in @entries
1230 * find_get_entries() will search for and return a group of up to
1231 * @nr_entries entries in the mapping. The entries are placed at
1232 * @entries. find_get_entries() takes a reference against any actual
1235 * The search returns a group of mapping-contiguous page cache entries
1236 * with ascending indexes. There may be holes in the indices due to
1237 * not-present pages.
1239 * Any shadow entries of evicted pages, or swap entries from
1240 * shmem/tmpfs, are included in the returned array.
1242 * find_get_entries() returns the number of pages and shadow entries
1245 unsigned find_get_entries(struct address_space
*mapping
,
1246 pgoff_t start
, unsigned int nr_entries
,
1247 struct page
**entries
, pgoff_t
*indices
)
1250 unsigned int ret
= 0;
1251 struct radix_tree_iter iter
;
1257 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, start
) {
1260 page
= radix_tree_deref_slot(slot
);
1261 if (unlikely(!page
))
1263 if (radix_tree_exception(page
)) {
1264 if (radix_tree_deref_retry(page
)) {
1265 slot
= radix_tree_iter_retry(&iter
);
1269 * A shadow entry of a recently evicted page, a swap
1270 * entry from shmem/tmpfs or a DAX entry. Return it
1271 * without attempting to raise page count.
1275 if (!page_cache_get_speculative(page
))
1278 /* Has the page moved? */
1279 if (unlikely(page
!= *slot
)) {
1284 indices
[ret
] = iter
.index
;
1285 entries
[ret
] = page
;
1286 if (++ret
== nr_entries
)
1294 * find_get_pages - gang pagecache lookup
1295 * @mapping: The address_space to search
1296 * @start: The starting page index
1297 * @nr_pages: The maximum number of pages
1298 * @pages: Where the resulting pages are placed
1300 * find_get_pages() will search for and return a group of up to
1301 * @nr_pages pages in the mapping. The pages are placed at @pages.
1302 * find_get_pages() takes a reference against the returned pages.
1304 * The search returns a group of mapping-contiguous pages with ascending
1305 * indexes. There may be holes in the indices due to not-present pages.
1307 * find_get_pages() returns the number of pages which were found.
1309 unsigned find_get_pages(struct address_space
*mapping
, pgoff_t start
,
1310 unsigned int nr_pages
, struct page
**pages
)
1312 struct radix_tree_iter iter
;
1316 if (unlikely(!nr_pages
))
1320 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, start
) {
1323 page
= radix_tree_deref_slot(slot
);
1324 if (unlikely(!page
))
1327 if (radix_tree_exception(page
)) {
1328 if (radix_tree_deref_retry(page
)) {
1329 slot
= radix_tree_iter_retry(&iter
);
1333 * A shadow entry of a recently evicted page,
1334 * or a swap entry from shmem/tmpfs. Skip
1340 if (!page_cache_get_speculative(page
))
1343 /* Has the page moved? */
1344 if (unlikely(page
!= *slot
)) {
1350 if (++ret
== nr_pages
)
1359 * find_get_pages_contig - gang contiguous pagecache lookup
1360 * @mapping: The address_space to search
1361 * @index: The starting page index
1362 * @nr_pages: The maximum number of pages
1363 * @pages: Where the resulting pages are placed
1365 * find_get_pages_contig() works exactly like find_get_pages(), except
1366 * that the returned number of pages are guaranteed to be contiguous.
1368 * find_get_pages_contig() returns the number of pages which were found.
1370 unsigned find_get_pages_contig(struct address_space
*mapping
, pgoff_t index
,
1371 unsigned int nr_pages
, struct page
**pages
)
1373 struct radix_tree_iter iter
;
1375 unsigned int ret
= 0;
1377 if (unlikely(!nr_pages
))
1381 radix_tree_for_each_contig(slot
, &mapping
->page_tree
, &iter
, index
) {
1384 page
= radix_tree_deref_slot(slot
);
1385 /* The hole, there no reason to continue */
1386 if (unlikely(!page
))
1389 if (radix_tree_exception(page
)) {
1390 if (radix_tree_deref_retry(page
)) {
1391 slot
= radix_tree_iter_retry(&iter
);
1395 * A shadow entry of a recently evicted page,
1396 * or a swap entry from shmem/tmpfs. Stop
1397 * looking for contiguous pages.
1402 if (!page_cache_get_speculative(page
))
1405 /* Has the page moved? */
1406 if (unlikely(page
!= *slot
)) {
1412 * must check mapping and index after taking the ref.
1413 * otherwise we can get both false positives and false
1414 * negatives, which is just confusing to the caller.
1416 if (page
->mapping
== NULL
|| page
->index
!= iter
.index
) {
1422 if (++ret
== nr_pages
)
1428 EXPORT_SYMBOL(find_get_pages_contig
);
1431 * find_get_pages_tag - find and return pages that match @tag
1432 * @mapping: the address_space to search
1433 * @index: the starting page index
1434 * @tag: the tag index
1435 * @nr_pages: the maximum number of pages
1436 * @pages: where the resulting pages are placed
1438 * Like find_get_pages, except we only return pages which are tagged with
1439 * @tag. We update @index to index the next page for the traversal.
1441 unsigned find_get_pages_tag(struct address_space
*mapping
, pgoff_t
*index
,
1442 int tag
, unsigned int nr_pages
, struct page
**pages
)
1444 struct radix_tree_iter iter
;
1448 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
)) {
1462 slot
= radix_tree_iter_retry(&iter
);
1466 * A shadow entry of a recently evicted page.
1468 * Those entries should never be tagged, but
1469 * this tree walk is lockless and the tags are
1470 * looked up in bulk, one radix tree node at a
1471 * time, so there is a sizable window for page
1472 * reclaim to evict a page we saw tagged.
1479 if (!page_cache_get_speculative(page
))
1482 /* Has the page moved? */
1483 if (unlikely(page
!= *slot
)) {
1489 if (++ret
== nr_pages
)
1496 *index
= pages
[ret
- 1]->index
+ 1;
1500 EXPORT_SYMBOL(find_get_pages_tag
);
1503 * find_get_entries_tag - find and return entries that match @tag
1504 * @mapping: the address_space to search
1505 * @start: the starting page cache index
1506 * @tag: the tag index
1507 * @nr_entries: the maximum number of entries
1508 * @entries: where the resulting entries are placed
1509 * @indices: the cache indices corresponding to the entries in @entries
1511 * Like find_get_entries, except we only return entries which are tagged with
1514 unsigned find_get_entries_tag(struct address_space
*mapping
, pgoff_t start
,
1515 int tag
, unsigned int nr_entries
,
1516 struct page
**entries
, pgoff_t
*indices
)
1519 unsigned int ret
= 0;
1520 struct radix_tree_iter iter
;
1526 radix_tree_for_each_tagged(slot
, &mapping
->page_tree
,
1527 &iter
, start
, tag
) {
1530 page
= radix_tree_deref_slot(slot
);
1531 if (unlikely(!page
))
1533 if (radix_tree_exception(page
)) {
1534 if (radix_tree_deref_retry(page
)) {
1535 slot
= radix_tree_iter_retry(&iter
);
1540 * A shadow entry of a recently evicted page, a swap
1541 * entry from shmem/tmpfs or a DAX entry. Return it
1542 * without attempting to raise page count.
1546 if (!page_cache_get_speculative(page
))
1549 /* Has the page moved? */
1550 if (unlikely(page
!= *slot
)) {
1555 indices
[ret
] = iter
.index
;
1556 entries
[ret
] = page
;
1557 if (++ret
== nr_entries
)
1563 EXPORT_SYMBOL(find_get_entries_tag
);
1566 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1567 * a _large_ part of the i/o request. Imagine the worst scenario:
1569 * ---R__________________________________________B__________
1570 * ^ reading here ^ bad block(assume 4k)
1572 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1573 * => failing the whole request => read(R) => read(R+1) =>
1574 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1575 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1576 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1578 * It is going insane. Fix it by quickly scaling down the readahead size.
1580 static void shrink_readahead_size_eio(struct file
*filp
,
1581 struct file_ra_state
*ra
)
1587 * do_generic_file_read - generic file read routine
1588 * @filp: the file to read
1589 * @ppos: current file position
1590 * @iter: data destination
1591 * @written: already copied
1593 * This is a generic file read routine, and uses the
1594 * mapping->a_ops->readpage() function for the actual low-level stuff.
1596 * This is really ugly. But the goto's actually try to clarify some
1597 * of the logic when it comes to error handling etc.
1599 static ssize_t
do_generic_file_read(struct file
*filp
, loff_t
*ppos
,
1600 struct iov_iter
*iter
, ssize_t written
)
1602 struct address_space
*mapping
= filp
->f_mapping
;
1603 struct inode
*inode
= mapping
->host
;
1604 struct file_ra_state
*ra
= &filp
->f_ra
;
1608 unsigned long offset
; /* offset into pagecache page */
1609 unsigned int prev_offset
;
1612 index
= *ppos
>> PAGE_SHIFT
;
1613 prev_index
= ra
->prev_pos
>> PAGE_SHIFT
;
1614 prev_offset
= ra
->prev_pos
& (PAGE_SIZE
-1);
1615 last_index
= (*ppos
+ iter
->count
+ PAGE_SIZE
-1) >> PAGE_SHIFT
;
1616 offset
= *ppos
& ~PAGE_MASK
;
1622 unsigned long nr
, ret
;
1626 page
= find_get_page(mapping
, index
);
1628 page_cache_sync_readahead(mapping
,
1630 index
, last_index
- index
);
1631 page
= find_get_page(mapping
, index
);
1632 if (unlikely(page
== NULL
))
1633 goto no_cached_page
;
1635 if (PageReadahead(page
)) {
1636 page_cache_async_readahead(mapping
,
1638 index
, last_index
- index
);
1640 if (!PageUptodate(page
)) {
1642 * See comment in do_read_cache_page on why
1643 * wait_on_page_locked is used to avoid unnecessarily
1644 * serialisations and why it's safe.
1646 wait_on_page_locked_killable(page
);
1647 if (PageUptodate(page
))
1650 if (inode
->i_blkbits
== PAGE_SHIFT
||
1651 !mapping
->a_ops
->is_partially_uptodate
)
1652 goto page_not_up_to_date
;
1653 if (!trylock_page(page
))
1654 goto page_not_up_to_date
;
1655 /* Did it get truncated before we got the lock? */
1657 goto page_not_up_to_date_locked
;
1658 if (!mapping
->a_ops
->is_partially_uptodate(page
,
1659 offset
, iter
->count
))
1660 goto page_not_up_to_date_locked
;
1665 * i_size must be checked after we know the page is Uptodate.
1667 * Checking i_size after the check allows us to calculate
1668 * the correct value for "nr", which means the zero-filled
1669 * part of the page is not copied back to userspace (unless
1670 * another truncate extends the file - this is desired though).
1673 isize
= i_size_read(inode
);
1674 end_index
= (isize
- 1) >> PAGE_SHIFT
;
1675 if (unlikely(!isize
|| index
> end_index
)) {
1680 /* nr is the maximum number of bytes to copy from this page */
1682 if (index
== end_index
) {
1683 nr
= ((isize
- 1) & ~PAGE_MASK
) + 1;
1691 /* If users can be writing to this page using arbitrary
1692 * virtual addresses, take care about potential aliasing
1693 * before reading the page on the kernel side.
1695 if (mapping_writably_mapped(mapping
))
1696 flush_dcache_page(page
);
1699 * When a sequential read accesses a page several times,
1700 * only mark it as accessed the first time.
1702 if (prev_index
!= index
|| offset
!= prev_offset
)
1703 mark_page_accessed(page
);
1707 * Ok, we have the page, and it's up-to-date, so
1708 * now we can copy it to user space...
1711 ret
= copy_page_to_iter(page
, offset
, nr
, iter
);
1713 index
+= offset
>> PAGE_SHIFT
;
1714 offset
&= ~PAGE_MASK
;
1715 prev_offset
= offset
;
1719 if (!iov_iter_count(iter
))
1727 page_not_up_to_date
:
1728 /* Get exclusive access to the page ... */
1729 error
= lock_page_killable(page
);
1730 if (unlikely(error
))
1731 goto readpage_error
;
1733 page_not_up_to_date_locked
:
1734 /* Did it get truncated before we got the lock? */
1735 if (!page
->mapping
) {
1741 /* Did somebody else fill it already? */
1742 if (PageUptodate(page
)) {
1749 * A previous I/O error may have been due to temporary
1750 * failures, eg. multipath errors.
1751 * PG_error will be set again if readpage fails.
1753 ClearPageError(page
);
1754 /* Start the actual read. The read will unlock the page. */
1755 error
= mapping
->a_ops
->readpage(filp
, page
);
1757 if (unlikely(error
)) {
1758 if (error
== AOP_TRUNCATED_PAGE
) {
1763 goto readpage_error
;
1766 if (!PageUptodate(page
)) {
1767 error
= lock_page_killable(page
);
1768 if (unlikely(error
))
1769 goto readpage_error
;
1770 if (!PageUptodate(page
)) {
1771 if (page
->mapping
== NULL
) {
1773 * invalidate_mapping_pages got it
1780 shrink_readahead_size_eio(filp
, ra
);
1782 goto readpage_error
;
1790 /* UHHUH! A synchronous read error occurred. Report it */
1796 * Ok, it wasn't cached, so we need to create a new
1799 page
= page_cache_alloc_cold(mapping
);
1804 error
= add_to_page_cache_lru(page
, mapping
, index
,
1805 mapping_gfp_constraint(mapping
, GFP_KERNEL
));
1808 if (error
== -EEXIST
) {
1818 ra
->prev_pos
= prev_index
;
1819 ra
->prev_pos
<<= PAGE_SHIFT
;
1820 ra
->prev_pos
|= prev_offset
;
1822 *ppos
= ((loff_t
)index
<< PAGE_SHIFT
) + offset
;
1823 file_accessed(filp
);
1824 return written
? written
: error
;
1828 * generic_file_read_iter - generic filesystem read routine
1829 * @iocb: kernel I/O control block
1830 * @iter: destination for the data read
1832 * This is the "read_iter()" routine for all filesystems
1833 * that can use the page cache directly.
1836 generic_file_read_iter(struct kiocb
*iocb
, struct iov_iter
*iter
)
1838 struct file
*file
= iocb
->ki_filp
;
1840 size_t count
= iov_iter_count(iter
);
1843 goto out
; /* skip atime */
1845 if (iocb
->ki_flags
& IOCB_DIRECT
) {
1846 struct address_space
*mapping
= file
->f_mapping
;
1847 struct inode
*inode
= mapping
->host
;
1850 size
= i_size_read(inode
);
1851 retval
= filemap_write_and_wait_range(mapping
, iocb
->ki_pos
,
1852 iocb
->ki_pos
+ count
- 1);
1854 struct iov_iter data
= *iter
;
1855 retval
= mapping
->a_ops
->direct_IO(iocb
, &data
);
1859 iocb
->ki_pos
+= retval
;
1860 iov_iter_advance(iter
, retval
);
1864 * Btrfs can have a short DIO read if we encounter
1865 * compressed extents, so if there was an error, or if
1866 * we've already read everything we wanted to, or if
1867 * there was a short read because we hit EOF, go ahead
1868 * and return. Otherwise fallthrough to buffered io for
1869 * the rest of the read. Buffered reads will not work for
1870 * DAX files, so don't bother trying.
1872 if (retval
< 0 || !iov_iter_count(iter
) || iocb
->ki_pos
>= size
||
1874 file_accessed(file
);
1879 retval
= do_generic_file_read(file
, &iocb
->ki_pos
, iter
, retval
);
1883 EXPORT_SYMBOL(generic_file_read_iter
);
1887 * page_cache_read - adds requested page to the page cache if not already there
1888 * @file: file to read
1889 * @offset: page index
1890 * @gfp_mask: memory allocation flags
1892 * This adds the requested page to the page cache if it isn't already there,
1893 * and schedules an I/O to read in its contents from disk.
1895 static int page_cache_read(struct file
*file
, pgoff_t offset
, gfp_t gfp_mask
)
1897 struct address_space
*mapping
= file
->f_mapping
;
1902 page
= __page_cache_alloc(gfp_mask
|__GFP_COLD
);
1906 ret
= add_to_page_cache_lru(page
, mapping
, offset
, gfp_mask
& GFP_KERNEL
);
1908 ret
= mapping
->a_ops
->readpage(file
, page
);
1909 else if (ret
== -EEXIST
)
1910 ret
= 0; /* losing race to add is OK */
1914 } while (ret
== AOP_TRUNCATED_PAGE
);
1919 #define MMAP_LOTSAMISS (100)
1922 * Synchronous readahead happens when we don't even find
1923 * a page in the page cache at all.
1925 static void do_sync_mmap_readahead(struct vm_area_struct
*vma
,
1926 struct file_ra_state
*ra
,
1930 struct address_space
*mapping
= file
->f_mapping
;
1932 /* If we don't want any read-ahead, don't bother */
1933 if (vma
->vm_flags
& VM_RAND_READ
)
1938 if (vma
->vm_flags
& VM_SEQ_READ
) {
1939 page_cache_sync_readahead(mapping
, ra
, file
, offset
,
1944 /* Avoid banging the cache line if not needed */
1945 if (ra
->mmap_miss
< MMAP_LOTSAMISS
* 10)
1949 * Do we miss much more than hit in this file? If so,
1950 * stop bothering with read-ahead. It will only hurt.
1952 if (ra
->mmap_miss
> MMAP_LOTSAMISS
)
1958 ra
->start
= max_t(long, 0, offset
- ra
->ra_pages
/ 2);
1959 ra
->size
= ra
->ra_pages
;
1960 ra
->async_size
= ra
->ra_pages
/ 4;
1961 ra_submit(ra
, mapping
, file
);
1965 * Asynchronous readahead happens when we find the page and PG_readahead,
1966 * so we want to possibly extend the readahead further..
1968 static void do_async_mmap_readahead(struct vm_area_struct
*vma
,
1969 struct file_ra_state
*ra
,
1974 struct address_space
*mapping
= file
->f_mapping
;
1976 /* If we don't want any read-ahead, don't bother */
1977 if (vma
->vm_flags
& VM_RAND_READ
)
1979 if (ra
->mmap_miss
> 0)
1981 if (PageReadahead(page
))
1982 page_cache_async_readahead(mapping
, ra
, file
,
1983 page
, offset
, ra
->ra_pages
);
1987 * filemap_fault - read in file data for page fault handling
1988 * @vma: vma in which the fault was taken
1989 * @vmf: struct vm_fault containing details of the fault
1991 * filemap_fault() is invoked via the vma operations vector for a
1992 * mapped memory region to read in file data during a page fault.
1994 * The goto's are kind of ugly, but this streamlines the normal case of having
1995 * it in the page cache, and handles the special cases reasonably without
1996 * having a lot of duplicated code.
1998 * vma->vm_mm->mmap_sem must be held on entry.
2000 * If our return value has VM_FAULT_RETRY set, it's because
2001 * lock_page_or_retry() returned 0.
2002 * The mmap_sem has usually been released in this case.
2003 * See __lock_page_or_retry() for the exception.
2005 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2006 * has not been released.
2008 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2010 int filemap_fault(struct vm_area_struct
*vma
, struct vm_fault
*vmf
)
2013 struct file
*file
= vma
->vm_file
;
2014 struct address_space
*mapping
= file
->f_mapping
;
2015 struct file_ra_state
*ra
= &file
->f_ra
;
2016 struct inode
*inode
= mapping
->host
;
2017 pgoff_t offset
= vmf
->pgoff
;
2022 size
= round_up(i_size_read(inode
), PAGE_SIZE
);
2023 if (offset
>= size
>> PAGE_SHIFT
)
2024 return VM_FAULT_SIGBUS
;
2027 * Do we have something in the page cache already?
2029 page
= find_get_page(mapping
, offset
);
2030 if (likely(page
) && !(vmf
->flags
& FAULT_FLAG_TRIED
)) {
2032 * We found the page, so try async readahead before
2033 * waiting for the lock.
2035 do_async_mmap_readahead(vma
, ra
, file
, page
, offset
);
2037 /* No page in the page cache at all */
2038 do_sync_mmap_readahead(vma
, ra
, file
, offset
);
2039 count_vm_event(PGMAJFAULT
);
2040 mem_cgroup_count_vm_event(vma
->vm_mm
, PGMAJFAULT
);
2041 ret
= VM_FAULT_MAJOR
;
2043 page
= find_get_page(mapping
, offset
);
2045 goto no_cached_page
;
2048 if (!lock_page_or_retry(page
, vma
->vm_mm
, vmf
->flags
)) {
2050 return ret
| VM_FAULT_RETRY
;
2053 /* Did it get truncated? */
2054 if (unlikely(page
->mapping
!= mapping
)) {
2059 VM_BUG_ON_PAGE(page
->index
!= offset
, page
);
2062 * We have a locked page in the page cache, now we need to check
2063 * that it's up-to-date. If not, it is going to be due to an error.
2065 if (unlikely(!PageUptodate(page
)))
2066 goto page_not_uptodate
;
2069 * Found the page and have a reference on it.
2070 * We must recheck i_size under page lock.
2072 size
= round_up(i_size_read(inode
), PAGE_SIZE
);
2073 if (unlikely(offset
>= size
>> PAGE_SHIFT
)) {
2076 return VM_FAULT_SIGBUS
;
2080 return ret
| VM_FAULT_LOCKED
;
2084 * We're only likely to ever get here if MADV_RANDOM is in
2087 error
= page_cache_read(file
, offset
, vmf
->gfp_mask
);
2090 * The page we want has now been added to the page cache.
2091 * In the unlikely event that someone removed it in the
2092 * meantime, we'll just come back here and read it again.
2098 * An error return from page_cache_read can result if the
2099 * system is low on memory, or a problem occurs while trying
2102 if (error
== -ENOMEM
)
2103 return VM_FAULT_OOM
;
2104 return VM_FAULT_SIGBUS
;
2108 * Umm, take care of errors if the page isn't up-to-date.
2109 * Try to re-read it _once_. We do this synchronously,
2110 * because there really aren't any performance issues here
2111 * and we need to check for errors.
2113 ClearPageError(page
);
2114 error
= mapping
->a_ops
->readpage(file
, page
);
2116 wait_on_page_locked(page
);
2117 if (!PageUptodate(page
))
2122 if (!error
|| error
== AOP_TRUNCATED_PAGE
)
2125 /* Things didn't work out. Return zero to tell the mm layer so. */
2126 shrink_readahead_size_eio(file
, ra
);
2127 return VM_FAULT_SIGBUS
;
2129 EXPORT_SYMBOL(filemap_fault
);
2131 void filemap_map_pages(struct vm_area_struct
*vma
, struct vm_fault
*vmf
)
2133 struct radix_tree_iter iter
;
2135 struct file
*file
= vma
->vm_file
;
2136 struct address_space
*mapping
= file
->f_mapping
;
2139 unsigned long address
= (unsigned long) vmf
->virtual_address
;
2144 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, vmf
->pgoff
) {
2145 if (iter
.index
> vmf
->max_pgoff
)
2148 page
= radix_tree_deref_slot(slot
);
2149 if (unlikely(!page
))
2151 if (radix_tree_exception(page
)) {
2152 if (radix_tree_deref_retry(page
)) {
2153 slot
= radix_tree_iter_retry(&iter
);
2159 if (!page_cache_get_speculative(page
))
2162 /* Has the page moved? */
2163 if (unlikely(page
!= *slot
)) {
2168 if (!PageUptodate(page
) ||
2169 PageReadahead(page
) ||
2172 if (!trylock_page(page
))
2175 if (page
->mapping
!= mapping
|| !PageUptodate(page
))
2178 size
= round_up(i_size_read(mapping
->host
), PAGE_SIZE
);
2179 if (page
->index
>= size
>> PAGE_SHIFT
)
2182 pte
= vmf
->pte
+ page
->index
- vmf
->pgoff
;
2183 if (!pte_none(*pte
))
2186 if (file
->f_ra
.mmap_miss
> 0)
2187 file
->f_ra
.mmap_miss
--;
2188 addr
= address
+ (page
->index
- vmf
->pgoff
) * PAGE_SIZE
;
2189 do_set_pte(vma
, addr
, page
, pte
, false, false, true);
2197 if (iter
.index
== vmf
->max_pgoff
)
2202 EXPORT_SYMBOL(filemap_map_pages
);
2204 int filemap_page_mkwrite(struct vm_area_struct
*vma
, struct vm_fault
*vmf
)
2206 struct page
*page
= vmf
->page
;
2207 struct inode
*inode
= file_inode(vma
->vm_file
);
2208 int ret
= VM_FAULT_LOCKED
;
2210 sb_start_pagefault(inode
->i_sb
);
2211 file_update_time(vma
->vm_file
);
2213 if (page
->mapping
!= inode
->i_mapping
) {
2215 ret
= VM_FAULT_NOPAGE
;
2219 * We mark the page dirty already here so that when freeze is in
2220 * progress, we are guaranteed that writeback during freezing will
2221 * see the dirty page and writeprotect it again.
2223 set_page_dirty(page
);
2224 wait_for_stable_page(page
);
2226 sb_end_pagefault(inode
->i_sb
);
2229 EXPORT_SYMBOL(filemap_page_mkwrite
);
2231 const struct vm_operations_struct generic_file_vm_ops
= {
2232 .fault
= filemap_fault
,
2233 .map_pages
= filemap_map_pages
,
2234 .page_mkwrite
= filemap_page_mkwrite
,
2237 /* This is used for a general mmap of a disk file */
2239 int generic_file_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2241 struct address_space
*mapping
= file
->f_mapping
;
2243 if (!mapping
->a_ops
->readpage
)
2245 file_accessed(file
);
2246 vma
->vm_ops
= &generic_file_vm_ops
;
2251 * This is for filesystems which do not implement ->writepage.
2253 int generic_file_readonly_mmap(struct file
*file
, struct vm_area_struct
*vma
)
2255 if ((vma
->vm_flags
& VM_SHARED
) && (vma
->vm_flags
& VM_MAYWRITE
))
2257 return generic_file_mmap(file
, vma
);
2260 int generic_file_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2264 int generic_file_readonly_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2268 #endif /* CONFIG_MMU */
2270 EXPORT_SYMBOL(generic_file_mmap
);
2271 EXPORT_SYMBOL(generic_file_readonly_mmap
);
2273 static struct page
*wait_on_page_read(struct page
*page
)
2275 if (!IS_ERR(page
)) {
2276 wait_on_page_locked(page
);
2277 if (!PageUptodate(page
)) {
2279 page
= ERR_PTR(-EIO
);
2285 static struct page
*do_read_cache_page(struct address_space
*mapping
,
2287 int (*filler
)(void *, struct page
*),
2294 page
= find_get_page(mapping
, index
);
2296 page
= __page_cache_alloc(gfp
| __GFP_COLD
);
2298 return ERR_PTR(-ENOMEM
);
2299 err
= add_to_page_cache_lru(page
, mapping
, index
, gfp
);
2300 if (unlikely(err
)) {
2304 /* Presumably ENOMEM for radix tree node */
2305 return ERR_PTR(err
);
2309 err
= filler(data
, page
);
2312 return ERR_PTR(err
);
2315 page
= wait_on_page_read(page
);
2320 if (PageUptodate(page
))
2324 * Page is not up to date and may be locked due one of the following
2325 * case a: Page is being filled and the page lock is held
2326 * case b: Read/write error clearing the page uptodate status
2327 * case c: Truncation in progress (page locked)
2328 * case d: Reclaim in progress
2330 * Case a, the page will be up to date when the page is unlocked.
2331 * There is no need to serialise on the page lock here as the page
2332 * is pinned so the lock gives no additional protection. Even if the
2333 * the page is truncated, the data is still valid if PageUptodate as
2334 * it's a race vs truncate race.
2335 * Case b, the page will not be up to date
2336 * Case c, the page may be truncated but in itself, the data may still
2337 * be valid after IO completes as it's a read vs truncate race. The
2338 * operation must restart if the page is not uptodate on unlock but
2339 * otherwise serialising on page lock to stabilise the mapping gives
2340 * no additional guarantees to the caller as the page lock is
2341 * released before return.
2342 * Case d, similar to truncation. If reclaim holds the page lock, it
2343 * will be a race with remove_mapping that determines if the mapping
2344 * is valid on unlock but otherwise the data is valid and there is
2345 * no need to serialise with page lock.
2347 * As the page lock gives no additional guarantee, we optimistically
2348 * wait on the page to be unlocked and check if it's up to date and
2349 * use the page if it is. Otherwise, the page lock is required to
2350 * distinguish between the different cases. The motivation is that we
2351 * avoid spurious serialisations and wakeups when multiple processes
2352 * wait on the same page for IO to complete.
2354 wait_on_page_locked(page
);
2355 if (PageUptodate(page
))
2358 /* Distinguish between all the cases under the safety of the lock */
2361 /* Case c or d, restart the operation */
2362 if (!page
->mapping
) {
2368 /* Someone else locked and filled the page in a very small window */
2369 if (PageUptodate(page
)) {
2376 mark_page_accessed(page
);
2381 * read_cache_page - read into page cache, fill it if needed
2382 * @mapping: the page's address_space
2383 * @index: the page index
2384 * @filler: function to perform the read
2385 * @data: first arg to filler(data, page) function, often left as NULL
2387 * Read into the page cache. If a page already exists, and PageUptodate() is
2388 * not set, try to fill the page and wait for it to become unlocked.
2390 * If the page does not get brought uptodate, return -EIO.
2392 struct page
*read_cache_page(struct address_space
*mapping
,
2394 int (*filler
)(void *, struct page
*),
2397 return do_read_cache_page(mapping
, index
, filler
, data
, mapping_gfp_mask(mapping
));
2399 EXPORT_SYMBOL(read_cache_page
);
2402 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2403 * @mapping: the page's address_space
2404 * @index: the page index
2405 * @gfp: the page allocator flags to use if allocating
2407 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2408 * any new page allocations done using the specified allocation flags.
2410 * If the page does not get brought uptodate, return -EIO.
2412 struct page
*read_cache_page_gfp(struct address_space
*mapping
,
2416 filler_t
*filler
= (filler_t
*)mapping
->a_ops
->readpage
;
2418 return do_read_cache_page(mapping
, index
, filler
, NULL
, gfp
);
2420 EXPORT_SYMBOL(read_cache_page_gfp
);
2423 * Performs necessary checks before doing a write
2425 * Can adjust writing position or amount of bytes to write.
2426 * Returns appropriate error code that caller should return or
2427 * zero in case that write should be allowed.
2429 inline ssize_t
generic_write_checks(struct kiocb
*iocb
, struct iov_iter
*from
)
2431 struct file
*file
= iocb
->ki_filp
;
2432 struct inode
*inode
= file
->f_mapping
->host
;
2433 unsigned long limit
= rlimit(RLIMIT_FSIZE
);
2436 if (!iov_iter_count(from
))
2439 /* FIXME: this is for backwards compatibility with 2.4 */
2440 if (iocb
->ki_flags
& IOCB_APPEND
)
2441 iocb
->ki_pos
= i_size_read(inode
);
2445 if (limit
!= RLIM_INFINITY
) {
2446 if (iocb
->ki_pos
>= limit
) {
2447 send_sig(SIGXFSZ
, current
, 0);
2450 iov_iter_truncate(from
, limit
- (unsigned long)pos
);
2456 if (unlikely(pos
+ iov_iter_count(from
) > MAX_NON_LFS
&&
2457 !(file
->f_flags
& O_LARGEFILE
))) {
2458 if (pos
>= MAX_NON_LFS
)
2460 iov_iter_truncate(from
, MAX_NON_LFS
- (unsigned long)pos
);
2464 * Are we about to exceed the fs block limit ?
2466 * If we have written data it becomes a short write. If we have
2467 * exceeded without writing data we send a signal and return EFBIG.
2468 * Linus frestrict idea will clean these up nicely..
2470 if (unlikely(pos
>= inode
->i_sb
->s_maxbytes
))
2473 iov_iter_truncate(from
, inode
->i_sb
->s_maxbytes
- pos
);
2474 return iov_iter_count(from
);
2476 EXPORT_SYMBOL(generic_write_checks
);
2478 int pagecache_write_begin(struct file
*file
, struct address_space
*mapping
,
2479 loff_t pos
, unsigned len
, unsigned flags
,
2480 struct page
**pagep
, void **fsdata
)
2482 const struct address_space_operations
*aops
= mapping
->a_ops
;
2484 return aops
->write_begin(file
, mapping
, pos
, len
, flags
,
2487 EXPORT_SYMBOL(pagecache_write_begin
);
2489 int pagecache_write_end(struct file
*file
, struct address_space
*mapping
,
2490 loff_t pos
, unsigned len
, unsigned copied
,
2491 struct page
*page
, void *fsdata
)
2493 const struct address_space_operations
*aops
= mapping
->a_ops
;
2495 return aops
->write_end(file
, mapping
, pos
, len
, copied
, page
, fsdata
);
2497 EXPORT_SYMBOL(pagecache_write_end
);
2500 generic_file_direct_write(struct kiocb
*iocb
, struct iov_iter
*from
)
2502 struct file
*file
= iocb
->ki_filp
;
2503 struct address_space
*mapping
= file
->f_mapping
;
2504 struct inode
*inode
= mapping
->host
;
2505 loff_t pos
= iocb
->ki_pos
;
2509 struct iov_iter data
;
2511 write_len
= iov_iter_count(from
);
2512 end
= (pos
+ write_len
- 1) >> PAGE_SHIFT
;
2514 written
= filemap_write_and_wait_range(mapping
, pos
, pos
+ write_len
- 1);
2519 * After a write we want buffered reads to be sure to go to disk to get
2520 * the new data. We invalidate clean cached page from the region we're
2521 * about to write. We do this *before* the write so that we can return
2522 * without clobbering -EIOCBQUEUED from ->direct_IO().
2524 if (mapping
->nrpages
) {
2525 written
= invalidate_inode_pages2_range(mapping
,
2526 pos
>> PAGE_SHIFT
, end
);
2528 * If a page can not be invalidated, return 0 to fall back
2529 * to buffered write.
2532 if (written
== -EBUSY
)
2539 written
= mapping
->a_ops
->direct_IO(iocb
, &data
);
2542 * Finally, try again to invalidate clean pages which might have been
2543 * cached by non-direct readahead, or faulted in by get_user_pages()
2544 * if the source of the write was an mmap'ed region of the file
2545 * we're writing. Either one is a pretty crazy thing to do,
2546 * so we don't support it 100%. If this invalidation
2547 * fails, tough, the write still worked...
2549 if (mapping
->nrpages
) {
2550 invalidate_inode_pages2_range(mapping
,
2551 pos
>> PAGE_SHIFT
, end
);
2556 iov_iter_advance(from
, written
);
2557 if (pos
> i_size_read(inode
) && !S_ISBLK(inode
->i_mode
)) {
2558 i_size_write(inode
, pos
);
2559 mark_inode_dirty(inode
);
2566 EXPORT_SYMBOL(generic_file_direct_write
);
2569 * Find or create a page at the given pagecache position. Return the locked
2570 * page. This function is specifically for buffered writes.
2572 struct page
*grab_cache_page_write_begin(struct address_space
*mapping
,
2573 pgoff_t index
, unsigned flags
)
2576 int fgp_flags
= FGP_LOCK
|FGP_WRITE
|FGP_CREAT
;
2578 if (flags
& AOP_FLAG_NOFS
)
2579 fgp_flags
|= FGP_NOFS
;
2581 page
= pagecache_get_page(mapping
, index
, fgp_flags
,
2582 mapping_gfp_mask(mapping
));
2584 wait_for_stable_page(page
);
2588 EXPORT_SYMBOL(grab_cache_page_write_begin
);
2590 ssize_t
generic_perform_write(struct file
*file
,
2591 struct iov_iter
*i
, loff_t pos
)
2593 struct address_space
*mapping
= file
->f_mapping
;
2594 const struct address_space_operations
*a_ops
= mapping
->a_ops
;
2596 ssize_t written
= 0;
2597 unsigned int flags
= 0;
2600 * Copies from kernel address space cannot fail (NFSD is a big user).
2602 if (!iter_is_iovec(i
))
2603 flags
|= AOP_FLAG_UNINTERRUPTIBLE
;
2607 unsigned long offset
; /* Offset into pagecache page */
2608 unsigned long bytes
; /* Bytes to write to page */
2609 size_t copied
; /* Bytes copied from user */
2612 offset
= (pos
& (PAGE_SIZE
- 1));
2613 bytes
= min_t(unsigned long, PAGE_SIZE
- offset
,
2618 * Bring in the user page that we will copy from _first_.
2619 * Otherwise there's a nasty deadlock on copying from the
2620 * same page as we're writing to, without it being marked
2623 * Not only is this an optimisation, but it is also required
2624 * to check that the address is actually valid, when atomic
2625 * usercopies are used, below.
2627 if (unlikely(iov_iter_fault_in_readable(i
, bytes
))) {
2632 if (fatal_signal_pending(current
)) {
2637 status
= a_ops
->write_begin(file
, mapping
, pos
, bytes
, flags
,
2639 if (unlikely(status
< 0))
2642 if (mapping_writably_mapped(mapping
))
2643 flush_dcache_page(page
);
2645 copied
= iov_iter_copy_from_user_atomic(page
, i
, offset
, bytes
);
2646 flush_dcache_page(page
);
2648 status
= a_ops
->write_end(file
, mapping
, pos
, bytes
, copied
,
2650 if (unlikely(status
< 0))
2656 iov_iter_advance(i
, copied
);
2657 if (unlikely(copied
== 0)) {
2659 * If we were unable to copy any data at all, we must
2660 * fall back to a single segment length write.
2662 * If we didn't fallback here, we could livelock
2663 * because not all segments in the iov can be copied at
2664 * once without a pagefault.
2666 bytes
= min_t(unsigned long, PAGE_SIZE
- offset
,
2667 iov_iter_single_seg_count(i
));
2673 balance_dirty_pages_ratelimited(mapping
);
2674 } while (iov_iter_count(i
));
2676 return written
? written
: status
;
2678 EXPORT_SYMBOL(generic_perform_write
);
2681 * __generic_file_write_iter - write data to a file
2682 * @iocb: IO state structure (file, offset, etc.)
2683 * @from: iov_iter with data to write
2685 * This function does all the work needed for actually writing data to a
2686 * file. It does all basic checks, removes SUID from the file, updates
2687 * modification times and calls proper subroutines depending on whether we
2688 * do direct IO or a standard buffered write.
2690 * It expects i_mutex to be grabbed unless we work on a block device or similar
2691 * object which does not need locking at all.
2693 * This function does *not* take care of syncing data in case of O_SYNC write.
2694 * A caller has to handle it. This is mainly due to the fact that we want to
2695 * avoid syncing under i_mutex.
2697 ssize_t
__generic_file_write_iter(struct kiocb
*iocb
, struct iov_iter
*from
)
2699 struct file
*file
= iocb
->ki_filp
;
2700 struct address_space
* mapping
= file
->f_mapping
;
2701 struct inode
*inode
= mapping
->host
;
2702 ssize_t written
= 0;
2706 /* We can write back this queue in page reclaim */
2707 current
->backing_dev_info
= inode_to_bdi(inode
);
2708 err
= file_remove_privs(file
);
2712 err
= file_update_time(file
);
2716 if (iocb
->ki_flags
& IOCB_DIRECT
) {
2717 loff_t pos
, endbyte
;
2719 written
= generic_file_direct_write(iocb
, from
);
2721 * If the write stopped short of completing, fall back to
2722 * buffered writes. Some filesystems do this for writes to
2723 * holes, for example. For DAX files, a buffered write will
2724 * not succeed (even if it did, DAX does not handle dirty
2725 * page-cache pages correctly).
2727 if (written
< 0 || !iov_iter_count(from
) || IS_DAX(inode
))
2730 status
= generic_perform_write(file
, from
, pos
= iocb
->ki_pos
);
2732 * If generic_perform_write() returned a synchronous error
2733 * then we want to return the number of bytes which were
2734 * direct-written, or the error code if that was zero. Note
2735 * that this differs from normal direct-io semantics, which
2736 * will return -EFOO even if some bytes were written.
2738 if (unlikely(status
< 0)) {
2743 * We need to ensure that the page cache pages are written to
2744 * disk and invalidated to preserve the expected O_DIRECT
2747 endbyte
= pos
+ status
- 1;
2748 err
= filemap_write_and_wait_range(mapping
, pos
, endbyte
);
2750 iocb
->ki_pos
= endbyte
+ 1;
2752 invalidate_mapping_pages(mapping
,
2754 endbyte
>> PAGE_SHIFT
);
2757 * We don't know how much we wrote, so just return
2758 * the number of bytes which were direct-written
2762 written
= generic_perform_write(file
, from
, iocb
->ki_pos
);
2763 if (likely(written
> 0))
2764 iocb
->ki_pos
+= written
;
2767 current
->backing_dev_info
= NULL
;
2768 return written
? written
: err
;
2770 EXPORT_SYMBOL(__generic_file_write_iter
);
2773 * generic_file_write_iter - write data to a file
2774 * @iocb: IO state structure
2775 * @from: iov_iter with data to write
2777 * This is a wrapper around __generic_file_write_iter() to be used by most
2778 * filesystems. It takes care of syncing the file in case of O_SYNC file
2779 * and acquires i_mutex as needed.
2781 ssize_t
generic_file_write_iter(struct kiocb
*iocb
, struct iov_iter
*from
)
2783 struct file
*file
= iocb
->ki_filp
;
2784 struct inode
*inode
= file
->f_mapping
->host
;
2788 ret
= generic_write_checks(iocb
, from
);
2790 ret
= __generic_file_write_iter(iocb
, from
);
2791 inode_unlock(inode
);
2794 ret
= generic_write_sync(iocb
, ret
);
2797 EXPORT_SYMBOL(generic_file_write_iter
);
2800 * try_to_release_page() - release old fs-specific metadata on a page
2802 * @page: the page which the kernel is trying to free
2803 * @gfp_mask: memory allocation flags (and I/O mode)
2805 * The address_space is to try to release any data against the page
2806 * (presumably at page->private). If the release was successful, return `1'.
2807 * Otherwise return zero.
2809 * This may also be called if PG_fscache is set on a page, indicating that the
2810 * page is known to the local caching routines.
2812 * The @gfp_mask argument specifies whether I/O may be performed to release
2813 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
2816 int try_to_release_page(struct page
*page
, gfp_t gfp_mask
)
2818 struct address_space
* const mapping
= page
->mapping
;
2820 BUG_ON(!PageLocked(page
));
2821 if (PageWriteback(page
))
2824 if (mapping
&& mapping
->a_ops
->releasepage
)
2825 return mapping
->a_ops
->releasepage(page
, gfp_mask
);
2826 return try_to_free_buffers(page
);
2829 EXPORT_SYMBOL(try_to_release_page
);